예제 #1
0
def ffcontour(grids, X0=None):
	# if X0==None: assume square
	if X0==None: X0=(len(grids))**.5
	#
	# in this case, X0 is explicitly the width of a row, including borders.
	Xs=[]
	Ys=[]
	Z=scipy.array(grids)
	Z.shape=(X0, math.ceil(len(grids)/X0))
	
	Xs=range(X0)
	Ys=range(X0)
	
	#for i in xrange(len(grids)):
	#	Xs+=[i%X0]
	#	Ys+=[int(i/X0)]
	#	# Z+=[[i%X0, int(i/X0), grids[i]]]
	X,Y=numpy.meshgrid(Xs, Ys)
	#Z.shape=(X0, math.ceil(len(grids)/X0))
	#print "lens: %d * %d = %d, %d" % (len(Xs), len(Ys), len(Xs)*len(Ys), len(grids))
	Z.shape=(len(Xs), len(Ys))
	plt.contourf(X,Y,Z, alpha=.35)
	#plt.colorbar(ticks=[-5,-4,-3,-2,-1])
	plt.colorbar()
	plt.spectral()
예제 #2
0
파일: fdct2.py 프로젝트: weltenwort/diplom
def show_fdct(filename, channel=0, scales=4, angles=16):
    image = pyplot.imread(filename)[:, :, channel]
    transformation = fdct2(image.shape, scales, angles, True, norm=True)

    cl = transformation.fwd(image)

    #fig, axs = pyplot.subplots(angles, scales + 1)
    pyplot.spectral()
    fig = pyplot.figure(1)

    # display original image
    #img_orig = axs[0, 0].imshow(image)
    img_orig = pyplot.imshow(image)
    pyplot.colorbar(orientation="horizontal")
    #pyplot.colorbar(img_orig, ax=axs[0, 0], orientation="horizontal")

    #imgs = []
    angles = [1, ] + [angles] * (scales - 1)
    for scale in range(scales):
        fig = pyplot.figure(scale + 100)
        grid = ImageGrid(fig, 111, (1, angles[scale]))
        for angle in range(angles[scale]):
            print("displaying",scale,angle)
            cl_img = cl(scale, angle)
            print(cl_img.shape)
            grid[angle].imshow(cl_img)
            #img = axs[0, scale + 1].imshow(cl_img)
        #pyplot.colorbar(img, ax=axs[0, scale + 1], orientation="horizontal")
        #imgs.append(img)

    pyplot.show()
예제 #3
0
def plotar_silhueta(silhueta_dados):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    flat_silhueta_dados = []
    for cluster in silhueta_dados:
        cluster = list(cluster)
        cluster.sort(key=lambda x: x) #sort ordem decrescente
        for dado in cluster:
            flat_silhueta_dados.append(dado)
    Y = np.arange(0, len(flat_silhueta_dados))
    plt.spectral()
    ax.fill_betweenx(Y, flat_silhueta_dados)
    plt.show()
예제 #4
0
 def GetExec(self, f, coverPanel, rec,  geMat, colorList):
     self.rec = rec
     self.coverPanel = coverPanel
     self.geMat = geMat
     self.bPSize = self.coverPanel.GetSize()
     self.plotter = mpl.PlotNotebook(self.coverPanel,
                             size = (self.bPSize[1], self.bPSize[1] * 1.08),
                             pos = ((self.bPSize[0]-self.bPSize[1])/2,
                                    -self.bPSize[1] * .08))
     self.plotter.Show(True)
     self.axes1 = self.plotter.add('figure 1').gca()
     colMat = GetExec(self.rec, geMat, 'tri')
     self.Z3 = np.transpose(np.array(colMat))
     plt.spectral()
     self.DoDraw()
     return self.geMat
예제 #5
0
def plot_clustering(n_clusters, cluster_labels, X):
    plt.figure()
    sample_silhouette_values = silhouette_samples(X, cluster_labels)
    y_lower = 10
    for i in range(n_clusters):
        # Aggregate the silhouette scores for samples belonging to
        # cluster i, and sort them
        ith_cluster_silhouette_values = \
            sample_silhouette_values[cluster_labels == i]

        ith_cluster_silhouette_values.sort()

        size_cluster_i = ith_cluster_silhouette_values.shape[0]
        y_upper = y_lower + size_cluster_i

        color = plt.spectral(float(i) / n_clusters)
        plt.fill_betweenx(np.arange(y_lower, y_upper),
                          0, ith_cluster_silhouette_values,
                          facecolor=color, edgecolor=color, alpha=0.7)

        # Label the silhouette plots with their cluster numbers at the middle
        plt.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))

        # Compute the new y_lower for next plot
        y_lower = y_upper + 10  # 10 for the 0 samples

    plt.set_title("The silhouette plot for the various clusters.")
    plt.set_xlabel("The silhouette coefficient values")
    plt.set_ylabel("Cluster label")

    # The vertical line for average silhouette score of all the values
    plt.axvline(x=silhouette_avg, color="red", linestyle="--")

    plt.set_yticks([])  # Clear the yaxis labels / ticks
    plt.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
    plt.show()
예제 #6
0
              recvbuf=[counts, MPI.INTEGER],
              root=MPI.ROOT)
worker.Gatherv(sendbuf=None,
               recvbuf=[indices, (counts, None), MPI.INTEGER],
               root=MPI.ROOT)
rowtype = MPI.INTEGER.Create_contiguous(w).Commit()
worker.Gatherv(sendbuf=None,
               recvbuf=[result, (counts, None), rowtype],
               root=MPI.ROOT)
rowtype.Free()

# disconnect worker
worker.Disconnect()

# reconstruct result
C = numpy.empty([h, w], dtype='i')
C[indices, :] = result

try:
    from matplotlib import pyplot as plt
    plt.imshow(C, aspect='equal')
    plt.spectral()
    if not plt.isinteractive():
        import signal
        def action(*args): raise SystemExit
        signal.signal(signal.SIGALRM, action)
        signal.alarm(2)
    plt.show()
except:
    pass
예제 #7
0
import matplotlib.pyplot as plt
import numpy as np
plt.spectral()  #setting the default color map to "spectral"
plt.rcParams['contour.negative_linestyle'] = 'solid'


def getfile(ts=None, dtype=None, filename=None, fmt="%s.%06d_p000000.h5"):
    '''
	Return the hdf5 file pointer. "filename" is either given explicitly, or formatted from "ts"(timestep) and "dtype"('pfd'/'tfd') according to "fmt".
	'''
    import h5py, os
    if filename == None:
        if ts != None and dtype != None:
            filename = fmt % (dtype, ts)
        else:
            print "ERROR: either ts & dtype together, or filename alone should be given"
            return
    try:
        f = h5py.File(filename, 'r')
    except IOError:
        print "ERROR: Cannot open %s" % filename
        return
    return f


def getfld_file(fld,
                f,
                dims='xz',
                n=0,
                i1b=0,
                i1e=None,
예제 #8
0
    local_height = height - default_local_height * (size - 1)
local_array_len = local_height * width
local_result = np.zeros(shape=[local_array_len],
                        dtype='i')

dx = a / height
dy = b / width
for row in range(local_height):
    shift = default_local_height * rank
    y = -b / 3 + (row + shift) * dy
    for col in range(width):
        x = -a + col * dx
        local_result[col + row * width] = mandelbrot(x, y, max_iter)
print('{0} process for {1} seconds'.format(rank, time.time() - t0))
local_result.shape = (local_height, width)
pyplot.imshow(local_result, aspect='equal')
pyplot.spectral()
pyplot.show()
result = None
if rank == 0:
    result = np.empty([height * width], dtype='i')
comm.Gather(sendbuf=local_result,
            recvbuf=result,
            root=0)
if rank == 0:
    result.shape = (height, width)
    print('all time for execution {}'.format(time.time() - t0))
    pyplot.imshow(result, aspect='equal')
    pyplot.spectral()
    pyplot.show()
예제 #9
0
# without load balancing
# for i in range(rank*strip_size,rank*strip_size+strip_size):
# 	y = y1 + i*dx
# 	for j in range(ny):
# 		x = x1 + j*dy
# 		c[i,j] = mandlebrot(x,y,127)

# with load balancing by cyclic distribution
i = rank
while i < nx:
	y = y1 + i*dx
	for j in range(ny):
		x = x1 + j*dy
		c[i,j] = mandlebrot(x,y,127)
	i += size

end_local = MPI.Wtime()
print "Total time taken for local calculation by process "+str(rank)+" : "+str(end_local-start)


comm.Allreduce(MPI.IN_PLACE,c,op=MPI.MAX)

if rank == 0:
	# print c
	end_comm = time.time()
	print "Total time taken for all communications : "+str(end_comm-start)
	pyplot.imshow(c, aspect='equal')
	pyplot.spectral()
	pyplot.show()
예제 #10
0
warnings = ['No','Low','Guarded','Elevated','High','Severe']

#-----------------------------------------------------------------------------#

Z_i = numpy.loadtxt('tmp/Zarray.dat')

Y_i =   37.0 + .1*numpy.arange(Z_i.shape[0])
X_i = -127.5 + .1*numpy.arange(Z_i.shape[1])

print(Z_i.shape, len(Y_i), len(X_i))

#-----------------------------------------------------------------------------#

# Create the KML file
cs = plt.contourf(X_i, Y_i, Z_i, LevelsNumber,
                  cm=plt.spectral()).collections

file = open('doc.kml','w')
file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
file.write('<kml xmlns="http://www.opengis.net/kml/2.2">\n')
file.write('<Document>\n')

for i in range(0,len(cs)):
    bgra_array = 255*cs[i].get_facecolor()[0]
    file.write('<Style id="l%d">\n' % i)
    file.write('<LineStyle><color>00000000</color></LineStyle>\n')
    file.write('<PolyStyle><color>7d%02x%02x%02x</color></PolyStyle>\n' %\
                   ( bgra_array[2] , bgra_array[1] , bgra_array[0] ) )
    file.write('</Style>\n')

file.write('<ScreenOverlay id="scale">\n')
예제 #11
0
파일: vispsc2d.py 프로젝트: ALaDyn/psc
import matplotlib.pyplot as plt
import numpy as np
plt.spectral()#setting the default color map to "spectral"
plt.rcParams['contour.negative_linestyle'] = 'solid'

def getfile(ts=None,dtype=None,filename=None,fmt="%s.%06d_p000000.h5"):
	'''
	Return the hdf5 file pointer. "filename" is either given explicitly, or formatted from "ts"(timestep) and "dtype"('pfd'/'tfd') according to "fmt".
	'''
	import h5py,os
	if filename==None:
		if ts!=None and dtype!=None:
			filename=fmt%(dtype,ts)
		else:
			print "ERROR: either ts & dtype together, or filename alone should be given"
			return
	try:
		f=h5py.File(filename,'r')
	except IOError:
		print "ERROR: Cannot open %s"%filename
		return
	return f

def getfld_file(fld,f,dims='xz',n=0,i1b=0,i1e=None,i2b=0,i2e=None,stride1=None,stride2=None,stride=1):
	'''
	Retrieve field named by "fld" from a hdf5 file pointer. For the first dimension(e.g., 'x' in 'xz'), indices ;i1b'/'i1e' specify a range from which data is retrieved. Data array will also be strided every 'stride1' step. If 'stride1' is not set, the value of 'stride' will be used, which is 1 (no striding) by default.	Similarly, for the second dimension, 'i2b', 'i2e', 'stride2' can be used.
	'''
	if stride1==None:
		stride1=stride
	if stride2==None:
		stride2=stride