Esempio n. 1
0
def ecdf(data, show=False,savename=None):
	
 	ecdf = sm.distributions.ECDF(data)

 	x = np.linspace(data.min(),data.max())
 	y = ecdf(x)

 	cutoff = x[y>0.85][0]
	fig = plt.figure()
	ax = fig.add_subplot(111)
	ax.plot(x,y,'k',linewidth=3)
	artist.adjust_spines(ax)

	ax.annotate(r'\Large \textbf{Cutoff:} $%.03f$'%cutoff, xy=(.3, .2),  xycoords='axes fraction',
                horizontalalignment='center', verticalalignment='center')
	ax.set_xlabel(artist.format('Absolute Correlation'))
	ax.set_ylabel(artist.format('Percentile'))
	ax.axhline(y=0.85,color='r',linestyle='--',linewidth=2)
	ax.axvline(x=cutoff,color='r',linestyle='--',linewidth=2)
	ax.set_xlim((0,1))
	plt.tight_layout()

	if savename:
		plt.savefig('%s.png'%savename,dpi=200)
	if show:
		plt.show()

	return cutoff
Esempio n. 2
0
def snapshots(data, indices,basepath=None, data_label='data'):
		indices = zip(indices,indices[1:])

		for start_idx,stop_idx in indices:
			initial_distribution = data[:,start_idx]
			final_distribution = data[:,stop_idx]

			fig = plt.figure()
			ax = fig.add_subplot(111)
			ax.hist(initial_distribution,color='r',alpha=0.5,bins=20,label='Initial', range=(-1,1))
			ax.hist(final_distribution,color='k',alpha=0.5,bins=20,label='Final',range=(-1,1))
			artist.adjust_spines(ax)
			ax.set_xlabel(artist.format(data_label))
			ax.set_ylabel(artist.format('Prevalence'))

			H,p =kruskal(initial_distribution,final_distribution)
			effect_size = np.linalg.norm(final_distribution-initial_distribution)
			ax.annotate('\Large $d=%.02f, \; p=%.04f$'%(effect_size,p), xy=(.3, .9),  
				xycoords='axes fraction', horizontalalignment='right', verticalalignment='top')
			plt.tight_layout()
			plt.legend(frameon=False)

			filename = os.path.join(basepath,'%s-compare-%d-%d.png'%(data_label,start_idx,stop_idx))
			plt.savefig(filename,dpi=300)	
			plt.close()
Esempio n. 3
0
def coefficients(model,labels,show=False,savename=None,title=None):

	fig = plt.figure(figsize=(8,10))
	ax = fig.add_subplot(111)
	x = -model.coef_.transpose()
	x /= np.absolute(x).max()
	y = np.arange(len(x))+0.5

	cutoff = scoreatpercentile(np.absolute(x),85)
	ax.barh(y,x,color=['r' if datum < 0 else 'g' for datum in x])
	ax.axvline(cutoff,linewidth=2,linestyle='--',color='r')
	ax.axvline(-cutoff,linewidth=2,linestyle='--',color='r')
	artist.adjust_spines(ax)
	ax.grid(True)
	ax.set_ylim(ymax=62)
	ax.set_xlim(xmin=-1.1,xmax=1.1)
	ax.set_yticks(y)
	ax.set_yticklabels(map(format,labels),y)
	ax.set_xlabel(format('Regression coefficient'))

	if title:
		ax.set_title(r'\Large \textbf{%s}'%title)
	plt.tight_layout()
	if show:
		plt.show()
Esempio n. 4
0
	def frequencies(self,str, ax=None, cutoff=30):
		words = nltk.word_tokenize(''.join(ch for ch in str 
											if ch not in exclude 
												and ord(ch)<128 
												and not ch.isdigit()).lower())
		words = [word for word in words if word not in stopwords 
										and word not in emoticons 
										and word  not in ['rt','amp']]
		fdist = nltk.FreqDist(words)
		freqs = fdist.items()[:cutoff]
		word,f =zip(*freqs)
		f = np.array(f).astype(float)
		print f,'kkkkkkk'
		f /= float(f.sum())
		print f,'jjjjjjjjjjjj'
		if not ax:
			fig = plt.figure()
			ax = fig.add_subplot(111)

		ax.plot(-f*np.log(f),'k',linewidth=2)
		artist.adjust_spines(ax)
		ax.yaxis.grid()
		ax.xaxis.grid()
		ax.set_xticks(range(len(word)))
		ax.set_xticklabels(map(format,word),range(len(word)), rotation=45)
		ax.set_ylabel(r'\Large $\log \left(\mathbf{Frequency}\right)$')
		plt.tight_layout()
		plt.show()
Esempio n. 5
0
def covariance(heatmap,labels,show=False,savename=None,ml=False):
	#Covariance matrix
	fig = plt.figure(figsize=(13,13))
	ax = fig.add_subplot(111)
	cax = ax.imshow(heatmap,interpolation='nearest',aspect='equal')
	artist.adjust_spines(ax)
	ax.set_xticks(range(len(labels)))
	ax.set_xticklabels(map(artist.format,labels),range(len(labels)),rotation=90)

	ax.set_yticks(range(len(labels)))
	ax.set_yticklabels(map(artist.format,labels))

	if ml:
		ax.annotate(r'\LARGE \textbf{Training}', xy=(.2, .2),  xycoords='axes fraction',
		                horizontalalignment='center', verticalalignment='center')


		ax.annotate(r'\LARGE \textbf{Testing}', xy=(.7, .7),  xycoords='axes fraction',
		                horizontalalignment='center', verticalalignment='center')

	plt.colorbar(cax, fraction=0.10, shrink=0.8)
	plt.tight_layout()

	if savename:
		plt.savefig('%s.png'%savename,dpi=200)
	if show:
		plt.show()
Esempio n. 6
0
 def draw(self):
     GraphicsCard.enable('blend')
     GraphicsCard.setBlendFunction('src_alpha', 'one_minus_src_alpha')
     GraphicsCard.disable('lighting', 'texture_2d')
     alpha = max( float(self.timeleft / 2.0), 0 )
     GraphicsCard.setColorRGBA( alpha/2.0, 0, 0, alpha )
     Graphics.drawSphere( self.location, 4, 8, 4 )
     GraphicsCard.enable('texture_2d')
Esempio n. 7
0
def plot(aList,ax, cutoff=20):
	tokens,frequencies = zip(*sorted(aList,key=lambda item:item[1],reverse=True))

	tokens = tokens[:cutoff][::-1]
	frequencies = frequencies[:cutoff][::-1]

	ax.plot(frequencies,xrange(cutoff),'k--', linewidth=2)
	artist.adjust_spines(ax)
	ax.set_yticks(xrange(cutoff))
	ax.set_yticklabels(map(artist.format,tokens),rotation='horizontal')
Esempio n. 8
0
def main():
    # Loop until the user clicks the close button.
    done = False
    loopCount = 0
    while not done:
        loopCount += 1
        Input.update()
        if(Input.Trigger(Input.Close)):
            done = True
        map.update()
        Graphics.update()
Esempio n. 9
0
	def draw(self):
		#find camera's transform matrix
		m = MathUtil.buildTransformMatrix(self.ent.headLocation,
										  self.ent.yaw + math.pi,
										  self.ent.pitch,
										  self.ent.roll)
		glPushMatrix()
		glMultMatrixf( m.toList() )
		Graphics.drawPyramid(30, 10, 100.0)
		Graphics.drawWirePyramid(30, 10, 100.0)
		glPopMatrix()
Esempio n. 10
0
def network_stability(energy_trace,savename):

	fig = plt.figure()
	ax = fig.add_subplot(111)
	ax.plot(energy_trace,'k',linewidth=2)
	artist.adjust_spines(ax)
	ax.set_xlabel(artist.format('Time'))
	ax.set_ylabel(artist.format('Stability (energy)'))

	plt.savefig('%s.png'%savename,dpi=200)
	plt.close()
Esempio n. 11
0
 def SystemShutdown(self):
     import Graphics
     Graphics._ViewManager().Shutdown()
     self.exitTaskletManager = True
     # tell all services to shut down!
     for service in self._running_services.values():
         try:
             print "shutting down - ", service.__ID__
             service.state = SERVICE_STATES.STOPPED
             service.OnSystemShutdown()
         except Exception, e:
             print "Exception in Service", service.__ID__, e
def plot_and_save(frequencies, words, ylabel, savefile):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.semilogy(frequencies,'k--',linewidth=3)
    artist.adjust_spines(ax)

    ax.set_xticks(xrange(len(words)))
    ax.set_xticklabels([r'\textbf{\textsc{%s}'%word for word in words],rotation='vertical')
    ax.set_ylabel(artist.format(ylabel))

    plt.tight_layout()
    plt.show()
    plt.savefig(savefile, bbox_inches="tight")
Esempio n. 13
0
def memory_stability(mat,savename):

	fig = plt.figure()
	ax = fig.add_subplot(111)
	cax = ax.imshow(mat,interpolation='nearest',aspect='auto')
	
	artist.adjust_spines(ax)
	ax.set_ylabel(artist.format('Memory'))
	ax.set_xlabel(artist.format('Time'))

	cbar = plt.colorbar(cax)
	cbar.set_label(artist.format('Energy'))
	plt.savefig('%s.png'%savename,dpi=200)
	plt.close()
Esempio n. 14
0
def runWin():

	

	Label(window, image=photo).grid(row=0, column=1)

	Label(window, text="BigRep Configuration UI", font=Graphics.getBigRepFont(window, 40)).grid(row=0, column = 2)
Esempio n. 15
0
def _processRenderSurface(logDir, attributes):
  def attr(name):
    return attributes[name]
    
  w, h            = attr("render_surface_width"), attr("render_surface_height")
  redMask         = attr("red_mask")
  greenMask       = attr("green_mask")
  blueMask        = attr("blue_mask")
  alphaMask       = attr("alpha_mask")
  depthMask       = attr("depth_mask")
  stencilMask     = attr("stencil_mask")
  isLinear        = attr("is_linear")
  isPremultiplied = attr("is_premultiplied")
  
  # Convert the color buffer
  if "color_buffer" in attributes:
    fileName    = attr("color_buffer")
    if not os.path.exists(fileName):
      fileName  = os.path.join(logDir, fileName)
    fileNameOut = fileName.rsplit(".", 1)[0] + ".png"
    
    # Only do the conversion if the image doesn't already exist
    # or if the source file is newer.
    if fileName.endswith(".dat") and \
       (not os.path.exists(fileNameOut) or \
        (os.path.exists(fileName) and os.path.getmtime(fileName) > os.path.getmtime(fileNameOut))
       ):
      stride      = attr("color_stride")
      
      f           = open(fileName, "rb")
      data        = f.read(stride * h)
      f.close()
      
      if len(data) != h * stride or not data:
        Log.error("Invalid color buffer data size: %d"  % len(data))
        return
      
      colorBuffer = Graphics.decodeImageData(data, (w, h), stride, redMask, greenMask, blueMask, alphaMask, isLinear, isPremultiplied)
      colorBuffer = colorBuffer.convert("RGBA")
      colorBuffer.save(fileNameOut)
      
      # We can remove the original file now
      os.unlink(fileName)
      
      # Replace the original file name with the decoded file
      attributes["color_buffer"] = fileNameOut
      
    # Eat the render surface attributes since they are of little use further down the road
    #for attrName in ["red_mask", "green_mask", "blue_mask", "alpha_mask",
    #                 "depth_mask", "stencil_mask", "color_stride",
    #                 "is_linear", "is_premultiplied", "color_data_type", 
    #                 "depth_data_type", "stencil_data_type"]:
    #  if attrName in attributes:
    #    del attributes[attrName]

  for bufferName in ["depth_buffer", "stencil_buffer"]:
    if bufferName in attributes and not os.path.exists(attributes[bufferName]):
      # Fill in the full buffer file name
      attributes[bufferName] = os.path.join(logDir, attr(bufferName))
Esempio n. 16
0
def sensitivity(x,y, show=False, savename=None):
	fig = plt.figure()
	ax = fig.add_subplot(111)
	ax.plot(x,y,'ko--',linewidth=2,clip_on=False)

	artist.adjust_spines(ax)
	ax.set_xlabel(r'\Large \textbf{Mixing fraction,} $\; \alpha$')
	ax.set_ylabel(r'\Large \textbf{Maximum accuracy,}$\; q_{\max}$')
	ax.set_ylim((-1.1))
	plt.tight_layout()

	if savename:
		plt.savefig('%s.png'%savename,dpi=300)
	if show:
		plt.show()
	plt.close()
	return pearsonr(x,y)
Esempio n. 17
0
def minConflicts(csp, variables):
    """
    Min-conflicts approach to solving the Sudoku puzzle
    """
    
    assignment, domains = csp  # Domains not applicable for this problem, but included for readability
    
    # Iterate through list, and randomly assign numbers
    for var in variables:

        # Randomly assign number
        num = random.randint(1,9)
        
        # Update the stack to include the new number, whether it works or not
        assignment[var[0]][var[1]] = num
    
    
    # Loop while the problem is not solved
    while variables != []:
        
        Graphics.showPuzzle(assignment)
        
        print variables
        
        # Randomly choose a variable from the list
        var = random.choice(variables)
        
        # Create value for least-conflict value
        bestValue, leastConstraints = None, sys.maxsize
        
        # Loop over possible domain values, and update best value if applicable
        for value in range(1,10):
            conflicts = countConflicts(assignment, var, value)
            if conflicts < leastConstraints:
                bestValue, leastConstraints = value, conflicts
        
        # Update the state with the new value
        assignment[var[0]][var[1]] = bestValue
        
        # If the variable does not violate any constraints, remove it from conflicted
        if leastConstraints == 0:
            variables.remove(var) 
            
    print "Solution Found!"
    
    return assignment
Esempio n. 18
0
def grayscale(imageName):
    win = g.GraphWin()
    image = g.Image(point(0, 0), imageName)
    # for each row in the image:
    for rown in image:
        for column in image:
            r, g, b = # get pixel information for current row and column
            brightness = int(round((0.299 * r) + (0.587 * g) + (0.114 * b)))
            pixel_color = color_rgb(brightness, brightness, brightness)
       # update the image # to see progress row by row

    for row in image:
        for column in image:
            r, g, b = g.getPixel(row, column)
            brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
            g.color_rgb(brightness, brightness, brightness)

    g.draw(win)
Esempio n. 19
0
def mvr_coefficients(model,labels,show=False,savename=None):

	fig = plt.figure()
	ax = fig.add_subplot(111)
	cax = ax.imshow(model.coef_.transpose(),interpolation='nearest',aspect='auto',
		vmin=-0.5,vmax=0.5)
	artist.adjust_spines(ax)
	ax.set_yticks(range(len(labels)))
	ax.set_yticklabels(map(artist.format,[name for name in labels if 'EVD' not in name]))
	ax.set_xticks(range(3))
	ax.set_xticklabels(map(artist.format,range(1,4)))
	ax.set_xlabel(artist.format('Placement grade'))
	plt.colorbar(cax)
	plt.tight_layout()
	if savename:
		plt.savefig('%s.png'%savename,dpi=200)
	if show:
		plt.show()
Esempio n. 20
0
def correlation_visualization(data, show=False,savename=None):
	correlations = ['Quu','Qru','Qvu']
	#Analyze correlations

	fig,axs = plt.subplots(nrows=3,ncols=1,sharex=True)
	for ax,data,label in zip(axs,map(dq,[data[correlation] for correlation in correlations]),correlations):
		ax.plot(data,'k',linewidth=2,label=artist.format(label))

		artist.adjust_spines(ax)

		ax.set_ylabel(r'\Large $\mathbf{\partial \left(\det %s_{%s}\right)}$'%(label[0],label[1:]),rotation='horizontal')
		ax.set_xlabel(artist.format('Time'))

	plt.tight_layout()
	if savename:
		plt.savefig('%s.png'%savename,dpi=200)
	if show:
		plt.show()
	plt.close()
Esempio n. 21
0
 def setUpPlayer (self, pos, clrBase = None, clrTurret = None):
     if self.side == 'player':
         self.maze.addPlayer (self)
     self.pos = pos
     self.vel = 0
     self.cooldownTimer = 0
     self.viewTheta = math.pi / 8
     self.base = Graphics.cube (clrBase)
     self.base.transform (Matrix.scale (7.5, 7.5, 3.75))
     self.base.translate (self.pos.x (), self.pos.y(), 10)
     self.turretp1 = Graphics.icosahedron (clrTurret)
     self.turretp1.transform (Matrix.scale (5, 5, 5))
     self.turretp2 = Graphics.cube (clrTurret)
     self.turretp2.transform (Matrix.scale (1, 7.5, 1))
     self.turretp2.translate (0, 3.5, 0)
     self.turret = self.turretp1.union (self.turretp2)
     self.turret.translate (self.pos.x (), self.pos.y(), 0)
     self.theta = 0
     self.turretTheta = 0
     self.changeAngle (math.pi / 4)
     self.alive = True
def compare_distributions(variable_source_name,idxs,rng=(0,1)):
	#Assume idxs is dictionary structured as {name:[corresponding indices]}
	fig = plt.figure()
	ax = fig.add_subplot(111)
	data =  np.loadtxt(make_filename('%s.txt'%(variable_source_name)),delimiter=TAB)

	fig = plt.figure()
	ax = fig.add_subplot(111)
	plt.hold(True)
	for subpopulation,idx,color in idxs:
		weights = np.ones_like(data[idx])/len(data[idx])
		ax.hist(data[idx],color=color,label=artist.format(subpopulation),histtype='step',range=rng,weights=weights)

	fig.canvas.mpl_connect('draw_event', artist.on_draw)
	artist.adjust_spines(ax)
	ax.set_ylabel(artist.format('Prevalance'))
	ax.set_xlabel(artist.format(variable_source_name))
	plt.legend(frameon=False,ncol=2,loc='upper center',bbox_to_anchor=(.5,1.05))
	plt.tight_layout()
	plt.savefig(make_filename('%s-%s.png'%(variable_source_name,'-'.join([idx[0] for idx in idxs]))),dpi=300)
	del fig,ax
Esempio n. 23
0
def dashboard(data,numpc=3):
	coeff,projections,latent = tech.princomp(data,numpc=numpc)
	panels = {'projection':plt.subplot2grid((2,3),(0,0),colspan=2, rowspan=2),
			  'spectrum':plt.subplot2grid((2,3),(0,2)),
			  'silhouette':plt.subplot2grid((2,3),(1,2))}
	panels['projection'].scatter(projections[0],projections[1],s=30)
	artist.adjust_spines(panels['projection'])
	panels['projection'].set_xlabel(r'\Large \textbf{Principal Component 1}')
	panels['projection'].set_ylabel(r'\Large \textbf{Principal Component 2}')

	cutoff=10
	panels['spectrum'].stem(range(1,cutoff+1),latent[:cutoff]/np.sum(latent))
	panels['spectrum'].set_xlim(0,cutoff+1)
	panels['spectrum'].set_ylim((0,1))
	artist.adjust_spines(panels['spectrum'])
	panels['spectrum'].set_xlabel(r'\Large \textbf{Eigenvector}')
	panels['spectrum'].set_ylabel(r'\Large \textbf{Eigenvalue} $\left(\lambda\right)$')

	silhouettes = tech.silhouette(projections, k=8)
	idx = range(2,len(silhouettes)+2)
	panels['silhouette'].stem(idx,[silhouettes[x]['data'] for x in idx])

	#Get confidence intervals
	CIs = np.array([scoreatpercentile(silhouettes[x]['distribution'], 95) for x in idx])
	plt.hold(True)
	panels['silhouette'].plot(idx,CIs,linewidth=2,color='r',linestyle='--')
	artist.adjust_spines(panels['silhouette'])
	panels['silhouette'].set_xlim((0,len(idx)+3))
	panels['silhouette'].set_ylim((0,1))
	panels['silhouette'].set_xlabel(r'\Large \textbf{Number of clusters}')
	panels['silhouette'].set_ylabel(r'\Large \textbf{Silhouette coefficient}')
	plt.tight_layout()

	rot = plt.figure()
	panel = rot.add_subplot(111)
	dt = coeff*(latent[:3]/np.sum(latent))
	dt_args = np.argsort(dt,axis=0)

	cax = panel.imshow(np.sort(coeff*(latent[:3]/np.sum(latent)),axis=0)[::-1], aspect='auto',interpolation='nearest', vmin=-.15,vmax=0.15)
	artist.adjust_spines(panel)
	
	panel.set_yticks(np.arange(len(useful_keys)))
	panel.set_yticklabels(map(lambda word: word.strip().capitalize(),[useful_keys[x[0]] for x in dt_args[::-1]]))
	panel.set_xticks(np.arange(3))
	panel.set_xticklabels(np.arange(3)+1)
	panel.set_xlabel(r'\Large \textbf{Principal Component}')
	rot.colorbar(cax)
	plt.tight_layout()
	plt.grid(True)
	plt.show()
Esempio n. 24
0
def plot_variable(data,basepath=None,dataname='',criterion=None, criterionname=[]):
	fig = plt.figure()
	ax = fig.add_subplot(111)
	x = range(data.shape[1])
	ap('Plotting %s'%dataname)
	if criterion != None:
		if type(criterion) != list:
			median, lq, uq = perc(data[criterion,:])
			ax.plot(x,median,linewidth=2, color='#B22400')
			ax.fill_between(x, lq, uq, alpha=0.25, linewidth=0, color='#B22400')
		else:
			bmap = brewer2mpl.get_map('Set2', 'qualitative', 7)
			colors = bmap.mpl_colors
			for i,(x_criterion,x_label) in enumerate(itertools.izip_longest(criterion,criterionname,fillvalue='Group')):
				median, lq, uq = perc(data[x_criterion,:])
				ax.plot(x,median,linewidth=2, color=colors[i], label=artist.format(x_label))
				ax.fill_between(x, lq, uq, alpha=0.25, linewidth=0, color=colors[i])
	
	median, lq, uq = perc(data)
	ax.plot(x,median,linewidth=2, color='#B22400',label=artist.format('Full population'))
	ax.fill_between(x, lq, uq, alpha=0.25, linewidth=0, color='#B22400')
	
	artist.adjust_spines(ax)
	ax.set_ylabel(artist.format(dataname))
	ax.set_xlabel(artist.format('Time'))
	ax.axvline(data.shape[1]/3,color='r',linewidth=2,linestyle='--')
	ax.axvline(2*data.shape[1]/3,color='r',linewidth=2,linestyle='--')
	plt.legend(frameon=False,loc='lower left')
	plt.tight_layout()
	plt.savefig(os.path.join(basepath,'%s.png'%dataname))
Esempio n. 25
0
def betterSimulatedAnnealing(csp, variables):
    """
    Better Min-conflicts with a factor of randomness approach. Schedule is a mapping of time to temperature
    """
    # Unpack the CSP
    assignment, domains = csp
    
    # Create Dictionary of conflicted variables and number of conflicts
    
    conflicted = {}
    
     # Iterate through list, randomly assign numbers, and add conflicted variables to array
    for var in variables:

        # Randomly assign number
        num = random.choice(domains[var])
        
        # Update the stack to include the new number, whether it works or not
        assignment[var[0]][var[1]] = num
        
    for var in variables:
        conflicted[var] = countConflicts(assignment, var, assignment[var[0]][var[1]])
        
    t = 1
    
    while assessValue(assignment) != 0 and t < 1000000:
        print "Completion =", 100-assessValue(assignment),"%"
        changingVar = random.choice(conflicted.keys())

        totalConflicts = assessValue(assignment)
        
        originalVal = assignment[changingVar[0]][changingVar[1]]
        newVal = random.choice(domains[changingVar])
         
        assignment[changingVar[0]][changingVar[1]] = newVal
        newTotalConflicts = assessValue(assignment)
        deltaE = newTotalConflicts - totalConflicts
        
        if deltaE > 0:
            if random.random() > P(deltaE, T(t)):
                #reset to original
                assignment[changingVar[0]][changingVar[1]] = originalVal
                
        Graphics.showPuzzle(assignment)
        t+=1
        for var in variables:
            conflicted[var] = countConflicts(assignment, var, assignment[var[0]][var[1]])
     
        
    if t != 1000000:
        Graphics.showPuzzle(assignment)    
        print "Solution Found!"
    
        return assignment
    else:
        Graphics.showPuzzle(assignment)
        print "Failed with Completion =", 100-assessValue(assignment),"%"
        return -1
Esempio n. 26
0
def getImageLoaders(project, trace):
  """
  Return a list of (event, func) pairs, where event is a image upload event and
  func is a function that returns an Image containing the image data when called.
  """
  library   = project.targets["code"].library
  constants = Collections.DictProxy(library.constants)
  loaders   = []

  formats = {
    constants.VG_sRGBX_8888:           ("b", 4, False, False, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_sRGBA_8888:           ("b", 4, False, False, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_sRGBA_8888_PRE:       ("b", 4, False, True,  0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_sRGB_565:             ("h", 3, False, False,     0x001f,     0x07e0,     0xf800,        0x0),
    constants.VG_sRGBA_5551:           ("h", 4, False, False,     0x001f,     0x03e0,     0x7c00,     0x8000),
    constants.VG_sRGBA_4444:           ("h", 4, False, False,     0x000f,     0x00f0,     0x0f00,     0xf000),
    constants.VG_sL_8:                 ("b", 1, False, False,       0xff,        0x0,        0x0,        0x0),
    constants.VG_lRGBX_8888:           ("b", 4, True,  False, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_lRGBA_8888:           ("b", 4, True,  False, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_lRGBA_8888_PRE:       ("b", 4, True,  True,  0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000),
    constants.VG_lL_8:                 ("b", 1, True,  False,       0xff,        0x0,        0x0,        0x0),
    constants.VG_A_8:                  ("b", 1, True,  False,       0xff,        0x0,        0x0,        0x0),
    constants.VG_BW_1:                 ("b", 1, True,  False,        0x1,        0x0,        0x0,        0x0),
  }
  
  task = Task.startTask("prepare-images", "Looking for images", len(trace.events))
  for event in trace.events:
    task.step()
    
    if event.name == "vgImageSubData" and event.values.get("data"):
      width  = event.values["width"]
      height = event.values["height"]
      stride = event.values["dataStride"]
      format = event.values["dataFormat"]
      
      if format in formats:
        unit, components, isLinear, isPremultiplied, redMask, greenMask, blueMask, alphaMask = formats[format]
      else:
        continue

      data = event.values["data"]
      data = struct.pack("<%d%s" % (len(data), unit), *data)
      size = (width, height)

      # Construct copies of the passed variables to make sure the proper data goes into the lambda when called
      func = lambda d=data, s=size, st=stride, rb=redMask, gb=greenMask, bb=blueMask, ab=alphaMask, il=isLinear, ip=isPremultiplied: \
             Graphics.decodeImageData(d, s, st, rb, gb, bb, ab, isLinear = il, isPremultiplied = ip)
      loaders.append((event, func))
      
  return loaders
Esempio n. 27
0
def handleInput(hand,selection,state,play_made):
	# temporary value should throw error if unchanged
	card = 52 
	
	#wait for keypress
	keypress = wait()
	
	# check for QUIT events
	for event in pygame.event.get(QUIT): 
		#end the game
		state = False
	
	if keypress == K_ESCAPE:
		#end the game
		state = False
	
	if keypress == K_RETURN and len(hand)>0:
		#display player's played card
		card = hand.pop(selection)
		graphics.displayCardPlay(card,0)
		
		play_made = True
		
		#if we select the last card, we must decrement selection,
		#since the hand is now one card fewer
		if selection == len(hand):
			selection -= 1
		
	if keypress == K_LEFT and selection > 0:
		#move the selection left
		selection -= 1
		
	if keypress == K_RIGHT and selection < len(hand)-1:
		#move the selection right
		selection += 1
		
	return (hand,selection,state,play_made,card)
Esempio n. 28
0
def track_matrices(mat,savename):

	mat = mat.astype(np.float32)
	base = mat[:,:,0]

	base_values,base_vectors = np.linalg.eig(base)

	idx = np.argsort(base_values)[::-1] #Want eigenvectors in descending order

	base_vectors = base_vectors[idx][:10] #Now eigvectors are in descending order, display top 10
	base_norm = np.linalg.norm(base_vectors)
	DURATION = mat.shape[2]
	#Awful magic constant of 10 eigenvectors
	data = np.zeros((10,DURATION))
	for t in range(1,DURATION):
		these_values,these_vectors = np.linalg.eig(mat[:,:,t])
		this_idx = np.argsort(these_values)[::-1]
		these_vectors = these_vectors[this_idx][:10]

		data[:,t] = [a.dot(b.T)/(np.linalg.norm(a)*np.linalg.norm(b)) for a,b in zip(base_vectors,these_vectors)]
		#Scale by eigenvalues?
	fig = plt.figure()
	ax = fig.add_subplot(111)
	cax= ax.imshow(data,interpolation='nearest',aspect='auto')
	artist.adjust_spines(ax)
	ax.set_xlabel(artist.format('Time'))
	ax.set_yticks(range(10))
	ax.set_yticklabels([r'\Large $\mathbf{e_%d\left(0\right) \cdot e_%d}$'%(x,x) for x in range(10)])

	ax.set_xticks(range(mat.shape[2])[::10])
	ax.set_xticklabels([10*x for x in range(mat.shape[2])[::10]])

	plt.colorbar(cax)
	fig.tight_layout()
	plt.savefig('%s.png'%savename,dpi=200)
	plt.close()
Esempio n. 29
0
def time_series(basepath=None, criterion=None, criterionname=''):
	filename = os.path.join(basepath,'attitudes.txt')
	attitudes = np.loadtxt(filename,delimiter=TAB)
	fig = plt.figure()
	ax = fig.add_subplot(111)
	#ax.fill_between(xrange(attitudes.shape[1]), attitudes.mean(axis=0)-attitudes.std(axis=0),
    #            attitudes.mean(axis=0) + attitudes.std(axis=0), color='k', alpha=0.4,
    #            label=artist.format('Full population'))
	ax.errorbar(xrange(attitudes.shape[1]),attitudes.mean(axis=0),yerr=(attitudes.std(axis=0)/attitudes.shape[0]))
#	ax.plot(xrange(attitudes.shape[1]),attitudes.mean(axis=0),color='k',linewidth=2)
	if criterion:
		data = attitudes[criterion]
		ax.fill_between(xrange(data.shape[1]), data.mean(axis=0)-data.std(axis=0),
                data.mean(axis=0) + data.std(axis=0), color='r', alpha=0.4,
                label=artist.format('criterionname'))
		ax.plot(xrange(data.shape[1]),data.mean(axis=0),color='r',linewidth=2)
	artist.adjust_spines(ax)
	ax.axvline(attitudes.shape[1]/3.,color='r',linewidth=2,linestyle='--') #This is a hack
	ax.axvline(2*attitudes.shape[1]/3.,color='r',linewidth=2,linestyle='--') #This is a hack
	ax.set_ylabel(artist.format('Intent to drink'))
	ax.set_xlabel(artist.format('Time'))
	ax.set_ylim(ymin=0)
	filename = os.path.join(os.getcwd(),basepath,'timecourse.png' if criterionname == '' else 'timecourse-%s.png'%criterionname)
	plt.savefig(filename,dpi=300)
Esempio n. 30
0
def sensitivities(x,im,show=False, savename=None):
	fig = plt.figure()
	ax = fig.add_subplot(111)

	cax = ax.imshow(im,interpolation='nearest',aspect='auto', vmin=-1,vmax=1) 
	cbar = plt.colorbar(cax)

	artist.adjust_spines(ax)
	ax.set_xticks(range(len(x)))
	xlabs = [r'\Large $\mathbf{%.02f}$'%alpha for alpha in map(sn,x)]
	xlabs[0] = r'\Large $\mathrm{All \; signal}$'
	xlabs[-1] = r'\Large $\mathrm{All \; noise}$'
	ax.set_xticklabels(xlabs)
	ax.set_xlabel(r'\Large $\mathrm{\frac{Signal}{Noise}}$')
	ax.set_ylabel(r'\Large $\mathrm{Pattern} $', rotation='horizontal')
	cbar.set_label(r'\Large $\mathrm{Accuracy,} \; q_{\max}$')

	plt.tight_layout()
	if savename:
		plt.savefig('%s.png'%savename,dpi=200)
	if show:
		plt.show()
	plt.close()
	return [pearsonr(row,x) for row in im]
Esempio n. 31
0
    out_file.write('fitness, generation, highest round\n')
    # load starting graphics that don't need to be reloaded
    # Graphics.load_static_gfx()
    # loops the whole simulation
    done = 0
    Stats.generation = 0
    while done < 30:
        game = Game(birds_for_generation)
        done_generation = False

        # loops each generation
        while not done_generation:
            screen.fill(Constants.WHITE)
            game.update_obstacles()
            game.draw_game(screen)
            Graphics.draw_stats(screen)
            Graphics.draw_key(screen)
            # game.check_actions returns True if all the birds are dead
            if game.check_actions(game.birds):
                done_generation = True

            # pygame specific functions
            pygame.display.update()
            pygame.display.flip()

            # check to quit
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    print("Reached quit in check_actions function, quitting now...")
                    exit(0)
Esempio n. 32
0
def getTextureLoaders(project, trace):
  """
  Return a list of (event, func) pairs, where event is a texture upload event and
  func is a function that returns an Image containing the texture data when called.
  """
  library   = project.targets["code"].library
  constants = Collections.DictProxy(library.constants)
  loaders   = []

  componentCount = {
    constants.GL_ALPHA:           1,
    constants.GL_RGB:             3,
    constants.GL_RGBA:            4,
    constants.GL_LUMINANCE:       1,
    constants.GL_LUMINANCE_ALPHA: 2,
  }
  
  task = Task.startTask("prepare-textures", "Looking for textures", len(trace.events))
  for event in trace.events:
    task.step()
    
    # We don't handle compressed texture formats
    if event.name in ["glTexImage2D", "glTexSubImage2D"] and event.values.get("pixels"):
      width  = event.values["width"]
      height = event.values["height"]
      format = event.values["format"]
      type   = event.values["type"]
      
      if format in componentCount:
        components = componentCount[format]
      else:
        continue

      if type == constants.GL_UNSIGNED_BYTE:
        bytesPerPixel = components
        format    = "b"
        redMask   = 0x00ff0000
        greenMask = 0x0000ff00
        blueMask  = 0x000000ff
        alphaMask = 0xff000000
      elif type == constants.GL_UNSIGNED_SHORT_5_6_5:
        bytesPerPixel = 2
        format    = "h"
        redMask   = 0x001f
        greenMask = 0x07e0
        blueMask  = 0xf800
        alphaMask = 0x0000
      elif type == constants.GL_UNSIGNED_SHORT_5_5_5_1:
        bytesPerPixel = 2
        format    = "h"
        redMask   = 0x001f
        greenMask = 0x03e0
        blueMask  = 0x7c00
        alphaMask = 0x8000
      elif type == constants.GL_UNSIGNED_SHORT_4_4_4_4:
        bytesPerPixel = 2
        format    = "h"
        redMask   = 0x000f
        greenMask = 0x00f0
        blueMask  = 0x0f00
        alphaMask = 0xf000
      else:
        continue

      pixels = event.values["pixels"]
      data   = struct.pack("<%d%s" % (len(pixels), format), *pixels)
        
      if components < 4:
        alphaMask = 0
      if components < 3:
        blueMask = 0
      if components < 2:
        greenMask = 0
        
      size   = (width, height)
      stride = width * bytesPerPixel

      # Construct copies of the passed variables to make sure the proper data goes into the lambda when called
      func = lambda d=data, s=size, st=stride, rb=redMask, gb=greenMask, bb=blueMask, ab=alphaMask: \
             Graphics.decodeImageData(d, s, st, rb, gb, bb, ab)
      loaders.append((event, func))
      
  return loaders
Esempio n. 33
0
class Container():
    def __init__(self, msgbrowser):
        self.unitOp = []
        self.thermoPackage = None
        self.compounds = None
        self.flowsheet = None
        self.conn = defaultdict(list)
        self.op = defaultdict(list)
        self.ip = defaultdict(list)
        self.msg = msgbrowser
        self.msg.setText("")
        self.opl = []
        self.result = []
        self.graphics = Graphics(self.unitOp)

    def currentTime(self):
        now = datetime.datetime.now()
        time = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
        return time

    def updateConn(self, key, value):
        self.conn[key].append(value)
        self.msg.append("<span style=\"color:blue\">[" +
                        str(self.currentTime()) + "]<b> " + key.name +
                        " </b> output is connected to input of<b> " +
                        value.name + " </b></span>")

    def connection(self):
        try:
            self.op.clear()
            self.ip.clear()
            self.opl.clear()
            stm = ['MaterialStream', 'EngStm']
            for i in self.conn:
                if i.type not in stm:
                    self.op[i] = self.conn[i]

                for j in range(len(self.conn[i])):
                    if self.conn[i][j].type not in stm:
                        self.ip[self.conn[i][j]].append(i)

            for i in self.op:
                i.connect(InputStms=self.ip[i], OutputStms=self.op[i])

            self.opl.append([self.op[i] for i in self.op])
            self.opl = flatlist(flatlist(self.opl))
        except Exception as e:
            print(e)

    @staticmethod
    def addUnitOpObj(obj):
        self.unitOp.append(obj)

    def addUnitOp(self, obj):
        box = None
        self.obj = obj
        self.scene = self.graphics.getScene()
        box = self.graphics.createNodeItem(self.obj)
        self.scene.addItem(box)
        box.setPos(2500 - 30, 2500 - 30)

        if (obj in self.unitOp):
            pass
        else:
            self.unitOp.append(obj)
            self.msg.append("<span style=\"color:blue\">[" +
                            str(self.currentTime()) + "]<b> " + obj.name +
                            " </b>is instantiated ."
                            "</span>")

    def fetchObject(self, name):
        for i in self.unitOp:
            if (i.name == name):
                return i

    def addCompounds(self, comp):
        self.compounds = comp

    def add_thermoPackage(self, thermo):
        self.thermoPackage = thermo

    def msgBrowser(self):
        std = self.flowsheet.stdout.decode("utf-8")
        if (std):
            stdout = str(std)
            stdout = stdout.replace("\n", "<br/>")
            self.msg.append("<span style=\"color:green\">" + stdout +
                            "</span>")

        stde = self.flowsheet.stderr.decode("utf-8")
        if (stde):
            stdout = str(stde)
            stdout = stdout.replace("\n", "<br/>")
            self.msg.append("<span style=\"color:red\">" + stdout + "</span>")

    def simulate(self, mode):
        print("SIMULATE")
        print(mode)
        self.compounds = compound_selected
        self.flowsheet = Flowsheet()
        self.flowsheet.add_comp_list(self.compounds)
        print("######## connection master#########\n", self.conn)
        for i in self.unitOp:
            print("here", i)
            self.flowsheet.add_UnitOpn(i)

        if mode == 'SM':
            self.msg.append(
                "<span>[" + str(self.currentTime()) +
                "] Simulating in <b>Sequential</b> mode ... </span>")
            self.flowsheet.simulateSM(self.ip, self.op)
            self.msgBrowser()
            self.result = self.flowsheet.resdata
            print("under SEQ mode simulation")
        elif mode == 'EQN':
            self.msg.append("<span>[" + str(self.currentTime()) +
                            "] Simulating in <b>equation</b> mode ... </span>")
            self.flowsheet.simulateEQN()
            self.msgBrowser()
            self.result = self.flowsheet.resdata
            print("under Eqn mode simulation")
Esempio n. 34
0
        map_type = SimulationParams.MAP_TYPE_TREN_MADRID
    else:
        print('Error: Unknown Simulation Type')

    if DisplayParams.DRAW_GRAPHS:
        vmax = 0.11  # TODO: minor, clean this up. it's color map encoding
        if SimulationParams.SIMULATION_TYPE == SimulationParams.SUBWAY_SIM:
            vmax = 0.0011
        elif SimulationParams.SIMULATION_TYPE == SimulationParams.TRAIN_SIM:
            vmax = 0.0007

        #Draws the graph. figure and model required if you want to draw the map as well
        Graphics.draw_graph(nx_graph,
                            DisplayParams.GRAPH_BY_FEATURE,
                            timestamp=str(i),
                            map_type=map_type,
                            figure=f,
                            model=model,
                            vmax=vmax)

        f.savefig("Visualizations/time" + f'{i:03}')
        if DisplayParams.ALWAYS_SHOW_GRAPH or (math.log2(i).is_integer() and
                                               DisplayParams.SHOW_EVERY_2X):
            plt.show()
    plt.close(f)

# Save final SEIR Results
f = plt.figure()
Graphics.draw_SEIR_curve(SEIR_Statistics,
                         f,
                         benchmark_SEIR=benchmark_statistics)
Esempio n. 35
0
    def Game(self):
        turn = 0
        turnCounter = 15
        turnCondition = True
        key = True
        while turnCondition:
            stddraw.show(0)
            Graphics.drawTurnCounter(turnCounter)
            Graphics.drawWinThing()
            if turn == 0:
                if stddraw.mousePressed():
                    mx = stddraw.mouseX()
                    my = stddraw.mouseY()

                    if mx < 4.69 and my >= 1 and my < 10:
                        Graphics.clickHelp()
                        for i in range(self.x):
                            if mx > i / 1.5 and mx < i / 1.5 + (2 / 3):
                                mDrawX1 = i / 1.5
                                mEmojiX1 = i + 1

                        for i in range(self.y + 1):
                            if my > i and my < i + 1:
                                mDrawY1 = i
                                mEmojiY1 = i + 1 / 2

                        for i in range(self.y):
                            for j in range(self.x):
                                if self.board[i][
                                        j].x == mEmojiX1 and self.board[i][
                                            j].y == mEmojiY1:
                                    e1emoji = self.board[i][j].emoji
                                    e1i, e1j = i, j

                        Graphics.tileSelected(mDrawX1, mDrawY1)
                        turn = 1

            if turn == 1:
                if stddraw.mousePressed():
                    mx = stddraw.mouseX()
                    my = stddraw.mouseY()

                    if mx < 4.69 and my >= 1 and my < 10:

                        for i in range(self.x):
                            if mx > i / 1.5 and mx < i / 1.5 + (2 / 3):
                                mEmojiX2 = i + 1

                        for i in range(self.y + 1):
                            if my > i and my < i + 1:
                                mEmojiY2 = i + 1 / 2

                        for i in range(self.y):
                            for j in range(self.x):
                                if self.board[i][
                                        j].x == mEmojiX2 and self.board[i][
                                            j].y == mEmojiY2:
                                    e2emoji = self.board[i][j].emoji
                                    e2i, e2j = i, j

                        #Swapping the emojis
                        """
                        NOTE THAT THE X POSITIONS ETC HAVE STILL NOT BEEN FIXED
                        11/18/2018 12:14 AM
                        Conversion system new: when x == 1, emoji true position is 1/3, x == 2, 1,
                        x == 3, 5/3
                        """

                        if mEmojiX2 == mEmojiX1 + 1 and mEmojiY2 == mEmojiY1 or mEmojiX2 == mEmojiX1 - 1 and mEmojiY2 == mEmojiY1 or mEmojiY2 == mEmojiY1 + 1 and mEmojiX2 == mEmojiX1 or mEmojiY2 == mEmojiY1 - 1 and mEmojiX2 == mEmojiX1:

                            Graphics.clickHelpClear()
                            self.board[e1i][e1j].emoji = e2emoji
                            self.board[e2i][e2j].emoji = e1emoji

                            counter = 0

                            while test.check(self.board) != 0:
                                self.checkDraw(mDrawX1, mDrawY1)

                                #Erase Vertical
                                if test.getD() == 0:
                                    counter = 0
                                    marker = self.board[test.getY()][
                                        test.getX()].emoji
                                    while marker != 0:
                                        if test.getY() + counter != 9:

                                            if marker == self.board[test.getY(
                                            ) + counter][test.getX()].emoji:
                                                self.board[test.getY() +
                                                           counter][test.getX(
                                                           )].emoji = 0
                                                Score.score += 1
                                                counter += 1
                                            else:
                                                marker = 0
                                        else:
                                            marker = 0

                                    self.checkDraw(mDrawX1, mDrawY1)

                                    #Vertical Drop
                                    count = 0

                                    for j in range(9):
                                        if test.getY() + count + counter < 9:
                                            self.board[
                                                test.getY() + count][test.getX(
                                                )].emoji = self.board[
                                                    test.getY() + count +
                                                    counter][test.getX()].emoji
                                            self.board[
                                                test.getY() + count +
                                                counter][test.getX()].emoji = 0

                                            count += 1

                                    self.checkDraw(mDrawX1, mDrawY1)

                                    temp = 9 - counter

                                    for i in range(counter):
                                        self.board[temp][
                                            test.getX()].emoji = self.ranNum()
                                        temp += 1

                                    self.checkDraw(mDrawX1, mDrawY1)

                                #Erase Horizontal
                                else:
                                    counter = 0
                                    marker = self.board[test.getY()][
                                        test.getX()].emoji
                                    while marker != 0:
                                        if test.getX() + counter != 7:

                                            if marker == self.board[test.getY(
                                            )][test.getX() + counter].emoji:
                                                self.board[test.getY()][
                                                    test.getX() +
                                                    counter].emoji = 0
                                                Score.score += 1
                                                counter += 1
                                            else:
                                                marker = 0
                                        else:
                                            marker = 0

                                    self.checkDraw(mDrawX1, mDrawY1)

                                    #Horizontal Drop
                                    count = 0
                                    for i in range(counter):
                                        count = 0
                                        for j in range(9):
                                            if test.getY() + count < 8:
                                                temp = count + 1
                                                self.board[
                                                    test.getY() + count][
                                                        test.getX() +
                                                        i].emoji = self.board[
                                                            test.getY() +
                                                            temp][test.getX() +
                                                                  i].emoji
                                                self.board[test.getY() +
                                                           temp][test.getX() +
                                                                 i].emoji = 0

                                            count += 1
                                    self.checkDraw(mDrawX1, mDrawY1)

                                    for i in range(counter):
                                        self.board[8][test.getX() +
                                                      i].emoji = self.ranNum()
                                    self.checkDraw(mDrawX1, mDrawY1)

                                turn = 0

                            #For when it is not a match 3
                            if counter == 0:
                                self.board[e1i][e1j].emoji = e1emoji
                                self.board[e2i][e2j].emoji = e2emoji
                                Graphics.clickHelpClear()
                                Graphics.drawInvalidMatch3()
                                Graphics.clearInvalidSwitch()
                                Graphics.tileSelectedClear(mDrawX1, mDrawY1)
                                turn = 0
                            else:
                                turnCounter -= 1

                        #For when you want to select the tile again
                        elif mEmojiX1 == mEmojiX2 and mEmojiY1 == mEmojiY2:
                            Graphics.clickHelpClear()
                            Graphics.tileSelectedClear(mDrawX1, mDrawY1)
                            turn = 0

                        #For when there is an invaid switch
                        else:
                            Graphics.clickHelpClear()
                            Graphics.tileSelectedClear(mDrawX1, mDrawY1)
                            Graphics.drawInvalidSwitch()
                            Graphics.clearInvalidSwitch()
                            turn = 0

                    else:
                        turn = 1

                #Note, mouse does not need to be pressed in order for this CheckWin
                if turnCounter == 0 and Score.score >= 75:
                    Graphics.drawTurnCounter(turnCounter)
                    turnCondition = False
                    while key:
                        Graphics.drawWinCondition()
                        if stddraw.mousePressed():
                            key = False
                elif turnCounter == 0 and Score.score <= 75:
                    Graphics.drawTurnCounter(turnCounter)
                    turnCondition = False
                    while key:
                        Graphics.drawLossCondition()
                        if stddraw.mousePressed():
                            key = False
Esempio n. 36
0
    return 800 * x + 100

T_a = analyticSol(x)
error = fvm.calcError(T, T_a)
datos = {'x(m)': x,
         'T(x)': T,
         'Analytic': T_a,
         'Error': error}
fvm.printFrame(datos)
print('||Error|| = ', np.linalg.norm(error))
print('.'+ '-'*70 + '.')

#  -------------------------------------------------------------------
#   Calculamos la solución exacta en una malla más fina para graficar
#  -------------------------------------------------------------------
x1 = np.linspace(0,L,100)
T_a = analyticSol(x1)

#  -----------------------------------------------------
#    Se grafica la solución
#  -----------------------------------------------------
plt.close('all')
title_graf = 'Solución de $ \partial (k  \partial T/\partial x)/\partial x = 0$ con FVM'
plt2.plotG(x, T, kind = '--o', xlabel = '$x$ [m]', ylabel = 'T [°C]', 
           label = 'Sol. FVM', title_graf = title_graf)
plt2.plotG(x1, T_a, kind = "-", xlabel = '$x$ [m]', ylabel = 'T [°C]', 
           label = 'Sol. analítica', lw=2, title_graf = title_graf)
plt.show()

# Guarda la grafica
#plt.savefig('Tarea1.svg')
Esempio n. 37
0
                   friction=0.3,
                   categoryBits=0x0004,
                   maskBits=0x0002)
box.filter.groupIndex = -2
body = world.CreateDynamicBody(position=(25, 20), fixtures=box)

timeStep = 1.0 / 60
vel_iters, pos_iters = 10, 10

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    Graphics.BackDrop(dif, land, window)

    x1, y1 = joint1.GetReactionForce(1 / timeStep)
    x2, y2 = joint2.GetReactionForce(1 / timeStep)
    x3, y3 = joint3.GetReactionForce(1 / timeStep)
    x4, y4 = joint4.GetReactionForce(1 / timeStep)
    x5, y5 = joint5.GetReactionForce(1 / timeStep)
    x6, y6 = joint6.GetReactionForce(1 / timeStep)
    x7, y7 = joint7.GetReactionForce(1 / timeStep)
    x8, y8 = joint8.GetReactionForce(1 / timeStep)
    x9, y9 = joint9.GetReactionForce(1 / timeStep)
    x10, y10 = joint10.GetReactionForce(1 / timeStep)
    x11, y11 = joint11.GetReactionForce(1 / timeStep)
    x12, y12 = joint12.GetReactionForce(1 / timeStep)
    x13, y13 = joint13.GetReactionForce(1 / timeStep)
    x14, y14 = joint14.GetReactionForce(1 / timeStep)
Esempio n. 38
0
class Container():
    def __init__(self, msgbrowser):
        self.unitOp = []
        self.thermoPackage = None
        self.compounds = None
        self.flowsheet = None
        self.conn = defaultdict(list)
        self.op = defaultdict(list)
        self.ip = defaultdict(list)
        self.msg = msgbrowser
        self.msg.setText("")
        self.opl = []
        self.result = []
        self.graphics = Graphics(self.unitOp)
        self.scene = self.graphics.getScene()

    def currentTime(self):
        now = datetime.datetime.now()
        time = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
        return time

    # def updateConn(self,key,value):
    #     self.conn[key].append(value)
    #     self.msg.append("<span style=\"color:blue\">["+str(self.currentTime())+"]<b> "+key.name+" </b> output is connected to input of<b> "+value.name +" </b></span>")
    #
    # def connection(self):
    #     try:
    #         self.op.clear()
    #         self.ip.clear()
    #         self.opl.clear()
    #         stm = ['MaterialStream','EngStm']
    #         for i in self.conn:
    #             if i.type not in stm:
    #                 self.op[i]=self.conn[i]
    #
    #             for j in range(len(self.conn[i])):
    #                 if self.conn[i][j].type not in stm:
    #                     self.ip[self.conn[i][j]].append(i)
    #
    #         for i in self.op:
    #             i.connect(InputStms=self.ip[i],OutputStms=self.op[i])
    #
    #         self.opl.append([self.op[i] for i in self.op])
    #         self.opl=flatlist(flatlist(self.opl))
    #     except Exception as e:
    #         print(e)

    # @staticmethod
    # def addUnitOpObj(obj):
    #     self.unitOp.append(obj)

    def addUnitOp(self, obj):
        box = None
        self.obj = obj
        self.scene = self.graphics.getScene()
        box = self.graphics.createNodeItem(self.obj, self)
        self.scene.addItem(box)
        box.setPos(2500 - 30, 2500 - 30)

        if (obj in self.unitOp):
            pass
        else:
            self.unitOp.append(obj)
            data = self.unitOp[:]
            data.append(compound_selected)
            PUSH('Undo', data)
            self.msg.append("<span style=\"color:blue\">[" +
                            str(self.currentTime()) + "]<b> " + obj.name +
                            " </b>is instantiated ."
                            "</span>")

    '''
        Deletes the selected item from the canvas and also the objects created for that type.
    '''

    def delete(self, l):
        for item in l:
            self.scene.removeItem(item)
            if hasattr(item, 'Input'):
                for x in item.Input:
                    if x.newLine:
                        self.scene.removeItem(x.newLine)
                        del x.newLine
                    if x.otherLine:
                        self.scene.removeItem(x.otherLine)
                        del x.otherLine
            if hasattr(item, 'Output'):
                for x in item.Output:
                    if x.newLine:
                        self.scene.removeItem(x.newLine)
                        del x.newLine
                    if x.otherLine:
                        self.scene.removeItem(x.otherLine)
                        del x.otherLine
            if hasattr(item, 'obj'):
                self.unitOp.remove(item.obj)
                for k in list(self.conn):
                    if item.obj == k:
                        del self.conn[k]
                    elif item.obj in self.conn[k]:
                        self.conn[k].remove(item.obj)
                self.msg.append("<span style=\"color:blue\">[" +
                                str(self.currentTime()) + "]<b> " +
                                item.obj.name + " </b>is deleted ."
                                "</span>")
                del item.obj
            del item

            CLEAN_FILE('Redo')
            data = self.unitOp[:]
            data.append(compound_selected)
            PUSH('Undo', data)

    def fetchObject(self, name):
        for i in self.unitOp:
            if (i.name == name):
                return i

    def addCompounds(self, comp):
        self.compounds = comp

    def add_thermoPackage(self, thermo):
        self.thermoPackage = thermo

    def msgBrowser(self):
        std = self.flowsheet.stdout.decode("utf-8")
        if (std):
            stdout = str(std)
            stdout = stdout.replace("\n", "<br/>")
            self.msg.append("<span style=\"color:green\">" + stdout +
                            "</span>")

        stde = self.flowsheet.stderr.decode("utf-8")
        if (stde):
            stdout = str(stde)
            stdout = stdout.replace("\n", "<br/>")
            self.msg.append("<span style=\"color:red\">" + stdout + "</span>")

    def simulate(self, mode):
        print("SIMULATE")
        print(mode)
        self.compounds = compound_selected
        self.flowsheet = Flowsheet()
        self.flowsheet.add_comp_list(self.compounds)
        print("######## connection master#########\n", self.conn)
        for i in self.unitOp:
            print("here", i)
            self.flowsheet.add_UnitOpn(i)

        if mode == 'SM':
            self.msg.append(
                "<span>[" + str(self.currentTime()) +
                "] Simulating in <b>Sequential</b> mode ... </span>")
            self.flowsheet.simulateSM(self.ip, self.op)
            self.msgBrowser()
            self.result = self.flowsheet.resdata
            print("under SEQ mode simulation")
        elif mode == 'EQN':
            self.msg.append("<span>[" + str(self.currentTime()) +
                            "] Simulating in <b>equation</b> mode ... </span>")
            self.flowsheet.simulateEQN()
            self.msgBrowser()
            self.result = self.flowsheet.resdata
            print("under Eqn mode simulation")

        DockWidget.showResult(NodeItem.getDockWidget())
Esempio n. 39
0
import numpy as np
import matplotlib.pyplot as plt
import Graphics as artist

from matplotlib import rcParams
rcParams['text.usetex'] = True

m = np.loadtxt('correlation-matrix.tsv', delimiter='\t')

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(m,
                interpolation='nearest',
                aspect='auto',
                cmap=plt.cm.bone_r,
                vmin=-1,
                vmax=1)
artist.adjust_spines(ax)
plt.colorbar(cax)
plt.show()
Esempio n. 40
0
def main(n_epochs=1):
    if n_epochs == 1:
        # Single trial
        n_training_trials = 40  # Training trials
        n_navigation_trials = 20  # Navigation trials
    elif n_epochs == 3:
        # For reasonable data
        n_training_trials = 100  # Training trials
        n_navigation_trials = 20  # Navigation trials
    else:
        # For quick trials
        n_training_trials = 20  # Training trials
        n_navigation_trials = 20  # Navigation trials

    training_steps = np.zeros((n_training_trials, n_epochs), dtype=float)
    navigation_steps = np.zeros((n_navigation_trials, n_epochs), dtype=float)
    """
    # This version uses threads, which are quite slow in python because of GIL
    threads = [None] * n_epochs
    for epoch in range(n_epochs):
        threads[epoch] = MazeThread(epoch, n_training_trials, n_navigation_trials)
        threads[epoch].start()

    # Wait for all threads to complete
    for t in threads:
        t.join()

    for epoch in range(n_epochs):
        training_steps[:, epoch] = threads[epoch].training_steps
        navigation_steps[:, epoch] = threads[epoch].navigation_steps
    """

    threads = multiprocessing.Pool(n_epochs)
    training_results = threads.map(testMaze,
                                   [(n_training_trials, n_navigation_trials)
                                    for x in range(n_epochs)])
    for epoch in range(n_epochs):
        training_steps[:, epoch] = training_results[epoch][0] * MOVE_DISTACE
        navigation_steps[:, epoch] = training_results[epoch][1] * MOVE_DISTACE

    mean_training_steps = np.reshape(np.mean(training_steps, axis=1),
                                     (n_training_trials, 1))
    mean_navigation_steps = np.reshape(np.mean(navigation_steps, axis=1),
                                       (n_navigation_trials, 1))

    # Use this for plotting absolute data deviation
    """
    min_dev_training_steps = np.reshape(np.min(training_steps-mean_training_steps, axis=1), (1, n_training_trials))
    max_dev_training_steps = np.reshape(np.max(training_steps-mean_training_steps, axis=1), (1, n_training_trials))
    err_training_steps = np.abs(np.append(min_dev_training_steps, max_dev_training_steps, axis=0))

    min_dev_navigation_steps = np.reshape(np.min(navigation_steps-mean_navigation_steps, axis=1), (1, n_navigation_trials))
    max_dev_navigation_steps = np.reshape(np.max(navigation_steps-mean_navigation_steps, axis=1), (1, n_navigation_trials))
    err_navigation_steps = np.abs(np.append(min_dev_navigation_steps, max_dev_navigation_steps, axis=0))
    """

    # For plotting the SEM measure, use this!
    err_training_steps = stats.sem(training_steps, axis=1)
    err_navigation_steps = stats.sem(navigation_steps, axis=1)

    # Print all the data before plotting
    # print('%d Training trials'%n_training_trials)
    # pprint(mean_training_steps)

    training_fig = pl.figure()
    training_ax = training_fig.add_subplot(111)
    training_ax.errorbar(range(n_training_trials),
                         mean_training_steps,
                         yerr=err_training_steps,
                         marker='d',
                         linewidth=2.0,
                         elinewidth=2.0,
                         alpha=0.7,
                         ecolor='black',
                         capsize=2.0)
    training_ax.set_xlabel('Trials')
    training_ax.set_ylabel('Distance Moved')
    training_ax.set_xlim((-1, 20))
    training_ax.set_xticks((0, 5, 10, 15, 20))
    training_ax.set_ylim((0, 100))
    training_ax.set_yticks((0, 50, 100))
    Graphics.cleanAxes(training_ax)
    pl.show()

    # print('%d Navigation trials'%n_navigation_trials)
    # pprint(mean_navigation_steps)

    navigation_fig = pl.figure()
    navigation_ax = navigation_fig.add_subplot(111)
    navigation_ax.errorbar(range(n_navigation_trials),
                           mean_navigation_steps,
                           yerr=err_navigation_steps,
                           marker='o',
                           linewidth=2.0,
                           elinewidth=2.0,
                           ecolor='black',
                           alpha=0.7,
                           capsize=2.0)
    navigation_ax.set_xlabel('Trials')
    navigation_ax.set_ylabel('Distance Moved')
    navigation_ax.set_ylim((0, 100))
    navigation_ax.set_xlim((-1, 20))
    navigation_ax.set_xticks((0, 5, 10, 15, 20))
    navigation_ax.set_yticks((0, 50, 100))
    Graphics.cleanAxes(navigation_ax)
    pl.show()

    print('Execution complete. Exiting!')
Esempio n. 41
0
import AudioLoader  #enables loading and unloading of music and sound
import Graphics  #system to handle loading unloading and rendering of graphics
import Entities
import Events

#!!!! Priority write assignments !!!!
#Connect map to render
#add entities

#####INITIALIZATION#####
pygame.init()
screenRez = ((400, 300))
Plot = Events.Plot()
#//screen = pygame.display.set_mode((800,600))
#background = load image here
Graphics.init(screenRez)
run = True

#player = Entities.Player()
#player.x = (40 * 4)
#player.y = (40 * 2) - 15
#Graphics.add(player) #//player sprite
#king = Entities.King()
#king.x = (40 * 9)
#king.y = (40 * 2) - 15
#Graphics.add(king)

#king = Entities.King()
#Graphics.add(king)
#vizzi = Entities.Vizzi()
#Graphics.add(vizzi)
Esempio n. 42
0
exec(f'from {player1name} import *')
if player1name != 'HumanPlayer':
   exec(f'player1 = {player1name}({timeLimit})')
else:
   exec(f'player1 = {player1name}({1e6})')

exec(f'from {player2name} import *')
if player2name != 'HumanPlayer':
   exec(f'player2 = {player2name}({timeLimit})')
else:
   exec(f'player2 = {player2name}({1e6})')

size = int(input('Enter the width of the graphics window (0 for text mode): '))
if size > 0:
   from Graphics import *
   g = Graphics(size)
else:
   g = None


state = Pente()

moveSequence = []

while not state.gameOver():
   print(state)
  
   if state.getTurn() % 2 == 0:
      player1._startTime = time.time()
      player1.findMove(state)
      move = player1.getMove()
Esempio n. 43
0
def _processRenderSurface(logDir, attributes):
    def attr(name):
        return attributes[name]

    w, h = attr("render_surface_width"), attr("render_surface_height")
    redMask = attr("red_mask")
    greenMask = attr("green_mask")
    blueMask = attr("blue_mask")
    alphaMask = attr("alpha_mask")
    depthMask = attr("depth_mask")
    stencilMask = attr("stencil_mask")
    isLinear = attr("is_linear")
    isPremultiplied = attr("is_premultiplied")

    # Convert the color buffer
    if "color_buffer" in attributes:
        fileName = attr("color_buffer")
        if not os.path.exists(fileName):
            fileName = os.path.join(logDir, fileName)
        fileNameOut = fileName.rsplit(".", 1)[0] + ".png"

        # Only do the conversion if the image doesn't already exist
        # or if the source file is newer.
        if fileName.endswith(".dat") and \
           (not os.path.exists(fileNameOut) or \
            (os.path.exists(fileName) and os.path.getmtime(fileName) > os.path.getmtime(fileNameOut))
           ):
            stride = attr("color_stride")

            f = open(fileName, "rb")
            data = f.read(stride * h)
            f.close()

            if len(data) != h * stride or not data:
                Log.error("Invalid color buffer data size: %d" % len(data))
                return

            colorBuffer = Graphics.decodeImageData(data, (w, h), stride,
                                                   redMask, greenMask,
                                                   blueMask, alphaMask,
                                                   isLinear, isPremultiplied)
            colorBuffer = colorBuffer.convert("RGBA")
            colorBuffer.save(fileNameOut)

            # We can remove the original file now
            os.unlink(fileName)

            # Replace the original file name with the decoded file
            attributes["color_buffer"] = fileNameOut

        # Eat the render surface attributes since they are of little use further down the road
        #for attrName in ["red_mask", "green_mask", "blue_mask", "alpha_mask",
        #                 "depth_mask", "stencil_mask", "color_stride",
        #                 "is_linear", "is_premultiplied", "color_data_type",
        #                 "depth_data_type", "stencil_data_type"]:
        #  if attrName in attributes:
        #    del attributes[attrName]

    for bufferName in ["depth_buffer", "stencil_buffer"]:
        if bufferName in attributes and not os.path.exists(
                attributes[bufferName]):
            # Fill in the full buffer file name
            attributes[bufferName] = os.path.join(logDir, attr(bufferName))
def testMaze(n_trials, dbg_lvl=1):
    ValueLearning.DBG_LVL = dbg_lvl
    move_distance = 0.29

    # Open field - Rather boring
    # maze         = Environment.RandomGoalOpenField(nx, ny)

    # Maze with partition - 6 x 6 environment
    #           ----------------- (6,6)
    #           |               |
    #           | (2,3)   (4,3) |
    #           |-----     -----| (6,3)
    #           |               |
    #           |               |
    #     (0,0) -----------------

    """
    nx = 6
    ny = 6
    maze = Environment.RandomGoalOpenField(nx, ny, move_distance)
    use_limits = True
    """

    # Adding walls and constructing the environment
    """
    nx = 6
    ny = 6
    lp_wall = Environment.Wall((0,3), (2,3))
    rp_wall = Environment.Wall((4,3), (6,3))
    maze    = Environment.MazeWithWalls(nx, ny, [lp_wall, rp_wall], move_distance)
    use_limits = False
    """

    # Maze with walls - 10 x 10 environment
    #           (2,10)   (8,10)
    #       --------------------- (10,10)
    #       |    |              |
    #       |    |  (4, 6) |    | (10, 8)
    #       |    |   ------|    | 
    #       |    |  (6,4)  |    |
    # (0,4) |    |------   |    |
    #       |    |         |    |
    #       |     (2,2)    |    |
    # (0,0) ---------------------

    nx = 10
    ny = 10
    # Adding walls and constructing the environment
    lh_wall = Environment.Wall((2,4), (6,4))
    lv_wall = Environment.Wall((2,2), (2,10))
    rh_wall = Environment.Wall((4,6), (8,6))
    rv_wall = Environment.Wall((8,0), (8,8))
    maze    = Environment.MazeWithWalls(nx, ny, [lh_wall, lv_wall, rh_wall, rv_wall])
    use_limits = False

    n_fields     = round(1.0 * (nx+3) * (ny+3))
    Hippocampus.N_CELLS_PER_FIELD = 1
    n_cells      = n_fields * Hippocampus.N_CELLS_PER_FIELD
    place_fields = Hippocampus.setupPlaceFields(maze, n_fields)
    place_cells  = Hippocampus.assignPlaceCells(n_cells, place_fields)

    # Learn the value function
    amateur_critic = None
    n_episodes     = 25
    canvas         = Graphics.MazeCanvas(maze)
    weights        = np.empty((n_cells, n_episodes), dtype=float)
    for episode in range(n_episodes):
        (_, amateur_critic, _) = ValueLearning.learnValueFunction(n_trials, maze, place_cells, critic=amateur_critic, max_steps=1000)
        weights[:, episode]    = amateur_critic.getWeights()
        print('Ended Episode %d'% episode)

        # canvas.plotValueFunction(place_cells, amateur_critic, continuous=True)
        # input()

    # Draw the final value funciton
    canvas.plotValueFunction(place_cells, amateur_critic, continuous=True, limits=use_limits)
    # canvas.plotValueFunction(place_cells, amateur_critic)

    """ DEBUG
    print(components.explained_variance_ratio_)
    print(components.singular_values_)
    """

    # Graphics.showDecomposition(weights)

    # Evaluate the theoritical value function for a random policy
    ideal_critic = Agents.IdealValueAgent(maze, place_cells)
    optimal_value_function = ideal_critic.getValueFunction()

    scaling_factor = 1.0/(1 - amateur_critic.getDiscountFactor())
    # Graphics.showImage(optimal_value_function, xticks=range(1,nx), yticks=range(1,ny), range=(maze.NON_GOAL_STATE_REWARD, scaling_factor * maze.GOAL_STATE_REWARD))
    Graphics.showImage(optimal_value_function, xticks=range(1,nx), yticks=range(1,ny), range=(maze.NON_GOAL_STATE_REWARD, scaling_factor * maze.GOAL_STATE_REWARD))
    input('Press any key to Exit!')
Esempio n. 45
0
class MainApp(QMainWindow,ui):


    flag = True

    def __init__(self):
        '''
            Initializing the application
        '''
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.zoomcount = 0
        
        self.graphics = Graphics()
        self.scene = self.graphics.getScene()
        Graphics.flag = MainApp.flag

        self.previewBtn.setChecked(True)
        self.editingBtn.toggled.connect(lambda:self.btnState(self.previewBtn))
        self.previewBtn.toggled.connect(lambda:self.btnState(self.editingBtn))

        self.graphicsView.setScene(self.scene)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.keyPressEvent=self.deleteCall
    
        self.menuBar()
        self.unitOperationListInit()

    def unitOperationListInit(self):
        self.gl1.addWidget(self.createCellWidget("Air-blownCooler"), 1, 0)
        self.gl1.addWidget(self.createCellWidget("Bag"), 1, 1)
        self.gl1.addWidget(self.createCellWidget("Boiler"), 1, 2)
        self.gl1.addWidget(self.createCellWidget("Tank"), 2, 0)
        self.gl1.addWidget(self.createCellWidget("Breaker"), 2, 1)
        self.gl1.addWidget(self.createCellWidget("BriquettingMachine"), 2, 2)
        self.gl1.addWidget(self.createCellWidget("Centrifugal"), 3, 0)
        self.gl1.addWidget(self.createCellWidget("CentrifugalCompressor"), 3, 1)
        self.gl1.addWidget(self.createCellWidget("CentrifugalPump"), 3, 2)
        self.gl1.addWidget(self.createCellWidget("CentrifugalPump2"), 4, 0)
        self.gl1.addWidget(self.createCellWidget("CentrifugalPump3"), 4, 1)
        self.gl1.addWidget(self.createCellWidget("Column"), 4, 2)
        self.gl1.addWidget(self.createCellWidget("Compressor"), 5, 0)
        self.gl1.addWidget(self.createCellWidget("CompressorSilencers"), 5, 1)
        self.gl1.addWidget(self.createCellWidget("Condenser"), 5, 2)
        self.gl1.addWidget(self.createCellWidget("Cooler"), 6, 0)
        self.gl1.addWidget(self.createCellWidget("CoolingTower2"), 6, 1)
        self.gl1.addWidget(self.createCellWidget("CoolingTower3"), 6, 2)
        self.gl1.addWidget(self.createCellWidget("Crusher"), 7, 0)
        self.gl1.addWidget(self.createCellWidget("DoublePipeHeat"), 7, 1)
        self.gl1.addWidget(self.createCellWidget("ExtractorHood"), 7, 2)
        self.gl1.addWidget(self.createCellWidget("FiredHeater"), 8, 0)
        self.gl1.addWidget(self.createCellWidget("Forced-draftCooling"), 8, 1)
        self.gl1.addWidget(self.createCellWidget("Forced-draftCoolingTower"), 8, 2)
        self.gl1.addWidget(self.createCellWidget("Furnance"), 9, 0)
        self.gl1.addWidget(self.createCellWidget("GasBottle"), 9, 1)
        self.gl1.addWidget(self.createCellWidget("HalfPipeMixingVessel"), 9, 2)
        self.gl1.addWidget(self.createCellWidget("Heater"), 10, 0)
        self.gl1.addWidget(self.createCellWidget("HeatExchanger"), 10, 1)
        self.gl1.addWidget(self.createCellWidget("HeatExchanger2"), 10, 2)
        self.gl1.addWidget(self.createCellWidget("HorizontalVessel"), 11, 0)
        self.gl1.addWidget(self.createCellWidget("JacketedMixingVessel"), 11, 1)
        self.gl1.addWidget(self.createCellWidget("LiquidRingCompressor"), 11, 2)
        self.gl1.addWidget(self.createCellWidget("Mixing"),12 , 0)
        self.gl1.addWidget(self.createCellWidget("MixingReactor"), 12, 1)
        self.gl1.addWidget(self.createCellWidget("OilBurner"), 12, 2)
        self.gl1.addWidget(self.createCellWidget("OpenTank"), 13, 0)
        self.gl1.addWidget(self.createCellWidget("ProportioningPump"), 13, 1)
        self.gl1.addWidget(self.createCellWidget("Pump"), 13, 2)
        self.gl1.addWidget(self.createCellWidget("Pump2"), 14, 0)
        self.gl1.addWidget(self.createCellWidget("ReboilerHeatExchanger"), 14, 1)
        self.gl1.addWidget(self.createCellWidget("ReciprocativeCompressor"), 14, 2)
        self.gl1.addWidget(self.createCellWidget("RotaryCompressor"), 15, 0)
        self.gl1.addWidget(self.createCellWidget("RotaryGearPump"), 15, 1)
        self.gl1.addWidget(self.createCellWidget("ScrewPump"),15 , 2)
        self.gl1.addWidget(self.createCellWidget("SelectableCompressor"), 16, 0)
        self.gl1.addWidget(self.createCellWidget("SelectableFan"), 16, 1)
        self.gl1.addWidget(self.createCellWidget("SinglePassHeat"), 16, 2)
        self.gl1.addWidget(self.createCellWidget("SpiralHeatExchanger"), 17, 0)
        self.gl1.addWidget(self.createCellWidget("StraightTubesHeat"), 17, 1)
        self.gl1.addWidget(self.createCellWidget("Tank"), 17, 2)
        self.gl1.addWidget(self.createCellWidget("TurbinePump"), 18, 0)
        self.gl1.addWidget(self.createCellWidget("U-TubeHeatExchanger"), 18, 1)
        self.gl1.addWidget(self.createCellWidget("VacuumPump"), 18, 2)
        self.gl1.addWidget(self.createCellWidget("VerticalPump"), 19, 0)
        self.gl1.addWidget(self.createCellWidget("VerticalVessel"), 19, 1)
        self.gl1.addWidget(self.createCellWidget("WastewaterTreatment"), 19, 2)
        
        self.gl2.addWidget(self.createCellWidget("Air-blownCooler"), 1, 0)
        self.gl2.addWidget(self.createCellWidget("Bag"), 1, 1)
        self.gl2.addWidget(self.createCellWidget("Boiler"), 1, 2)
        self.gl2.addWidget(self.createCellWidget("Tank"), 2, 0)
        self.gl2.addWidget(self.createCellWidget("Breaker"), 2, 1)
        self.gl2.addWidget(self.createCellWidget("BriquettingMachine"), 2, 2)
        self.gl2.addWidget(self.createCellWidget("Centrifugal"), 3, 0)
        self.gl2.addWidget(self.createCellWidget("CentrifugalCompressor"), 3, 1)
        self.gl2.addWidget(self.createCellWidget("CentrifugalPump"), 3, 2)
        self.gl2.addWidget(self.createCellWidget("CentrifugalPump2"), 4, 0)
        self.gl2.addWidget(self.createCellWidget("CentrifugalPump3"), 4, 1)
        self.gl2.addWidget(self.createCellWidget("Column"), 4, 2)
        self.gl2.addWidget(self.createCellWidget("Compressor"), 5, 0)
        self.gl2.addWidget(self.createCellWidget("CompressorSilencers"), 5, 1)
        self.gl2.addWidget(self.createCellWidget("Condenser"), 5, 2)
        self.gl2.addWidget(self.createCellWidget("Cooler"), 6, 0)
        self.gl2.addWidget(self.createCellWidget("CoolingTower2"), 6, 1)
        self.gl2.addWidget(self.createCellWidget("CoolingTower3"), 6, 2)
        self.gl2.addWidget(self.createCellWidget("Crusher"), 7, 0)
        self.gl2.addWidget(self.createCellWidget("DoublePipeHeat"), 7, 1)
        self.gl2.addWidget(self.createCellWidget("ExtractorHood"), 7, 2)
        self.gl2.addWidget(self.createCellWidget("FiredHeater"), 8, 0)
        self.gl2.addWidget(self.createCellWidget("Forced-draftCooling"), 8, 1)
        self.gl2.addWidget(self.createCellWidget("Forced-draftCoolingTower"), 8, 2)
        self.gl2.addWidget(self.createCellWidget("Furnance"), 9, 0)
        self.gl2.addWidget(self.createCellWidget("GasBottle"), 9, 1)
        self.gl2.addWidget(self.createCellWidget("HalfPipeMixingVessel"), 9, 2)
        self.gl2.addWidget(self.createCellWidget("Heater"), 10, 0)
        self.gl2.addWidget(self.createCellWidget("HeatExchanger"), 10, 1)
        self.gl2.addWidget(self.createCellWidget("HeatExchanger2"), 10, 2)
        self.gl2.addWidget(self.createCellWidget("HorizontalVessel"), 11, 0)
        self.gl2.addWidget(self.createCellWidget("JacketedMixingVessel"), 11, 1)
        self.gl2.addWidget(self.createCellWidget("LiquidRingCompressor"), 11, 2)
        self.gl2.addWidget(self.createCellWidget("Mixing"),12 , 0)
        self.gl2.addWidget(self.createCellWidget("MixingReactor"), 12, 1)
        self.gl2.addWidget(self.createCellWidget("OilBurner"), 12, 2)
        self.gl2.addWidget(self.createCellWidget("OpenTank"), 13, 0)
        self.gl2.addWidget(self.createCellWidget("ProportioningPump"), 13, 1)
        self.gl2.addWidget(self.createCellWidget("Pump"), 13, 2)
        self.gl2.addWidget(self.createCellWidget("Pump2"), 14, 0)
        self.gl2.addWidget(self.createCellWidget("ReboilerHeatExchanger"), 14, 1)
        self.gl2.addWidget(self.createCellWidget("ReciprocativeCompressor"), 14, 2)
        self.gl2.addWidget(self.createCellWidget("RotaryCompressor"), 15, 0)
        self.gl2.addWidget(self.createCellWidget("RotaryGearPump"), 15, 1)
        self.gl2.addWidget(self.createCellWidget("ScrewPump"),15 , 2)
        self.gl2.addWidget(self.createCellWidget("SelectableCompressor"), 16, 0)
        self.gl2.addWidget(self.createCellWidget("SelectableFan"), 16, 1)
        self.gl2.addWidget(self.createCellWidget("SinglePassHeat"), 16, 2)
        self.gl2.addWidget(self.createCellWidget("SpiralHeatExchanger"), 17, 0)
        self.gl2.addWidget(self.createCellWidget("StraightTubesHeat"), 17, 1)
        self.gl2.addWidget(self.createCellWidget("Tank"), 17, 2)
        self.gl2.addWidget(self.createCellWidget("TurbinePump"), 18, 0)
        self.gl2.addWidget(self.createCellWidget("U-TubeHeatExchanger"), 18, 1)
        self.gl2.addWidget(self.createCellWidget("VacuumPump"), 18, 2)
        self.gl2.addWidget(self.createCellWidget("VerticalPump"), 19, 0)
        self.gl2.addWidget(self.createCellWidget("VerticalVessel"), 19, 1)
        self.gl2.addWidget(self.createCellWidget("WastewaterTreatment"), 19, 2)

    def createCellWidget(self, text):
        pic=QtGui.QPixmap("unitOp/type1/"+text+".png")
        icon = QIcon(pic)
        button = QToolButton()
        button.setText(text)
        button.setIcon(icon)
        button.setIconSize(QSize(44, 44))
        button.setToolTip(text) 
        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        #layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)
        widget = QWidget()
        widget.setLayout(layout)

        button.pressed.connect(lambda:self.component(text))
        
        return widget

    def btnState(self, b): 
        
        item = QGraphicsLineItem(QLineF(0,0,0,0))
        self.scene.addItem(item)
        #item.setPos(QPointF(2500,2500))
        item.setPos(NodeItem.pos)
        if b.text() == "Editing":
            if b.isChecked() == True:
                MainApp.flag = not MainApp.flag
                Graphics.flag = MainApp.flag
                for socket in socketLst:
                    NodeSocket.restoreSockets(socket)
                for i in lst:
                    NodeSocket.removeSockets(i[1])
                    NodeSocket.removeSockets(i[2])
        else:
            if b.isChecked() == True:
                MainApp.flag = not MainApp.flag
                Graphics.flag = MainApp.flag
                for socket in socketLst:               
                    NodeSocket.removeSockets(socket)
		   
    def menuBar(self):
        '''
            MenuBar function handels all the all the operations of 
            menu bar like new,zoom,comounds selector, simulation options.
        '''
        self.actionNew.triggered.connect(self.new)
        self.actionZoomIn.triggered.connect(self.zoomIn)
        self.actionZoomOut.triggered.connect(self.zoomOut)
        self.actionZoomReset.triggered.connect(self.zoomReset)
        self.actionSave.triggered.connect(self.save)
        self.actionInsertText.triggered.connect(self.insertText)
        self.actionSocket.triggered.connect(self.socket)
        self.actionNumber.triggered.connect(self.number)

    def zoomReset(self):
        '''
            Resets the zoom level to default scaling
        '''
        if(self.zoomcount>0):
            for i in range(self.zoomcount):
                self.zoomOut()
        elif(self.zoomcount<0): 
            for i in range(abs(self.zoomcount)):
                self.zoomIn()

    def zoomOut(self):
        '''
            ZoomOut the canvas
        '''
        self.graphicsView.scale(1.0/1.15,1.0/1.15)
        self.zoomcount -=1
 
    def zoomIn(self):
        '''
            ZoomIn the canvas
        '''
        if self.zoomcount < 0:
            self.graphicsView.scale(1.15,1.15)
            self.zoomcount +=1
  
    def component(self,unitOpType):
        '''
            Instantiate a NodeItem object for selected type of
            component and added that on canvas/flowsheeting area.
        ''' 
        if MainApp.flag == True:
            self.type = unitOpType
            self.obj = self.graphics.createNodeItem(self.type, self.graphicsView)
            self.scene.addItem(self.obj)
            self.obj.setPos(QPointF(2500-30, 2500-30))
          
    def new(self):
        '''
            New is used to delete all the existing work.
        ''' 
        if MainApp.flag: 
            del self.graphics
            self.graphics = Graphics()
            self.scene = self.graphics.getScene()
            self.graphicsView.setScene(self.scene)
            self.graphicsView.setMouseTracking(True)
            self.graphicsView.keyPressEvent=self.deleteCall
    
    def deleteCall(self,event):
        '''
            Handels all the operations which will happen when delete button is pressed.
        '''
        try:
            if event.key() == QtCore.Qt.Key_Delete:
                l=self.scene.selectedItems()
                self.delete(l)
        except Exception as e:
            print(e)
    
    def delete(self,l): 
        '''
            Deletes the selected item from the canvas and also the objects 
            created for that type.
        '''      
        if MainApp.flag:
            for item in l:
                self.scene.removeItem(item)
                if (item.typee == 'Graphics.NodeLine'):
                    for i in lst:
                        if i[0] == item:                
                            NodeSocket.restoreSockets(i[1])
                            NodeSocket.restoreSockets(i[2])
                            lst.remove(i) 
                del item

    def socket(self):
        if MainApp.flag:
            item = self.graphics.createNodeItem('none1',self.graphicsView)
            self.scene.addItem(item)  
            item.setPos(QPointF(2020, 2200))

    def number(self):
        if MainApp.flag:
            self.numberItem = NumberItem(self.graphicsView)
            self.scene.addItem(self.numberItem)  
            self.numberItem.setPos(QPointF(2020, 2200))

    def insertText(self):
        if MainApp.flag:
            self.textItem = TextItem(self.graphicsView)
            self.scene.addItem(self.textItem)  
            self.textItem.setPos(QPointF(2020, 2200))
            
    def save(self):
        '''
            Function for saving the current canvas items and compound_selected
        '''
        '''# Get region of scene to capture from somewhere.
        #area = get_QRect_to_capture_from_somewhere()
        area = QRectF(QPointF(0,0), QPointF(1500, 1500))

        # Create a QImage to render to and fix up a QPainter for it.
        image = QImage(area.width() , area.height(), QImage.Format_ARGB32_Premultiplied)

        painter = QPainter(image)

        # Render the region of interest to the QImage.
        self.scene.render(painter)
        painter.end()
       
        fileFormat = 'png'
        initialPath = QDir.currentPath() + 'image.' + fileFormat
        fileName, _ = QFileDialog.getSaveFileName(self, "Save As",
                                                  initialPath, "%s Files (*.%s);; All Files (*)" %
                                                  (fileFormat.upper(), fileFormat))
        if fileName != "":
            with open(fileName, 'wb') as f: 
                image.save(fileName+fileFormat)
        
        '''
        fileFormat = 'png'
        initialPath = QDir.currentPath() + 'untitled.' + fileFormat
        fileName, _ = QFileDialog.getSaveFileName(self, "Save As",
                                                  initialPath, "%s Files (*.%s);; All Files (*)" %
                                                  (fileFormat.upper(), fileFormat))
        screen = QApplication.primaryScreen()
        screenshot = screen.grabWindow(self.graphicsView.winId())
        screenshot.save(fileName, fileFormat)
        button['label'] = 'Use Floodfill'
        print('Search algorithm switched to A*')


# Program entry point
if __name__ == "__main__":
    pathfinderAlgo = 'A*'

    mapNodes = Graph.getNodes()

    # Create car object

    # carStartingNode = mapNodes[randint(0, len(mapNodes))] # Uncomment for random staring point
    carStartingNode = mapNodes[153]

    car = Entity.newEntity(carStartingNode['x'], carStartingNode['y'])
    car.moveSpeed = 5
    car.timeSpeedup = 4

    renderEngine = Graphics.Init(overlayMap_width, overlayMap_height)
    renderEngine.on_loop = update
    renderEngine.on_render = draw
    renderEngine.on_mouseDown = mouseDown

    overlayMap = pygame.image.load('sample_map.png')
    overlayMapRect = overlayMap.get_rect()

    renderEngine.button(20, 20, 135, 35, "Use Floodfill", changeAlgorithm)

    renderEngine.on_execute()
Esempio n. 47
0
    def load(self):
        self.keyDown = {}
        self.fps = 0
        self.right_btn = False
        #initialize the screen/window
        self.size = self.width, self.height = Settings.Resolution
        self.fullscreen = Settings.Fullscreen
        self.resetVideoMode()

        #init network variable thingy
        self.network = None

        #create console
        self.console = Console.Console(
            Graphics.Rectangle(20, 20, self.width - 20, self.height - 20))
        self.console.setAsStdOut()
        self.console.onInput = self.onConsoleInput

        #initialize some basic opengl states
        GraphicsCard.enable('depth_test')
        GraphicsCard.setDepthFunc('less')
        GraphicsCard.setShadeModel('smooth')
        GraphicsCard.setScreenProjection(float(self.width / self.height), 0.1,
                                         5000.0)

        self.font = Font.TextureFont('../base/fonts/tahoma.fnt')
        self.bigfont = Font.TextureFont('../base/fonts/tahoma_20.fnt')
        FontManager.GetFont(Settings.ConsoleFont)
        loadscreen = TextureManager.GetTexture(
            '../base/art/ui/facehatlogo.png')

        #Draw loading screen
        GraphicsCard.clearDepth(1.0)
        GraphicsCard.clearColor((1, 1, 1, 1))
        GraphicsCard.clear()
        #glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
        GraphicsCard.setBlendFunction('src_alpha', 'one_minus_src_alpha')
        GraphicsCard.enable('blend', 'texture_2d')
        gl2D.start2D()
        gl2D.drawTexture2D(loadscreen, self.width / 2 - 256,
                           self.height / 2 - 256, 512, 512)
        self.bigfont.draw(self.width / 2, self.height / 2 - 280, "Loading...")
        gl2D.end2D()
        pygame.display.flip()

        #hide/show cursor
        if Settings.GrabMouse:
            pygame.mouse.set_visible(False)
            pygame.event.set_grab(True)
        else:
            pygame.mouse.set_visible(True)
            pygame.event.set_grab(False)

        #Initialize OpenGL extensions
        GraphicsCard.initExtensions()

        #check for OpenGL 2.0
        if Settings.UseShaders and GraphicsCard.hasShaders():
            print "Shader Support Present"
            Settings.UseShaders = True
        else:
            print "Warning: No shader support, or shaders disabled"
            Settings.UseShaders = False
        print "Max Anisotropy:", GraphicsCard.getMaxAnisotropy()

        ###load the map
        if Settings.SinglePlayer:
            self.world = World.World(Settings.DefaultMod,
                                     Settings.DefaultMap,
                                     is_server=True,
                                     graphics_enabled=True)
        else:
            self.world = World.World(Settings.DefaultMod,
                                     Settings.DefaultMap,
                                     is_server=False,
                                     graphics_enabled=True)
        self.world.initGraphics()
        self.lastjump = time_in_seconds()

        #setup lighting
        n = vec3(0, 1, 0)
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0])
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [0.9, 0.9, 0.9, 1.0])
        glLightfv(GL_LIGHT0, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])
        glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1.0])
        glLightfv(GL_LIGHT0, GL_POSITION, [n.x, n.y, n.z, 0])
        GraphicsCard.clearColor((0.0, 0.0, 1.0, 0.0))
        GraphicsCard.enable('light0')
drug_names = [
    drug for item in drug_names.itervalues() for drug in item['drugs']
    if drug in filtered_list
]
drug_name_frequencies = Counter(drug_names)

cutoff = 20
name, frequency = zip(*drug_name_frequencies.most_common(cutoff))
idx = range(len(frequency))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(idx, frequency, color='k')

artist.adjust_spines(ax)
ax.set_ylabel(artist.format('No. of mentions'))
ax.set_xticks(np.array(range(len(name))) + 0.4)
ax.set_xticklabels(map(artist.format, name), rotation=90)

a = plt.axes([.65, .6, .2, .2])
_, full_frequencies = zip(*drug_name_frequencies.most_common())
a.hist(full_frequencies, color='k')
artist.adjust_spines(a)
a.set_xlabel(artist.format('No. of mentions'))
a.set_ylabel(artist.format('No. of substances'))
plt.yscale('log', nonposy='clip')
for label in a.get_xticklabels()[1::2]:
    label.set_visible(False)
plt.tight_layout()
plt.savefig('drug-name-frequency-lycaeum.png')
Esempio n. 49
0
class Game(SetupWindow):
    def __init__(self):
        super().__init__()
        self.__players = ('W', 'B')
        self.__turn = self.__players[0]
        self.__graphics = Graphics()
        self.__board = Board()
        self.__board.initializePieces('g')
        self.__selectedPiece = None
        self.__jump = False
        self.__buttonActions = ['Reset', 'Menu']
        self.__backMenu = False
        self.__buttonSize = [200, 50]
        self.__endGame = False

    def getBackMenu(self):
        return self.__backMenu

    def eventLoopPvP(self):
        for event in pygame.event.get():
            mousePos = self.__graphics.boardCoord(pygame.mouse.get_pos())
            if event.type == pygame.QUIT:
                self.terminate_game()
            self.buttonFunc()
            self.__board.jumpAvailable(self.__turn)
            self.__graphics.message_display(self.turndisplay(self.__turn), 50,
                                            self.getDisplayWidth() / 2,
                                            self.getDisplayHeight() / 20,
                                            colors["BRIGHT_SUMMER_SUN"])
            self.__graphics.drawBoardSquares(self.__board)
            self.__graphics.drawPieceCircles(self.__board)
            self.clock.tick(60)
            if self.__selectedPiece is not None and self.__jump is True and not self.__board.legalMoves(
                    self.__selectedPiece, self.__jump):
                self.end_turn(self.__board)
            if self.__selectedPiece is not None and not self.__board.legalMoves(
                    self.__selectedPiece):
                if self.__board.location(
                        self.__selectedPiece).occupant is not None:
                    self.__board.location(
                        self.__selectedPiece).occupant.selected = False
                self.__selectedPiece = None
                self.invalidMove()
            if self.__selectedPiece is not None and self.__board.jumpAvailablePieces:
                if self.__selectedPiece not in self.__board.jumpAvailablePieces:
                    self.__board.location(
                        self.__selectedPiece).occupant.selected = False
                    self.__selectedPiece = None
                    self.invalidMove()
            if self.__selectedPiece:
                if self.__jump is False:
                    self.__graphics.highlightMoves(
                        self.__board.legalMoves(self.__selectedPiece))
                else:
                    self.__graphics.highlightMoves(
                        self.__board.legalMoves(self.__selectedPiece,
                                                self.__jump))
            if event.type == pygame.MOUSEBUTTONDOWN and self.__board.isOnBoard(
                    mousePos):
                if self.__jump is False:
                    if self.__board.location(
                            mousePos
                    ).occupant is not None and self.__board.location(
                            mousePos
                    ).occupant.color == self.__turn and self.__selectedPiece is None:
                        self.__selectedPiece = mousePos
                        self.__board.location(
                            mousePos).occupant.selected = True
                    elif self.__selectedPiece is not None:
                        if mousePos in self.__board.legalMoves(
                                self.__selectedPiece):
                            colisionMove = self.__board.checkColision(
                                self.__selectedPiece, mousePos)
                            self.__board.movePiece(self.__selectedPiece,
                                                   mousePos)
                            if mousePos not in self.__board.adjacent(
                                    self.__selectedPiece) and isinstance(
                                        self.__board.location(
                                            mousePos).occupant, King) is False:
                                self.__board.removePiece(
                                    (self.__selectedPiece[0] + int(
                                        (mousePos[0] - self.__selectedPiece[0])
                                        / 2), self.__selectedPiece[1] + int(
                                            (mousePos[1] -
                                             self.__selectedPiece[1]) / 2)))
                                self.__jump = True
                                self.__selectedPiece = mousePos
                                self.__board.location(
                                    mousePos).occupant.selected = True
                            elif isinstance(
                                    self.__board.location(mousePos).occupant,
                                    King) is True and colisionMove:
                                self.__board.removePiece(colisionMove)
                                self.__jump = True
                                self.__selectedPiece = mousePos
                                self.__board.location(
                                    mousePos).occupant.selected = True
                            else:
                                self.end_turn(self.__board)
                        else:
                            self.invalidMove()
                else:
                    if self.__selectedPiece is not None and mousePos in self.__board.legalMoves(
                            self.__selectedPiece, self.__jump):
                        self.__board.movePiece(self.__selectedPiece, mousePos)
                        self.__board.removePiece(
                            (self.__selectedPiece[0] + int(
                                (mousePos[0] - self.__selectedPiece[0]) / 2),
                             self.__selectedPiece[1] + int(
                                 (mousePos[1] - self.__selectedPiece[1]) / 2)))
                        self.__board.location(
                            mousePos).occupant.selected = True
                        self.__selectedPiece = mousePos
                        if not self.__board.legalMoves(mousePos, self.__jump):
                            self.end_turn(self.__board)
                    else:
                        self.invalidMove()
            if self.__endGame:
                self.endGameDisplay()
            pygame.display.update()

    def invalidMove(self):
        self.__graphics.message_display('Ruch', 40,
                                        self.getDisplayWidth() / 2 + 270,
                                        self.getDisplayHeight() / 1.5,
                                        colors["CHERRY"])
        self.__graphics.message_display('Nieprawidłowy!', 35,
                                        self.getDisplayWidth() / 2 + 270,
                                        self.getDisplayHeight() / 1.5 + 40,
                                        colors["CHERRY"])

    def terminate_game(self):
        pygame.quit()
        quit()

    def end_turn(self, board):
        if self.__turn == self.__players[0]:
            self.__turn = self.__players[1]
        else:
            self.__turn = self.__players[0]
        self.__selectedPiece = None
        for x in range(8):
            for y in range(8):
                if board.matrix[x][y].occupant is not None:
                    board.matrix[x][y].occupant.selected = False
        self.__jump = False
        self.__board.jumpAvailablePieces = []
        self.__board.jump = []
        if self.checkEndgame():
            self.__endGame = True

    def turndisplay(self, turn):
        if turn == 'W':
            return 'Tura gracza 1'
        else:
            return 'Tura gracza 2'

    def checkEndgame(self):
        for x in range(8):
            for y in range(8):
                if self.__board.location(
                    (x, y)).color == '1' and self.__board.location(
                        (x, y)).occupant is not None and self.__board.location(
                            (x, y)).occupant.color == self.__turn:
                    if self.__board.legalMoves((x, y)):
                        return False
        return True

    def gameButtons(self, msg, msg_size, x, y, w, h, ic, ac, action=None):
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if x + w > mouse[0] > x and y + h > mouse[1] > y:
            colour = ac
            if click[0] == 1 and action is not None:
                if action == self.__buttonActions[0]:
                    self.resetGame()
                else:
                    self.__backMenu = True
        else:
            colour = ic
        pygame.draw.rect(self.screen, colour, (x, y, w, h))
        smallText = pygame.font.Font("freesansbold.ttf", msg_size)
        textSurf, textRect = self.__graphics.text_objects(
            msg, smallText, colors["MUSTARD"])
        textRect.center = ((x + (w / 2)), (y + (h / 2)) + 5)
        self.screen.blit(textSurf, textRect)

    def buttonFunc(self):
        for action, i in zip(self.__buttonActions, [540, 480]):
            self.gameButtons(
                action, 60,
                self.getDisplayWidth() -
                (self.getDisplayWidth() - self.__graphics.getBoardSize()) / 2 -
                self.__buttonSize[0] / 2, i, self.__buttonSize[0],
                self.__buttonSize[1], colors["SUMMER_SUN"],
                colors["BRIGHT_SUMMER_SUN"], action)

    def endGameDisplay(self):
        if self.__turn == self.__players[0]:
            self.__graphics.message_display('Wygrał 2', 100,
                                            self.getDisplayWidth() / 2,
                                            self.getDisplayHeight() / 2,
                                            colors["CHERRY"])
        else:
            self.__graphics.message_display('Wygrał 1', 100,
                                            self.getDisplayWidth() / 2,
                                            self.getDisplayHeight() / 2,
                                            colors["CHERRY"])

    def resetGame(self):
        self.__turn = self.__players[0]
        self.__board = Board()
        self.__board.initializePieces()
        self.__selectedPiece = None
        self.__endGame = False
Esempio n. 50
0
 def onInit(self):
     self.console = Console.Console(Graphics.Rectangle(30, 30, 512, 160))
     self.setRepeatRate(200, 50)
     self.console.setAsStdOut()
     print "WHATS UP BITCHES!!"
     print "yeah, thought so!"
Esempio n. 51
0
    def checkDraw(self, mDrawX1, mDrawY1):
        rowSwitch = self.y
        switcher = 1
        Graphics.tileSelectedClear(mDrawX1, mDrawY1)
        for index in range(self.y):
            for index in range(self.x):

                if self.board[switcher - 1][index].emoji == 1:
                    Graphics.drawMoon(index, switcher)
                if self.board[switcher - 1][index].emoji == 2:
                    Graphics.drawAvocado(index, switcher)
                if self.board[switcher - 1][index].emoji == 3:
                    Graphics.drawFire(index, switcher)
                if self.board[switcher - 1][index].emoji == 4:
                    Graphics.drawCoconut(index, switcher)
                if self.board[switcher - 1][index].emoji == 5:
                    Graphics.drawJoy(index, switcher)
                if self.board[switcher - 1][index].emoji == 6:
                    Graphics.drawHeart(index, switcher)
                if self.board[switcher - 1][index].emoji == 0:
                    Graphics.drawEmpty(index, switcher)

            rowSwitch -= 1
            switcher += 1

        Graphics.eraseScore(self.x, self.y)
        Graphics.drawTotalScore(self.x, self.y, Score.score)
Esempio n. 52
0
def testMaze(n_steps, learning_dbg_lvl=1, navigation_dbg_lvl=0):
    nT = n_steps[0]  # Training steps
    nN = n_steps[1]  # Navigation steps
    ValueLearning.DBG_LVL = learning_dbg_lvl
    move_distance = MOVE_DISTANCE

    # Parameters describing the maze
    # Build the Maze (add walls etc.)
    # Maze with partition - 6 x 6 environment
    #           ----------------- (6,6)
    #           |               |
    #           | (2,3)   (4,3) |
    #           |-----     -----| (6,3)
    #           |               |
    #           |               |
    #     (0,0) -----------------

    nx = 6
    ny = 6
    lp_wall = Environment.Wall((0, 3), (2, 3))
    rp_wall = Environment.Wall((4, 3), (6, 3))
    maze = Environment.MazeWithWalls(nx, ny, [lp_wall, rp_wall], move_distance)

    # 10 x 10 Maze with an L barrier
    #           (2,10)
    #       --------------------- (10,10)
    #       |    |              |
    #       |    |              |
    #       |    |              |
    #       |    |     (4,4)    |
    # (0,4) |    |------        |
    #       |    |              |
    #       |     (2,2)         |
    # (0,0) ---------------------
    """
    nx = 10
    ny = 10

    h_wall = Environment.Wall((2,4), (4,4))
    v_wall = Environment.Wall((2,2), (2,10))
    maze   = Environment.MazeWithWalls(nx, ny, [h_wall, v_wall])
    """

    # Create a initial and goal location including the information about wall locations

    # Object for plotting and visualization
    canvas = Graphics.WallMazeCanvas(maze)

    # Add Place fields and place cells
    n_fields = round(1.0 * (nx + 3) * (ny + 3))
    Hippocampus.N_CELLS_PER_FIELD = 4
    n_cells = n_fields * Hippocampus.N_CELLS_PER_FIELD

    place_fields = Hippocampus.setupPlaceFields(maze, n_fields)
    place_cells = Hippocampus.assignPlaceCells(n_cells, place_fields)

    if (learning_dbg_lvl > 2):
        canvas.visualizePlaceFields(place_cells)

    # Learn how to navigate this Environment
    (actor, critic,
     learning_steps) = ValueLearning.learnValueFunction(nT,
                                                        maze,
                                                        place_cells,
                                                        max_steps=4000)

    # Try a single trial on the same Maze and see how we do
    ValueLearning.DBG_LVL = navigation_dbg_lvl
    navigation_steps = ValueLearning.navigate(nN,
                                              maze,
                                              place_cells,
                                              actor,
                                              critic,
                                              max_steps=400)
    return (learning_steps, navigation_steps)
def Simulate(Mol, Simulations):

    if 'Graphics' in Simulations:
        #Save a graph of the molecule and the 4 states around the Fermi Energy
        Graph = Graphics()
        Graph.SetMolecule(Mol)
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Molecule.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 2] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 2])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - H**O 2.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 1] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 1])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - H**O 1.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 0] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 0])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - LUMO 1.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 + 1] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 + 1])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - LUMO 2.png",
                   part='Molecule')

    if 'Lifting' in Simulations:
        #Set up the plots
        fig = plt.figure()
        axLift, axOrbs = [fig.add_subplot(1, 2, 1), fig.add_subplot(1, 2, 2)]

        #Load and plot the experimental data if available
        for root, dirs, files in os.walk(Mol.szOutputFolder +
                                         'Experimental Data/'):
            for file in files:
                print(file)
                header, values = ImportData(Mol.szOutputFolder +
                                            'Experimental Data/' + file)
                axLift.plot(10 * values[:, 0],
                            values[:, 1],
                            'k',
                            marker='.',
                            lw=0,
                            label=file,
                            alpha=0.1)

        #Create MD folder if it did not already exists
        if not os.path.exists(Mol.szOutputFolder + 'MD'):
            os.makedirs(Mol.szOutputFolder + 'MD')

        #Perform lifting simulation
        MD = MD_Lifting(Mol)
        dz = np.linspace(0, np.max(Mol.Atom[:, 1]) - 0.1, 50)
        #        Mol.SetBias(0.01)
        I = MD.PerformLifting(dz, export=['param', 'dzI', 'xyz'], axOrb=axOrbs)

        #Plot tweaking and saving
        axLift.plot(dz,
                    np.log(I),
                    color='midnightblue',
                    label='Simulated',
                    lw=2,
                    alpha=0.8)
        axLift.plot(dz,
                    np.log(I),
                    color='midnightblue',
                    label='Simulated',
                    lw=0,
                    alpha=0.8,
                    marker='o',
                    markersize=10)
        #        axLift.legend()
        #        axLift.set_title('Lifting')
        axLift.set_xlabel('$\Delta \ z [A]$')
        axLift.set_ylabel('$ln(I)$')
        axLift.set_xlim([np.min(dz), np.max(dz)])
        ymin, ymax = np.min(np.log(I)), np.max(np.log(I))
        axLift.set_ylim(
            [ymin - 0.1 * (ymax - ymin), ymax + 0.1 * (ymax - ymin)])

        #        #Plot Beta factor
        #        axBeta = axLift.twinx()
        #        axBeta.plot((dz[0:-4]+dz[4:])/2, (np.log(I[0:-4])-np.log(I[4:]))/(dz[4]-dz[0])*10, c='r', alpha=0.5, lw=2)
        #        axBeta.set_ylabel('$Beta$')

        axOrbs.set_title('Orbitals')
        axOrbs.set_xlabel('$\Delta z [A]$')
        axOrbs.set_ylabel('$E_{Fermi} [eV]$')
        axOrbs.legend(['H**O 2', 'H**O 1', 'LUMO 1', 'LUMO 2'])

        fig.set_size_inches(20.5, 6.5)
        mpl.rcParams.update({'font.size': 20})
        fig.savefig(Mol.szOutputFolder + Mol.Name +
                    ' - Lifting vs Current.png',
                    dpi=fig.dpi)

    if 'LiftingSpectroscopy' in Simulations:
        #Set up parameters and perform simulation
        MD = MD_Lifting(Mol)
        dz = np.linspace(0, np.max(Mol.Atom[:, 1]) - 0.1, 50)
        neg_bias = -np.linspace(0.015, 0.5, 100)[::-1]
        pos_bias = np.linspace(0.005, 0.5, 100)
        I = MD.PerformLiftingSpectroscopy(dz,
                                          np.concatenate((neg_bias, pos_bias)),
                                          export=['dz-V-I'])
        I = [I[:, 0:len(neg_bias)], I[:, len(neg_bias):]]

        #Set up the figure
        c = mcolors.ColorConverter().to_rgb
        fig = plt.figure()
        axI, axdIdV, axBeta = [
            fig.add_subplot(1, 3, 1),
            fig.add_subplot(1, 3, 2),
            fig.add_subplot(1, 3, 3)
        ]

        #Plot ln(I) data
        BIAS, DZ = [[None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            BIAS[i], DZ[i] = np.meshgrid(bias, dz)
        im = axI.contourf(np.concatenate([DZ[0], DZ[1]], axis=1),
                          np.concatenate([BIAS[0], BIAS[1]], axis=1),
                          np.log(abs(np.concatenate([I[0], I[1]], axis=1))),
                          100,
                          cmap=make_colormap([c('white'),
                                              c('midnightblue')]))
        axI.set_ylabel('$Bias$ [$V$]')
        axI.set_xlabel('$\Delta z \ [\AA{}]$')
        fig.colorbar(im, ax=axI, label='$ln(I)$')

        #Plot dI/dV data
        dIdV, mBIAS, mDZ = [[None, None], [None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            dIdV[i] = (I[i][:, 1:] - I[i][:, 0:-1]) / (bias[1] - bias[0])
            mBIAS[i], mDZ[i] = np.meshgrid(0.5 * (bias[1:] + bias[0:-1]), dz)
        im = axdIdV.contourf(np.concatenate([mDZ[0], mDZ[1]], axis=1),
                             np.concatenate([mBIAS[0], mBIAS[1]], axis=1),
                             np.log(np.concatenate([dIdV[0], dIdV[1]],
                                                   axis=1)),
                             100,
                             cmap=make_colormap([c('white'),
                                                 c('darkgreen')]))
        axdIdV.set_ylabel('$Bias$ [$V$]')
        axdIdV.set_xlabel('$\Delta z \  [\AA{}]$')
        fig.colorbar(im, ax=axdIdV, label='$ln(dI/dV)$')

        #Plot beta factor
        Beta, BIAS, DZ = [[None, None], [None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            Beta[i] = (np.log(abs(I[i][1:, :])) -
                       np.log(abs(I[i][0:-1, :]))) / (dz[1] - dz[0])
            BIAS[i], DZ[i] = np.meshgrid(bias, 0.5 * (dz[1:] + dz[0:-1]))
        im = axBeta.contourf(np.concatenate([DZ[0], DZ[1]], axis=1),
                             np.concatenate([BIAS[0], BIAS[1]], axis=1),
                             np.concatenate([Beta[0], Beta[1]], axis=1),
                             100,
                             cmap=make_colormap([c('darkred'),
                                                 c('white')]))
        axBeta.set_ylabel('$Bias$ [$V$]')
        axBeta.set_xlabel('$\Delta \ z$ [$\AA{}]$')
        fig.colorbar(im, ax=axBeta, label='$Beta factor$')
        mpl.rcParams.update({'font.size': 42})
        fig.set_size_inches(100.5, 13.5)
        fig.savefig(Mol.szOutputFolder + Mol.Name +
                    ' - LiftingSpectroscopy.png',
                    dpi=fig.dpi)

    if 'MD' in Simulations:
        #Perform a molecular dynamics simulation only
        MD = MD_Lifting(Mol)
        MD.PerformLiftingMD(np.linspace(0,
                                        np.max(Mol1.Atom[:, 1]) - 0.1, 50),
                            export=['xyz'])
Esempio n. 54
0
    # For plotting the SEM measure, use this!
    err_training_steps = stats.sem(training_steps, axis=1)
    err_navigation_steps = stats.sem(navigation_steps, axis=1)

    training_fig = pl.figure()
    training_ax = training_fig.add_subplot(111)
    training_ax.errorbar(range(n_training_trials),
                         mean_training_steps,
                         yerr=err_training_steps,
                         marker='d',
                         ecolor='black',
                         capsize=0.5)
    training_ax.set_xlabel('Trials')
    training_ax.set_ylabel('Distance Moved')
    Graphics.cleanAxes(training_ax)
    pl.show()

    navigation_fig = pl.figure()
    navigation_ax = navigation_fig.add_subplot(111)
    navigation_ax.errorbar(range(n_navigation_trials),
                           mean_navigation_steps,
                           yerr=err_navigation_steps,
                           marker='o',
                           ecolor='black',
                           capsize=0.5)
    navigation_ax.set_xlabel('Trials')
    navigation_ax.set_ylabel('Distance Moved')
    Graphics.cleanAxes(navigation_ax)
    pl.show()
Esempio n. 55
0
f = open("data.txt", 'w')
for i in range(len(p)):
    pathString = str(p[i][0]) + str(p[i][1]) + ' '
    f.write(pathString)
runString = "\n"
for i in range(len(runResult[1])):
    if runResult[1][i] == "jump" or runResult[1][i] == "stay":
        runString += "0"
    else:
        runString += "1"
f.write(runString)
f.close()

if "-na" not in sys.argv and "-g" not in sys.argv:
    if "-g" not in sys.argv: print("Displaying best solution")
    Graphics.main()
else:
    if "-g" not in sys.argv: print("Skipping animation.")

# Plot the longest solutions
if "-np" not in sys.argv and "-g" not in sys.argv:
    if "-g" not in sys.argv: print("Plotting solution lengths")
    axes = plt.gca()
    axes.set_xlim([0, len(longestSolutions)])
    axes.set_ylim([0, pathlength])
    xaxis = []
    for i in range(len(longestSolutions)):
        xaxis += [i]
    plt.title("Solution Length over Time")
    plt.xlabel("Generation")
    plt.ylabel("Longest Solution")
Esempio n. 56
0
def calculateStatistics(project, trace):
  """
  Calculate derived OpenGL ES statistics instrumentation sensor data and trace events.
  """
  
  if not "code" in project.targets:
    raise ValueError("No code information in project file")

  task      = Task.startTask("gles-stats", "Calculating OpenGL ES statistics", len(trace.events))
  library   = project.targets["code"].library
  constants = Collections.DictProxy(library.constants)
  
  # Create the derived sensors
  trace.sensors["average_triangle_size"]   = Trace.InstrumentationSensor("Average triangle size", isAverage = True)
  trace.sensors["texel_fetches_per_pixel"] = Trace.InstrumentationSensor("Texel fetches per pixel", isAverage = True)
  trace.sensors["texel_uploads"]           = Trace.InstrumentationSensor("Texel uploads")
  trace.sensors["vertices_in"]             = Trace.InstrumentationSensor("Vertices in")
  trace.sensors["triangles_in"]            = Trace.InstrumentationSensor("Triangles in")
  trace.sensors["render_calls"]            = Trace.InstrumentationSensor("Rendering calls")
  trace.sensors["rasterizer_discarded_pixels"] = Trace.InstrumentationSensor("Rasterizer discarded pixels")
  trace.sensors["draw_ratio"]              = Trace.InstrumentationSensor("Draw ratio")
  
  prevRenderEvent = None
  depthMask       = 1
  
  for event in trace.events:
    task.step()
    
    func = library.functions[event.name]

    if func.isRenderCall:
      event.sensorData["render_calls"] = 1

    if func.isRenderCall and "count" in event.values and "mode" in event.values:
      m = event.values["mode"]
      if m == constants.GL_TRIANGLES:
        event.sensorData["triangles_in"] = int(event.values["count"] / 3)
      elif m == constants.GL_TRIANGLE_STRIP:
        event.sensorData["triangles_in"] = int(event.values["count"] - 2)
      elif m == constants.GL_TRIANGLE_FAN:
        event.sensorData["triangles_in"] = int(event.values["count"] - 2)
      elif m == constants.GL_POINTS:
        event.sensorData["triangles_in"] = int(event.values["count"] * 2)
      elif m == constants.GL_LINES:
        event.sensorData["triangles_in"] = int(event.values["count"])
      elif m == constants.GL_LINE_STRIP:
        event.sensorData["triangles_in"] = int(event.values["count"] * 2)
      elif m == constants.GL_LINE_LOOP:
        event.sensorData["triangles_in"] = int(event.values["count"] * 2 + 2)

    fragments  = event.sensorData.get("rasterizer_pixels", 0)
    triangles  = event.sensorData.get("triangles_in", 0)
    texFetches = event.sensorData.get("rasterizer_texel_fetches", 0)
    
    if triangles and fragments:
      event.sensorData["average_triangle_size"] = fragments / float(triangles)
      
    if fragments and texFetches:
      event.sensorData["texel_fetches_per_pixel"] = fragments / float(texFetches)
      
    if event.name in ["glTexImage2D", "glTexSubImage2D"]:
      event.sensorData["texel_uploads"] = int(event.values["width"] * event.values["height"])

    if func.isRenderCall and "count" in event.values:
      event.sensorData["vertices_in"] = int(event.values["count"])
      
    if event.name == "glDepthMask":
      depthMask = event.values["flag"]
      
    # If we have the depth buffers for this event and the previous draw event, see how many pixels
    # actually changed and use that value to estimate overdraw
    if func.isRenderCall and not "rasterizer_discarded_pixels" in event.sensorData:
      if depthMask and prevRenderEvent and "depth_stride" in event.sensorData and "depth_mask" in event.sensorData:
        f1 = player.Instrumentation.getBufferFileName(prevRenderEvent, "depth")
        f2 = player.Instrumentation.getBufferFileName(event, "depth")
        if f1 and f2:
          diff = Graphics.compareDepthBuffers(f1, f2, event.sensorData["depth_stride"], event.sensorData["depth_mask"])
          event.sensorData["rasterizer_discarded_pixels"] = fragments - diff
      prevRenderEvent = event
    
    discFragments = event.sensorData.get("rasterizer_discarded_pixels", 0)
    width         = event.sensorData.get("render_surface_width", 0)
    height        = event.sensorData.get("render_surface_height", 0)

    if fragments and width and height:
      event.sensorData["draw_ratio"] = (fragments - discFragments) / float(width * height)
Esempio n. 57
0
 def __init__(self):
     self.graphics = Graphics()
     self.board = Board()
Esempio n. 58
0
import Graphics
import matrix 
import DEBUG
import MatGraph
import math
from Mesh import *
import random
from typing import List
from dataclasses import dataclass
import threading
DEBUG.init()
Graphics.initDisplayHandler(DEBUG.window,(1920,1080),100,30*math.pi/180)


def PointAt(pos,target,up):
    
    
    NewForward = target-pos
    #print(NewForward.v)
    try:
        size = math.sqrt(NewForward.v[0]**2+NewForward.v[0]**2+NewForward.v[0]**2)
        NewForward.v[0] /= size
        NewForward.v[1] /= size
        NewForward.v[2] /= size
    except:
        pass

    
    
    a = NewForward * MatGraph.DotProduct(up,NewForward)
    NewUp = up - a
Esempio n. 59
0
 def getOnscreenPos(self):
     if self.currentState == CONST.CurrentPlayerState.Small:
         return Graphics.getOnScreenPos(self.pos, self.cameraPos)
     return Graphics.getOnScreenPos(
         (self.pos[0], self.pos[1] +
          (CONST.PlayerLargeSizeY - CONST.PlayerSizeY)), self.cameraPos)
Esempio n. 60
0
])



TranslationMatrix2 = matrix.mat3x3([
    [-0,0,0],
    [-0,0,0],
    [-0,0,0],

])


Cam = matrix.vector([0,0,0])
Light = matrix.vector([0,-0,-1])

Graphics.init()

theta = math.pi/3
spd = 0.01
Test = Mesh.Load3DElement("Gplanneur/Tests/Test 3D/3D rotations/GAMIIIING.obj")
#print(Test.v)
while Graphics.ProgramRunning :
    
    cube2 = copy.deepcopy([Test])

    Graphics.PrintFPS()

    if(Graphics.SpaceToken):
        theta += math.pi/8
    else:
        theta += math.pi/512