Exemple #1
0
    def __call__(self, x_new):
        """Find linearly interpolated y_new = <name>(x_new).

        Inputs:
          x_new -- New independent variables.

        Outputs:
          y_new -- Linearly interpolated values corresponding to x_new.
        """
        # 1. Handle values in x_new that are outside of x.  Throw error,
        #    or return a list of mask array indicating the outofbounds values.
        #    The behavior is set by the bounds_error variable.
        ## RHC -- was   x_new = atleast_1d(x_new)
        x_new_1d = atleast_1d(x_new)
        out_of_bounds = self._check_bounds(x_new_1d)
        # 2. Find where in the orignal data, the values to interpolate
        #    would be inserted.
        #    Note: If x_new[n] = x[m], then m is returned by searchsorted.
        x_new_indices = searchsorted(self.x, x_new_1d)
        # 3. Clip x_new_indices so that they are within the range of
        #    self.x indices and at least 1.  Removes mis-interpolation
        #    of x_new[n] = x[0]
        # RHC -- changed Int to Numeric_Int to avoid name clash with numarray
        x_new_indices = clip(x_new_indices, 1,
                             len(self.x) - 1).astype(Numeric_Int)
        # 4. Calculate the slope of regions that each x_new value falls in.
        lo = x_new_indices - 1
        hi = x_new_indices

        # !! take() should default to the last axis (IMHO) and remove
        # !! the extra argument.
        x_lo = take(self.x, lo, axis=self.interp_axis)
        x_hi = take(self.x, hi, axis=self.interp_axis)
        y_lo = take(self.y, lo, axis=self.interp_axis)
        y_hi = take(self.y, hi, axis=self.interp_axis)
        slope = (y_hi - y_lo) / (x_hi - x_lo)
        # 5. Calculate the actual value for each entry in x_new.
        y_new = slope * (x_new_1d - x_lo) + y_lo
        # 6. Fill any values that were out of bounds with NaN
        # !! Need to think about how to do this efficiently for
        # !! mutli-dimensional Cases.
        yshape = y_new.shape
        y_new = y_new.flat
        new_shape = list(yshape)
        new_shape[self.interp_axis] = 1
        sec_shape = [1] * len(new_shape)
        sec_shape[self.interp_axis] = len(out_of_bounds)
        out_of_bounds.shape = sec_shape
        new_out = ones(new_shape) * out_of_bounds
        putmask(y_new, new_out.flat, self.fill_value)
        y_new.shape = yshape
        # Rotate the values of y_new back so that they correspond to the
        # correct x_new values.
        result = swapaxes(y_new, self.interp_axis, self.axis)
        try:
            len(x_new)
            return result
        except TypeError:
            return result[0]
        return result
    def __init__(self, x, y, axis=-1, makecopy=0, bounds_error=1,
                 fill_value=None):
        """Initialize a piecewise-constant interpolation class

        Description:
          x and y are arrays of values used to approximate some function f:
            y = f(x)
          This class returns a function whose call method uses piecewise-
          constant interpolation to find the value of new points.

        Inputs:
            x -- a 1d array of monotonically increasing real values.
                 x cannot include duplicate values. (otherwise f is
                 overspecified)
            y -- an nd array of real values.  y's length along the
                 interpolation axis must be equal to the length
                 of x.
            axis -- specifies the axis of y along which to 
                    interpolate. Interpolation defaults to the last
                    axis of y.  (default: -1)
            makecopy -- If 1, the class makes internal copies of x and y.
                    If 0, references to x and y are used. The default 
                    is to copy. (default: 0)
            bounds_error -- If 1, an error is thrown any time interpolation
                            is attempted on a value outside of the range
                            of x (where extrapolation is necessary).
                            If 0, out of bounds values are assigned the
                            NaN (#INF) value.  By default, an error is
                            raised, although this is prone to change.
                            (default: 1)
        """
        self.datapoints = (array(x, Float), array(y, Float))   # RHC -- for access from PyDSTool
        self.type = Float   # RHC -- for access from PyDSTool
        self.axis = axis
        self.makecopy = makecopy   # RHC -- renamed from copy to avoid nameclash
        self.bounds_error = bounds_error
        if fill_value is None:
            self.fill_value = NaN   # RHC -- was:   array(0.0) / array(0.0)
        else:
            self.fill_value = fill_value

        # Check that both x and y are at least 1 dimensional.
        if len(shape(x)) == 0 or len(shape(y)) == 0:
            raise ValueError, "x and y arrays must have at least one dimension."  
        # make a "view" of the y array that is rotated to the
        # interpolation axis.
        oriented_x = x
        oriented_y = swapaxes(y,self.interp_axis,axis)
        interp_axis = self.interp_axis
        len_x,len_y = shape(oriented_x)[interp_axis], \
                            shape(oriented_y)[interp_axis]
        if len_x != len_y:
            raise ValueError, "x and y arrays must be equal in length along "\
                              "interpolation axis."
        if len_x < 2 or len_y < 2:
            raise ValueError, "x and y arrays must have more than 1 entry"            
        self.x = array(oriented_x,copy=self.makecopy)
        self.y = array(oriented_y,copy=self.makecopy)
    def __call__(self,x_new):
        """Find linearly interpolated y_new = <name>(x_new).

        Inputs:
          x_new -- New independent variables.

        Outputs:
          y_new -- Linearly interpolated values corresponding to x_new.
        """
        # 1. Handle values in x_new that are outside of x.  Throw error,
        #    or return a list of mask array indicating the outofbounds values.
        #    The behavior is set by the bounds_error variable.
        ## RHC -- was   x_new = atleast_1d(x_new)
        x_new_1d = atleast_1d(x_new)
        out_of_bounds = self._check_bounds(x_new_1d)
        # 2. Find where in the orignal data, the values to interpolate
        #    would be inserted.
        #    Note: If x_new[n] = x[m], then m is returned by searchsorted.
        x_new_indices = searchsorted(self.x,x_new_1d)
        # 3. Clip x_new_indices so that they are within the range of 
        #    self.x indices and at least 1.  Removes mis-interpolation
        #    of x_new[n] = x[0]
        # RHC -- changed Int to Numeric_Int to avoid name clash with numarray
        x_new_indices = clip(x_new_indices,1,len(self.x)-1).astype(Numeric_Int)
        # 4. Calculate the slope of regions that each x_new value falls in.
        lo = x_new_indices - 1; hi = x_new_indices
        
        # !! take() should default to the last axis (IMHO) and remove
        # !! the extra argument.
        x_lo = take(self.x,lo,axis=self.interp_axis)
        x_hi = take(self.x,hi,axis=self.interp_axis)
        y_lo = take(self.y,lo,axis=self.interp_axis)
        y_hi = take(self.y,hi,axis=self.interp_axis)
        slope = (y_hi-y_lo)/(x_hi-x_lo)
        # 5. Calculate the actual value for each entry in x_new.
        y_new = slope*(x_new_1d-x_lo) + y_lo 
        # 6. Fill any values that were out of bounds with NaN
        # !! Need to think about how to do this efficiently for 
        # !! mutli-dimensional Cases.
        yshape = y_new.shape
        y_new = y_new.flat
        new_shape = list(yshape)
        new_shape[self.interp_axis] = 1
        sec_shape = [1]*len(new_shape)
        sec_shape[self.interp_axis] = len(out_of_bounds)
        out_of_bounds.shape = sec_shape
        new_out = ones(new_shape)*out_of_bounds
        putmask(y_new, new_out.flat, self.fill_value)
        y_new.shape = yshape
        # Rotate the values of y_new back so that they correspond to the
        # correct x_new values.
        result = swapaxes(y_new,self.interp_axis,self.axis)
        try:
            len(x_new)
            return result
        except TypeError:
            return result[0]
        return result
Exemple #4
0
    isfb=0
    for t in elements['array']:
      if t[0]['name'] == 'prf':
        data=[]
        pts=[]
        head=[]
        for z in t[2]['axis']:
          head.append(z[0]['name'])
          pts.append(map(float,z[1].split('\n')))
        for z in range(len(pts[0])):
          err1=pts[head.index('RMSRES')][z]/(pts[head.index('NUM')][z])**0.5
          err2=skysig/(2.)**0.5 # note sqrt(2) kluge
          data.append([pts[head.index('RAD')][z],pts[head.index('INTENS')][z],1,(err1**2+err2**2)**0.5])
        tmp=numarray.array(pts)
        pts=numarray.swapaxes(tmp,1,0)
        if sys.argv[1] == '-p': break
      if t[0]['name'] == 'sfb' and sys.argv[1] != '-p':
        isfb=1
        data=[]
        tmp=[]
        head=[]
        for z in t[2]['axis']:
          head.append(z[0]['name'])
          tmp.append(map(float,z[1].split('\n')))
        for z in range(len(tmp[0])):
          try: # if errorbars in sfb area
            data.append([tmp[head.index('radius')][z],tmp[head.index('mu')][z], \
                         int(tmp[head.index('kill')][z]),tmp[head.index('error')][z]])
          except:
            data.append([tmp[head.index('radius')][z],tmp[head.index('mu')][z], \
def plotXYSVG(drawSpace, dataX, dataY, rank=0, dataLabel=[], plotColor = "black", axesColor="black", labelColor="black", symbolColor="red", XLabel=None, YLabel=None, title=None, fitcurve=None, connectdot=1, displayR=None, loadingPlot = 0, offset= (80, 20, 40, 60), zoom = 1, specialCases=[], showLabel = 1):
    'displayR : correlation scatter plot, loadings : loading plot'

    dataXRanked, dataYRanked = webqtlUtil.calRank(dataX, dataY, len(dataX))

    # Switching Ranked and Unranked X and Y values if a Spearman Rank Correlation
    if rank == 0:
        dataXPrimary = dataX
        dataYPrimary = dataY
        dataXAlt = dataXRanked
        dataYAlt = dataYRanked

    else:
        dataXPrimary = dataXRanked
        dataYPrimary = dataYRanked
        dataXAlt = dataX
        dataYAlt = dataY



    xLeftOffset, xRightOffset, yTopOffset, yBottomOffset = offset
    plotWidth = drawSpace.attributes['width'] - xLeftOffset - xRightOffset
    plotHeight = drawSpace.attributes['height'] - yTopOffset - yBottomOffset
    if plotHeight<=0 or plotWidth<=0:
        return
    if len(dataXPrimary) < 1 or  len(dataXPrimary) != len(dataYPrimary) or (dataLabel and len(dataXPrimary) != len(dataLabel)):
        return

    max_X=max(dataXPrimary)
    min_X=min(dataXPrimary)
    max_Y=max(dataYPrimary)
    min_Y=min(dataYPrimary)

    #for some reason I forgot why I need to do this
    if loadingPlot:
        min_X = min(-0.1,min_X)
        max_X = max(0.1,max_X)
        min_Y = min(-0.1,min_Y)
        max_Y = max(0.1,max_Y)

    xLow, xTop, stepX=detScale(min_X,max_X)
    yLow, yTop, stepY=detScale(min_Y,max_Y)
    xScale = plotWidth/(xTop-xLow)
    yScale = plotHeight/(yTop-yLow)

    #draw drawing region
    r = svg.rect(xLeftOffset, yTopOffset, plotWidth,  plotHeight, 'none', axesColor, 1)
    drawSpace.addElement(r)

    #calculate data points
    data = map(lambda X, Y: (X, Y), dataXPrimary, dataYPrimary)
    xCoord = map(lambda X, Y: ((X-xLow)*xScale + xLeftOffset, yTopOffset+plotHeight-(Y-yLow)*yScale), dataXPrimary, dataYPrimary)
    labelFontF = "verdana"
    labelFontS = 11

    if loadingPlot:
        xZero = -xLow*xScale+xLeftOffset
        yZero = yTopOffset+plotHeight+yLow*yScale
        for point in xCoord:
            drawSpace.addElement(svg.line(xZero,yZero,point[0],point[1], "red", 1))
    else:
        if connectdot:
            pass
            #drawSpace.drawPolygon(xCoord,edgeColor=plotColor,closed=0)
        else:
            pass

    for i, item in enumerate(xCoord):
        if dataLabel and dataLabel[i] in specialCases:
            drawSpace.addElement(svg.rect(item[0]-3, item[1]-3, 6, 6, "none", "green", 0.5))
            #drawSpace.drawCross(item[0],item[1],color=pid.blue,size=5)
        else:
            drawSpace.addElement(svg.line(item[0],item[1]+5,item[0],item[1]-5,symbolColor,1))
            drawSpace.addElement(svg.line(item[0]+5,item[1],item[0]-5,item[1],symbolColor,1))
        if showLabel and dataLabel:
            pass
            drawSpace.addElement(svg.text(item[0], item[1]+14, dataLabel[i], labelFontS,
                    labelFontF, text_anchor="middle", style="stroke:blue;stroke-width:0.5;"))
            #canvas.drawString(, item[0]- canvas.stringWidth(dataLabel[i],
            #       font=labelFont)/2, item[1]+14, font=labelFont, color=pid.blue)

    #draw scale
    #scaleFont=pid.Font(ttf="cour",size=14,bold=1)
    x=xLow
    for i in range(stepX+1):
        xc=xLeftOffset+(x-xLow)*xScale
        drawSpace.addElement(svg.line(xc,yTopOffset+plotHeight,xc,yTopOffset+plotHeight+5, axesColor, 1))
        strX = cformat(d=x, rank=rank)
        drawSpace.addElement(svg.text(xc,yTopOffset+plotHeight+20,strX,13, "courier", text_anchor="middle"))
        x+= (xTop - xLow)/stepX

    y=yLow
    for i in range(stepY+1):
        yc=yTopOffset+plotHeight-(y-yLow)*yScale
        drawSpace.addElement(svg.line(xLeftOffset,yc,xLeftOffset-5,yc, axesColor, 1))
        strY = cformat(d=y, rank=rank)
        drawSpace.addElement(svg.text(xLeftOffset-10,yc+5,strY,13, "courier", text_anchor="end"))
        y+= (yTop - yLow)/stepY

    #draw label
    labelFontF = "verdana"
    labelFontS = 17
    if XLabel:
        drawSpace.addElement(svg.text(xLeftOffset+plotWidth/2.0,
                yTopOffset+plotHeight+yBottomOffset-10,XLabel,
                labelFontS, labelFontF, text_anchor="middle"))

    if YLabel:
        drawSpace.addElement(svg.text(xLeftOffset-50,
                 yTopOffset+plotHeight/2,YLabel,
                labelFontS, labelFontF, text_anchor="middle", style="writing-mode:tb-rl", transform="rotate(270 %d %d)" % (xLeftOffset-50,  yTopOffset+plotHeight/2)))
        #drawSpace.drawString(YLabel, xLeftOffset-50, yTopOffset+plotHeight- (plotHeight-drawSpace.stringWidth(YLabel,font=labelFont))/2.0,
        #       font=labelFont,color=labelColor,angle=90)


    if fitcurve:
        sys.argv = [ "mod_python" ]
        #from numarray import linear_algebra as la
        #from numarray import ones, array, dot, swapaxes
        fitYY = array(dataYPrimary)
        fitXX = array([ones(len(dataXPrimary)),dataXPrimary])
        AA = dot(fitXX,swapaxes(fitXX,0,1))
        BB = dot(fitXX,fitYY)
        bb = la.linear_least_squares(AA,BB)[0]

        xc1 = xLeftOffset
        yc1 = yTopOffset+plotHeight-(bb[0]+bb[1]*xLow-yLow)*yScale
        if yc1 > yTopOffset+plotHeight:
            yc1 = yTopOffset+plotHeight
            xc1 = (yLow-bb[0])/bb[1]
            xc1=(xc1-xLow)*xScale+xLeftOffset
        elif yc1 < yTopOffset:
            yc1 = yTopOffset
            xc1 = (yTop-bb[0])/bb[1]
            xc1=(xc1-xLow)*xScale+xLeftOffset
        else:
            pass

        xc2 = xLeftOffset + plotWidth
        yc2 = yTopOffset+plotHeight-(bb[0]+bb[1]*xTop-yLow)*yScale
        if yc2 > yTopOffset+plotHeight:
            yc2 = yTopOffset+plotHeight
            xc2 = (yLow-bb[0])/bb[1]
            xc2=(xc2-xLow)*xScale+xLeftOffset
        elif yc2 < yTopOffset:
            yc2 = yTopOffset
            xc2 = (yTop-bb[0])/bb[1]
            xc2=(xc2-xLow)*xScale+xLeftOffset
        else:
            pass

        drawSpace.addElement(svg.line(xc1,yc1,xc2,yc2,"green", 1))

    if displayR:
        labelFontF = "trebuc"
        labelFontS = 14
        NNN = len(dataX)

        corr = webqtlUtil.calCorrelation(dataXPrimary,dataYPrimary,NNN)[0]

        if NNN < 3:
            corrPValue = 1.0
        else:
            if abs(corr) >= 1.0:
                corrPValue = 0.0
            else:
                ZValue = 0.5*log((1.0+corr)/(1.0-corr))
                ZValue = ZValue*sqrt(NNN-3)
                corrPValue = 2.0*(1.0 - reaper.normp(abs(ZValue)))

        NStr = "N of Cases=%d" % NNN

        if rank == 1:
            corrStr = "Spearman's r=%1.3f P=%3.2E" % (corr, corrPValue)
        else:
            corrStr = "Pearson's r=%1.3f P=%3.2E" % (corr, corrPValue)

        drawSpace.addElement(svg.text(xLeftOffset,yTopOffset-10,NStr,
                labelFontS, labelFontF, text_anchor="start"))
        drawSpace.addElement(svg.text(xLeftOffset+plotWidth,yTopOffset-25,corrStr,
                labelFontS, labelFontF, text_anchor="end"))
    """
    """
    return
Exemple #6
0
def plotXY(canvas, dataX, dataY, rank=0, dataLabel=[], plotColor = pid.black, axesColor=pid.black, labelColor=pid.black, lineSize="thin", lineColor=pid.grey, idFont="arial", idColor=pid.blue, idSize="14", symbolColor=pid.black, symbolType="circle", filled="yes", symbolSize="tiny", XLabel=None, YLabel=None, title=None, fitcurve=None, connectdot=1, displayR=None, loadingPlot = 0, offset= (80, 20, 40, 60), zoom = 1, specialCases=[], showLabel = 1, bufferSpace = 15):
	'displayR : correlation scatter plot, loadings : loading plot'
	
	dataXRanked, dataYRanked = webqtlUtil.calRank(dataX, dataY, len(dataX))
		
	#get ID font size
	idFontSize = int(idSize)	
	
	#If filled is yes, set fill color
	if filled == "yes":
		fillColor = symbolColor
	else:
		fillColor = None	
	
	if symbolSize == "large":
		sizeModifier = 7
		fontModifier = 12
	elif symbolSize == "medium":
		sizeModifier = 5
		fontModifier = 8
	elif symbolSize == "small":
		sizeModifier = 3
		fontModifier = 3
	else:
		sizeModifier = 1
		fontModifier = -1	
			
	if rank == 0:    # Pearson correlation
		bufferSpace = 0
		dataXPrimary = dataX
		dataYPrimary = dataY
		dataXAlt = dataXRanked    #Values used just for printing the other corr type to the graph image
		dataYAlt = dataYRanked    #Values used just for printing the other corr type to the graph image
	else:    # Spearman correlation: Switching Ranked and Unranked X and Y values
		dataXPrimary = dataXRanked
		dataYPrimary = dataYRanked
		dataXAlt = dataX    #Values used just for printing the other corr type to the graph image
		dataYAlt = dataY    #Values used just for printing the other corr type to the graph image
	
	xLeftOffset, xRightOffset, yTopOffset, yBottomOffset = offset
	plotWidth = canvas.size[0] - xLeftOffset - xRightOffset
	plotHeight = canvas.size[1] - yTopOffset - yBottomOffset
	if plotHeight<=0 or plotWidth<=0:
		return
	if len(dataXPrimary) < 1 or  len(dataXPrimary) != len(dataYPrimary) or (dataLabel and len(dataXPrimary) != len(dataLabel)):
		return
	
	max_X=max(dataXPrimary)
	min_X=min(dataXPrimary)
	max_Y=max(dataYPrimary)
	min_Y=min(dataYPrimary)
	
	#for some reason I forgot why I need to do this
	if loadingPlot:
		min_X = min(-0.1,min_X)
		max_X = max(0.1,max_X)
		min_Y = min(-0.1,min_Y)
		max_Y = max(0.1,max_Y)
	
	xLow, xTop, stepX=detScale(min_X,max_X)
	yLow, yTop, stepY=detScale(min_Y,max_Y)
	xScale = plotWidth/(xTop-xLow)
	yScale = plotHeight/(yTop-yLow)
	
	#draw drawing region
	canvas.drawRect(xLeftOffset-bufferSpace, yTopOffset, xLeftOffset+plotWidth, yTopOffset+plotHeight+bufferSpace)
	canvas.drawRect(xLeftOffset-bufferSpace+1, yTopOffset, xLeftOffset+plotWidth, yTopOffset+plotHeight+bufferSpace-1)

	#calculate data points	
	data = map(lambda X, Y: (X, Y), dataXPrimary, dataYPrimary)
	xCoord = map(lambda X, Y: ((X-xLow)*xScale + xLeftOffset, yTopOffset+plotHeight-(Y-yLow)*yScale), dataXPrimary, dataYPrimary)

	labelFont=pid.Font(ttf=idFont,size=idFontSize,bold=0)

	if loadingPlot:
		xZero = -xLow*xScale+xLeftOffset
		yZero = yTopOffset+plotHeight+yLow*yScale
		for point in xCoord:
			canvas.drawLine(xZero,yZero,point[0],point[1],color=pid.red)
	else:
		if connectdot:
			canvas.drawPolygon(xCoord,edgeColor=plotColor,closed=0)
		else:
			pass

	symbolFont = pid.Font(ttf="fnt_bs", size=12+fontModifier,bold=0)

	for i, item in enumerate(xCoord):
		if dataLabel and dataLabel[i] in specialCases:
			canvas.drawRect(item[0]-3, item[1]-3, item[0]+3, item[1]+3, edgeColor=pid.green)
			#canvas.drawCross(item[0],item[1],color=pid.blue,size=5)
		else:
			if symbolType == "vertRect":
				canvas.drawRect(x1=item[0]-sizeModifier+2,y1=item[1]-sizeModifier-2, x2=item[0]+sizeModifier-1,y2=item[1]+sizeModifier+2, edgeColor=symbolColor, edgeWidth=1, fillColor=fillColor)
			elif (symbolType == "circle" and filled != "yes"):
				canvas.drawString(":", item[0]-canvas.stringWidth(":",font=symbolFont)/2+1,item[1]+2,color=symbolColor, font=symbolFont)
			elif (symbolType == "circle" and filled == "yes"):
				canvas.drawString("5", item[0]-canvas.stringWidth("5",font=symbolFont)/2+1,item[1]+2,color=symbolColor, font=symbolFont)
			elif symbolType == "horiRect":
				canvas.drawRect(x1=item[0]-sizeModifier-1,y1=item[1]-sizeModifier+3, x2=item[0]+sizeModifier+3,y2=item[1]+sizeModifier-2, edgeColor=symbolColor, edgeWidth=1, fillColor=fillColor)
			elif (symbolType == "square"):
				canvas.drawRect(x1=item[0]-sizeModifier+1,y1=item[1]-sizeModifier-4, x2=item[0]+sizeModifier+2,y2=item[1]+sizeModifier-3, edgeColor=symbolColor, edgeWidth=1, fillColor=fillColor)
			elif (symbolType == "diamond" and filled != "yes"):
				canvas.drawString(",", item[0]-canvas.stringWidth(",",font=symbolFont)/2+2, item[1]+6, font=symbolFont, color=symbolColor)
			elif (symbolType == "diamond" and filled == "yes"):
				canvas.drawString("D", item[0]-canvas.stringWidth("D",font=symbolFont)/2+2, item[1]+6, font=symbolFont, color=symbolColor)	
			elif symbolType == "4-star":
				canvas.drawString("l", item[0]-canvas.stringWidth("l",font=symbolFont)/2+1, item[1]+3, font=symbolFont, color=symbolColor)	
			elif symbolType == "3-star":
				canvas.drawString("k", item[0]-canvas.stringWidth("k",font=symbolFont)/2+1, item[1]+3, font=symbolFont, color=symbolColor)	
			else:	
				canvas.drawCross(item[0],item[1]-2,color=symbolColor, size=sizeModifier+2)

		if showLabel and dataLabel:
			if (symbolType == "vertRect" or symbolType == "diamond"):
				labelGap = 15
			elif (symbolType == "4-star" or symbolType == "3-star"):
				labelGap = 12
			else:
			    labelGap = 11
			canvas.drawString(dataLabel[i], item[0]- canvas.stringWidth(dataLabel[i],
				font=labelFont)/2 + 1, item[1]+(labelGap+sizeModifier+(idFontSize-12)), font=labelFont, color=idColor)
                        	
	#draw scale
	scaleFont=pid.Font(ttf="cour",size=16,bold=1)
	

	x=xLow
	for i in range(stepX+1):
		xc=xLeftOffset+(x-xLow)*xScale
		if ((x == 0) & (rank == 1)):
			pass
		else:
			canvas.drawLine(xc,yTopOffset+plotHeight + bufferSpace,xc,yTopOffset+plotHeight+5 + bufferSpace, color=axesColor)		
		strX = cformat(d=x, rank=rank)
		if ((strX == "0") & (rank == 1)):
			pass
		else:
			canvas.drawString(strX,xc-canvas.stringWidth(strX,font=scaleFont)/2,yTopOffset+plotHeight+20 + bufferSpace,font=scaleFont)
		x+= (xTop - xLow)/stepX
	
	y=yLow
	for i in range(stepY+1):
		yc=yTopOffset+plotHeight-(y-yLow)*yScale
		if ((y == 0) & (rank == 1)):
			pass
		else:
			canvas.drawLine(xLeftOffset - bufferSpace,yc,xLeftOffset-5 - bufferSpace,yc, color=axesColor)
		strY = cformat(d=y, rank=rank)
		if ((strY == "0") & (rank == 1)):
			pass
		else:
			canvas.drawString(strY,xLeftOffset-canvas.stringWidth(strY,font=scaleFont)- 10 - bufferSpace,yc+4,font=scaleFont)
		y+= (yTop - yLow)/stepY
			
	#draw label

	labelFont=pid.Font(ttf="verdana",size=canvas.size[0]/45,bold=0)
	titleFont=pid.Font(ttf="verdana",size=canvas.size[0]/40,bold=0)
		
	if (rank == 1 and not title):
		canvas.drawString("Spearman Rank Correlation", xLeftOffset-canvas.size[0]*.025+(plotWidth-canvas.stringWidth("Spearman Rank Correlation",font=titleFont))/2.0,
						  25,font=titleFont,color=labelColor)
	elif (rank == 0 and not title):
		canvas.drawString("Pearson Correlation", xLeftOffset-canvas.size[0]*.025+(plotWidth-canvas.stringWidth("Pearson Correlation",font=titleFont))/2.0,
						  25,font=titleFont,color=labelColor)
		
	if XLabel:
		canvas.drawString(XLabel,xLeftOffset+(plotWidth-canvas.stringWidth(XLabel,font=labelFont))/2.0,
			yTopOffset+plotHeight+yBottomOffset-25,font=labelFont,color=labelColor)
	
	if YLabel:
		canvas.drawString(YLabel, xLeftOffset-65, yTopOffset+plotHeight- (plotHeight-canvas.stringWidth(YLabel,font=labelFont))/2.0,
			font=labelFont,color=labelColor,angle=90)

	labelFont=pid.Font(ttf="verdana",size=20,bold=0)
	if title:
		canvas.drawString(title,xLeftOffset+(plotWidth-canvas.stringWidth(title,font=labelFont))/2.0,
			20,font=labelFont,color=labelColor)
	
	if fitcurve:
		import sys
		sys.argv = [ "mod_python" ]
		#from numarray import linear_algebra as la
		#from numarray import ones, array, dot, swapaxes
		fitYY = array(dataYPrimary)
		fitXX = array([ones(len(dataXPrimary)),dataXPrimary])
		AA = dot(fitXX,swapaxes(fitXX,0,1))
		BB = dot(fitXX,fitYY)
		bb = la.linear_least_squares(AA,BB)[0]
		
		xc1 = xLeftOffset
		yc1 = yTopOffset+plotHeight-(bb[0]+bb[1]*xLow-yLow)*yScale 
		if yc1 > yTopOffset+plotHeight:
			yc1 = yTopOffset+plotHeight
			xc1 = (yLow-bb[0])/bb[1]
			xc1=(xc1-xLow)*xScale+xLeftOffset
		elif yc1 < yTopOffset:
			yc1 = yTopOffset
			xc1 = (yTop-bb[0])/bb[1]
			xc1=(xc1-xLow)*xScale+xLeftOffset
		else:
			pass
		
		xc2 = xLeftOffset + plotWidth 
		yc2 = yTopOffset+plotHeight-(bb[0]+bb[1]*xTop-yLow)*yScale
		if yc2 > yTopOffset+plotHeight:
			yc2 = yTopOffset+plotHeight
			xc2 = (yLow-bb[0])/bb[1]
			xc2=(xc2-xLow)*xScale+xLeftOffset
		elif yc2 < yTopOffset:
			yc2 = yTopOffset
			xc2 = (yTop-bb[0])/bb[1]
			xc2=(xc2-xLow)*xScale+xLeftOffset
		else:
			pass

		canvas.drawLine(xc1 - bufferSpace,yc1 + bufferSpace,xc2,yc2,color=lineColor)
		if lineSize == "medium":
			canvas.drawLine(xc1 - bufferSpace,yc1 + bufferSpace+1,xc2,yc2+1,color=lineColor)
		if lineSize == "thick":
			canvas.drawLine(xc1 - bufferSpace,yc1 + bufferSpace+1,xc2,yc2+1,color=lineColor)
			canvas.drawLine(xc1 - bufferSpace,yc1 + bufferSpace-1,xc2,yc2-1,color=lineColor)
		
		
	if displayR:
		labelFont=pid.Font(ttf="trebuc",size=canvas.size[0]/60,bold=0)
		NNN = len(dataX)
		corr = webqtlUtil.calCorrelation(dataXPrimary,dataYPrimary,NNN)[0]

		if NNN < 3:
			corrPValue = 1.0
		else:
			if abs(corr) >= 1.0:
				corrPValue = 0.0
			else:
				ZValue = 0.5*log((1.0+corr)/(1.0-corr))
				ZValue = ZValue*sqrt(NNN-3)
				corrPValue = 2.0*(1.0 - reaper.normp(abs(ZValue)))
				
		NStr = "N = %d" % NNN
		strLenN = canvas.stringWidth(NStr,font=labelFont)

		if rank == 1:
		    if corrPValue < 0.0000000000000001:
				corrStr = "Rho = %1.3f P < 1.00 E-16" % (corr)
		    else:
				corrStr = "Rho = %1.3f P = %3.2E" % (corr, corrPValue)
		else:
		    if corrPValue < 0.0000000000000001:
				corrStr = "r = %1.3f P < 1.00 E-16" % (corr)
		    else:
				corrStr = "r = %1.3f P = %3.2E" % (corr, corrPValue)
		strLen = canvas.stringWidth(corrStr,font=labelFont)

		canvas.drawString(NStr,xLeftOffset,yTopOffset-10,font=labelFont,color=labelColor)
		canvas.drawString(corrStr,xLeftOffset+plotWidth-strLen,yTopOffset-10,font=labelFont,color=labelColor)

	return xCoord
Exemple #7
0
    def __init__(self,
                 x,
                 y,
                 axis=-1,
                 makecopy=0,
                 bounds_error=1,
                 fill_value=None):
        """Initialize a piecewise-constant interpolation class

        Description:
          x and y are arrays of values used to approximate some function f:
            y = f(x)
          This class returns a function whose call method uses piecewise-
          constant interpolation to find the value of new points.

        Inputs:
            x -- a 1d array of monotonically increasing real values.
                 x cannot include duplicate values. (otherwise f is
                 overspecified)
            y -- an nd array of real values.  y's length along the
                 interpolation axis must be equal to the length
                 of x.
            axis -- specifies the axis of y along which to 
                    interpolate. Interpolation defaults to the last
                    axis of y.  (default: -1)
            makecopy -- If 1, the class makes internal copies of x and y.
                    If 0, references to x and y are used. The default 
                    is to copy. (default: 0)
            bounds_error -- If 1, an error is thrown any time interpolation
                            is attempted on a value outside of the range
                            of x (where extrapolation is necessary).
                            If 0, out of bounds values are assigned the
                            NaN (#INF) value.  By default, an error is
                            raised, although this is prone to change.
                            (default: 1)
        """
        self.datapoints = (array(x, Float), array(y, Float)
                           )  # RHC -- for access from PyDSTool
        self.type = Float  # RHC -- for access from PyDSTool
        self.axis = axis
        self.makecopy = makecopy  # RHC -- renamed from copy to avoid nameclash
        self.bounds_error = bounds_error
        if fill_value is None:
            self.fill_value = NaN  # RHC -- was:   array(0.0) / array(0.0)
        else:
            self.fill_value = fill_value

        # Check that both x and y are at least 1 dimensional.
        if len(shape(x)) == 0 or len(shape(y)) == 0:
            raise ValueError, "x and y arrays must have at least one dimension."
        # make a "view" of the y array that is rotated to the
        # interpolation axis.
        oriented_x = x
        oriented_y = swapaxes(y, self.interp_axis, axis)
        interp_axis = self.interp_axis
        len_x,len_y = shape(oriented_x)[interp_axis], \
                            shape(oriented_y)[interp_axis]
        if len_x != len_y:
            raise ValueError, "x and y arrays must be equal in length along "\
                              "interpolation axis."
        if len_x < 2 or len_y < 2:
            raise ValueError, "x and y arrays must have more than 1 entry"
        self.x = array(oriented_x, copy=self.makecopy)
        self.y = array(oriented_y, copy=self.makecopy)