示例#1
0
class LargePlotDialog(wx.Dialog):

    """
    Creates a larger version of the plot as a separate window
    """

    def __init__(self, *args, **kw):
        super(LargePlotDialog, self).__init__(*args, **kw)
        #WorldState.Instance() = WorldState.Instance()
        graph_panel = wx.Panel(self, -1)
        graph_panel.SetBackgroundColour(_BG_COLOUR)
        graph_width = int((WorldState.Instance().dispW - 10) / _DPI)
        graph_height = int(graph_width/_PHI)
        graph_fig = Figure((graph_width, graph_height))
        graph_fig.set_facecolor('white')
        self.graph_canvas = FigCanvas(graph_panel, -1, graph_fig)
        self.graph_axes = graph_fig.add_subplot(111)
        graph_vbox = wx.BoxSizer(wx.VERTICAL)
        graph_vbox.Add(self.graph_canvas)
        toolbar = NavigationToolbar(self.graph_canvas)
        graph_vbox.Add(toolbar)
        graph_panel.SetSizer(graph_vbox)
        graph_vbox.Fit(self)
        self.SetSize((WorldState.Instance().dispW - 10, ((WorldState.Instance().dispW) / _PHI) + 50))
        self.Centre()
        self.draw_plot = Plotter(self.graph_axes)
        self.draw_plot.mpl_legend = True
        self.draw_plot.plot()
    def plot_all_methods(self, word, period, smooth=None):
        time_series = TimeSeries(word)
        series = time_series.get_series()
        original_series = time_series.get_modified_series(series)
        if smooth != None:
            series = time_series.smoothify_series(original_series, smooth)
        else:
            series = original_series

        x0 = [i + self.year_range[0] for i in range(self.max_range)]
        y0 = self.compute_relevance(original_series)

        y = []

        level_peak = LevelPeakDetector(series)
        y.append(self.compute_relevance(level_peak.get_levels(1)))
        y.append(self.compute_relevance(level_peak.get_levels(2)))

        window_peak = WindowPeakDetector(series)
        y.append(self.compute_relevance(window_peak.compute_peaks(1)))
        y.append(self.compute_relevance(window_peak.compute_peaks(2)))
        y.append(self.compute_relevance(window_peak.compute_peaks(3)))

        double_peak = DoubleChangePeakDetector(series)
        y.append(double_peak.compute_relevance(0.1))

        plotter = Plotter(x0, series, period)
        plotter.plot_multiple_peaks(word, y, period)
示例#3
0
 def test_12_plot_stacked_bars(self):
     image_filename = get_filename_from_frame(inspect.currentframe())
     my_plot = Plotter(self.data['bar-data'])
     my_plot.stacked_bar(x_column='year', y_column='quantity',
                         y_labels='product_name',
                         title='Stacked bars example')
     my_plot.save(image_filename)
    def plot_historical_relevance(self, word, period, method, smooth=None):
        time_series = TimeSeries(word)
        series = time_series.get_series()
        original_series = time_series.get_modified_series(series)
        if smooth != None:
            series = time_series.smoothify_series(original_series, smooth)
        else:
            series = original_series

        x0 = [i + self.year_range[0] for i in range(self.max_range)]
        y0 = self.compute_relevance(original_series)

        if 'level' in method:
            level_peak = LevelPeakDetector(series)
            if method == 'level 1':
                y = self.compute_relevance(level_peak.get_levels(1))
            else:
                y = self.compute_relevance(level_peak.get_levels(2))
        elif 'window' in method:
            window_peak = WindowPeakDetector(series)
            if method == 'window 1':
                y = self.compute_relevance(window_peak.compute_peaks(1))
            elif method == 'window 2':
                y = self.compute_relevance(window_peak.compute_peaks(2))
            else:
                y = self.compute_relevance(window_peak.compute_peaks(3))
        elif 'double' in method:
            double_peak = DoubleChangePeakDetector(series)
            y = double_peak.compute_relevance(0.1)

        plotter = Plotter(x0, series, period)
        plotter.plot_peaks(word, y, method + ' function')
示例#5
0
文件: crpss.py 项目: wking/murcss
  def bootstrapEnsembleSpreadscore(self, ensAnoms, anomalies, tempSmoothedObs, spreadscore, bootstrap_number):
      print 'Bootstrapping spreadscore'
      tmpDir = self.tmpDir + 'bootstrap_ensspread/'
      if not os.path.isdir(tmpDir):
          os.mkdir(tmpDir)
      
      bootstrapList = []       
      for i in range(0,bootstrap_number):
          tmp_ensAnoms = dict()
          tmp_anoms = dict()
          tmp_obs = dict()
          for year in self.decadals:
              choice_year = choice(self.decadals)
              tmp_ensAnoms[year] = ensAnoms[choice_year]
              tmp_anoms[year] = anomalies[year]
              tmp_obs[year] = tempSmoothedObs[year]
          
          tmp_ensspread = self.getEnsembleStd(tmp_ensAnoms)
          tmp_rmse = self.getReferenceStd(tmp_anoms, tmp_obs)
          tmp_spreadscore = cdo.div(input=' '.join([tmp_ensspread, tmp_rmse]),
                                    output=tmpDir+str(i)+'spreadscore_bootstrap')        
          bootstrapList.append(tmp_spreadscore)
 
      significance = Significance(self.tmpDir, self.outputPlots)
      (sig_lon, sig_lat) = significance.checkSignificance(bootstrapList, spreadscore, check_value=1)
      m = Plotter.plotField(spreadscore, 0, 2, 'RdBu_r', lonlatbox=self.lonlatbox)
      
      Plotter.addCrosses(m, sig_lon, sig_lat)
      Plotter.saveFig(self.outputPlots, spreadscore.split('/')[-1])
          
      return bootstrapList  
示例#6
0
 def test_13_use_colors_instead_of_colormap_stacked_bar(self):
     image_filename = get_filename_from_frame(inspect.currentframe())
     my_plot = Plotter(self.data['bar-data'])
     my_plot.stacked_bar(x_column='year', y_column='quantity',
                         y_labels='product_name',
                         title='Stacked bars example',
                         colors=['red', 'blue', 'yellow', 'magenta', 'gray'])
     my_plot.save(image_filename)
示例#7
0
def plot_step_by_step(X_all, U_all, Z_all, B_all, EB_all, model):
    fig, axes = plt.subplots(1, 2, figsize=(20, 8))
    fig.tight_layout()
    xlim = (-5, 35)
    ylim = (-5, 30)
    Plotter.plot_mpc(
        fig, axes, xlim, ylim, model, X_all, Z_all, B_all, EB_all
    )
示例#8
0
def plot_full(x_all, z_all, b_all):
    fig, ax = plt.subplots()
    fig.tight_layout()
    handles = Plotter.plot_trajectory(ax, x_all)
    handles.extend(Plotter.plot_observed_ball_trajectory(ax, z_all))
    handles.extend(Plotter.plot_filtered_trajectory(ax, b_all))
    ax.legend(handles=handles, loc='upper left')
    ax.set_aspect('equal')
    plt.show()
    def __init__(self):
        app = wx.PySimpleApp()
        frame = wx.Frame(None, title="Hello, world.", size=(800, 500))
        wavereader = WaveReader('data.wav')
        plotter = Plotter(frame, wavereader.readframes())

        plotter.draw()
        frame.Show()
        app.MainLoop()
示例#10
0
def qjump_once(*args, **kwargs):
    dirname = make_results_dir(kwargs.get("dir", DEFAULT_RESULTS_DIR))
    kwargs["dir"] = dirname
    update_qjump_args(kwargs)
    log_arguments(*args, **kwargs)
    ping_times = qjump(*args, **kwargs)
    if ping_times:
        plotter = Plotter()
        plotter.plotCDF(ping_times, dir=dirname, figname="pingCDF")
        print("Results saved to " + dirname)
示例#11
0
    def run(self):
        # parameters
        Sim.scheduler.reset()

        if "a" in self.debug:
            Sim.set_debug('AppHandler')
        if "t" in self.debug:
            Sim.set_debug('TCP')

        # setup network
        networkPlotter = Plotter('out/2-flows-simple')
        net = Network(config='networks/one-hop.txt',plotter=networkPlotter)
        net.loss(self.loss)

        # setup routes
        n1 = net.get_node('n1')
        n2 = net.get_node('n2')
        n1.add_forwarding_entry(address=n2.get_address('n1'),link=n1.links[0])
        n2.add_forwarding_entry(address=n1.get_address('n2'),link=n2.links[0])

        # setup transport
        t1 = Transport(n1)
        t2 = Transport(n2)

        # setup connection
        c1 = TCP(t1,n1.get_address('n2'),1,n2.get_address('n1'),1,AppHandler(inputfile=self.inputfile,identifier="c1"),window=self.window,type=self.type,window_size_plot=True,sequence_plot=True)
        c2 = TCP(t2,n2.get_address('n1'),1,n1.get_address('n2'),1,AppHandler(inputfile=self.inputfile,plot=True,identifier="c2"),window=self.window,type=self.type,receiver_flow_plot=True)
        
        c3 = TCP(t1,n1.get_address('n2'),2,n2.get_address('n1'),2,AppHandler(inputfile=self.inputfile,identifier="c3"),window=self.window,type=self.type,window_size_plot=True,sequence_plot=True)
        c4 = TCP(t2,n2.get_address('n1'),2,n1.get_address('n2'),2,AppHandler(inputfile=self.inputfile,plot=True,identifier="c4"),window=self.window,type=self.type,receiver_flow_plot=True)

        global tcps
        tcps = [c1, c2, c3, c4]

        global original_size
        f = open(self.inputfile, "rb")
        try:
            data = f.read(1000)
            while data != "":
                original_size += len(data)
                Sim.scheduler.add(delay=0, event=data, handler=c1.send)
                Sim.scheduler.add(delay=0, event=data, handler=c3.send)
                data = f.read(1000)
        finally:
            f.close()

        # run the simulation

        global decisecondEvent
        decisecondEvent = Sim.scheduler.add(delay=0.1, event=Sim, handler=self.decisecond)

        Sim.scheduler.run()

        networkPlotter.plot(self.sequencefile)
        plotter.plot(self.sequencefile);
示例#12
0
 def _plotField(self, fileName, vmin, vmax):
     """
     @deprecated: use the static Plotter class instead
     Plot any field variable
     
     :param fileName: filepath
     :param vmin: min value for colorbar
     :param vmax: max value for colorbar
     """
     Plotter.plotField(fileName, vmin, vmax, colormap='', output_folder=self.outputPlots, lonlatbox=self.lonlatbox)
     Plotter.saveFig(self.outputPlots, fileName.split(self.outputDir)[-1])
    def plot_keywords(self, event, words, period):
        time_series = []
        for i in range(len(words)):
            original_series = TimeSeries(words[i]).get_series()
            original_series = original_series.get_modified_series(original_series)
            series = original_series.smoothify_series(original_series, 2)
            time_series.append(series)

        x0 = [i + self.year_range[0] for i in range(self.max_range)]
        plotter = Plotter(x0, [], period)
        plotter.plot_keywords(event, words, time_series)
def main():
    config = "end"
    num = 5
    remove_peg = 11
    examples = make_state_space()
    default_state_space = examples[num]
    a = Plotter('fig/remove_peg'+str(remove_peg)+'_'+config+'_state_' + str(num) + '.png')
    action_space = ActionSpace(default_state_space)
    end_state = action_space.remove_convex(default_state_space,remove_peg)
    if config == "end":
        a.plot(end_state)
    else:
        a.plot(default_start_state)
示例#15
0
    def bootstrap(self, crps, crpsRef, tag, crpss, bootstrap_number=500, plot_range=[-1, 1], colorbar='RdBu_r'):
        """
        Bootstrap function to calculate significance crosses for crpss and other metrics. 
        It also plots the fields with significance crosses
        """
        tmpDir = self.outputDir
        self.outputDir = self.tmpDir + 'bootstrap_' + tag + '/'
        if not os.path.isdir(self.outputDir):
            os.mkdir(self.outputDir)

        poolArgs = self.getPoolArgs(bootstrap_number, self, crps, crpsRef, tag, crpss, range(0, bootstrap_number),
                                    '_multiBootstrap')
        bootstrapList = self.multiProcess(poolArgs)
            
        self.outputDir = tmpDir      
        
        significance = Significance(self.tmpDir, self.outputPlots)
        if self.fieldmean:
            (sig_lon, sig_lat) = significance.checkSignificanceFldmean(bootstrapList, crpss)
        else:
            (sig_lon, sig_lat) = significance.checkSignificance(bootstrapList, crpss)
            if self.zonalmean:
                m = Plotter.plotVerticalProfile(crpss, plot_range[0], plot_range[1], colorbar, lonlatbox=self.lonlatbox)
                Plotter.addCrossesXY(m, crpss+'_significance_mask')
    
            else:
                m = Plotter.plotField(crpss, plot_range[0], plot_range[1], colorbar, lonlatbox=self.lonlatbox)
                Plotter.addCrosses(m, sig_lon, sig_lat)
            Plotter.saveFig(self.outputPlots, crpss.split('/')[-1])
            
        return bootstrapList   
示例#16
0
 def newDataset( self, path, dsIndex ):
     dsHandle = ServerHandle( self.dvName, self, isListening = False )
     yield dsHandle( 'cd', path )
     fullPath, name = yield dsHandle( 'open', dsIndex )
     plotter = Plotter( name, fullPath, dsHandle, self )
     plotter.initDefer.addCallback( lambda _: plotter.show() )
     plotter.initDefer.addErrback(self.catchError)
     delTimer = QtCore.QTimer( self )
     delTimer.setSingleShot( True )
     delTimer.setInterval( cacheTime )
     plotter.finished.connect( lambda result: delTimer.start() )
     delTimer.timeout.connect( plotter.deleteLater )
     self.datasets[( tuple( path ), dsIndex )] = plotter, delTimer
     delTimer.timeout.connect( lambda: self.datasets.pop( ( tuple( path ), dsIndex ) ) )
示例#17
0
文件: trimbits.py 项目: hperrey/pyxar
 def cleanup(self, config):
     color_dict = [ROOT.kYellow,ROOT.kBlack,ROOT.kRed,ROOT.kBlue,ROOT.kGreen]
     plot = Plotter(self.config, self)
     for roc in self.dut.rocs():
         min_axis = numpy.amin([self.vthr_dists[0][roc.number]-self.vthr_dists[step][roc.number] for step in range(1,5)])
         max_axis = numpy.amax([self.vthr_dists[0][roc.number]-self.vthr_dists[step][roc.number] for step in range(1,5)])
         vthr_stack = ROOT.THStack("%s_%s" %(self.dac, roc.number),"%s dist for each trim bit setting; %s; # pixels" %(self.dac, self.dac))
         for step in range(5):
             self._histos.append(plot.matrix_to_th2(self.vthr_dists[step][roc.number],'Vthr_Map_%s_ROC_%s' %(step, roc.number),'col','row'))
             if step == 0:
                 continue
             h_vthr = Plotter.create_th1(self.vthr_dists[0][roc.number]-self.vthr_dists[step][roc.number],'VthrCompDifference_Trim_%s_ROC_%s' %(self.trim_bit[step], roc.number), self.dac, '# pixels', min_axis, max_axis) 
             h_vthr.SetLineColor(color_dict[step])
             vthr_stack.Add(h_vthr)
             self._histos.append(h_vthr)
         self._histos.append(vthr_stack)
示例#18
0
class InputThread(threading.Thread):
    def __init__(self, router, plotter=None):
        super(InputThread, self).__init__()
        self._plotter = Plotter(router)
        self._generator = EventGenerator(router)

    def run(self):
        while True:
            try:
                value = raw_input().split()

                if len(value) < 1:
                    continue
                elif value[0] == "q":
                    self._generator.stop_simulation()
                    break
                elif value[0] == "al":
                    if len(value) != 6:
                        continue
                    self._generator.add_link(value[1], value[2], value[3], int(value[4]), int(value[5]))
                elif value[0] == "rl":
                    if len(value) != 2:
                        continue
                    self._generator.remove_link(value[1])
                elif value[0] == "ud":
                    if len(value) != 3:
                        continue
                    self._generator.update_demand(value[1], int(value[2]))
                elif value[0] == "gb":
                    if len(value) != 2:
                        continue
                    self._generator.generate_breakdown(value[1])
                elif value[0] == "rr":
                    if len(value) == 3 and value[2].endswith(".cfg"):
                        self._generator.reset_router(value[1], filename=value[2])
                    elif len(value) == 3:
                        self._generator.reset_router(value[1], another_router_id=value[2])
                    elif len(value) == 4:
                        self._generator.reset_router(value[1], another_router_id=value[2], demand=int(value[3]))

                elif value[0] == "sg":
                    self._plotter.present_flow()

            except EOFError:
                pass

        thread.interrupt_main()
示例#19
0
	def __init__(self,isPlayer1=False, loadOldTable=False, overwriteFile = False, 
				 epsilon=.20, alpha=0.5, name="Qlearner", plot_freq=0, trainingMode=False):

		super(BasicQlearnAgent, self).__init__(name)
		self.p1 = isPlayer1

		self.epsilon = epsilon

		self.discount = 0.90

		# queue of previous states 
		self.prevStates = []
		self.counter = 0

		# high 
		self.alpha = 0.1
		self.prevGamestate = GameState(-4,0,100,4,0,100)
		self.prevAction = Actions.doNothing
		self.bodywidth = 1.0;
		self.isTraining = False
		self.possibleXdists = [0, 1, 2, 3, 4, 5, 6]

		if (overwriteFile):
			signal.signal(signal.SIGINT, self.signalHandler)
		self.actions = [a for a in Actions]
		self.numActions = len(self.actions)
		self.actionDic = dict()
		self.makeActionDic()

		# sparse feature extractor
		self.w = {}

		self.fn = 'savedWeightsp1.txt'
		self.bindport = 5555
		if (not self.p1):
			self.fn = 'savedWeightsp2.txt'
			self.bindport=5565

		self.ipc_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)    
		self.ipc_server.bind((HOST, self.bindport))
    
		self.ipc_client =  socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
		
		if (not loadOldTable):
			self.initW()
			self.epsilon = .1
		else:
			self.retrieveWeightsFromFile(self.fn)

		# times per second to plot
		# 0 is 'off', but we add modulo plot_freq + 1, and update
		# when counter = 1
		self.plot_freq = (60/(plot_freq + 1))
		self.plot_counter = 0

		if plot_freq > 0:
			self.plotter = Plotter()

		print("Done initializing!")
示例#20
0
 def __init__(self):
         self.A=[]
         self.b=[]
         self.xyz=[]
         self.D=[]
         self.M=[]
         self.WD=[]
         self.W=[] ##walkable surface
         self.plot = Plotter()
示例#21
0
	def process_data(self):
		if self.chk_btn_plot.get_active() or self.chk_btn_csv.get_active():
			filters = []
			paths = []
			tags = []
			self.liststore.foreach(lambda model, path, iter, user_data: paths.append(path), None)
			for i in paths:
				iter = self.liststore.get_iter(i)
				filters.append([self.liststore.get_value(iter,0),self.liststore.get_value(iter,1)])
				tags.append(self.liststore.get_value(iter,0))
			if self.entry_interval.get_text().strip() is not '':
				interval = float(self.entry_interval.get_text())
			else:
				interval = 1
			if self.chkbtnOtherTraffic.get_active():
				othertrafficfilter = ''
				for i in filters:
					othertrafficfilter = othertrafficfilter + '!(' + i[1] + ') and '
				othertrafficfilter = othertrafficfilter[:-5]
				filters.append(['Other',othertrafficfilter])
				tags.append('Other')
			timeline,yvalues = Filterer(str(self.file_chooser.get_filename()).replace(' ','\ '),filters,interval,self.chk_btn_crc.get_active(),self.chk_btn_csv.get_active()).start()
			self.waiting = False

			if self.chk_btn_csv.get_active():
				dec_sep = self.entry_csv_decimal_sep.get_text()
                		values_sep = self.entry_csv_values_sep.get_text()
				sep_dec = self.entry_csv_decimal_sep.get_text()
				sep_val = self.entry_csv_values_sep.get_text()
				if self.entry_csv_savefile.get_text().strip() is not '':
					try:
						savepath = os.path.join(self.fchooser_csv.get_filename(),self.entry_csv_savefile.get_text())
						f = open(savepath,'w')
						f.write('TIME')
						for i in timeline:
							f.write(sep_val+str(i).replace('.',sep_dec))
						f.write('\n')
						for i in range(0,len(filters)):
							f.write(filters[i][0])
							for j in yvalues[i]:
								f.write(sep_val+str(j).replace('.',sep_dec))
							f.write('\n')
						f.close()
						print("%s succesfully created."%savepath)
					except Exception,e:
						print e
			gtk.gdk.threads_enter()
			self.window.set_opacity(1)
			self.win_wait.hide()
			if self.chk_btn_plot.get_active():
				plt = Plotter(timeline,yvalues,tags,self.entry_title.get_text())
				if self.combobox_plot_style.get_active() is 0:
					plt.simpleplot()
				elif self.combobox_plot_style.get_active() is 1:
					plt.stackareaplot()
				else: plt.simpleplot()
			gtk.gdk.threads_leave()
示例#22
0
文件: hrtest.py 项目: nmohr/pyxar
    def cleanup(self, config):
        '''Convert test result data into histograms for display.'''
        self.fill_histo()
        for roc in self.dut.rocs():
            plot_dict = {'title':self.test+'_ROC_%s' %roc.number, 'x_title': self.x_title, 'y_title': self.y_title, 'data': self.dut.data[roc.number]}
        self._results.append(plot_dict)
        plot = Plotter(self.config, self)
        #Create PH histograms for every ROC and whole DUT
        for roc in self.dut.rocs():
            ph_adc = numpy.array(self.dut.ph_array[roc.number])
            ph_vcal = numpy.array(self.dut.ph_cal_array[roc.number])
            PH_ADC = Plotter.create_th1(ph_adc,'PH_ADC_ROC_%s' %roc.number, 'ADC units', '# entries', 0, 255)
            PH_VCAL = Plotter.create_th1(ph_vcal,'PH_VCAL_ROC_%s' %roc.number, 'Vcal units', '# entries', 0, 255)
            self._histos.append(PH_ADC)
            self._histos.append(PH_VCAL)

        self._histos.extend(plot.histos)
        #calculating results
        for roc in self.dut.rocs():
            ia = self.tb.get_ia()
            self.logger.info('%s: ia = %.2f' %(roc, ia))
            id = self.tb.get_id()
            self.logger.info('%s: id = %.2f' %(roc, id))
        self._n_rocs = int(config.get('Module','rocs'))
        sensor_area = self._n_rocs * 52 * 80 * 0.01 * 0.015 #in cm^2
        self.logger.debug('number of rocs %s' %self._n_rocs)
        self.logger.debug('sensor area %s' %round(sensor_area,2))
        hits = numpy.sum(self.dut.data)
        trigger_rate = 1.0e6 / (40.0 * self.period)
        rate = hits / (self.data_taking_time * trigger_rate * 1e3 * 25e-9 * self.scc * 1.0e6 * sensor_area)    

        self.logger.info('data aquisition time    %i' %self.data_taking_time)
        self.logger.info('number of hits          %i' %hits)
        self.logger.info('trigger rate            %s kHz' %round(trigger_rate,1))
        self.logger.info('hit rate                %s MHz/cm^2' %round(rate,6))
        self.logger.info('scc                     %i ' %self.scc)
       

        self._histos.extend([self._dut_histo])
        if self.window:
            self.window.histos.pop()
示例#23
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.MAX_LINES = 100
        self.dataSource = emptyGenerator()

        self.input = []
        self.totalLines = 0
        self.curve = collections.defaultdict(self.createCurveData)
        self.nextCurveId = 0
        self.maxValue = 1

        self.plot = Plotter()
        self.plot.setDataGetter(self.mainPlotGetter)
        self.plot.setCurveGetter(self.curveGetter)
        self.plot.setMouseTracking(True)

        self.plotScroller = PlotScroller()
        self.plotScroller.setDataGetter(self.plotScrollerGetter)
        self.plotScroller.setCurveGetter(self.curveGetter)
        self.plotScroller.selectionChanged.connect(self.onScrollerChanged)

        self.inputView = LogViewer()
        self.inputView.setMaxLineCount(500)
        self.parsersPanel = input_parsers_gui.ParserListPanel()
        self.parsersPanel.itemsChanged.connect(self.onParsersChanged)

        self.rightPanel = QtGui.QVBoxLayout()
        self.rightPanel.addWidget(self.parsersPanel)
        self.rightPanel.setStretch(1, 1)

        self.leftPanel = QtGui.QVBoxLayout()
        self.leftPanel.addWidget(QtGui.QLabel("Details graph"))
        self.leftPanel.setStretch(0, 0)
        self.leftPanel.addWidget(self.plot)
        self.leftPanel.setStretch(1, 1)
        self.leftPanel.addWidget(QtGui.QLabel("Input graph (left-click: select range, right click: move range):"))
        self.leftPanel.setStretch(2, 0)
        self.leftPanel.addWidget(self.plotScroller)
        self.leftPanel.setStretch(3, 1)
        self.leftPanel.addWidget(QtGui.QLabel("Input lines:"))
        self.leftPanel.setStretch(4, 0)
        self.leftPanel.addWidget(self.inputView)
        self.leftPanel.setStretch(5, 1)

        self.layout = QtGui.QGridLayout(self)
        self.layout.addLayout(self.leftPanel, 0, 0)
        self.layout.addLayout(self.rightPanel, 0, 1)
        self.layout.setColumnStretch(0, 1)

        self.resize(600, 500)
        self.startTimer(50)

        self.oldSelection = None
示例#24
0
文件: test.py 项目: nmohr/pyxar
 def cleanup(self, config):
     '''Convert test result data into histograms for display.'''
     for roc in self.dut.rocs():
         plot_dict = {'title':self.test+'_ROC_%s' %roc.number, 'x_title': self.x_title, 'y_title': self.y_title, 'data': roc.data}
         self._results.append(plot_dict)
     plot = Plotter(self.config, self)
     for roc in self.dut.rocs():
         th1 = Plotter.create_th1(roc.data,self.test+'_Distribution_ROC_%s' %(roc.number), 'Projection of test', '# pixels')
         self._histos.append(th1)
     self._histos.extend(plot.histos)
     self.fill_histo()
     self._histos.append(self._dut_histo)
示例#25
0
文件: trim.py 项目: hperrey/pyxar
 def cleanup(self, config):
     color_dict = [1,13,15,17,2]
     #TODO decide what is important to the user
     plot = Plotter(self.config, self)
     for roc in self.dut.rocs():
         #save data
         roc.save(self.vcal)
         min_axis = numpy.amin(self.vcal_dists)
         max_axis = numpy.amax(self.vcal_dists)
         vcal_stack = ROOT.THStack("Vcal %s" %roc.number,"Vcal dist for each trimming step; Vcal; # pixels")
         trim_stack = ROOT.THStack("TrimBits %s" %roc.number,"Trim bits for each trimming step; TrimBit; # pixels")
         try:
             self._histos.append(plot.matrix_to_th2(self.dut_VthrComp_map[roc.number],'Vthr_Map_ROC_%s'%roc.number,'col','row'))
             self._histos.append(plot.matrix_to_th2(self.dut_Noise_map[roc.number],'Noise_Map_ROC_%s'%roc.number,'col','row'))
         except AttributeError:
             pass
         for step in range(self.n_steps+1):
             self._histos.append(plot.matrix_to_th2(self.vcal_dists[step][roc.number],'Vcal_Map_%s_ROC_%s' %(step, roc.number),'col','row'))
             self._histos.append(plot.matrix_to_th2(self.trim_dists[step][roc.number],'Trim_Map_%s_ROC_%s' %(step, roc.number),'col','row'))
             h_vcal = Plotter.create_th1(self.vcal_dists[step][roc.number],'%s_%s_ROC_%s' %('Vcal_Distribution', step, roc.number), self.dac, '# pixels', min_axis, max_axis) 
             h_vcal.SetLineColor(color_dict[step])
             vcal_stack.Add(h_vcal)
             h_trim = Plotter.create_th1(self.trim_dists[step][roc.number],'%s_%s_ROC_%s' %('Trim_Distribution', step, roc.number), 'Trim bit', '# pixels', self._min_trim_bit, self._max_trim_bit) 
             h_trim.SetLineColor(color_dict[step])
             trim_stack.Add(h_trim)
             if step == 4:
                 h_trim.SetFillStyle(3002)
                 h_trim.SetFillColor(color_dict[step])
                 h_vcal.SetFillStyle(3002)
                 h_vcal.SetFillColor(color_dict[step])
                 self._histos.append(h_vcal)
                 self._histos.append(h_trim)
         self._histos.append(trim_stack)
         self._histos.append(vcal_stack)
示例#26
0
文件: plotterGui.py 项目: wesshih/bhb
  def getValues(self,save=False,trend=False):
    print 'save: ' + `save`
    print 'TEST CLICK'
    self.x_var = self.vars[0].get()
    self.y_var = [] # reset the y var list
    for i in range(len(self.y_en)):
      if self.y_en[i].get() == 1:
        print 'got a 1, adding to vars'
        self.y_var.append(self.vars[i+1].get())

    if self.rangex.get() == 1:
      self.x_min = float(self.ex_min.get())
      self.x_max = float(self.ex_max.get())
    else:
      self.x_min = None
      self.x_max = None

    if self.rangey.get() == 1:
      self.y_min = float(self.ey_min.get())
      self.y_max = float(self.ey_max.get())
    else:
      self.y_min = None
      self.y_max = None

    cc = []
    if self.con1.get() == 1:
      cc.append((self.con1_var.get(),float(self.con1_min.get()),float(self.con1_max.get())))
    if self.con2.get() == 1:
      cc.append((self.con2_var.get(),float(self.con2_min.get()),float(self.con2_max.get())))
    if self.con3.get() == 1:
      cc.append((self.con3_var.get(),float(self.con3_min.get()),float(self.con3_max.get())))


    test_plotter = Plotter(self.x_var,self.y_var,self.x_min,self.x_max,self.y_min,self.y_max,cc)
    test_plotter.plot(save,trend)

    '''
示例#27
0
def qjump_all(*args, **kwargs):
    """Runs all three tests for Figure 3a. Replaces 'iperf' and 'qjump'
    arguments with its own."""

    dirname = make_results_dir(kwargs.get("dir", DEFAULT_RESULTS_DIR))
    kwargs["dir"] = dirname
    update_qjump_args(kwargs)
    log_arguments(*args, **kwargs)

    clean_up()

    print("*** Test for ping alone ***\n")
    os.mkdir(os.path.join(dirname, "ping-alone"))
    kwargs.update(dict(iperf=False, qjump=False, dir=os.path.join(dirname, "ping-alone")))
    ping_alone = qjump(*args, **kwargs)

    clean_up()

    print("\n*** Test for ping + iperf without QJump ***\n")
    os.mkdir(os.path.join(dirname, "ping-iperf-noqjump"))
    kwargs.update(dict(iperf=True, qjump=False, dir=os.path.join(dirname, "ping-iperf-noqjump")))
    ping_noQjump = qjump(*args, **kwargs)

    clean_up()

    print("\n*** Test for ping + iperf with QJump ***\n")
    os.mkdir(os.path.join(dirname, "ping-iperf-qjump"))
    kwargs.update(dict(iperf=True, qjump=True, dir=os.path.join(dirname, "ping-iperf-qjump")))
    ping_Qjump = qjump(*args, **kwargs)

    ping_alone = filter_out_dropped_pings(ping_alone, "with ping alone")
    ping_noQjump = filter_out_dropped_pings(ping_noQjump, "with ping and iperf, without QJump")
    ping_Qjump = filter_out_dropped_pings(ping_Qjump, "with ping and iperf, without QJump")
    plotter = Plotter()
    plotter.plotCDFs(ping_alone, ping_noQjump, ping_Qjump, dir=dirname, figname="pingCDFs")

    print("\nResults all saved to " + dirname)
示例#28
0
 def on_realize(self, widget=None):
     self.realized = True
     winctx = self.window.cairo_create()
     
     if self.plotbuffer is None:
         self.plotsize = (1600, 960)
         self.plotbuffer = winctx.get_target().create_similar(cairo.CONTENT_COLOR_ALPHA,
                                                              self.plotsize[0], self.plotsize[1])
         self.plotter = Plotter(self.plotbuffer, self.plotsize, self.datastore,
                                self.xAxis, self.yAxis, self.profiles)
     overlaysize = self.size
     self.overlaybuffer = winctx.get_target().create_similar(cairo.CONTENT_COLOR_ALPHA,
                                                          self.size[0], self.size[1])
     self.overlayplotter = OverlayPlotter(self.overlaybuffer, overlaysize, self.xAxis, self.yAxis)
     self.overlayplotter.draw()
示例#29
0
文件: crpss.py 项目: wking/murcss
    def bootstrap(self, crps, crpsRef, tag, crpss, bootstrap_number=500, plot_range=[-1,1], colorbar='RdBu_r'):
        tmpDir = self.outputDir
        self.outputDir = self.tmpDir + 'bootstrap_' + tag + '/'
        if not os.path.isdir(self.outputDir):
            os.mkdir(self.outputDir)

        poolArgs = self.getPoolArgs(bootstrap_number,self,crps,crpsRef,tag,crpss,range(0,bootstrap_number),'_multiBootstrap')
        bootstrapList = self.multiProcess(poolArgs)
            
        self.outputDir = tmpDir      
        
        significance = Significance(self.tmpDir, self.outputPlots)
        (sig_lon, sig_lat) = significance.checkSignificance(bootstrapList, crpss)
        
#        if tag == 'ens-vs-ref_':
#            m = Plotter.plotField(crpss, -0.5, 0.5, 'RdBu_r', lonlatbox=self.lonlatbox)
#        else:
#            m = Plotter.plotField(crpss, -1, 1, 'RdBu_r', lonlatbox=self.lonlatbox)
        m = Plotter.plotField(crpss, plot_range[0], plot_range[1], colorbar, lonlatbox=self.lonlatbox)
        
        Plotter.addCrosses(m, sig_lon, sig_lat)
        Plotter.saveFig(self.outputPlots, crpss.split('/')[-1])
            
        return bootstrapList   
示例#30
0
 def _calcSignificance(self, bootstrap_folders, output_folder, plot_folder, file_to_check):
     '''
     Caluclate the significance for the intput field (file_to_check)
     The field is also plotted with significance crosses
     
     :param bootstrap_folder: path of bootstraped data
     :param output_folder: path
     :param plot_folder: path
     :param file_to_check: fn
     '''
     fn = file_to_check
     file_to_check = self.extractFilename(file_to_check)
     b_array_list = list()
     for folder in bootstrap_folders:
         
         b_array_list.append(folder+file_to_check)
         
     
     significance = Significance(self.tmpDir, self.outputPlots)
     (sig_lon, sig_lat) = significance.checkSignificance(b_array_list, fn)
     
     m = Plotter.plotField(fn, -1, 1, colormap='RedBlu', lonlatbox=self.lonlatbox)
     Plotter.addCrosses(m, sig_lon, sig_lat)
     Plotter.saveFig(plot_folder, fn.split(output_folder)[-1])
示例#31
0
def main():
    plotter = Plotter()
    print('read polygon.csv')
    plot_polygon()
    print('read input.csv')
    point_list()
    print('categorize points')
    rca()
    print('write output.csv')
    output()
    print('plot polygon and points')
    m = mbr()
    p = plot_polygon()
    plotter.add_polygon(p[1], p[2])
    plt.plot(m[0], m[1])
    p = rca()
    for i in range(len(p[0])):
        plotter.add_point(p[1][i], p[2][i], p[3][i])

    plotter.show()
示例#32
0
 def algorithm(self, operand):
     data = []
     #                             bias   x     y    out
     if operand == 'AND':
         data = [[1.0, 1.0, 1.0, 1.0], [1.0, -1.0, 1.0, -1.0],
                 [1.0, 1.0, -1.0, -1.0], [1.0, -1.0, -1.0, -1.0]]
     elif operand == 'XOR':
         data = [[1.0, 1.0, 1.0, -1.0], [1.0, -1.0, 1.0, 1.0],
                 [1.0, 1.0, -1.0, 1.0], [1.0, -1.0, -1.0, -1.0]]
     weights = np.random.rand(len(data[0]) - 1, 1)
     error_min = len(data) * 2
     error_this_epoch = 1
     w_min = weights
     error_per_epoch = []
     plotter = Plotter()
     for epoch in range(self.iterations):  # COTA del ppt
         if error_this_epoch > 0:
             total_error = 0
             #if (epoch % 100 == 0):
             #    weights = np.random.rand(len(data[0]) - 1, 1)
             for i in range(
                     len(data)):  # tamano del conjunto de entrenamiento
                 sumatoria = self.get_sum(
                     data[i][:-1], weights
                 )  # dame toda la fila menos el ultimo elemento => x_i => x0, x1, x2, ...
                 activation = self.get_activation(sumatoria)
                 error = data[i][
                     -1] - activation  # y(1,i_x) - activacion del ppt
                 fixed_diff = self.alpha * error
                 for j in range(len(weights)):
                     weights[j] = weights[j] + (fixed_diff * data[i][j])
                 total_error += error**2
             error_this_epoch = self.error_function(total_error)
             error_per_epoch.append(error_this_epoch)
             if self.adaptive and epoch % 10 == 0:
                 self.adjust_learning_rate(error_per_epoch)
             if error_this_epoch < error_min:
                 error_min = error_this_epoch
                 w_min = weights
         else:
             break
     print('Linear data post analysis:')
     print('epochs: {}'.format(epoch + 1))
     print('Initial alpha: {}'.format(self.initial_alpha))
     print('End alpha: {}'.format(self.alpha))
     print('Best ever error: {}'.format(error_min))
     if len(w_min) != 0 or w_min != None:
         plotter.create_plot_ej1(data, w_min, operand)
     else:
         plotter.create_plot_ej1(data, weights, operand)
     return
示例#33
0
def Select(population, MSR, RV, BI_size, population_K ,nsol, new_msr, new_rv,new_bisize, new_K, generation,self_population,Zdt_definitions,PPlotter,PProblem,EEvolution,population_label,children_label):
    if (Zdt_definitions is None) and (PPlotter is None) and (PProblem is None) and (EEvolution is None):

        zdt_definitions = ZDT3Definitions()
        plotter = Plotter(zdt_definitions)
        problem = ZDT(zdt_definitions)
        evolution = Evolution(problem, 1, len(population))
        evolution.register_on_new_generation(plotter.plot_population_best_front)
        evolution.register_on_new_generation(collect_metrics)
    else:
        zdt_definitions=Zdt_definitions
        plotter=PPlotter
        problem=PProblem
        evolution=EEvolution


    new_pop,objectives,self_population,Final_label,K= evolution.evolve(population,MSR, RV, BI_size, population_K,nsol, new_msr, new_rv, new_bisize, new_K,generation,self_population,population_label,children_label)

    return new_pop,objectives,self_population,zdt_definitions,plotter,problem,evolution,Final_label,K
 def _createPlotterProc(self):
     saveFigPath = None
     if self._keyboardListener.saveFlag:
         saveFigPath = self._fileIO.filePath[:-4] + self._figExtention
     plotter = Plotter()
     proc = Process(target=plotter.plot,
                    kwargs={
                        'axesNames': self._plotAxes,
                        'labelNames': self._plotLabels,
                        'engineeringFormat': self._plotEngineeringFormat,
                        'figSize': self._plotFigSize,
                        'markersize': self._plotMarkerSize,
                        'plotLabelFormat': self._plotLabelFormat,
                        'updateInterval': self._plotUpdateInterval,
                        'saveFigPath': saveFigPath,
                        'keepFig': self._keepFig
                    })
     proc.start()
     return plotter, proc
示例#35
0
    def testDayPlot(self):
        
        granularity = 86400
        
        end_time_str = '2016-01-01 12:00:00.000000'
        end_time = datetime.datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S.%f')
        
        duration = granularity * 300
        start_time = end_time - timedelta(seconds=duration)
        
        range_df = self.data.getHistoryRange(start_time, end_time, granularity)

        range_df['time'] = range_df.index
        print (range_df.head(20))
        
        
        plot = Plotter.showPlot(range_df)

        assert(True)
示例#36
0
def main():
    config = "end"
    num = 5
    remove_peg = 11
    examples = make_state_space()
    default_state_space = examples[num]
    a = Plotter('fig/remove_peg' + str(remove_peg) + '_' + config + '_state_' +
                str(num) + '.png')
    action_space = ActionSpace(default_state_space)
    end_state = action_space.remove_convex(default_state_space, remove_peg)
    if config == "end":
        a.plot(end_state)
    else:
        a.plot(default_start_state)
示例#37
0
文件: qaobject.py 项目: jyamu/qmc
class QAobject(Pobj):

    _global = obj()
    _global.dynamic_methods_objects = []

    plotter = Plotter()

    opt_methods = set(['opt', 'linear', 'cslinear'])

    def __init__(self):
        return

    #end def __init__

    @staticmethod
    def condense_name(name):
        return name.strip().lower().replace(' ', '_').replace('-',
                                                              '_').replace(
                                                                  '__', '_')

    #end def condense_name

    def _register_dynamic_methods(self):
        QAobject._global.dynamic_methods_objects.append(self)
        return

    #end def _register_dynamic_methods

    def _unlink_dynamic_methods(self):
        for o in QAobject._global.dynamic_methods_objects:
            o._unset_dynamic_methods()
        #end for
        return

    #end def _unlink_dynamic_methods

    def _relink_dynamic_methods(self):
        for o in QAobject._global.dynamic_methods_objects:
            o._reset_dynamic_methods()
        #end for
        return
示例#38
0
def initialize_plotting(hyperparameter_space: dict):
    # Initialize video object
    DEFAULT_VIDEO_DIR = "videos"

    if not os.path.exists('figures'):
        os.makedirs('figures')
    if not os.path.exists(DEFAULT_VIDEO_DIR):
        os.makedirs(DEFAULT_VIDEO_DIR)
    if not os.path.exists('logs'):
        os.makedirs('logs')
    if not os.path.exists('results'):
        os.makedirs('results')

    video = VideoRecorder(DEFAULT_VIDEO_DIR if hyperparameter_space.get('save_video') else None)

    # Init the Plotter
    plotter = Plotter(hyperparameter_space.get('episodes'))

    video.init()
    recording_interval = hyperparameter_space.get('recording_interval')
    return video, plotter, recording_interval
示例#39
0
    def t_sweep(self):
        t = self.time()
        g=self.gain()
        max_voltage = float(gains[str(g)])
        data_pts = []
        time_pts = []
        ch = self.channel()
        dc= self.duty_cycle()
        
        run_adapwm(self.channel(), 0)
        time.sleep(1)

        start_time = time.time()
        
        run_adapwm(ch, dc)
        while time.time()-start_time < t:
            data_pts.append(self.adaadc().read_adc(0, gain=g))
            time_pts.append(time.time())

        discharge_t = time.time()

        run_adapwm(self.channel(), 0)
        while time.time() - discharge_t < 4:
            data_pts.append(self.adaadc().read_adc(0, gain=g))
            time_pts.append(time.time())
        
        max_voltage = float(gains[str(g)])
            
        voltages = np.array(data_pts)*max_voltage/2**15
        times = np.array(time_pts) - start_time

        file = open(str(self.name()), "w")
        file.write("Time [s] \t Voltage \t Gain=" + str(max_voltage) + "\n")

        for i in range(voltages.size): 
            file.write(str(times[i]) + "\t" + str(voltages[i])+"\n")

        file.close()
        
        Plotter(self.name()).show_plot(title="time sweep", x_axis="time [s]", y_axis="Voltage [V]")
示例#40
0
class TestBasicPlotter:

    plotter = Plotter()

    def test_virtual(self):
        assert self.plotter.virtual == True

    def test_status_report(self):
        self.plotter.status()

    def test_defaults_of_default_plotter(self):
        assert (self.plotter.angles_to_pw_1 ==
                self.plotter.naive_angles_to_pulse_widths_1)
        assert (self.plotter.angles_to_pw_2 ==
                self.plotter.naive_angles_to_pulse_widths_2)
        assert self.plotter.get_pulse_widths() == (1500, 1500)

    def test_can_land_at_0_degrees(self):
        self.plotter.set_angles(0, 0)
        assert (self.plotter.angle_1, self.plotter.angle_2) == (0, 0)

    def test_xy(self):
        self.plotter.xy(0, 6)
示例#41
0
def main():
    lv = LaunchVehicle()
    plotter = Plotter()

    # Initialise state
    time_s = 0.0
    dt = 0.0005

    # Run simulation
    print("Simulating flight...")
    while(time_s < 4.0 or lv.state.pos > 0.0):
        lv.update(time_s, dt)
        plotter.serialise(time_s, lv)
        time_s += dt

    # Show results
    print("Complete.")
    plotter.display_results(lv._motor.motor_name+".png")
示例#42
0
def simulation():

    real_mu = 0 * np.pi

    model_mu = 0 * np.pi
    model_rho = -0.35 * np.pi
    stime = 50000

    rng = np.random.RandomState()
    plotter = Plotter(time_window=stime)

    # init the generative model (agent) and the generative process
    # (environment)
    gprocess = Env(rng)
    gmodel = Model(rng, mu=model_mu, rho=model_rho)

    state = gprocess.reset(mu=real_mu)
    for t in range(stime):

        # Update model via gradient descent and get action
        action = gmodel.update(state)

        # Generated fake sensory state from model
        gstate = gmodel.gstate

        # do action
        state = gprocess.step(action)

        # update plot every n steps
        plotter.append_mu(gprocess.mu, gmodel.mu)
        if t % 1000 == 0 or t == stime - 1:
            plotter.sensed_arm.update(state[0], state[1:])
            plotter.real_arm.update(gprocess.istate[0], gprocess.istate[1:])
            plotter.generated_arm.update(gstate[0], gstate[1:])
            plotter.target_arm.update(gmodel.rho, g(gmodel.rho))
            plotter.update()

    input("Press any button to close.")
示例#43
0
import numpy as np
import sys

from plotter import Plotter

x = np.linspace(-np.pi, np.pi, 201)

to_plot = [
    {
        "title": "Example 1",
        "type": "plot",
        "data": [x, np.sin(x)]
    },
    {
        "title": "Example 2",
        "type": "matrix",
        "data": np.random.random((100, 100))
    },
]

pl = Plotter(to_plot, figsuptitle="Multi-plot")
pl.show()
示例#44
0
    netD.cuda()
    netG.cuda()
    netT.cuda()
    criterion_D.cuda()
    criterion_G.cuda()
    criterion_T.cuda()
    inputs, label = inputs.cuda(), label.cuda()
    noise, fixed_noise = noise.cuda(), fixed_noise.cuda()

# fixed_noise = Variable(fixed_noise)

# Plotters
plot_gan_loss = Plotter("%s/gan_loss.jpeg" % (opt.plotdir),
                        num_lines=2,
                        legends=["g_loss", "d_loss"],
                        xlabel="Number of iterations",
                        ylabel="Loss",
                        title="GAN Loss vs Iterations(%s->%s)" %
                        (opt.sourceDataset, opt.targetDataset))

plot_clf_loss = Plotter("%s/%s_clf_loss.jpeg" %
                        (opt.plotdir, opt.sourceDataset),
                        num_lines=1,
                        legends=[""],
                        xlabel="Number of iterations",
                        ylabel="Loss",
                        title="Classifier loss vs Iterations(%s->%s)" %
                        (opt.sourceDataset, opt.targetDataset))

plot_source_acc = Plotter("%s/%s_clf_acc.jpeg" %
                          (opt.plotdir, opt.sourceDataset),
示例#45
0
				return 'q'
			elif link_length.isdigit():
				link_length = int(link_length)
				link_lengths.append(link_length)
			else:
				print("Invalid input!")
				link_length = None

	return link_lengths



while True:

	
	plotter = Plotter()

	link_lengths = None
	start_cood = None
	end_cood = None
	obs_coods = None

	ga_genr_2 = 250
	ga_genr_3 = 20
	ga_genr = None
	ga_pop_sz = 40
	ga_mut_ratio = 0.05
	ga_xov_ratio = 0.30
	ga_mu_2 = [0.5,0.5]
	ga_mu_3 = [0.4,0.3,0.3]
	ga_mu = None
示例#46
0
 def plot(self, fig, flag=True):
     """plot grafica la solución actual."""
     if flag:
         pt = Plotter(self.locations, self.facilities, self.p,
                      self.travel_cost)
         pt.plot_results(fig)
    "x3": np.random.sample(1000),
    "x4": np.random.randint(10, size=1000).tolist()
})
y = df.apply(lambda row: set_target(row), axis=1)
print(y.value_counts())
X_train, X_test, y_train, y_test = train_test_split(df, y, random_state=seed)

# --- Model Training
model = LogisticRegression(random_state=random.seed(seed))
model.fit(X_train, y_train)

test_score = model.score(X_test, y_test)
print(test_score)

# --- SHAP
explainer = shap.LinearExplainer(model, X_train)
shap_values = explainer.shap_values(X_train)
shap.summary_plot(shap_values, X_train, plot_type="bar")

# --- DOE
dx = DoeXai(x_data=X_train,
            y_data=y_train,
            model=model,
            feature_names=list(df.columns))
cont = dx.find_feature_contribution(
    user_list=[["x1", "x2", "x3"], ["x1", "x2"], ["x1", "x3"], ["x3", "x2"]])
print(cont)

# --- Plot
p = Plotter(X_train)
p.plot_doe_feature_contribution(cont)
示例#48
0
print(args)

# wavelengths seperation between elements and reference
phi_domain = np.linspace(args.phi_min, args.phi_max, args.phi_points)
Z = np.zeros((args.phi_points, args.phi_points))

if args.array_geometry_file:
    arr = antenna_array.AntennaArray.mk_from_config(args.array_geometry_file)
else:
    if args.with_ref_element == True:
        arr = antenna_array.AntennaArray.mk_circular_with_ref(
            args.radius, args.elements)
    else:
        arr = antenna_array.AntennaArray.mk_circular(args.radius,
                                                     args.elements)
for antenna in arr.antennas:
    print("{x}, {y}".format(x=antenna.x, y=antenna.y))

for phi_idx, phi_val in enumerate(phi_domain):
    ref = arr.each_pair_phase_difference_at_angle(phi_val, args.freq)
    corr = Correlator(ref, arr)
    response = corr.many_directions(args.phi_min, args.phi_max,
                                    args.phi_points, args.freq)
    y = response.keys()
    y.sort()
    for i_idx, i_val in enumerate(y):
        Z[phi_idx, i_idx] = response[i_val]

Plotter(phi_domain, y, Z).colourmap()
#plotter.Plotter(x_domain, y, Z).surface()
示例#49
0
class elmanUi(Tk):
    def __init__(self):
        Tk.__init__(self)

        self.updatesQueue = multiprocessing.JoinableQueue()
        self.plotter = Plotter(self.updatesQueue)
        self.elman = None

        self.title("HW7")

        self.arch = Entry(self)
        self.backRate = Entry(self)
        self.learningRate = Entry(self)
        self.batchSize = Entry(self)
        self.seriesNum = Entry(self)
        self.stepNum = Entry(self)
        self.networkAddress = Entry(self)

        self.errorFunc = StringVar()

    def add_entry(self):
        Label(self, text="Add Parameter for Elman learning").grid(row=0)
        Label(self, text="Architecture").grid(row=3)
        Label(self, text="BakhpropagationRates").grid(row=4)
        Label(self, text="LearningRates").grid(row=5)
        Label(self, text="BatchSize").grid(row=6)
        Label(self, text="SeriesNum").grid(row=7)
        Label(self, text="StepsNum").grid(row=8)
        Label(self, text="NetworkAdress").grid(row=9)

        Button(self, text="Train", command=self.train).grid(row=19,
                                                            column=0,
                                                            sticky=W,
                                                            pady=4)
        # Button(self, text="Save Weights", command=self.save_weights).grid(row=11, column=1, sticky=W, pady=4)

        self.arch.grid(row=3, column=1)
        self.backRate.grid(row=4, column=1)
        self.learningRate.grid(row=5, column=1)
        self.batchSize.grid(row=6, column=1)
        self.seriesNum.grid(row=7, column=1)
        self.stepNum.grid(row=8, column=1)
        self.networkAddress.grid(row=9, column=1)

        self.arch.insert(0, "1,1,1")
        self.backRate.insert(0, 1)
        self.learningRate.insert(0, 0.01)
        self.batchSize.insert(0, 1)
        self.seriesNum.insert(0, 1)
        self.stepNum.insert(0, 1)

        Radiobutton(self,
                    text="MSE",
                    padx=20,
                    variable=self.errorFunc,
                    value="MSE").grid(row=11, column=0, sticky=W, pady=4)
        Radiobutton(self,
                    text="MAE",
                    padx=20,
                    variable=self.errorFunc,
                    value="MAE").grid(row=12, column=0, sticky=W, pady=4)
        Radiobutton(self,
                    text="RMAE",
                    padx=20,
                    variable=self.errorFunc,
                    value="RMAE").grid(row=13, column=0, sticky=W, pady=4)
        Radiobutton(self,
                    text="PI",
                    padx=20,
                    variable=self.errorFunc,
                    value="PI").grid(row=14, column=0, sticky=W, pady=4)

    def train(self):

        arch = [int(c) for c in str(self.arch.get()).strip().split(',')]
        backR = float(self.backRate.get())
        learnR = float(self.learningRate.get())
        bs = int(self.batchSize.get())
        serie = int(self.seriesNum.get())
        step = int(self.stepNum.get())
        errFunc = self.errorFunc.get()

        if not self.plotter.is_alive():
            self.plotter.start()

        if self.elman is not None:
            if self.elman.exitcode != 0:
                print 'Another learner is working.'
                return
            self.elman.terminate()

        self.elman = elmanNet.Elman(self.updatesQueue, 1, 1, 1)
        self.elman.start()
示例#50
0
def main():
    plotter = Plotter()

    print("read polygon.csv")
    # Init polygen_points to store points in the polygen
    polygen_points = []

    # Read polygon.csv
    with open('polygon.csv', 'r') as f:
        for line in f:
            if not line.startswith('id'):
                id = line.split(',')[0].strip()
                x = float(line.split(',')[1].strip())
                y = float(line.split(',')[2].strip())
                # Init a Point object
                point = Point(id, x, y)
                # Add the Point object to the list of points
                polygen_points.append(point)

    # Init a Polygon object
    polygen = Polygon('polygen', polygen_points)

    print("read input.csv")
    # Init test_points to store points to be tested
    test_points = []
    # Read input.csv
    with open('input.csv', 'r') as f:
        for line in f:
            if not line.startswith('id'):
                id = line.split(',')[0].strip()
                x = float(line.split(',')[1].strip())
                y = float(line.split(',')[2].strip())
                # Init a Point object
                point = Point(id, x, y)
                # Add the Point object to the list of test points
                test_points.append(point)

    print("categorize points")
    test_points_categories = []
    for id, test_point in enumerate(test_points):
        category = find_category(polygen, test_point)
        test_points_categories.append(category)

    print("write output.csv")
    with open('output.csv', 'w') as f:
        f.write('id,category\n')
        for i, category in enumerate(test_points_categories):
            f.write(f'{i+1},{category}\n')

    print("plot polygon and points")
    polygen_points = polygen.get_points()
    xs = []
    ys = []
    for polygen_point in polygen_points:
        xs.append(polygen_point.get_x())
        ys.append(polygen_point.get_y())
    plotter.add_polygon(xs, ys)
    for id, test_point in enumerate(test_points):
        plotter.add_point(test_point.get_x(), test_point.get_y(),
                          test_points_categories[id])

    plotter.show()
示例#51
0
    1: f1,
    2: f2,
    3: f3,
    4: f4,
    5: f5,
    6: f6,
    7: f7,
    8: f8,
    9: f9,
    10: f10
}
f, side = switcher.get(fnumber), int(argv[sideidx])
(first_xys, first_zs) = train_data(side, f, False)
if argv[1] == "view":
    points = first_xys + ast.literal_eval(argv[4])
    trip = Trip(f, (0, 0), points, probe(f, points), 100, Plotter('surface'),
                0)
    trip.select_kernel()
    trip.fit(n_restarts_optimizer=100)
    trip.plot_pred(argv[5])
    exit(0)
plot, seedval, time_limit, nb, budget, alg, online = argv[1].startswith(
    'plot'), int(argv[2]), float(argv[3]), int(argv[4]), int(
        argv[6]), argv[8], argv[9] == 'on'

# Initial settings.
seed(seedval)
(TSxy, TSz), depot = test_data(f), (-0.00001, -0.00001)
plotter = Plotter('surface') if plot else None

# Create initial model with kernel selected by cross-validation.
示例#52
0
def execute_with_collision(my_world):
    pltr = Plotter()
    for robot in my_world.robots:
        pltr.draw_start_end(robot)
    makespan = max(robot.trajectory[0] for robot in my_world.robots)
    for t in range(100):
        for robot in my_world.robots:
            if robot.trajectory[0] >= t * makespan / 100:
                pltr.plotting(robot.trajectory[1](t * makespan / 100),
                              robot.trajectory[2](t * makespan / 100), 'k')

    for robot in my_world.robots:
        robot.pose[2] = math.atan2(robot.trajectory[4](0),
                                   robot.trajectory[3](0))
        print robot.pose[2]
    exit()
    completed = set()
    while True:
        for robot in my_world.robots:
            del_x = robot.goal[0] - robot.pose[0]
            del_y = robot.goal[1] - robot.pose[1]
            rho = math.sqrt(del_x**2 + del_y**2)

            if abs(rho) < 0.25:
                completed.add(robot.id)
                continue

            t = my_world.time.time()
            vel = (robot.trajectory[3](t)**2 + robot.trajectory[4](t)**2)**0.5
            curv = curvature(robot.trajectory[1], robot.trajectory[2], t)
            robot.cmd_vel(vel, curv * vel)
            robot.update_step(my_world.time.dt)

            pltr.plotting(robot.pose[0], robot.pose[1], robot.color, s=5)
            pltr.mark_time(my_world.time.time())
        pltr.sleep(0.001)
        my_world.time.step()

        if completed == set([r.id for r in my_world.robots]):
            pltr.sleep(1)
            pltr.close('all')
            metric(my_world)
            break
示例#53
0
def execute_wo_collision(my_world):
    pltr = Plotter()
    for robot in my_world.robots:
        pltr.draw_start_end(robot)
    makespan = max(robot.trajectory[0] for robot in my_world.robots)
    for t in range(100):
        for robot in my_world.robots:
            if robot.trajectory[0] >= t * makespan / 100:
                pltr.plotting(robot.trajectory[1](t * makespan / 100),
                              robot.trajectory[2](t * makespan / 100), 'k')

    path_len = 0
    for robot in my_world.robots:
        for dt in range(1000):
            if dt == 0:
                continue
            t = robot.trajectory[0] * dt / 1000
            t_1 = robot.trajectory[0] * (dt - 1) / 1000
            dx = robot.trajectory[1](t) - robot.trajectory[1](t_1)
            dy = robot.trajectory[2](t) - robot.trajectory[2](t_1)
            path_len += (dx**2 + dy**2)**0.5
    # print "Total path length", path_len

    for robot in my_world.robots:
        robot.pose[2] = math.atan2(robot.trajectory[4](0),
                                   robot.trajectory[3](0))
    completed = set()

    total_time = 0
    while True:
        for robot in my_world.robots:
            del_x = robot.goal[0] - robot.pose[0]
            del_y = robot.goal[1] - robot.pose[1]
            rho = math.sqrt(del_x**2 + del_y**2)

            if abs(rho) < 0.25:
                if robot.id not in completed:
                    completed.add(robot.id)
                    total_time += my_world.time.time()
                continue

            t = my_world.time.time()
            for pt_id, pt in enumerate(robot.collision_points):
                # print ((robot.pose[0] - pt[0])**2 + (robot.pose[1] - pt[1])**2)**0.5
                if ((robot.pose[0] - pt[0])**2 +
                    (robot.pose[1] - pt[1])**2)**0.5 < 1:
                    print robot.id, " has changed its speed."
                    if robot.collision_priority[pt_id] == 'inc':
                        scaling_polynomial = np.poly1d([2, -t])
                    else:
                        scaling_polynomial = np.poly1d([0.5, t / 2])
                    robot.trajectory[1] = np.polyval(robot.trajectory[1],
                                                     scaling_polynomial)
                    robot.trajectory[2] = np.polyval(robot.trajectory[2],
                                                     scaling_polynomial)
                    robot.trajectory[3], robot.trajectory[4] = np.polyder(
                        robot.trajectory[1]), np.polyder(robot.trajectory[2])
                    del (robot.collision_points[pt_id])
                    del (robot.collision_priority[pt_id])
                    # del(robot.collision_with[pt_id])

            if len(robot.collision_points) != len(robot.collision_impending):
                r2 = robot.collision_with[0]
                if ((r2.pose[0] - robot.pose[0])**2 +
                    (r2.pose[1] - robot.pose[1])**2)**0.5 > 2.3:
                    print robot.id, " is back to its original speed."
                    if robot.id < r2.id:
                        scaling_polynomial = np.poly1d([0.5, t / 2])
                    else:
                        scaling_polynomial = np.poly1d([2, -t])
                    robot.trajectory[1] = np.polyval(robot.trajectory[1],
                                                     scaling_polynomial)
                    robot.trajectory[2] = np.polyval(robot.trajectory[2],
                                                     scaling_polynomial)
                    robot.trajectory[3], robot.trajectory[4] = np.polyder(
                        robot.trajectory[1]), np.polyder(robot.trajectory[2])
                    del (robot.collision_impending[0])
                    del (robot.collision_with[0])

            x_der = np.polyder(robot.trajectory[1])
            y_der = np.polyder(robot.trajectory[2])
            vel = (x_der(t)**2 + y_der(t)**2)**0.5
            curv = curvature(robot.trajectory[1], robot.trajectory[2], t)
            robot.cmd_vel(vel, curv * vel)
            robot.update_step(my_world.time.dt)

            pltr.plotting(robot.pose[0], robot.pose[1], robot.color, s=5)
            pltr.mark_time(my_world.time.time())
        pltr.sleep(0.001)
        my_world.time.step()

        if completed == set([r.id for r in my_world.robots]):
            pltr.sleep(1)
            pltr.close('all')
            print "Makespan: ", my_world.time.time()
            print "Total time: ", total_time
            print "Total path len: ", path_len
            break
示例#54
0
        return new_weights

    def run_generation(self, initial_bots):
        bots = []
        new_weights = []
        for bot1, bot2 in combinations(initial_bots, 2):
            new_weights.extend(self.reproduce(bot1, bot2, 20))
        print(len(new_weights))
        for weights in new_weights:
            bots.append((weights, self.run_test(weights)))
        return bots


if __name__ == "__main__":
    factory = BotFactory(default_settings)
    plotter = Plotter()
    bots = []

    if factory.settings.initial_seed is not None:
        initial_bot_weights = repeat(factory.settings.initial_seed, 10)
        for weights in initial_bot_weights:
            bots.append((weights, 99.0))
    else:
        initial_bot_weights = (2 * random((10, 10))) - 1
        for weights in initial_bot_weights:
            bots.append((weights, factory.run_test(weights)))

    for i in range(factory.settings.generation_amount):
        sorted_bots = sorted(bots, key=lambda tup: tup[1], reverse=True)[:2]
        bots = [value[0] for value in sorted_bots]
        print("------------")
示例#55
0
class MasterBoardTask:
    def __init__(self, trajectory_queue):
        #Instatiate Master Board and the plotter

        self.plotter = Plotter(f"Trapeze velocity profile | kp = {Config.kp}, kd = {Config.kd}, current saturation = {Config.current_saturation} A")

        self.master_board = MasterBoard(self.plotter)

        #Initiate global variables
        self.trajectory_queue = trajectory_queue
        self.trajectory = None

        self.num_joints = Config.num_joints

        self.encoder_readings = []

        self._running = True
        self._should_print = False
        #Initiate plots

        

        for i in range(Config.num_joints):
            self.plotter.create_plot(f"Joint {i}, Position Reference", "Position Reference [rad]")
            self.plotter.create_plot(f"Joint {i}, Position Reading", "Position Reading [rad]")
            self.plotter.create_plot(f"Joint {i}, Velocity Reference", "Velocity Reference [rad/s]")
            self.plotter.create_plot(f"Joint {i}, Velocity Reading", "Velocity Reading [rad/s]")
            self.plotter.create_plot(f"Joint {i}, Current Reference", "Current Reference [Ampere]")
            #self.plotter.create_plot(f"Joint {i}, Position Error", "Position Error [rad]")

    def run(self):
        print("Master board task started")

        #Initiate local variables
        t = 0

        timeout = False

        last = perf_counter()

        q = self.master_board.get_state()[0]
        q_prime = np.zeros(8)

        #Main loop
        #Executes every time step untill keyboardinterrupt or master_board sets timeout = True
        while(not timeout and self._running):
            elapsed_time = perf_counter() - last

            if (elapsed_time >= Config.dt): #Enter this if statement every timestep
                last = perf_counter()
                t += Config.dt

                if self.trajectory != None:
                    #Currently following a trajectory, just get the new values and send them
                    q, q_prime = self.trajectory.step(t)
                    self.master_board.set_reference(q, q_prime)

                    position_reading, velocity_reading = self.master_board.get_state()

                    #Then check if that was the last step, i.e. the trajectory is finished
                    if self.trajectory.Done():
                        #If the trajectory is finished, set it to None so that the next pass will fetch the next trajectory
                        #print("Trajectory finished, waiting for next...")
                        
                        #self.set_points.append(q[0])
                        self.encoder_readings.append(position_reading[0])
                        self.trajectory = None

                else:
                    #Not currently following a trajectory, so try to fetch the next one from the queue
                    try:
                        self.trajectory = self.trajectory_queue.get(block=False)
                        self.trajectory.set_initial_conditions(q, t) #Last reference sent and current time will be the intitial conditions for the trajectory
                    except Empty:
                        self.trajectory = None

                position_reading, velocity_reading = self.master_board.get_state()

                for i in range(self.num_joints):
                    self.plotter.add_data(f"Joint {i}, Position Reference", q[i])
                    self.plotter.add_data(f"Joint {i}, Position Reading", position_reading[i])
                    self.plotter.add_data(f"Joint {i}, Velocity Reference", q_prime[i])
                    self.plotter.add_data(f"Joint {i}, Velocity Reading", velocity_reading[i])
                
                #If a new reference was set, this will make the masterboard track that reference
                #If not, it will keep tracking its previous reference
                #This needs to be called every pass, even though there is no new trajectory, in case the actual position of the joints are changed, e.g. by gravity
                timeout = self.master_board.follow_trajectory()

                self.plotter.add_time(t)

            #Should print is set by InputTask whenever "Position" is input to the terminal
            #This is in an elif block, so that it doesn't increase the duration of a step
            elif self._should_print:
                self.print_current_position(q)

        #shut down the board correctly if the while loop breaks for any reason
        self.master_board.terminate()

        print("\nENCODER READINGS\n")
        for value in self.encoder_readings:
            output = np.degrees(value)
            output = str(output)
            output = output.replace(".", ",")
            print(output)
        print()

        for i in range(Config.num_joints):
            self.plotter.create_axis([f"Joint {i}, Velocity Reading"])
            self.plotter.create_axis([f"Joint {i}, Position Reading"])
       
            self.plotter.create_axis([f"Joint {i}, Current Reference"])
            self.plotter.create_axis([f"Joint {i}, Velocity Reference"])
            self.plotter.create_axis([f"Joint {i}, Position Reference"])
            self.plotter.plot()

    def print_current_position(self, current_pos_ref):
        #Prints the current reference and position of all the motors
        #Meant to be called by the InputTask through the use of synchronized bools
        np.set_printoptions(suppress=True)
        print(f"\nPosition Reference: \n{np.degrees(current_pos_ref).round(5)}\n")
        print(f"Current Position: \n{self.master_board.get_state()[0]}")
        print(f"Position Error: \n{np.degrees(current_pos_ref.round(5) - self.master_board.get_state()[0]).round(5)}")
        self._should_print = False

    def terminate(self):
        self._running = False

    def set_print(self):
        self._should_print = True
示例#56
0
    def sweep(self):
        g=self.gain()
        max_voltage = float(gains[str(g)])
        scale_fac = max_voltage/2**15
        samples = self.duty_cycles()

        data_array = np.zeros([self.__trials, self.N()])
        grounds_array = np.zeros([self.__trials, self.N()])
        references_array = np.zeros([self.__trials, self.N()])
        
        print("collectiing data...")
        print('|trial| point | V | GND | REF |'.format(*range(3)))
        print('-' * 37)

        for i in range(self.__trials):
            run_adapwm(0, 0)
            time.sleep(3)
            for j in range(len(samples)):
                run_adapwm(0, samples[j])
                time.sleep(2)
                # Data pin: A0, ground pin: A1, reference voltage pin: A2.
                data_array[i][j] = self.adaadc().read_adc(0, gain=g, data_rate=8)*scale_fac
                grounds_array[i][j] = self.adaadc().read_adc(1, gain=g, data_rate=8)
                references_array[i][j] = self.adaadc().read_adc(2, gain=g, data_rate=8)
                print(str(i) + " " + str(j)+"\t" + str(data_array[i][j]) + "\t" + str(grounds_array[i][j]) + "\t" + str(references_array[i][j]) +"\n")
        print("Finished collectiing data")
        
        mean_ref = references_array.mean()*scale_fac

        if "%.3f" %  mean_ref== self.reference():
            print("The ADC measured the reference voltage as " + self.reference() + ", as expected.")

        else:
            print("The mean reference voltage measured by the ADC was " + str(references_array.mean()*scale_fac) + ", but expected " + self.reference())

        means = np.zeros(self.N())
        stds = np.zeros(self.N())

        for k in range(self.N()):
            means[k] = data_array.T[k].mean()
            stds[k] = data_array.T[k].std()

        # writing the files!
        off_tick_scale_fac = 4095./100.
        mean_file = open("means_" + self.name(), "w")
        mean_file.write("Duty cycle off_tick" + "\tmean_voltage[V]" + "\tstd dev[V]" + "\tINFO: gain="+str(max_voltage) + "\treference=" + self.reference() + "\ttrials="+str(self.__trials)+"\n")
        for l in range(self.N()):
            mean_file.write(str(samples[l]*off_tick_scale_fac) + "\t" + str(means[l]) + "\t" + str(stds[l]) + "\n")
        mean_file.close()

        raw_file = open("raw_"+self.name(), "w")
        raw_file.write("\nraw_voltage_data\n")
        for m in data_array:
            for mi in range(m.size):
                raw_file.write(str(m[mi]) + " ")
            raw_file.write("\n")

        raw_file.write("\nraw_ground_pin_data\n")
        for n in grounds_array:
            for ni in range(n.size):
                raw_file.write(str(n[ni]) + " ")
            raw_file.write("\n")

        raw_file.write("\nraw_ref_voltage_data\n")
        for o in references_array:
            for oi in range(o.size):
                raw_file.write(str(o[oi]) + " ")
            raw_file.write("\n")
            
        Plotter("means_"+self.name()).stat_plot(title="PWM sweep", x_axis="PWM off tick", y_axis="Voltage [V]")
示例#57
0
class Renderer:
    """The default software renderer of the game"""
    def __init__(self):
        self.SCREEN = pygame.display.set_mode(settings.SCREEN_SIZE)
        self.plotter = Plotter()

        current_directory = os.path.dirname(os.path.realpath(__file__))
        wall_texture_folder_path = os.path.join(current_directory,
                                                "assets/textures/surfaces")

        sprite_texture_folder_path = os.path.join(current_directory,
                                                  "assets/textures/objects")

        self.WALL_TEXTURES = asset_loader.get_textures(
            wall_texture_folder_path)

        self.SPRITE_TEXTURES = asset_loader.get_textures(
            sprite_texture_folder_path)

        # init the z buffer to the size of the screen. This is faster than using append() and clear()
        self._wall_z_buffer = [None] * settings.SCREEN_WIDTH

    def _darken(self, surface):
        "This method takes in a surface and drops its brightness in half"

        # we create a new rectangle with the same dimensions as the texture
        darkened_surface = pygame.Surface(surface.get_size())

        # we set the brightness of this surface to 128/half (255 is max)
        darkened_surface.set_alpha(128)

        # Apply the darken mask to the original surface from its origin (x:0, y:0)
        surface.blit(darkened_surface, (0, 0))

    def _draw_ui(self, player, fps):
        if (__debug__):
            start_position = Vector2(10, 5)
            self._draw_debug(player, fps, start_position)

    def _draw_debug_text(self, font, text, position):

        text = font.render(text, True, colors.YELLOW)

        self.SCREEN.blit(text, (position.x, position.y))
        position.y = position.y + 35

    def _draw_debug(self, player, fps, start_position):
        basicfont = pygame.font.SysFont(None, 48)

        fps_text = f'fps: {fps}'
        player_x_text = f'x: {player.position.x:.2f}'
        player_y_text = f'y: {player.position.y:.2f}'
        player_rotation_text = f'rotation: {player.get_rotation_degrees():.0f}'

        self._draw_debug_text(basicfont, fps_text, start_position)
        self._draw_debug_text(basicfont, player_x_text, start_position)
        self._draw_debug_text(basicfont, player_y_text, start_position)
        self._draw_debug_text(basicfont, player_rotation_text, start_position)

    def _draw_floor(self):
        # fill screen with back buffer color and then draw the ceiling/sky.
        self.SCREEN.fill(colors.FLOOR_GRAY)

    def _draw_wall_line(self,
                        x,
                        start,
                        height,
                        image_slice,
                        side=Side.TopOrBottom):
        # figure out the position and size of the vertical line we want to draw on screen
        scale_rect = pygame.Rect(x, start, 1, height)

        # put the area of the image we want into the space we want to put on screen
        scaled = pygame.transform.scale(image_slice, scale_rect.size)

        # draw the scaled line where we want to on the screen.
        if (side == Side.LeftOrRight):
            self._darken(scaled)

        self.SCREEN.blit(scaled, scale_rect)

    def _get_wall_texture_slice(self, ray_direction, wall_x_percentage_across,
                                texture, side):
        # wall x will be somewhere between 0 and 1 (eg, 25% across will be 0.25)
        # figure out how many pixels across the texture to be in x
        # we cast to an int to floor the value as we cannot start drawing at a non integral
        # x value
        texture_x = int(wall_x_percentage_across * texture.get_width())

        # get the width of the texture where column 1 = 0, col 2 = 1 and so on.
        zero_indexed_width = texture.get_width() - 1

        # if side is left/right and we are travelling right, we have hit a LEFT side
        # draw the texture from right to left (NOT left to right as normal)
        # as otherwise we will draw the texture backwards like we are behind it.
        if side == Side.LeftOrRight and ray_direction.x > 0:
            texture_x = zero_indexed_width - texture_x

        # if side is top/bottom and we are travelling down, we have hit a TOP side.
        # draw the texture from right to left (NOT left to right as normal)
        # as otherwise we will draw the texture backwards like we are behind it.
        if side == Side.TopOrBottom and ray_direction.y < 0:
            texture_x = zero_indexed_width - texture_x

        # get the part of the image we want to draw from the texture
        image_location = pygame.Rect(texture_x, 0, 1, texture.get_height())
        image_slice = texture.subsurface(image_location)

        return image_slice

    def _perform_dda(self, distance_to_side, distance_delta, step, side,
                     map_pos):

        # jump to next map square, OR in x-direction, OR in y-direction - whichever is the closest side.
        if distance_to_side.x < distance_to_side.y:

            # increase the distance to side x by 1 map unit in x on the direction of this vector.
            # This means we will go from touching the next left/right side wall the the wall 1 unit after that.
            distance_to_side.x += distance_delta.x

            # increase the mapX index by 1/-1 depending on direction.
            map_pos.x += step.x

            # we are moving in x, so the current side to check is the left or right side.
            side = Side.LeftOrRight

        else:
            # increase the distance to side x by 1 map unit in y on the direction of this vector.
            # This means we will go from touching the next top/bottom side wall the the wall 1 unit after that.
            distance_to_side.y += distance_delta.y

            # increase the mapY index by 1/-1 depending on direction.
            map_pos.y += step.y

            # we are moving in y, so the current side to check is the top or bottom side.
            side = Side.TopOrBottom

        # Check if ray has hit a wall
        map_tile = settings.MAP[int(map_pos.x)][int(map_pos.y)]

        # we return two values here to get around the immutability of ints in python (an enum is basically an int!)
        if map_tile > 0 and map_tile < 10:
            return True, side
        else:
            return False, side

    def _get_wall_texture_for_block(self, map_pos):
        # get wall texture to use. -1 so we can start at index 0 of texture array
        texture_index = settings.MAP[int(map_pos.x)][int(map_pos.y)] - 1
        texture_index = max(0, texture_index)
        return self.WALL_TEXTURES[texture_index]

    def _draw_walls(self, player):

        for x in range(0, settings.SCREEN_WIDTH):

            # which box of the map we're in
            map_pos = Vector2()
            map_pos.x = int(player.position.x)
            map_pos.y = int(player.position.y)

            ray_direction = self.plotter.get_ray_direction(x, player)

            distance_delta = self.plotter.get_distance_delta(ray_direction)

            # length of ray from current position to next x or y-side
            distance_to_side = self.plotter.get_distance_to_side(
                player.position, map_pos, ray_direction, distance_delta)

            # what direction to step in x or y-direction (either +1 or -1)
            step = Vector2()
            step.x = -1 if ray_direction.x < 0 else 1
            step.y = -1 if ray_direction.y < 0 else 1

            side = Side.LeftOrRight  # was a NS or a EW wall hit?

            # perform DDA
            hit = False
            while not hit:
                hit, side = self._perform_dda(distance_to_side, distance_delta,
                                              step, side, map_pos)

            # Calculate distance projected on camera direction (oblique distance will give fisheye effect!)
            perceptual_wall_distance = self.plotter.get_perceptual_wall_distance(
                side, player, map_pos, step, ray_direction)

            # Calculate height of line to draw on screen
            # we bring this into screen space by calculating as distance 1 (at the same point as the camera plane) = screenheight. Distance 2 = 1/2 screenheight. Distance 0.5 = 2 * screenheight.
            # This makes sure the further away we are the smaller the line is and the closer the taller the line is, making sure the screen is filled by objects in the same place as the camera.
            line_height = self.plotter.get_object_size_based_on_distance(
                perceptual_wall_distance)

            # calculate lowest and highest pixel to fill in current stripe
            # a start of a line can be through of as half the line up (-y) from the center of the screen in y (screen height /2).
            draw_start = (-line_height / 2) + settings.HALF_SCREEN_HEIGHT

            texture = self._get_wall_texture_for_block(map_pos)

            wall_x_across_percentage = self.plotter.get_wall_x_across_percentage(
                side, player.position, ray_direction, perceptual_wall_distance)

            # get which pixel in x from the texture we want to use
            # it's too expensive to set each pixel directly so we
            # map the line we want from the texture and draw that directly
            # to the screens surface.
            texture_slice = self._get_wall_texture_slice(
                ray_direction, wall_x_across_percentage, texture, side)

            self._draw_wall_line(x, draw_start, line_height, texture_slice,
                                 side)

            # add this to z buffer
            self._wall_z_buffer[x] = (perceptual_wall_distance)

    def _get_sprite_positions(self, player):
        # find all sprites on the map!
        sprite_positions = []

        for column in range(len(settings.MAP)):

            for y in range(len(settings.MAP[column])):

                value = settings.MAP[column][y]

                if value > 10 and value < 20:  # ignore non sprite objects
                    sprite_pos = Vector2(column + 0.5, y + 0.5)
                    distance_from_player = abs(
                        (player.position - sprite_pos).length())
                    sprite = Sprite(value, sprite_pos, distance_from_player)
                    sprite_positions.append(sprite)

        # sort sprite positions so the ones furthest away are drawn first
        sprite_positions.sort(key=lambda column: column.distance_from_player,
                              reverse=True)

        return sprite_positions

    def _draw_sprite_columns(self, distance_from_player, sprite_draw_start,
                             sprite_texture):

        current_width = sprite_texture.get_width()
        current_height = sprite_texture.get_height()

        for column in range(current_width):

            # check z buffer (clamp index first)
            x_check = int(sprite_draw_start.x + column)
            x_check = max(x_check, 0)
            x_check = min(x_check, settings.SCREEN_WIDTH - 1)

            if self._wall_z_buffer[x_check] > distance_from_player:

                # draw sprite vertical line
                location = pygame.Rect(column, 0, 1, current_height)
                slice = sprite_texture.subsurface(location)

                sprite_image_location = (sprite_draw_start.x + column,
                                         sprite_draw_start.y)

                self.SCREEN.blit(slice, sprite_image_location)

    def _draw_sky(self, player):
        # load the sky texture
        current_directory = os.path.dirname(os.path.realpath(__file__))
        sky_texture_folder_path = os.path.join(
            current_directory, "assets/textures/skies/sky1.png")
        sky_texture = pygame.image.load(sky_texture_folder_path)

        # calculate how much of the sky texture should be on screen
        # based on how much the current FOV
        fov_over_circle_ratio = settings.FOV / constants.FULL_CIRCLE_IN_RADIANS

        sky_texture_window_width = sky_texture.get_width(
        ) * fov_over_circle_ratio

        sky_texture_window_width = sky_texture_window_width * (
            constants.HALF_CIRCLE_IN_RADIANS / settings.FOV)

        # avoid a divide by zero
        player_rotation_in_degrees = max(player.get_rotation_degrees(), 1)

        # use degrees here to avoid a negative value (player radian rotation can be negative)
        portion = player_rotation_in_degrees / 360

        x_start_pos = portion * sky_texture_window_width

        # get the part of the image we want to draw from the texture
        image_location = pygame.Rect(x_start_pos, 0, sky_texture_window_width,
                                     sky_texture.get_height())
        sky_texture_slice = sky_texture.subsurface(image_location)

        # scale that slice so it will fit the top half of the screen
        sky_texture_slice_scaled = pygame.transform.scale(
            sky_texture_slice,
            (int(settings.SCREEN_WIDTH), int(settings.HALF_SCREEN_HEIGHT)))

        #the sky texture scaled slice should be draw from the top left (x = 0, y = 0)
        self.SCREEN.blit(sky_texture_slice_scaled, (0, 0))

    def render(self, player, fps):
        """This method draws everything to the screen"""
        self._draw_floor()
        self._draw_sky(player)
        self._draw_walls(player)
        self._draw_ui(player, fps)

        # Go ahead and update the screen with what we've drawn.
        # This MUST happen after all the other drawing commands.
        pygame.display.update()
示例#58
0
from datetime import datetime
from agent import *

max_score = 0
acc_score = 0
mean_score = 0
mean_rewards = 0
num_episodes_played = 0
num_moves_played = 0
t_counter = 0
t_max_count = 0

replaybuffer = ReplayBuffer(1000000)

agent = DQNAgent((20, 10, 1), len(TetrisEnvironment.actions))
plotter = Plotter(datetime.now().strftime("%Y-%m-%d-%H:%M:%S"))


def draw_training_info(tetris_environment, reward, actionidx):
    print('')
    print('==== LEARNING STUFF ====')
    print('last action = {}'.format(TetrisEnvironment.actions[actionidx]))
    print('last reward = {}'.format(reward))
    print('epsilon = {}'.format(agent.epsilon))
    print('num moves played = {}'.format(num_moves_played))
    print('num episodes played = {}'.format(num_episodes_played))
    print('max score = {}'.format(max_score))
    print('mean score = {}'.format(mean_score))
    print('mean rewards last 1000 = {}'.format(mean_rewards))

示例#59
0
 def __init__(self):
     Plotter.__init__(self)
     self.smdata_list = filter(self.is_skymap, self.srtdata_list)
def main():
    london = 'london.csv'
    points = 'england_points.csv'

    plotter = Plotter()

    # calculate and plot the MBR polygon
    polygon_points = import_csv(london)
    poly = list(zip(polygon_points[1], polygon_points[2]))
    MBR_values = MBR(polygon_points)
    mbr = MBR_values.mbr_coordinates()
    plotter.add_polygon(polygon_points[1], polygon_points[2])
    plotter.add_poly_outline(mbr[0], mbr[1])

    # import the individual points
    raw_points = import_csv(points)
    points_id, points = raw_points[0], [raw_points[1], raw_points[2]]
    points_tuple = list(zip(raw_points[1], raw_points[2]))
    original_points = [points_id, points_tuple]

    # Test whether these points are within the Polygon's MBR
    poly_mbr = InsideMBR(points, mbr[0], mbr[1])
    mbr_ = poly_mbr.is_inside()
    coord_inside_mbr, coord_outside_mbr = mbr_[0], mbr_[1]

    # return the points on the vertex of the geometry
    test = Boundary(coord_inside_mbr, poly)
    vertex_points = test.on_vertex()
    res = test.points_on_line()
    coord_boundary, not_classified = res[0], res[1]

    # Enter the non classified points into the RCA
    final_round = RayCasting(not_classified, poly)
    rca = final_round.rca()
    rca_inside, rca_outside = rca[0], rca[1]

    # plot and append all points to individual classified lists
    outside_points, boundary_points, inside_points = [], [], []
    for i in range(len(vertex_points)):
        plotter.add_point(vertex_points[i][0], vertex_points[i][1], 'boundary')
        boundary_points.append(vertex_points[i])
    for i in range(len(coord_outside_mbr)):
        plotter.add_point(coord_outside_mbr[i][0], coord_outside_mbr[i][1],
                          'outside')
        outside_points.append(coord_outside_mbr[i])
    for i in range(len(coord_boundary)):
        plotter.add_point(coord_boundary[i][0], coord_boundary[i][1],
                          'boundary')
        boundary_points.append(coord_boundary[i])
    for i in range(len(rca_outside)):
        plotter.add_point(rca_outside[i][0], rca_outside[i][1], 'outside')
        outside_points.append(rca_outside[i])
    for i in range(len(rca_inside)):
        plotter.add_point(rca_inside[i][0], rca_inside[i][1], 'inside')
        inside_points.append(rca_inside[i])

    # this provides a third list with the points classification
    boundary = [boundary_points, ['boundary'] * len(boundary_points)]
    inside = inside_points, ['inside'] * len(inside_points)
    outside = outside_points, ['outside'] * len(outside_points)

    # join all the points together in one list
    boundary[0].extend(inside[0])
    boundary[1].extend(inside[1])
    boundary[0].extend(outside[0])
    boundary[1].extend(outside[1])

    # Combining the original ID, X and Y, with the classification list.
    original_points = [(y, x)
                       for x, y in zip(original_points[0], original_points[1])]
    id_, classification, xs, ys = [], [], [], []
    for point, flag in original_points:
        index = boundary[0].index(point)
        x, y = point
        id_.append(flag)
        classification.append(
            boundary[1][index]
        )  # returns the classification with the same coordinates as ID
        xs.append(x)
        ys.append(y)
    out_path = 'classified_london_points.csv'
    exportcsv(out_path, id_, classification, xs, ys)

    plotter.show('London Points.png')

    # opening up the CSV with pandas
    df = pd.read_csv('classified_london_points.csv')

    # turn the POINTS X, Y coordinates into point classes
    london_points = df.apply(lambda row: Point(row.x, row.y), axis=1)
    london_points.crs = {'init': 'epsg:27700'}

    # Plots the points with geopandas and matplotlib
    points = gpd.GeoDataFrame(df, geometry=london_points)
    temp = points.to_crs(epsg=3857)
    ax = temp.plot(column=points.classification,
                   categorical=True,
                   markersize=100,
                   legend=True,
                   cmap='tab20')
    ctx.add_basemap(ax)

    plt.ylabel('Northing')
    plt.xlabel('Easting')
    plt.title('Are your points inside or outside London?')

    plt.show()