def main():
	commandline_reminder()

	swRouteFile = '../Geant/Geant_sw_route.json'	
	with open(swRouteFile, 'rb') as ff:
		sw_route = json.load(ff)
	
	""" Result for four dataset in Geant"""
	print "Generating largeFlow throughRate for four dataset in GEANT network ..."
	multi_results = []
	ydelta = 0
	numrows = 2
	numcols = 2
	legend = ['Geant_0108', 'Geant_0215', 'Geant_0324', 'Geant_0401']
	for infile in infile_lst:
		traffic = csvread.csvread(infile)
		traffic = postprocess_traffic(traffic)
		post_sw_route = process_sw_route(sw_route)
		result = largeFlowThrough(traffic, post_sw_route)
		multi_results.append(result)
	
	
	outfile = 'largeFlowThroughSwitch.jpg'
	fig = draw.Draw(outfile)	# create Draw object
	x_axis = sorted([int(sw) for sw in sw_route])
	fig.multidraw_bar_subplot(x_axis, multi_results, numrows, numcols, legend)
	fig.set_title('Avg largeFlow through for each switch, GEANT')
	fig.set_xlabel('Switch ID')
	fig.set_ylabel('LargeFlow through (%)')
	fig.savefig()
 def diy_weapen_callback(self):
     global img_name
     img_name = draw.Draw()
     print(img_name)
     doc_num = input("请输入你想要保存的存档编号:(1-4):")
     save(img_name, True, doc_num)
     animation.model2_skin.refresh(load(True, doc_num)[0])
     self.level_1_callback()
Exemplo n.º 3
0
    def test_draw_from_video(self):
        file_name = "test.mp4"
        vp = processing.VideoProcessor(file_name)
        frames = vp.get_n_stills(12)
        ip = processing.ImgProcessor(frames)
        color_list = ip.average_list()

        draw = d.Draw(color_list)
        draw.draw_image("poster", 3900, 5700)
 def diy_char_callback(self):
     img_name2 = draw.Draw()
     image.image_process(img_name2)
     damage = input("请分配你创建角色的攻击值:(攻击+生命+速度=300)")
     life = input("请分配你创建角色的生命值:(攻击+生命+速度=300)")
     speed = 300 - eval(damage) - eval(life)
     print("damage,life,speed", damage, life, speed)
     doc_num = input("请输入你想要保存的存档编号:(1-4):")
     save(img_name2, False, doc_num, damage, life, speed)
     animation.diy_skin1.refresh(load(False, doc_num)[0])
     self.level_1_callback()
Exemplo n.º 5
0
def drawMarker(pos, color=(1, 1, 1), size=1):
    """Draw a marker.

    \param pos Marker position 
    \param color Marker color
    \param size Marker size (radius)
    """
    try:
        drw = getScene().worldObject("Global_Draw")
    except KeyError:
        drw = draw.Draw(name="Global_Draw")
    drw.marker(pos, color, size)
Exemplo n.º 6
0
def drawLine(pos1, pos2, color=(1, 1, 1), size=1):
    """Draw a line.

    \param pos1 First line point
    \param pos2 Second line point
    \param color Line color
    \param size Line width
    """
    try:
        drw = getScene().worldObject("Global_Draw")
    except KeyError:
        drw = draw.Draw(name="Global_Draw")
    drw.line(pos1, pos2, color, size)
Exemplo n.º 7
0
def run_project(args):

    opt = options.Options()

    parsed_args = opt.parse(args[1:])

    y = parsed_args.slice_yplus

    if y:
        print('Hello! ', y)


#    for key in f.prange.keys():
#        c.write_to_file(f.file_path_write+key+".csv",key)

    data = draw.Draw()
    #    data.draw_ur(f.file_path_main + "ur.pdf")
    #    data.draw_urnorm2(f.file_path_main + "urnorm2.pdf")
    data.draw_alpha(f.file_path_main + "alpha.pdf")
Exemplo n.º 8
0
def main(infile):
	with open(infile, 'rb') as ff:
		G = pickle.load(ff)

	nodeDegree = {}
	for node in G:
		swID = node.get_id()
		nodeDegree[swID] = len(node.get_connections()) + 1 # plus its own subnet

	outfile = 'nodeDegreeinTopo.jpg'
	fig = draw.Draw(outfile)	# create Draw object
	x = sorted([swID for swID in nodeDegree.keys()])
	y = [nodeDegree[swID] for swID in x]

	fig.draw_bar(x, y)
	fig.set_title('Node degrees in topology, Geant')
	fig.set_xlabel('Switch ID')
	fig.set_ylabel('Degrees')
	fig.savefig()
Exemplo n.º 9
0
 def show_draw_command(self):
     try:
         patern = "^(0$|-?[1-9]\d*(\.\d*[1-9]$)?|-?0\.\d*[1-9])$"
         str_a = self.input_a.get()
         str_b = self.input_b.get()
         str_c = self.input_c.get()
         str_d = self.input_d.get()
         str_y = self.input_y.get()
         str_start_point = self.input_start_point.get()
         str_finish_point = self.input_finish_point.get()
         float_a = float(str_a) if (re.match(patern, str_a)
                                    is not None) else 0.0
         float_b = float(str_b) if (re.match(patern, str_b)
                                    is not None) else 0.0
         float_c = float(str_c) if (re.match(patern, str_c)
                                    is not None) else 0.0
         float_d = float(str_d) if (re.match(patern, str_d)
                                    is not None) else 0.0
         float_y = float(str_y) if (re.match(patern, str_y)
                                    is not None) else 0.0
         float_start_point = float(str_start_point) if (re.match(
             patern, str_start_point) is not None) else 0.0
         float_finish_point = float(str_finish_point) if (re.match(
             patern, str_finish_point) is not None) else 0.0
         if (float_finish_point < float_start_point):
             temp = float_finish_point
             float_finish_point = float_start_point
             float_start_point = temp
         bool_is_sigma = self.is_sigma.get()
         self.intersection_points = points.SearchIntersectionPoint(
             float_a, float_b, float_c, float_d,
             bool_is_sigma).return_list_intersection_points(
                 float_start_point, float_finish_point, float_y)
         draw.Draw(float_a, float_b, float_c,
                   float_d).create_draw(float_start_point,
                                        float_finish_point, float_y,
                                        self.intersection_points)
     except BaseException as ex:
         messagebox.showinfo("Error", ex.args)
Exemplo n.º 10
0
	def beam_search(self, beam_width):
		start_time = time.process_time()
		#this is the priority queue, prepopulated with the start node
		#the first number is f(state): the total cost up to this point
		#plus the heuristic value of this point
		#the second number is the cost up to this point, and the third number is
		#the number of nodes we have explored before getting here
		pq = [(self.h(self.model.startState()), 0, 0, self.model.startState())]
		#the future explored set, currently empty
		#this has to be a dict so there is constant time lookup of whether a node is explored
		#else on large networks where the explored set is very long, each node we check whether
		#it has been explored is O(N) which is unacceptable
		explored = {}
		
		#create a dict that will store the parent of each node as it is visited
		parents = {}
		parents[self.model.startState()] = self.model.startState(), 0

		if draw:
			d = dr.Draw(self.model.startState())
			d.drawGoals(self.model.goalStates())
		else:
			d = None

		path_found = False
		max_frontier_size = 1
		while(len(pq) > 0 and not path_found):
			#pop a node from the pq
			heuristic_cost, cost_to_now, priority, current = heapq.heappop(pq)

			if draw:
				d.visitPoint(current)

			#check if the neighbor is a goal
			if self.model.goal(current):
				end_time = time.process_time()
				path_found = True
				self.output_ans(current, start_time, end_time, parents, max_frontier_size, path_found, d)
				break

			if(current in explored):
				continue
			self.nodecount += 1            
			explored[current] = 1
			#expand the node
			actions =  self.model.actions(current)
			for action in actions:
				neighbor = self.model.result(current, action)
				#store away the parent of a possible neighbor, plus the cost to get there

				if neighbor not in explored:

					if draw:
						d.explorePoint(neighbor)

					#else add them to the queue if they are not seen yet
					path_cost = cost_to_now + self.model.cost(current, action)
					heuristic_cost = path_cost + self.h(neighbor)
					heapq.heappush(pq, (heuristic_cost, path_cost, self.next_id, neighbor) )
					self.next_id += 1
					if neighbor not in parents or parents[neighbor][2] > path_cost:
						parents[neighbor] = current, self.model.cost(current, action), path_cost
			max_frontier_size = max(max_frontier_size, len(pq))
			#print("Len before pruning:", len(pq))
			pq = self.prune(pq, beam_width)
			#print("Len after pruning:", len(pq))
		if not path_found:
			end_time = time.process_time()
			self.output_ans(self.model.startState(), start_time, end_time, parents, max_frontier_size, path_found, d)
		
		if draw:
			input()
			d.reset()
Exemplo n.º 11
0
        optimizer = GradDesc(net_cfg['optimizer'][1])
    elif net_cfg['optimizer'][0] == 'decay_gradient':
        optimizer = DecayGradDesc(net_cfg['optimizer'][1],
                                  net_cfg['optimizer'][2])
    net = Net(layer_list, cost_func, optimizer, one_hot=net_cfg['one_hot'])
    return net


if __name__ == '__main__':
    cfg = util.config('config.1.json')
    one_hot = cfg['net']['one_hot']
    x = util.read_data(cfg['dataset']['x_path'])
    y = util.read_data(cfg['dataset']['y_path'])
    # x, y = x[38:44], y[38:44]
    x_test_mg, x_test = util.generate_test_data(x)
    draw = draw.Draw(x, y, x_test_mg, one_hot=one_hot, C=cfg['class'])
    net = establish_net(cfg['net'], x)
    if one_hot:
        y = util.encode_onehot(y, cfg['class'])
    sample_num = x.shape[0]
    batch_size = cfg['batch_size']
    for epoch in range(100000):
        cost_avg = 0
        for it in range(sample_num // batch_size):
            beg_idx = it * batch_size
            end_idx = sample_num if beg_idx + batch_size > sample_num else beg_idx + batch_size
            x_train = x[beg_idx:end_idx]
            y_train = y[beg_idx:end_idx]
            cost = net.train(x_train, y_train)
            # if (epoch * (sample_num // batch_size) + it) % 50 == 0:
            #   draw.drawLoss(epoch * (sample_num // batch_size) + it, cost)
Exemplo n.º 12
0
#!/usr/local/bin/python3

import random
import turtle as my_turtle

import color_bucket
import draw

color_bucket_obj = color_bucket.ColorBucket()
draw_obj = draw.Draw()

print(color_bucket_obj.colors)
print(color_bucket.ColorBucket.description)

my_turtle.Screen().bgcolor('black')

while True:
    size = random.choice(range(5, 50))
    x = random.choice(range(-200, 200))
    y = random.choice(range(-200, 200))

    draw_obj.draw_star(my_turtle, size, color_bucket_obj.get_color(), x, y, 8)
Exemplo n.º 13
0
 def close_application_command(self):
     draw.Draw().close_draw()
     self.__app.destroy()
Exemplo n.º 14
0
    def ExecuteTrendFollowing(self, exchange, moneta, tool, risultato):

        #Attention: static stoploss and dynamic stoploss cannot be activated simultaneously

        tool.attivazione_stoploss_statico = 0  #with zero not activated, with 1 activated
        tool.attivazione_stoploss_dinamico = 1  # with zero not activated, with 1 activated
        tool.profitto = 0.4  #minimum percentage of profit
        tool.stoploss_1 = 0.8  #percentage of stoploss
        tool.stoploss_2 = 2.0  #second level stoploss percentage (not active for now)
        tool.commissioni = 0.25  #percentage of fees in buy and sell
        tool.nrtransizioni = 2000  #do not use
        tool.stoploss_dinamico_moltiplicatore = 0.997  #multiplier of the trailing stop
        tool.stoploss_dinamico_formula = "row.close * tool.stoploss_dinamico_moltiplicatore"  #formula per il calcolo dello stoploss dinamico (trailing stop)
        tool.attivazione_stoploss_dinamico_limiti = 1  #with zero not activated, with 1 activated. It works if dynamic stoploss is activated
        tool.stoploss_dinamico_min_profitto = 0.30  #minimum profit compared to lastbuy if activated stoploss_dinamico_limiti
        tool.stoploss_dinamico_max_perdita = 2  #max loss in percentage compared to lastbuy if activated stoploss_dinamico_limiti
        tool.hours = 36  #timedelta from now
        tool.periodo = '5m' #candlestick timeframe

        self.nome = " Test Strategy Trend Following "

        candle = candlestick.Candlestick()

        self.df1 = candle.getCandle(exchange, moneta, tool.hours, tool.periodo)

        moneta = moneta

        exchange = exchange

        self.df1 = self.df1.apply(pd.to_numeric)

        #-------------Indicators and oscillators 
        self.df1['rsi'] = ta.RSI(self.df1.close.values, timeperiod=14)
        self.df1['adx'] = ta.ADX(self.df1['high'].values,
                                 self.df1['low'].values,
                                 self.df1['close'].values,
                                 timeperiod=14)

        # Bollinger bands with qtpylib--------------------------------------
        """ bollinger = qt.bollinger_bands(qt.typical_price(self.df1), window=20, stds=2)
        self.df1['lower'] = bollinger['lower']
        self.df1['middle'] = bollinger['mid']
        self.df1['upper'] = bollinger['upper'] """
        #------------------------------------------------------------------
        # Bollinger bands with TA library
        self.df1['upper'], self.df1['middle'], self.df1['lower'] = ta.BBANDS(
            self.df1['close'].values, timeperiod=5,nbdevup=1,nbdevdn=1, matype=1)  
        self.df1['upper2'], self.df1['middle2'], self.df1[
            'lower2'] = ta.BBANDS(self.df1['close'].values, timeperiod=5,nbdevup=1.6,nbdevdn=1.6, matype=1)
        self.df1['upper3'], self.df1['middle3'], self.df1[
            'lower3'] = ta.BBANDS(self.df1['close'].values, timeperiod=5,nbdevup=2,nbdevdn=2, matype=1)
        #------------------------------------------------------------------    
        self.df1['PrezzoMed'] = self.df1['close'].mean()
        self.df1['STDDEV'] = ta.STDDEV(self.df1['close'].values,
                                       timeperiod=15,
                                       nbdev=1)
        self.df1['macd'], self.df1['macdsignal'], self.df1[
            'macdhist'] = ta.MACD(self.df1.close.values,
                                  fastperiod=12,
                                  slowperiod=26,
                                  signalperiod=9)
        self.df1['minus_di'] = ta.MINUS_DI(self.df1['high'].values,
                                           self.df1['low'].values,
                                           self.df1['close'].values,
                                           timeperiod=25)
        self.df1['plus_di'] = ta.PLUS_DI(self.df1['high'].values,
                                         self.df1['low'].values,
                                         self.df1['close'].values,
                                         timeperiod=25)
        self.df1['sar'] = ta.SAR(self.df1['high'].values,
                                 self.df1['low'].values,
                                 acceleration=0,
                                 maximum=0)
        self.df1['mom'] = ta.MOM(self.df1['close'].values, timeperiod=14)
        self.df1['atr'] = ta.ATR(self.df1['high'].values,
                                 self.df1['low'].values,
                                 self.df1['close'].values,
                                 timeperiod=14)
        self.df1['ema'] = ta.EMA(self.df1['close'].values, timeperiod=20)
        self.df1['ema1'] = ta.EMA(self.df1['close'].values, timeperiod=28)
        self.df1['ema2'] = ta.EMA(self.df1['close'].values, timeperiod=35)
        self.df1['ema3'] = ta.EMA(self.df1['close'].values, timeperiod=48)
        self.df1['ema50'] = ta.EMA(self.df1['close'].values, timeperiod=50)
        self.df1['dema20']= ta.DEMA(self.df1['close'].values, timeperiod=20)
        self.df1['dema50']= ta.DEMA(self.df1['close'].values, timeperiod=50)
        self.df1['tema20']= ta.TEMA(self.df1['close'].values, timeperiod=5)
        self.df1['tema50']= ta.TEMA(self.df1['close'].values, timeperiod=20)
        self.df1['cci'] = ta.CCI(self.df1['high'].values,
                                 self.df1['low'].values,
                                 self.df1['close'].values,
                                 timeperiod=14)
        
        #ta lib moving average
        self.df1['shortma']= ta.SMA(self.df1['close'].values, timeperiod=10)
        self.df1['longma']= ta.SMA(self.df1['close'].values, timeperiod=20)
        
        # MFI
        self.df1['mfi'] = ta.MFI(self.df1['high'].values,self.df1['low'].values, self.df1['close'].values, self.df1['volume'].values, timeperiod=14)

        # Stoch
        self.df1['slowk'],self.df1['slowd'] = ta.STOCH(self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        
        # Hammer: values [0, 100] - pattern recognised
        self.df1['CDLHAMMER'] = ta.CDLHAMMER(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        # Inverted Hammer: values
        self.df1['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)   
        
         # Engulfing
        self.df1['CDLENGULFING'] = ta.CDLENGULFING(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        # Hiddake
        self.df1['CDLHIKKAKE'] = ta.CDLHIKKAKE(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        # Doji
        self.df1['CDLDOJI'] = ta.CDLDOJI(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        # DojiStar
        self.df1['CDLDOJISTAR'] = ta.CDLDOJISTAR(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values)
        
        # Stoch fast
        self.df1['fastk'], self.df1['fastd'] = ta.STOCHF(self.df1.high.values, self.df1.low.values, self.df1.close.values)
        
        # Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy)
        rsi = 0.1 * (self.df1['rsi'] - 50)
        self.df1['fisher_rsi'] =(np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)

        # EMA - Exponential Moving Average
        self.df1['ema5'] = ta.EMA(self.df1.close.values, timeperiod=5)
        self.df1['ema10'] = ta.EMA(self.df1.close.values, timeperiod=10)
        self.df1['ema50'] = ta.EMA(self.df1.close.values, timeperiod=50)
        self.df1['ema100'] = ta.EMA(self.df1.close.values, timeperiod=100)

        # SMA - Simple Moving Average
        self.df1['sma'] = ta.SMA(self.df1.close.values, timeperiod=40)
        
        #-----------------------------------------------------------------------

        self.df1['Sellsignal'] = 0
        self.df1['Buysignal'] = 0

        #---------------------example 1 strategy buy and sell ----------------------------------------
        #-------------Buy conditions----------------------------------------------------------
        """ self.df1.loc[(((
        (self.df1['macd'] > self.df1['macdsignal']) &
        (self.df1['cci'] <= -50.0)))),'BuySignal'] = 1 """

        #-------------Sell conditions----------------------------------------------------------
        """ self.df1.loc[(((
        (self.df1['macd'] < self.df1['macdsignal']) &
        (self.df1['cci'] >= 100.0)))),'SellSignal'] = -1 """

        #------------------------example 2 strategy buy and sell---------------------------------------
        #-------------Buy conditions----------------------------------------------------------
        """ self.df1.loc[(((
        (self.df1['adx'] > 25) &
        (self.df1['mom'] < 0) &
        (self.df1['minus_di'] > 25) &
        (self.df1['plus_di'] < self.df1['minus_di'])))),'BuySignal'] = 1 """
        #-------------Sell conditions----------------------------------------------------------
        """ self.df1.loc[(((
        (self.df1['adx'] > 25) &
        (self.df1['mom'] > 0) &
        (self.df1['minus_di'] > 25) &
        (self.df1['plus_di'] > self.df1['minus_di'])))),'SellSignal'] = -1 """
        
        # --------------------------------------------------------------------------
        #example 3 strategy macd and midprice with qtpylib Sell & Buy
        #-------------Sell conditions----------------------------------------------------------
        self.df1.loc[(((
            self.qt.crossed_below(self.df1['macd'], self.df1['macdsignal'])))), 'Sellsignal'] = -1
        #-------------Buy conditions----------------------------------------------------------
        self.df1.loc[(((
            self.qt.crossed_above(self.df1['macd'], self.df1['macdsignal'])) & (self.df1['close'] < self.df1['PrezzoMed']))), 'Buysignal'] = 1 
        
        # --------------------------------------------------------------------------
        #example 4 strategy Bollinger Bands with rsi 
        #-------------Buy conditions----------------------------------------------------------
        """ self.df1.loc[
            ((self.df1['close'] < self.df1['lower']) &  	    
		    (self.df1['rsi'] < 30)
	        ),'Buysignal'] = 1
        #-------------Sell conditions----------------------------------------------------------
        self.df1.loc[
            ((self.df1['close']>self.df1['upper']) | 
            (self.df1['rsi'] > 70)
            ),'Sellsignal'] = -1  """
        
        #---------------------------------------------------------------------------
        #example 5 Bollinger Bands with rsi qtpylib library Sell & Buy
        #-------------Buy conditions----------------------------------------------------------
        """ self.df1.loc[
            (
                    (self.df1['rsi'] < 30) &
                    (self.df1['close'] < self.df1['lower'])

            ),
            'Buysignal'] = 1
        #------------Sell conditions--------------------------------------------    
        self.df1.loc[
            (
                    (self.df1['rsi'] > 70)

            ),
            'Sellsignal'] = -1 """
        
        # --------------------------------------------------------------------------
        #example 6 strategy longma and shortma with qtpylib  Sell & Buy
        #-------------Sell conditions----------------------------------------------------------    
        """ self.df1.loc[(((
           self.qt.crossed_below(self.df1['shortma'], self.df1['longma'])))), 'Sellsignal'] = -1
        #-------------Buy and Sell conditions----------------------------------------------------------
        self.df1.loc[(((
            self.qt.crossed_above(self.df1['shortma'], self.df1['longma'])) & (self.df1['close'] < self.df1['PrezzoMed']))), 'Buysignal'] = 1 
        """
        #--------------------------------------------------------------------------      
        #example 7 strategy with qtpylib and TA-lib Sell & Buy
        #-------------Buy conditions--------------------------------
        """ self.df1.loc[
            (
                (self.df1['rsi'] < 28) &
                (self.df1['rsi'] > 0) &
                (self.df1['close'] < self.df1['sma']) &
                (self.df1['fisher_rsi'] < -0.94) &
                (self.df1['mfi'] < 16.0) &
                (
                    (self.df1['ema50'] > self.df1['ema100']) |
                    (qt.crossed_above(self.df1['ema5'], self.df1['ema10']))
                ) &
                (self.df1['fastd'] > self.df1['fastk']) &
                (self.df1['fastd'] > 0)
            ),
            'Buysignal'] = 1
        #------------Sell conditions---------------------------------------------
        self.df1.loc[
            (
                (self.df1['sar'] > self.df1['close']) &
                (self.df1['fisher_rsi'] > 0.3)
            ),
            'Sellsignal'] = -1 """
            
        # ----------------------------------------------------------------------
        #example 8 strategy - multiple indicators with pattern indicator HAMMER
        #------------------Sell conditions--------------------------------------
        """ self.df1.loc[
            (
                (self.df1['rsi'] < 30) &
                (self.df1['slowk'] < 20) &
                (self.df1['lower'] > self.df1['close']) &
                (self.df1['CDLHAMMER'] == 100)
            ),
            'Buysignal'] = 1
        #---------------Buy conditions------------------------------------------
        self.df1.loc[
            (
                (self.df1['sar'] > self.df1['close']) &
                (self.df1['fisher_rsi'] > 0.3)
            ),
            'Sellsignal'] = -1 """
        # ----------------------------------------------------------------------    
        #example 9 strategy pattern strategy ENGULFING strategy Sell and Buy
        #---------------Sell conditions------------------------------------------
        """ print(self.df1['CDLENGULFING'].values)
           
        self.df1.loc[
            (
                           
                (self.df1['CDLENGULFING'].values < -99) 
            ),
            'Buysignal'] = 1
        #---------------Buy conditions------------------------------------------    
        self.df1.loc[
            (
                (self.df1['CDLENGULFING'].values >  99)
            ),
            'Sellsignal'] = -1  """
            
        #---------------------------------------------------------------------------------
        #example 10 strategy Bollinger Bands with rsi with technical indicators Sell & Buy
         
        """risultati_index_buy = self.df1.index[self.df1['CDLINVERTEDHAMMER'] == 100].tolist() 
        risultato_last_index = self.df1.index[-1]
         
        if ((risultati_index_buy == None) or (risultato_last_index == None) or (risultato_last_index == '') or (len(risultati_index_buy) == 0)):
            print('None Result')
        else:
            risultato_last_index = str(risultati_index_buy[-1])
            risultato_last_index = risultato_last_index[:-3]
            risultato_last_index = (str(risultato_last_index))[:-3] #rimozione dei tre caratteri
            data1 = datetime.fromtimestamp(int(risultato_last_index))
            data2 = datetime.fromtimestamp(int(risultato_last_index))
            print(data2,data1)
            print(self.df1)
        #------------------Buy conditions----------------------------------
        self.df1.loc[(
                    self.df1['CDLINVERTEDHAMMER'] == 100
                    ),'CDLHIKKAKE_CLOSE'] = self.df1['close'] 
        
        self.df1.loc[
            (
                (self.df1['close'] < self.df1['lower3'])             
            )
                ,'Buysignal'] = 1
        #------------------Sell conditions----------------------------------
        self.df1.loc[
            (
            self.qt.crossed_above(self.df1['dema20'], self.df1['dema50'])
            ),'Sellsignal'] = -1 
        """   
        #---------------------------------------------------------------------- 
        #example 11 strategy DOJISTAR strategy Sell and Buy  
        #---------------Buy conditions------------------------------------------
        """ self.df1.loc[
            (
                (self.df1['CDLDOJISTAR'].values == -100) 
            ),
            'Buysignal'] = 1
        #---------------Sell conditions----------------------------------------    
        self.df1.loc[
            (
                (self.df1['CDLHIKKAKE'].values == 200)
            ),
            'Sellsignal'] = -1   """
        #-----------------------------------------------------------------------
        #example 12 strategy  DEMA of EMA BuySignal and SellSignal
        #---------------Buy conditions------------------------------------------
        """ self.df1.loc[(((
           self.qt.crossed_below(self.df1['ema50'], self.df1['dema200'])))), 'BuySignal'] = 1
        #---------------Sell conditions------------------------------------------
        self.df1.loc[
            (
                (self.df1['CDLHIKKAKE'].values > 99)

            ),
            'Sellsignal'] = -1   """
        
        #---------------------------trailing stoploss---------------------------
        
        #example 1

        #tool.stoploss_dinamico_formula = "row.close * tool.stoploss_dinamico_moltiplicatore" #formula for calculating dynamic stoploss (trailing stop)

        #example 2

        tool.stoploss_dinamico_formula = "row.ema3"

        x = []
        y = []
        balance = []
        lower_vect = []
        lower2_vect = []
        upper_vect = []
        upper2_vect = []
        pattern_vect = []
        close_vect = []
        buysignal_vect = []
        sellsignal_vect = []
        prezzmed_vect = []
        stdev_vect = []
        stoplosssignal_vect = []
        stoplossprezzo_vect = []
        ema_vect = []
        ema_long_vect = []
        ema_short_vect = []
        date = []
        volume_vect = []
        macd_vect = []
        macd_signal_vect = []
        macd_hist_vect = []
        atr_vect = []
        rsi_vect = []
        
        i = 0
        
        for row in self.df1.itertuples():
            
            a = row.Index / 1000.0
            b = datetime.fromtimestamp(a)

            self.stoploss = self.getStoploss(row, i, tool)

            logging.info("-----------Loop line processing " + str(i))
            logging.info("1) self.stoploss value = " + str(self.stoploss))

            if (i > 0):

                stoplossprezzo_vect.append(self.stoplossprezzo)

                logging.info(
                    "2) Value of i greater than zero not first loop for i =" +
                    str(i))

                logging.info("2.1) Value of self.stoplossprezzo = " +
                             str(self.stoplossprezzo))

            else:

                self.stoplossprezzo = row.close * 0.99

                logging.info(
                    "2) Value of i equal to zero first loop for i = " + str(i))

                stoplossprezzo_vect.append(self.stoplossprezzo)

                logging.info("2.1) Value of self.stoplossprezzo = " +
                             str(self.stoplossprezzo))

            if (self.stoploss == 1):

                logging.info(
                    "3) self.stoploss value = 1 after getstoploss method ")

            x.append(i)
            y.append(row.close)

            if (row.Sellsignal == 0
                    and self.stoploss == 0) or (row.Sellsignal == 1
                                                and self.stoploss == 1):

                logging.info("4) Value of self.stoploss before If for sell " +
                             str(self.stoploss))
                logging.info("4.1) Value of row.Sellsignal " +
                             str(row.Sellsignal))

                sellsignal_vect.append(np.nan)

                stoplosssignal_vect.append(np.nan)

            else:

                if (self.stoploss == 1):

                    logging.info("5) self.stoploss value = 1 else before if ")
                    logging.info(
                        "5.1) Indication of sell in presence of self.stoploss = 1"
                    )

                    if (self.sell == 0) and (self.buy == 1):

                        logging.info(
                            "5.2) Sell with self.stoploss = 1 self.stoploss = "
                            + str(self.stoploss))
                        logging.info(
                            "5.2.1) Sell with self.stoploss = 1 self.sell = " +
                            str(self.sell))
                        logging.info(
                            "5.2.2) Sell with self.stoploss = 1  self.buy = " +
                            str(self.buy))
                        
                        #increases variable by 1 num_of_trades by one
                        self.nr_of_trades = self.nr_of_trades+1
                        
                        sellsignal_vect.append(row.close)

                        stoplosssignal_vect.append(row.close)

                        percentualecommissioni = (
                            float(row.close) / 100) * float(tool.commissioni)

                        logging.info(
                            "5.3) Percentage of fees in presence of self.stoploss = 1"
                            + str(percentualecommissioni))

                        balance.append(
                            [row.close - (percentualecommissioni), 1])
                        
                        if ((row.close - percentualecommissioni) > self.lastbuy):
                            self.nr_positive_trades = self.nr_positive_trades +1
                        elif ((row.close - percentualecommissioni) < self.lastbuy):
                            self.nr_negative_trades = self.nr_negative_trades +1
                        else:
                            print('Non risulta positiva ne negativa')

                        self.totalecommissioni = self.totalecommissioni + percentualecommissioni

                        logging.info(
                            "5.4) Total fees in presence of self.stoploss = 1 "
                            + str(self.totalecommissioni))

                        self.sell = 1

                        self.buy = 0

                        self.stoploss = 0

                        logging.info(
                            "5.5) Assign value zero to self.stoploss = " +
                            str(self.stoploss))
                        logging.info("5.6) Assign value 1 to self.sell = " +
                                     str(self.sell))
                        logging.info("5.7) Assign value zero to self.buy = " +
                                     str(self.buy))

                    else:

                        sellsignal_vect.append(np.nan)

                        stoplosssignal_vect.append(np.nan)

                        self.stoploss = 0

                else:

                    stoplosssignal_vect.append(np.nan)

                    if ((self.sell == 0) and (self.buy == 1)
                            and (tool.attivazione_stoploss_dinamico == 0)):

                        logging.info(
                            "6.0) Sell ​​normal not in the presence of dynamic stoploss"
                        )
                        logging.info("6.1) Value of self.sell: " +
                                     str(self.sell))
                        logging.info("6.2) Value of self.buy: " +
                                     str(self.buy))
                        logging.info(
                            "6.3) Dynamic stoploss activation parameter value: "
                            + str(tool.attivazione_stoploss_dinamico))

                        price1 = float(self.lastbuy) + (
                            (float(self.lastbuy)) / 100) * float(tool.profitto)
                        logging.info("6.4) Value of self.lastbuy: " +
                                     str(self.lastbuy))
                        logging.info("6.5) Price1 price of sell: " +
                                     str(price1))
                        logging.info("6.6) Profit parameters: " +
                                     str(tool.profitto))

                        if (float(row.close) > float(price1)):

                            logging.info(
                                "6.7) Sell in presence of row.close greater than value of price1"
                            )
                            logging.info("6.8) Value of row.close: " +
                                         str(row.close))
                            logging.info("6.9) Value of sell price: " +
                                         str(price1))
                            #increases variable by 1 num_of_trades by one
                            
                            self.nr_positive_trades = self.nr_positive_trades +1

                            
                            sellsignal_vect.append(row.close)

                            percentualecommissioni = (float(
                                row.close) / 100) * float(tool.commissioni)

                            logging.info(
                                "6.9.1) Percentage of fees in presence of self.stoploss = 1 "
                                + str(percentualecommissioni))

                            balance.append(
                                [row.close - (percentualecommissioni), 1])

                            self.totalecommissioni = self.totalecommissioni + percentualecommissioni

                            logging.info(
                                "6.9.2) Total of fees in presence of self.stoploss = 1"
                                + str(self.totalecommissioni))

                            self.sell = 1
                            self.buy = 0
                            self.stoploss = 0

                            logging.info(
                                "6.9.3) Assign value zero to self.stoploss = "
                                + str(self.stoploss))
                            logging.info(
                                "6.9.4) Assign value 1 to self.sell = " +
                                str(self.sell))
                            logging.info(
                                "6.9.5) Assign value 0 to self.buy = " +
                                str(self.buy))

                        else:

                            sellsignal_vect.append(np.nan)

                    else:

                        sellsignal_vect.append(np.nan)

            if ((row.Buysignal == 0 or row.Buysignal == '0')):

                logging.info(
                    "7) Value of self.stoploss in if row.BuySignal = 0 " +
                    str(self.stoploss))
                logging.info("7.1) Value of row.Buysignal " +
                             str(row.Buysignal))

                buysignal_vect.append(np.nan)

            else:

                if ((row.Buysignal == 1 or row.Buysignal == '1')):

                    logging.info("8) Value of row.Buysignal " +
                                 str(row.Buysignal))

                    if (self.buy == '0' or self.buy == 0):

                        logging.info(
                            "8.1) Buy in presence of self.stoploss =  " +
                            str(self.stoploss))
                        logging.info("8.2) Value of self.sell = " +
                                     str(self.sell))
                        logging.info("8.3) Value of self.buy = " +
                                     str(self.buy))
                        
                        
                        buysignal_vect.append(row.close)

                        percentualecommissioni = (
                            float(row.close) / 100) * float(tool.commissioni)

                        logging.info(
                            "8.4) Percentage of fees in presence of self.stoploss = 1 "
                            + str(percentualecommissioni))

                        self.totalecommissioni = self.totalecommissioni + percentualecommissioni

                        logging.info(
                            "8.5) Total of fees in presence of stoploss = 1" +
                            str(self.totalecommissioni))

                        balance.append([(-row.close - percentualecommissioni),
                                        0])

                        self.buy = 1

                        self.sell = 0

                        logging.info(
                            "8.5.1) Assign value zero to self.stoploss = " +
                            str(self.stoploss))
                        logging.info(
                            "8.5.2) Assign value zero to self.sell = " +
                            str(self.sell))
                        logging.info("8.5.3) Assign value 1 to self.buy = " +
                                     str(self.buy))

                        if (tool.attivazione_stoploss_dinamico == 1):

                            logging.info(
                                "8.6) Value of tool.attivazione_stoploss_dinamico equal to : "
                                + str(tool.attivazione_stoploss_dinamico))

                            self.stoplossprezzo = eval(
                                tool.stoploss_dinamico_formula)

                            logging.info(
                                "8.6.1) Value of self.stoplossprezzo " +
                                str(self.stoplossprezzo))

                        else:

                            self.stoplossprezzo = (row.close - (
                                (row.close / 100) * tool.stoploss_1))

                            logging.info(
                                "8.7) Value of self.stoplossprezzo with tool.attivazione_stoploss_dinamico equal to 1 = "
                                + str(self.stoplossprezzo))

                        self.lastbuy = row.close

                        logging.info("8.8) Value of self.lastbuy" +
                                     str(self.lastbuy))
                        logging.info("8.9.0) Value of self.stoploss = " +
                                     str(self.stoploss))
                        logging.info("8.9.1) Value of self.sell = " +
                                     str(self.sell))
                        logging.info("8.9.2) Value of self.buy = " +
                                     str(self.buy))
                        logging.info("8.9.3) Value of self.stoplossprezzo = " +
                                     str(self.stoplossprezzo))
                        logging.info("8.9.4) Value of self.lastbuy = " +
                                     str(self.lastbuy))
                        logging.info(
                            "8.9.5) Value of  tool.attivazione_stoploss_dinamico = "
                            + str(tool.attivazione_stoploss_dinamico))
                        logging.info(
                            "8.9.6) Value of tool.attivazione_stoploss_statico = "
                            + str(tool.attivazione_stoploss_statico))

                    else:
                        buysignal_vect.append(np.nan)

                else:
                    buysignal_vect.append(np.nan)

            #add indicators,oscillators and others
            prezzmed_vect.append(row.PrezzoMed)
            stdev_vect.append(row.STDDEV)
            ema_vect.append(row.ema3)
            date.append(b)
            rsi_vect.append(row.rsi)
            #pattern_vect.append(row.CDLHIKKAKE_CLOSE)
            volume_vect.append(row.volume)
            lower2_vect.append(row.lower2)
            upper2_vect.append(row.upper2)
            ema_long_vect.append(row.tema50)
            ema_short_vect.append(row.tema20)
            lower_vect.append(row.lower)
            upper_vect.append(row.upper)
            macd_vect.append(row.macd)
            macd_signal_vect.append(row.macdsignal)
            macd_hist_vect.append(row.macdhist)
            atr_vect.append(row.atr)

            i = i + 1

        self.valorestrategia = self.getValoreStrategia(balance)

        tool.setVisualizzaGrafico(1)

        if (tool.visualizzagrafico == 1 or tool.visualizzagrafico == '1'):

            ds = draw.Draw()

            ds.setNrGrafici(2)

            ds.draw_graphic(moneta, x, y, self.nr_of_trades, self.nr_positive_trades,self.nr_negative_trades, buysignal_vect, sellsignal_vect,
                            prezzmed_vect, stoplossprezzo_vect, stdev_vect,
                            self.nome, self.valorestrategia, date, ema_vect,
                            rsi_vect,pattern_vect,volume_vect,lower2_vect,
                            upper2_vect,ema_short_vect,ema_long_vect,lower_vect,upper_vect,macd_vect,macd_signal_vect,macd_hist_vect,atr_vect)
Exemplo n.º 15
0
    def GoToDo():

        nonlocal switcher
        while True:
            #Draw the list
            os.system('clear')
            a = draw.Draw(today.todolist, today.name)
            b = draw.Draw(future.todolist, future.name)
            c = draw.Draw(post.todolist, post.name)
            d = draw.Draw(comp.todolist, comp.name)
            a.draw_TODO()
            b.draw_TODO()
            c.draw_TODO()
            d.draw_TODO()
            print("-" * 40)
            #Here is a problem
            if switcher % 4 == 0:
                try:
                    future.todolist[future.cursor[0]][2] = '[   ]'
                except:
                    pass
                current = today
                print("Your Current position: Today")
            elif switcher % 4 == 1:
                try:

                    today.todolist[today.cursor[0]][2] = '[   ]'
                except:
                    pass
                current = future
                print("Your Current position: Future")
            elif switcher % 4 == 2:
                try:
                    post.todolist[post.cursor[0]][2] = '[   ]'
                except:
                    pass

                current = post
                print("Your Current position: Gone")
            elif switcher % 4 == 3:

                try:
                    comp.todolist[post.cursor[0]][2] = '[   ]'
                except:
                    pass

                current = comp
                print("Your Current position: Complete")

            print("* * * * * * * Description * * * * * * *\n")
            try:
                print("->", current.todolist[current.cursor[0]][3])
            except:
                print("Nothing here")
            print("- - - - - - - - - - - - - - - - - - - -")

            action = useraction.get_user_action()

            if action == 'Switch':
                switcher += 1
                continue
            if action in useraction.moves:
                while True:
                    try:
                        movement.moves(action, current)
                        break
                    except IndexError:
                        print("Uhoh..Out of Range..")
                        break
                continue
            else:
                op = operation.Operation(current, post, comp, future, today)
                if op.execution(action, userid) == 0:
                    return False
Exemplo n.º 16
0
 def test_draw(self):
     draw = d.Draw(["#A250B2", "#B2B250", "#5054B2"])
     draw.draw_image("test", 1000, 1000)
Exemplo n.º 17
0
    while True:
        tasks = [
            fetchData('http://www.xm.com', pd.Xm),
            fetchData(
                'http://biz.aetoscg.com/content/get-ratio!callback.json?ln=0&group=TOOL&callback=showToolsLAS&_=1458550863266',
                pd.Atos),
            fetchData(calendar_url, pd.Calendar)
        ]

        future = asyncio.Future()
        asyncio.ensure_future(pd.Database(future))
        try:
            loop.run_until_complete(future)
            engine = future.result()
            loop.run_until_complete(asyncio.wait(tasks))
        except Exception:
            print('exception happend.')
            loop.run_until_complete(pd.CloseDB())
            continue

        if engine:
            loop.run_until_complete(draw.Draw(engine))
        n += 1
        print(n, ' rounds completed.')
        time.sleep(600)
        timenow = dt.now() - delta
        if timenow.isoweekday() == 6:
            break

    loop.close()
Exemplo n.º 18
0
        else:
            return

    def predict(self, x):
        y_ = self.forward(x)
        return y_


if __name__ == '__main__':
    x = util.read_data('ex4x.dat')
    y = util.read_data('ex4y.dat', squeeze=True)
    x_avg, x_std = util.compute_normal_param(x)

    x1_test_mg, x2_test_mg, x_test = util.generate_test_data(x)

    draw = draw.Draw(x, y, x1_test_mg, x2_test_mg)

    sub1 = SubConstant(x_avg)
    div1 = DivConstant(x_std)
    fc1 = Linear(2, 10)
    active1 = Sigmoid()
    fc2 = Linear(10, 1)
    active2 = Sigmoid()
    layer_list = [sub1, div1, fc1, active1, fc2, active2]
    cost_func = LeastSquare()
    optimizer = GradDesc(0.1)
    net = Net(layer_list, cost_func, optimizer)

    sample_num = x.shape[0]
    batch_size = 1
    for epoch in range(1000):
Exemplo n.º 19
0
#       'ytick.labelsize': 16,
#      # 'text.usetex': True,
#       #'text.latex.unicode': True,
#       'figure.figsize': [10,10]}
#matplotlib.rcParams.update(params)

fig = plt.figure(figsize=(14, 14))
ax1 = fig.add_subplot(1, 1, 1)
plt.grid(False)
plt.style.use("grayscale")
mat_valor = cv2.imread("roi.png")

#plt.show()
print("aqui")
ax1.clear()
pen = draw.Draw(ax1)
pen.mat_grid(2, 2, 10, 10, mat_valor[:, :0])
print(mat_valor)
#plt.imshow(mat_valor)
plt.savefig("mat.png", dpi=90)
plt.show()

# kernel=np.ones((3,3))/9
# ft=cv2.filter2D(mat_valor,-1,kernel)
# plt.imshow(ft)
# plt.show()

#ax1.clear()
#pen=draw.Draw(ax1)
#pen.mat_grid(2,2,3,3,mat_valor)
#plt.show()
Exemplo n.º 20
0
        x = self.norm(x)
        x = self.fc1(x)
        x = torch.sigmoid(x)
        x = self.fc2(x)
        x = torch.sigmoid(x)
        return x


if __name__ == '__main__':
    x = util.read_data('ex4x.dat', use_torch=True)
    y = util.read_data('ex4y.dat', use_torch=True)
    x_avg, x_std = util.compute_normal_param(x, use_torch=True)

    x1_test_mg, x2_test_mg, x_test = util.generate_test_data(x, use_torch=True)

    draw = draw.Draw(x, y, x1_test_mg, x2_test_mg, use_torch=True)

    net = Net(x_avg, x_std)
    print(net)
    optimizer = optim.SGD(net.parameters(), lr=0.03)
    criterion = nn.MSELoss()
    # TODO implement one-hot and cross-entropy-loss
    # criterion = nn.CrossEntropyLoss()
    sample_num = x.shape[0]
    batch_size = 5
    for epoch in range(1000):
        loss_avg = 0
        for it in range(sample_num // batch_size):
            beg_idx = it * batch_size
            end_idx = sample_num if beg_idx + batch_size > sample_num else beg_idx + batch_size
            net.zero_grad()
Exemplo n.º 21
0
        i = (i - 1) % width
        j -= 1


for i in range(size - len(obst)):
    # 距離が最小値の点を抽出
    v = unSearch.index(min(unSearch))
    dist[v] = unSearch[v]
    unSearch[v] = END
    searchDist(v)

searchRoute()
upHeight()
print(routeHeight)

d1 = draw.Draw(30, n)
for i in range(size):
    if (unSearch[i] == 20001):
        d1.drawObst(sufToCd(i), (192, 192, 192))

for i in range(size):
    if (parent[i] != -1):
        d1.drawLine(sufToCd(i), sufToCd(parent[i]), (0, 0, 255))

for i in range(size):
    if (unSearch[i] == 20001):
        col = (128, 128, 128)
    else:
        col = (0, 128, 0)
        d1.drawChara(sufToCd(i), str(dist[i]))
    d1.drawRect(sufToCd(i), col)
Exemplo n.º 22
0
        """
        integration_list: List[float] = []

        for i in range(repeat_count):
            integration_list.append(self.generate_integration(each_sample))

        mean: float = round(np.mean(integration_list), 5)
        variance: float = round(np.var(integration_list), 5)

        return integration_list, mean, variance


if __name__ == "__main__":
    approximate_integration = ApproximateIntegration(0, 1.0, lambda x: x**3)
    test_case: List[int] = (5, 10, 20, 30, 40, 50, 60, 70, 80, 100)

    means: List[float] = []
    variances: List[float] = []

    for each_sample in test_case:
        cur_result: Tuple[List[float], float,
                          float] = approximate_integration.generate_repeat(
                              each_sample=each_sample, repeat_count=100)
        means.append(cur_result[1])
        variances.append(cur_result[2])
        print('N = {} : {}'.format(each_sample, cur_result[0]))

    draw.Draw().draw_mean_variance(abscissa=test_case,
                                   mean=means,
                                   variance=variances)
Exemplo n.º 23
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
import display
import draw
import signalk
import json
import time
import atexit

target = display.DrawTarget()
dashboard = draw.Draw(target)


def on_message(ws, message):
    msg = json.loads(message)
    if not "updates" in msg:
        return
    for update in msg["updates"]:
        for value in update["values"]:
            if value["path"] == "navigation.state":
                if dashboard.display != value["value"]:
                    dashboard.set_display(value["value"])
                    signalk.subscribe(ws, dashboard.get_paths())
                    dashboard.variable_loop()
            else:
                dashboard.update_value(value, update["timestamp"])


def on_error(ws, error):
    message = str(error)
    print(message)
Exemplo n.º 24
0
 def draw(self):
     draw.Draw()
Exemplo n.º 25
0
import processing
import draw
import sys
import os

if __name__ == "__main__":
    file_name = input(
        "Place the file you wish to convert in the 'input' folder and type its name: "
    )
    poster_name = input("Name your poster png: ")
    num_stills = int(
        input("Select the number of layers you want your image to have"))
    vp = processing.VideoProcessor(file_name)
    frames = vp.get_n_stills(num_stills)
    ip = processing.ImgProcessor(frames)
    color_list = ip.average_list()

    draw = draw.Draw(color_list)
    draw.draw_image("output/" + poster_name, 3900, 5700)

    exit(0)
Exemplo n.º 26
0
    def search(self):
        start_time = time.process_time()
        #this is the queue, prepopulated with the start node
        q = [self.model.startState()]
        #the future explored set, currently empty
        #this has to be a dict so there is constant time lookup of whether a node is explored
        #else on large networks where the explored set is very long, each node we check whether
        #it has been explored is O(N) which is unacceptable
        explored = {}

        #create a dict that will store the parent of each node as it is visited
        parents = {}
        parents[self.model.startState()] = self.model.startState(), 0

        if draw:
            d = dr.Draw(self.model.startState())
            d.drawGoals(self.model.goalStates())
        else:
            d = None

        path_found = False
        max_frontier_size = 1
        while (len(q) > 0 and not path_found):
            #pop a node from the q
            current = q.pop(0)

            if draw:
                d.visitPoint(current)

            if (current in explored):
                #print("skipping explored node")
                continue
            self.nodecount += 1
            #            if self.nodecount % 500 == 0:
            #                print("Expanded:", self.nodecount)
            #                print("Len explored:", len(explored))
            #break
            explored[current] = 1
            #expand the node
            actions = self.model.actions(current)
            for action in actions:
                neighbor = self.model.result(current, action)
                #store away the parent of a possible neighbor, plus the cost to get there

                #check if the neighbor is a  goal
                if self.model.goal(neighbor):

                    if draw:
                        d.explorePoint(neighbor)

                    parents[neighbor] = current, self.model.cost(
                        current, action)
                    end_time = time.process_time()
                    path_found = True
                    self.outputAns(neighbor, start_time, end_time, parents,
                                   max_frontier_size, path_found, d)
                elif neighbor not in explored:

                    if draw:
                        d.explorePoint(neighbor)

                    #else add them to the queue if they are not seen yet
                    q.append(neighbor)
                    if neighbor not in parents:
                        parents[neighbor] = current, self.model.cost(
                            current, action)
            max_frontier_size = max(max_frontier_size, len(q))
        if not path_found:
            end_time = time.process_time()
            self.outputAns(self.model.startState(), start_time, end_time,
                           parents, max_frontier_size, path_found, d)

        if draw:
            input()
            d.reset()
Exemplo n.º 27
0
	def search(self):
		start_time = time.process_time()
		#this is the priority queue, prepopulated with the start node
		#the first number is the cost up to this point, the second number is
		#the number of nodes we have explored before getting here
		pq = [(0, 0, self.model.startState())]
		#the future explored set, currently empty
		#this has to be a dict so there is constant time lookup of whether a node is explored
		#else on large networks where the explored set is very long, each node we check whether
		#it has been explored is O(N) which is unacceptable
		explored = {}
		
		#create a dict that will store the parent of each node as it is visited
		#the tuple is formatted as follows:
		#parent, cost to traverse parent to child, path cost to this point
		parents = {}
		parents[self.model.startState()] = self.model.startState(), 0, 0
		
		if draw:
			d = dr.Draw(self.model.startState())
			d.drawGoals(self.model.goalStates())
		else:
			d = None
			
		path_found = False
		max_frontier_size = 1
		while(len(pq) > 0 and not path_found):
			#pop a node from the pq
			cost_to_now, priority, current = heapq.heappop(pq)
			
			if draw:
				d.visitPoint(current)
				
			#check if the neighbor is a  goal
			if self.model.goal(current):
				end_time = time.process_time()
				path_found = True
				self.outputAns(current, start_time, end_time, parents, max_frontier_size, path_found, d)
				break
				
			if(current in explored):
				#print("skipping explored node")
				continue
			
			self.nodecount += 1            
#            if self.nodecount % 500 == 0:
#                print("Expanded:", self.nodecount)
#                print("Len explored:", len(explored))
				#break
			explored[current] = 1
			#expand the node
			actions =  self.model.actions(current)
			for action in actions:
				neighbor = self.model.result(current, action)
				#store away the parent of a possible neighbor, plus the cost to get there
				


				if neighbor not in explored:

					if draw:
						d.explorePoint(neighbor)

					#add them to the queue if they are not seen yet                    
					path_cost = cost_to_now + self.model.cost(current, action)
					heapq.heappush(pq, (path_cost, self.next_id, neighbor) )
					self.next_id += 1
					if neighbor not in parents or parents[neighbor][2] > path_cost:
						parents[neighbor] = current, self.model.cost(current, action), path_cost

			heapq.heapify(pq)
			#print("Current was:", current, "heap is:", pq)
			max_frontier_size = max(max_frontier_size, len(pq))
			
		if not path_found:
			end_time = time.process_time()
			self.outputAns(self.model.startState(), start_time, end_time, parents, max_frontier_size, path_found, d)
			
		if draw:
			input()    
			d.reset()