Beispiel #1
0
    def add_to_cart(self, product):
        product_ = CRUD.retreive_name('"'+product+'"')
        print(product)
        if(util.check_if_exists(product, self.order_list)):
            index = util.get_index(product, self.order_list)
            self.order_qty[index] = self.Tracker.qty_change
            util.replace(index, self.Table_)
            s = str(index)
        else:
            self.order_list.append(product)
            self.order_qty.append(self.Tracker.qty_change)
            s = 'end'

        print(product_)
        qty = self.Tracker.qty_change
        price = util.wholesale_check(qty, product_)
        total = price * qty
        delta = self.Tracker.qty_change - self.Tracker.qty_ref
        stock = self.Tracker.qty_s - delta
        CRUD.update_stock(str(product), int(stock))
        
        if(qty == 0):
            a = int(util.get_index(product, self.order_list))
            name=self.order_list.pop(a)
            quan=self.order_qty.pop(a)
            # self.focus_item(a)
            # self.Table_.tree.delete(self.Table_.tree.selection())
        else:
            product=product.replace(" ", "")
        
            product=(product+" "+str(qty)+" " + str(price) + " "+ str(total))
            self.Table_.tree.insert('', s, values=(product))

        total = sum(float(self.Table_.tree.set(item,3)) for item in self.Table_.tree.get_children())
        self.totala.set(total)
Beispiel #2
0
 def __setitem__(self, indices, expr):
     if not isinstance(indices, tuple):
         indices = (indices, )
     indices = self.indices + indices
     index, bit, _ = util.get_index(self.tensor.shape, indices, 0)
     if not Stage.get_len():
         raise TensorError(
             "Cannot set tensor elements without compute APIs")
     builder = Stage.get_current()
     if bit is None:
         builder.emit(
             _make.Store(self.tensor.buf.data,
                         _make.Cast(self.tensor.dtype, expr), index))
     elif isinstance(bit, slice):
         load = _make.Load(self.tensor.dtype, self.tensor.buf.data, index)
         expr = _make.SetSlice(load, expr, bit.start, bit.stop)
         builder.emit(
             _make.Store(self.tensor.buf.data,
                         _make.Cast(self.tensor.dtype, expr), index))
     else:
         load = _make.Load(self.tensor.dtype, self.tensor.buf.data, index)
         expr = _make.SetBit(load, expr, bit)
         builder.emit(
             _make.Store(self.tensor.buf.data,
                         _make.Cast(self.tensor.dtype, expr), index))
Beispiel #3
0
 def __setitem__(self, indices, expr):
     indices = util.CastRemover().mutate(indices)
     Stage.get_current().input_stages.add(self.last_update)
     Stage.get_current().lhs_tensors.add(self)
     if not isinstance(indices, tuple):
         indices = (indices, )
     indices = util.CastRemover().mutate(indices)
     if len(indices) < len(self.shape):
         raise TensorError("Accessing a slice of tensor is not allowed")
     else:
         index, bit, _ = util.get_index(self.shape, indices, 0)
         if not Stage.get_len():
             raise TensorError(
                 "Cannot set tensor elements without compute APIs")
         builder = Stage.get_current()
         if bit is None:
             builder.emit(
                 _make.Store(self.buf.data, _make.Cast(self.dtype, expr),
                             index))
         elif isinstance(bit, slice):
             load = _make.Load(self.tensor.dtype, self.tensor.buf.data,
                               index)
             expr = _make.SetSlice(load, expr, bit.start, bit.stop)
             builder.emit(
                 _make.Store(self.tensor.buf.data,
                             _make.Cast(self.tensor.dtype, expr), index))
         else:
             load = _make.Load(self.tensor.dtype, self.tensor.buf.data,
                               index)
             expr = _make.SetBit(load, expr, bit)
             builder.emit(
                 _make.Store(self.tensor.buf.data,
                             _make.Cast(self.tensor.dtype, expr), index))
Beispiel #4
0
    def OnDouble_listbox(self, event):
        widget = event.widget
        selection=widget.curselection()
        product=self._list[selection[0]]
        for i in range(0, len(product)):
            if (product[i]==')'):
                product=product[i+1:]
                break
        #value = widget.get(selection[0])
        import re
        qty=(re.findall('\d+', self._list[selection[0]] ))
        qty=int(qty[0])

        if(util.check_if_exists(product, self.order_list)):
            util.focus_item(util.get_index(product, self.order_list), self.Table_)
            qty_c =  int(self.Table_.tree.item(self.Table_.tree.selection())['values'][1])
            self.r = 0
        else:   
            qty_c = 1
            self.r = 1
        self.Tracker = quantity_change(False, qty-self.r, qty_c)
        quantity(1, self.root, self.body, self.Tracker)
        
        if (self.Tracker.confirm_flag == True):
            self.add_to_cart(product)
            s = self.Tracker.qty_s - (self.Tracker.qty_change - self.Tracker.qty_ref)
            self._list[selection[0]]=("("+str(s)+")"+product)
            self.list_var.set(self._list)
Beispiel #5
0
def main():
    html = ''
    count = 0
    MY_STOCKS = get_stocks()

    for item in MY_STOCKS:
        k, stock = item.split(':')
        # logging.info(stock)
        count += 1
        try:
            report = stock_check(stock, name=k)
            html += report
            logging.info(stock)
        except Exception as exp:
            logging.exception(exp)
        if count % 4 == 0:
            time.sleep(60)
    INDEX_S = get_index()
    for ind in INDEX_S:
        name, index = ind.split(':')
        # logging.info(index)
        count += 1
        try:
            report = index_check(index, name=name)
            html += report
            logging.info(index)
        except Exception as exp:
            logging.exception(exp)
        if count % 4 == 0:
            time.sleep(60)
    today = str(datetime.date.today())
    html = get_complete_html(today, html)
    #print(html)
    theme = f'{today}**诊判报告'
    send_res_to_email(contents=html, theme=theme, content_type='html')
Beispiel #6
0
 def _find_direct_speech(self, con):
     layer = self._arg_finder._iter_paula_layer(
         'speechfinder.speechdcontent')
     for _, mark in layer:
         tokens = mark.ext
         start = get_index(tokens[0])
         if start > con.start_index:
             continue
         end = get_index(tokens[-1])
         if end < con.start_index or end < con.end_index:
             continue
         sent_idx = self._arg_finder._get_sent_index(tokens[0])
         print sent_idx, con.sent_index
         if sent_idx == con.sent_index:
             # Connective is in the first sentence of the segment.
             return -1
         return sent_idx
     return -1
Beispiel #7
0
 def asnode(self):
     if len(self.indices) < len(self.tensor.shape):
         raise TensorError("Accessing a slice of tensor is not allowed")
     index, bit, _ = util.get_index(self.tensor.shape, self.indices, 0)
     if bit is None:
         return _make.Load(self.tensor.dtype, self.tensor.buf.data, index)
     elif isinstance(bit, slice):
         return _make.GetSlice(
             _make.Load(self.tensor.dtype, self.tensor.buf.data, index),
             bit.start, bit.stop)
     return _make.GetBit(
         _make.Load(self.tensor.dtype, self.tensor.buf.data, index), bit)
def left_hashtag_sentiment(aspect,pos_tweet,is_neg) :
	sentiment=['NULL']*3
	sentiment[0]=aspect	
	ctr=util.get_index(pos_tweet,aspect,0)-1
	while(pos_tweet[ctr][1]!='#' and ctr>=0)	:
		ctr=ctr-1
	else :
		if(pos_tweet[ctr][1]=='#' and ctr>=0) :
			hashtag=pos_tweet[ctr][0]
			sentiment[1]=hashtag
			sentiment[2]=get_polarity(hashtag.lstrip('#'),is_neg)
			ctr=TERMINATE
	return sentiment
Beispiel #9
0
def right_hashtag_sentiment(aspect, pos_tweet, is_neg):
    sentiment = ['NULL'] * 3
    sentiment[0] = aspect
    ctr = util.get_index(pos_tweet, aspect, 0) + 1
    while (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] != '#'):
        ctr = ctr + 1
    else:
        if (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] == '#'):
            hashtag = pos_tweet[ctr][0]
            sentiment[1] = hashtag
            sentiment[2] = get_polarity(hashtag.lstrip('#'), is_neg)
            ctr = TERMINATE
    return sentiment
def left_verb_sentiment(aspect,pos_tweet,is_neg) :
	sentiment=['NULL']*3
	sentiment[0]=aspect	
	ctr=util.get_index(pos_tweet,aspect,0)-1
	while(pos_tweet[ctr][1]!='V' and ctr>=0)	:
		ctr=ctr-1
	else :
		if(pos_tweet[ctr][1]=='V' and ctr>=0) :
			verb=pos_tweet[ctr][0]
			sentiment[1]=verb
			sentiment[2]=get_polarity(verb,is_neg)
			ctr=TERMINATE
	return sentiment
Beispiel #11
0
def left_verb_sentiment(aspect, pos_tweet, is_neg):
    sentiment = ['NULL'] * 3
    sentiment[0] = aspect
    ctr = util.get_index(pos_tweet, aspect, 0) - 1
    while (pos_tweet[ctr][1] != 'V' and ctr >= 0):
        ctr = ctr - 1
    else:
        if (pos_tweet[ctr][1] == 'V' and ctr >= 0):
            verb = pos_tweet[ctr][0]
            sentiment[1] = verb
            sentiment[2] = get_polarity(verb, is_neg)
            ctr = TERMINATE
    return sentiment
Beispiel #12
0
 def shape_map(self, pred, method):
     '''method can be one of ['max', 'mean', 'max_pca', 'mean_pca']'''
     if method == 'max':
         shape = vectorize(get_index(pred))
         shape = shape * 4
     elif method == 'mean':
         shape = vectorize(get_index_mean(pred))
         shape = shape * 4
     elif method == 'max_pca':
         shape = vectorize(get_index(pred))
         shape = shape * 4
         shape = self.pca_noise_reduction(shape)
     elif method == 'mean_pca':
         shape = vectorize(get_index_mean(pred))
         shape = shape * 4
         shape_pca = self.pca_noise_reduction(shape)
         if p.debug:
             show_predict(self.img, shape)
             show_predict(self.img, shape_pca)
     else:
         print "Unknown method: ", method
         exit(0)
     return shape
Beispiel #13
0
 def shape_map(self, pred, method):
     '''method can be one of ['max', 'mean', 'max_pca', 'mean_pca']'''
     if method == 'max':
         shape = vectorize(get_index(pred))
         shape = shape * 4
     elif method == 'mean':
         shape = vectorize(get_index_mean(pred))
         shape = shape * 4
     elif method == 'max_pca':
         shape = vectorize(get_index(pred))
         shape = shape * 4
         shape = self.pca_noise_reduction(shape)
     elif method == 'mean_pca':
         shape = vectorize(get_index_mean(pred))
         shape = shape * 4
         shape_pca = self.pca_noise_reduction(shape)
         if p.debug:
             show_predict(self.img, shape)
             show_predict(self.img, shape_pca)
     else:
         print "Unknown method: ", method
         exit(0)
     return shape
def aspect_sentiment(aspects,pos_tweets) :
	nsentiments=[]	
	sentiments=[]
	aspect_senti=[]
	for i in range(0,len(aspects)) :
		for j in range(0,len(pos_tweets)) :
			if util.get_index(pos_tweets[j],aspects[i][0],0)!=-1 :
				sentiments.append(get_sentiment(aspects[i][0],pos_tweets[j]))
		nsentiments=[sentiment for sentiment in sentiments if sentiment!=[] ]
		polarity=classify_sentiment(nsentiments)
		x=["NULL"]*2
		x[0]=aspects[i][0]
		x[1]=polarity
		aspect_senti.append(x)
	return aspect_senti
Beispiel #15
0
 def _find_right_paren(self, con, left_paren):
     right_paren = self.PARENS[left_paren]
     for i in xrange(con.sent_index, len(self._arg_finder._sents)):
         sent = self._arg_finder._sents[i]
         for token in sent.ext:
             strng = token.getString()
             if strng in self.PARENS:
                 return -1
             elif strng == right_paren:
                 # Make sure that all parts of a (possibly discontinuous)
                 # connective are included in the segment.
                 if get_index(token) < con.end_index:
                     return -1
                 return i
     return -1
def left_adjective_sentiment(aspect,pos_tweet,is_neg) :
	sentiment=['NULL']*3
	sentiment[0]=aspect	
	ctr=util.get_index(pos_tweet,aspect,0)-1
	while(pos_tweet[ctr][1]!='A' and ctr>=0)	:
		ctr=ctr-1
	else :
		if(pos_tweet[ctr][1]=='A' and ctr>=0) :
			adj=pos_tweet[ctr][0]
			sentiment[1]=adj
			if util.is_in_file('lists/comparative-words.txt',adj,False) or util.is_in_file('lists/superlative-words.txt',adj,False) : 
				sentiment[2]=switch(get_polarity(adj,is_neg))
			else :
				sentiment[2]=get_polarity(adj,is_neg)
			ctr=TERMINATE			
	return sentiment
def right_verb_sentiment(aspect,pos_tweet,is_neg) :
	sentiment=['NULL']*3
	sentiment[0]=aspect	
	ctr=util.get_index(pos_tweet,aspect,0)+1
	while(ctr>=0 and ctr<len(pos_tweet) and pos_tweet[ctr][1]!='V')	:
		ctr=ctr+1
	else :
		if(ctr>=0 and ctr<len(pos_tweet) and pos_tweet[ctr][1]=='R') :
			verb=pos_tweet[ctr][0]
			sentiment[1]=verb
			if not(util.is_in_file('lists/copulative.txt',verb,False)) and not(util.is_in_file('lists/intensifier.txt',verb,False)) :
				sentiment[2]=get_polarity(verb,is_neg)
			else :
				sentiment[2]=str('0')
			ctr=TERMINATE
		return sentiment
def found_negation(aspect,pos_tweet,wsize=NEGATION_WINDOW): 
	is_neg=False	
	if len(pos_tweet)<wsize :
		wsize=len(pos_tweet)
	ind=util.get_index(pos_tweet,aspect,0)
	if ind<wsize :
		start=0
		end=wsize-1
	else :
		start=wsize-ind+1
		end=ind	
	for i in range(start,end+1):
		word=pos_tweet[i][0]
		if util.is_in_file('lists/negative-words.txt',word,False) or util.is_in_file('lists/swear-words.txt',word,False):
			is_neg=True
	return is_neg		
def right_adjective_sentiment(aspect,pos_tweet,is_neg) :
	sentiment=['NULL']*3
	sentiment[0]=aspect	
	ctr=util.get_index(pos_tweet,aspect,0)+1
	while(ctr>=0 and ctr<len(pos_tweet) and pos_tweet[ctr][1]!='A')	:
		ctr=ctr+1
	else :
		if(ctr>=0 and ctr<len(pos_tweet) and pos_tweet[ctr][1]=='A') :
			adj=pos_tweet[ctr][0]
			sentiment[1]=adj
			if not(util.is_in_file('lists/intensifier.txt',adj,False)) :
				if util.is_in_file('lists/comparative-words.txt',adj,False) or util.is_in_file('lists/superlative-words.txt',adj,False) :
					sentiment[2]=switch(get_polarity(adj,is_neg))
				else :
					sentiment[2]=get_polarity(adj,is_neg)
			ctr=TERMINATE
	return sentiment
Beispiel #20
0
def aspect_sentiment(aspects, pos_tweets):
    nsentiments = []
    sentiments = []
    aspect_senti = []
    for i in range(0, len(aspects)):
        for j in range(0, len(pos_tweets)):
            if util.get_index(pos_tweets[j], aspects[i][0], 0) != -1:
                sentiments.append(get_sentiment(aspects[i][0], pos_tweets[j]))
        nsentiments = [
            sentiment for sentiment in sentiments if sentiment != []
        ]
        polarity = classify_sentiment(nsentiments)
        x = ["NULL"] * 2
        x[0] = aspects[i][0]
        x[1] = polarity
        aspect_senti.append(x)
    return aspect_senti
Beispiel #21
0
 def shape_map_all(self, pred):
     shapes = []
     shape_max = vectorize(get_index(pred))
     shape_max = shape_max * 4
     shape_max_pca = self.pca_noise_reduction(shape_max)
     shape_mean = vectorize(get_index_mean(pred))
     shape_mean = shape_mean * 4
     shape_mean_pca = self.pca_noise_reduction(shape_mean)
     shapes.append(shape_max)
     shapes.append(shape_max_pca)
     shapes.append(shape_mean)
     shapes.append(shape_mean_pca)
     if p.debug:
         show_predict(self.img, shape_max)
         show_predict(self.img, shape_max_pca)
         show_predict(self.img, shape_mean)
         show_predict(self.img, shape_mean_pca)
     return shapes
Beispiel #22
0
def found_negation(aspect, pos_tweet, wsize=NEGATION_WINDOW):
    is_neg = False
    if len(pos_tweet) < wsize:
        wsize = len(pos_tweet)
    ind = util.get_index(pos_tweet, aspect, 0)
    if ind < wsize:
        start = 0
        end = wsize - 1
    else:
        start = wsize - ind + 1
        end = ind
    for i in range(start, end + 1):
        word = pos_tweet[i][0]
        if util.is_in_file('lists/negative-words.txt',
                           word, False) or util.is_in_file(
                               'lists/swear-words.txt', word, False):
            is_neg = True
    return is_neg
Beispiel #23
0
def left_adjective_sentiment(aspect, pos_tweet, is_neg):
    sentiment = ['NULL'] * 3
    sentiment[0] = aspect
    ctr = util.get_index(pos_tweet, aspect, 0) - 1
    while (pos_tweet[ctr][1] != 'A' and ctr >= 0):
        ctr = ctr - 1
    else:
        if (pos_tweet[ctr][1] == 'A' and ctr >= 0):
            adj = pos_tweet[ctr][0]
            sentiment[1] = adj
            if util.is_in_file('lists/comparative-words.txt', adj,
                               False) or util.is_in_file(
                                   'lists/superlative-words.txt', adj, False):
                sentiment[2] = switch(get_polarity(adj, is_neg))
            else:
                sentiment[2] = get_polarity(adj, is_neg)
            ctr = TERMINATE
    return sentiment
Beispiel #24
0
def right_verb_sentiment(aspect, pos_tweet, is_neg):
    sentiment = ['NULL'] * 3
    sentiment[0] = aspect
    ctr = util.get_index(pos_tweet, aspect, 0) + 1
    while (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] != 'V'):
        ctr = ctr + 1
    else:
        if (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] == 'R'):
            verb = pos_tweet[ctr][0]
            sentiment[1] = verb
            if not (util.is_in_file('lists/copulative.txt', verb,
                                    False)) and not (util.is_in_file(
                                        'lists/intensifier.txt', verb, False)):
                sentiment[2] = get_polarity(verb, is_neg)
            else:
                sentiment[2] = str('0')
            ctr = TERMINATE
        return sentiment
Beispiel #25
0
 def shape_map_all(self, pred):
     shapes = []
     shape_max = vectorize(get_index(pred))
     shape_max = shape_max * 4
     shape_max_pca = self.pca_noise_reduction(shape_max)
     shape_mean = vectorize(get_index_mean(pred))
     shape_mean = shape_mean * 4
     shape_mean_pca = self.pca_noise_reduction(shape_mean)
     shapes.append(shape_max)
     shapes.append(shape_max_pca)
     shapes.append(shape_mean)
     shapes.append(shape_mean_pca)
     if p.debug:
         show_predict(self.img, shape_max)
         show_predict(self.img, shape_max_pca)
         show_predict(self.img, shape_mean)
         show_predict(self.img, shape_mean_pca)
     return shapes
Beispiel #26
0
 def _find_left_paren(self, sents, con):
     frontier = max(
         0,
         min(con.sent_index - len(sents),
             con.sent_index - self.MAX_LOOKBEHIND))
     for i in xrange(con.sent_index - 1, frontier - 1, -1):
         sent = self._arg_finder._sentences[i].ext
         for j in xrange(len(sent) - 1, -1, -1):
             token = sent[j]
             strng = token.getString()
             if strng in self.RIGHT_PARENS:
                 return -1, None
             elif strng in self.PARENS:
                 # Make sure that all parts of a (possibly discontinuous)
                 # connective are included in the segment.
                 if get_index(token) > con.start_index:
                     return -1, None
                 return i, strng
     return -1, None
Beispiel #27
0
def right_adjective_sentiment(aspect, pos_tweet, is_neg):
    sentiment = ['NULL'] * 3
    sentiment[0] = aspect
    ctr = util.get_index(pos_tweet, aspect, 0) + 1
    while (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] != 'A'):
        ctr = ctr + 1
    else:
        if (ctr >= 0 and ctr < len(pos_tweet) and pos_tweet[ctr][1] == 'A'):
            adj = pos_tweet[ctr][0]
            sentiment[1] = adj
            if not (util.is_in_file('lists/intensifier.txt', adj, False)):
                if util.is_in_file('lists/comparative-words.txt', adj,
                                   False) or util.is_in_file(
                                       'lists/superlative-words.txt', adj,
                                       False):
                    sentiment[2] = switch(get_polarity(adj, is_neg))
                else:
                    sentiment[2] = get_polarity(adj, is_neg)
            ctr = TERMINATE
    return sentiment
Beispiel #28
0
def find_first_zero(array, galloc=__default_alloca):
    idx = get_index(0, array)
    get_arr = galloc("array", __build_java_array_fun, array)
    return f"""int [] arr = {get_arr}();
Beispiel #29
0
def binarysearch(high, expected_mid=None):
    key = __get_key(expected_mid, high, __array)
    result = get_index(key, __array)

    return f"""int [] array = {get_array};
Beispiel #30
0
if __name__ == '__main__':
    # usage: python shift_exp.py prototxt model layername root
    # filelists outRoot
    prototxt = sys.argv[1]
    model = sys.argv[2]
    layername = sys.argv[3]
    root = sys.argv[4]
    filelists = sys.argv[5]
    outRoot = sys.argv[6]

    net = caffe.Net(prototxt, model, caffe.TEST)
    (filenames, bbxs) = get_filenames_bbx(filelists)
    index = range(len(filenames))
    random.shuffle(index)
    for i in index:
        print i, filenames[i], bbxs[i][0], bbxs[i][1], bbxs[i][2], bbxs[i][3]
        img_crops = shift_exp(root, filenames[i], bbxs[i], outRoot)
        preds = get_preds_multiple(net, layername, img_crops)
        preds_shape = preds.shape
        preds = softmax(np.reshape(preds, (preds_shape[0]*preds_shape[1], \
            preds_shape[2]*preds_shape[3])))
        preds = np.reshape(preds, preds_shape)
        (hp, wp) = get_index(preds)
        hp = hp * 4
        wp = wp * 4
        for i in range(9):
            plt.subplot(3, 3, i + 1)
            plt.imshow(img_crops[i])
            plt.plot(wp[i], hp[i], '.g', hold=True)
        plt.show()
Beispiel #31
0
for epoch in range(num_epochs):
    print("Epoch: {}/{}".format(epoch + 1, num_epochs))
    epoch_loss = 0
    h0, c0 = Variable(torch.zeros(1, size_batch, lstm_dim)), Variable(
        torch.zeros(1, size_batch, lstm_dim))
    for batch in range(num_batches):
        # if((batch+1) % 50 == 0 or (batch+1) == num_batches):
        #     print("Training on batch: {}/{}".format(batch+1,num_batches))
        batch_begin = batch * size_batch
        batch_end = (batch + 1) * size_batch

        x_data = []
        y_data = []
        for i in range(batch_begin, batch_end):
            #x_data.append(util.convert_to_one_hot(words[i], words2int, vocab_size)) #caso one-hot
            x_data.append(util.get_index(words[i],
                                         words2int))  #caso indice per parola
            y_data.append(labels[i])

        x_tensor = Variable(torch.FloatTensor(x_data))
        y_tensor = Variable(torch.FloatTensor(y_data))

        optimizer.zero_grad()

        y_prob, (hn, cn) = model(torch.unsqueeze(x_tensor, 1), (h0, c0))
        loss = criterion(torch.squeeze(y_prob, 2),
                         torch.unsqueeze(y_tensor, 1))
        loss = torch.mul(class_weights, loss)
        loss = torch.mean(loss)
        loss.backward()
        optimizer.step()
        epoch_loss += loss.item()
Beispiel #32
0
if __name__ == '__main__':
    # usage: python shift_exp.py prototxt model layername root 
    # filelists outRoot
    prototxt = sys.argv[1]
    model = sys.argv[2]
    layername = sys.argv[3]
    root = sys.argv[4]
    filelists = sys.argv[5]
    outRoot = sys.argv[6]

    net = caffe.Net(prototxt, model, caffe.TEST)
    (filenames, bbxs) = get_filenames_bbx(filelists)
    index = range(len(filenames))
    random.shuffle(index)
    for i in index:
        print i, filenames[i], bbxs[i][0], bbxs[i][1], bbxs[i][2], bbxs[i][3]
        img_crops = shift_exp(root, filenames[i], bbxs[i], outRoot)
        preds = get_preds_multiple(net, layername, img_crops)
        preds_shape = preds.shape
        preds = softmax(np.reshape(preds, (preds_shape[0]*preds_shape[1], \
            preds_shape[2]*preds_shape[3])))
        preds = np.reshape(preds, preds_shape)
        (hp, wp) = get_index(preds)
        hp = hp * 4
        wp = wp * 4
        for i in range(9):
            plt.subplot(3, 3, i+1)
            plt.imshow(img_crops[i])
            plt.plot(wp[i], hp[i],'.g', hold=True)
        plt.show()
Beispiel #33
0
def compute_body(name,
                 lambda_ivs,
                 fcompute,
                 shape=(),
                 dtype=None,
                 tensor=None,
                 attrs=OrderedDict()):
    """Create a stage and perform the computation.

    If `tensor` is `None`, no tensor is returned.

    Parameters
    ----------
    name : str
        The name of the stage

    lambda_ivs : list of IterVar
        A list contains the iteration variables in the lambda function if
        exists

    fcompute : callable
        The computation rule

    shape : tuple, optional
        The output shape or the iteration domain

    dtype : Type, optional
        The data type of the output/updated tensor

    tensor : Tensor, optional
        The tensor to be updated. Create a new one if it is `None`

    Returns
    -------
    Tensor or None
    """
    var_list = [i.var for i in lambda_ivs]
    return_tensor = True if tensor is None else False

    with Stage(name, dtype, shape) as stage:
        if not return_tensor:
            stage.input_stages.add(tensor.last_update)
        else:
            tensor = Tensor(shape, stage._dtype, name, stage._buf)
        buffer_var = tensor._buf.data
        dtype = tensor.dtype
        shape = tensor.shape

        stage.stmt_stack.append([])
        ret = fcompute(*var_list)

        print(dir(ret))
        print(dir(ret.a))
        print(dir(ret.b))
        stage.lhs_tensors.add(tensor)
        for t in stage.lhs_tensors:
            t.last_update = stage

        stmt = None
        if ret is None:
            # replace all hcl.return_ with Store stmt
            indices = lambda_ivs
            index, _, _ = get_index(shape, indices, 0)
            stmt = stage.pop_stmt()
            stmt = ReplaceReturn(buffer_var, dtype, index).mutate(stmt)
            stmt = make_for(indices, stmt, 0)
        elif isinstance(ret,
                        (TensorSlice, Scalar, _expr.Expr, numbers.Number)):
            indices = lambda_ivs
            index, _, _ = get_index(shape, indices, 0)
            stage.emit(_make.Store(buffer_var, _make.Cast(dtype, ret), index))
            stmt = make_for(indices, stage.pop_stmt(), 0)
        elif isinstance(ret, Tensor):  # reduction
            ret_ivs = [
                _IterVar((0, ret.shape[i]), ret.name + "_i" + str(i), 0)
                for i in range(0, len(ret.shape))
            ]
            non_reduce_ivs = []
            indices = []
            rid = 0
            for iv in lambda_ivs:
                if iv.var.name[0] == "_":
                    indices.append(ret_ivs[rid])
                    rid += 1
                else:
                    indices.append(iv)
                    non_reduce_ivs.append(iv)
            if rid != len(ret.shape):
                raise APIError(
                    "Incorrect number of reduction axes in lambda arguments")
            index, _, _ = get_index(shape, indices, 0)
            st = _make.Store(buffer_var,
                             _make.Cast(dtype, ret[tuple(ret_ivs)]), index)
            stage.emit(make_for(ret_ivs, st, 0))
            stmt = stage.pop_stmt()
            stage.input_stages.remove(stage)
            if non_reduce_ivs:
                stmt = make_for(non_reduce_ivs, stmt, 0)
        else:
            raise APIError("Unknown return type of the computation rule")
        # add attributes to the loop
        if isinstance(stmt, _stmt.For):
            stmt = _make.For(stmt.loop_var, stmt.min, stmt.extent, 0,
                             0, stmt.body, list(attrs.keys()),
                             list(attrs.values()))
        stage.emit(stmt)
        stage.axis_list = indices + stage.axis_list

    if return_tensor:
        tensor._tensor = stage._op
        return tensor
    return None