Pinescript to Python getting The truth value of a Series is ambiguous - python

I'm converting a Pinescript Indicator to python to use it with pandas:
Here is pinescrip code:
RSI_Period = input(14,title='RSI')
SF = input(5,title='Slow Factor')
QQE=input(4.236)
Wilders_Period = RSI_Period * 2 - 1
Rsi = rsi(close,RSI_Period)
RsiMa = ema(Rsi, SF)
AtrRsi = abs(RsiMa[1] - RsiMa)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
dar = ema(MaAtrRsi,Wilders_Period) * QQE
DeltaFastAtrRsi= dar
RSIndex=RsiMa
newshortband= RSIndex + DeltaFastAtrRsi
newlongband= RSIndex - DeltaFastAtrRsi
longband=RSIndex[1] > longband[1] and RSIndex > longband[1]?
max(longband[1],newlongband):newlongband
shortband=RSIndex[1] < shortband[1] and RSIndex < shortband[1]?
min(shortband[1], newshortband):newshortband
trend=cross(RSIndex, shortband[1])?1:cross(longband[1], RSIndex)?-1:nz(trend[1],1)
FastAtrRsiTL = trend==1? longband: shortband
plot(FastAtrRsiTL,color=red)
plot(RsiMa,color=yellow)
Now this is what I got so far in python:
RSIPeriod = 14
SF = 5
QQE=4.236
WildersPeriod = RSIPeriod * 2 - 1
df['RSI'] = ta.RSI(df['Price'], RSIPeriod)
df['RSI_ma'] = ta.EMA(df['RSI'], SF)
df['ATRrsi'] = abs(df['RSI_ma'].shift(1) - df['RSI_ma'])
df['MaATRrsi'] = ta.EMA(df['ATRrsi'], WildersPeriod)
df['dar'] = ta.EMA(df['MaATRrsi'], WildersPeriod) * QQE
df['newshortband'] = df['RSI_ma'] + df['dar']
df['newlongband'] = df['RSI_ma'] - df['dar']
df['longband'] = 0.0
df['longband'] = np.where( df['RSI_ma'].shift(1) > df['longband'].shift(1) and df['RSI_ma'] > df['longband'].shift(1),
max(df['longband'].shift(1) ,df['newlongband']), df['newlongband'])
df['shortband'] = 0.0
df['shortband'] = np.where( df['RSI_ma'].shift(1) < df['shortband'].shift(1) and df['RSI_ma'] < df['shortband'].shift(1),
max(df['shortband'].shift(1) ,df['newshortband']), df['newshortband'])
df['trend'] = np.where(df['RSI_ma'] > df['dar'].shift(1), 1, -1)
df['FastAtrRsiTL'] = np.where(df['trend'] == 1, df['longband'], df['shortband'])
And this is the error:
----> 4 df['longband'] = np.where( df['RSI_ma'].shift(1) > df['longband'].shift(1) and df['RSI_ma'] > df['longband'].shift(1),
5 max(df['longband'].shift(1) ,df['newlongband']), df['newlongband'])
6 df['shortband'] = 0.0
~\Anaconda3\envs\finance\lib\site-packages\pandas\core\generic.py in nonzero(self)
1571 raise ValueError("The truth value of a {0} is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.class.name))
1574
1575 bool = nonzero
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I've managed to create a python function which takes a QQE indicator from TradingView.
The input is a Pandas.DataFrame which needs to have the column 'Close' that contains the Close price of the candles.
You can ofcourse change the input to fit your own parameters and needs.
def QQE(_candles):
#https://www.tradingview.com/script/tJ6vtBBe-QQE/
Close = _candles.Close
Fast=2.6180
Slow=4.2360
RSI=14
SF=2
def WiMA(src, length):
MA_s = [0]
for i, x in enumerate(src):
MA_s.append( (x + (MA_s[i] * (length-1)))/length )
return MA_s
def crossovers(p1,p2):
a = []
for i in range(1,min(len(p1),len(p2))):
if p1[i] < p2[i] and not p1[i-1] < p2[i-1]:
a.append(True)
elif p1[i] > p2[i] and not p1[i-1] > p2[i-1]:
a.append(True)
else:
a.append(False)
return a
RSIndex = ta.ema(ta.rsi(Close, RSI, fillna=0), SF, fillna=0)
TR = [0]
for i in range(1, len(Close)):
TH = RSIndex[i-1] if RSIndex[i-1] > RSIndex[i] else RSIndex[i]
TL = RSIndex[i-1] if RSIndex[i-1] < RSIndex[i] else RSIndex[i]
TR.append(TH - TL)
AtrRsi= WiMA(TR, 14)
SmoothedAtrRsi= WiMA(AtrRsi, 14)
# FastQQE
DeltaFastAtrRsi = [x*Fast for x in SmoothedAtrRsi]
newlongband = [x - i for x, i in zip(RSIndex,DeltaFastAtrRsi)]
longband = [0]
for i in range(1,len(RSIndex)):
if RSIndex[i-1] > longband[i-1] and RSIndex[i] > longband[i-1]:
longband.append(max(longband[i-1],newlongband[i]))
else:
longband.append(newlongband[i])
newshortband = [x + i for x, i in zip(RSIndex,DeltaFastAtrRsi)]
shortband = [0]
for i in range(1,len(RSIndex)):
if RSIndex[i-1] < shortband[i-1] and RSIndex[i] < shortband[i-1]:
shortband.append(min(shortband[i-1],newshortband[i]))
else:
shortband.append(newshortband[i])
trend = [0,0]
shortbandCross = crossovers(RSIndex, [0]+shortband)
longbandCross = crossovers([0]+longband, RSIndex)
for i in range(1,len(shortbandCross)):
if shortbandCross[i] == True:
trend.append(1)
elif longbandCross[i] == True:
trend.append(-1)
else:
trend.append(trend[i])
FastAtrRsiTL = [longband[i] if trend[i] == 1 else shortband[i] for i in range(len(trend))]
# SlowQQE
DeltaSlowAtrRsi = [x*Slow for x in SmoothedAtrRsi]
newlongband1 = [x - i for x, i in zip(RSIndex,DeltaSlowAtrRsi)]
longband1 = [0]
for i in range(1,len(RSIndex)):
if RSIndex[i-1] > longband1[i-1] and RSIndex[i] > longband1[i-1]:
longband1.append(max(longband1[i-1],newlongband1[i]))
else:
longband1.append(newlongband1[i])
newshortband1 = [x + i for x, i in zip(RSIndex,DeltaSlowAtrRsi)]
shortband1 = [0]
for i in range(1,len(RSIndex)):
if RSIndex[i-1] < shortband1[i-1] and RSIndex[i] < shortband1[i-1]:
shortband1.append(min(shortband1[i-1],newshortband1[i]))
else:
shortband1.append(newshortband1[i])
trend1 = [0,0]
shortbandCross1 = crossovers(RSIndex, [0]+shortband1)
longbandCross1 = crossovers([0]+longband1, RSIndex)
for i in range(1,len(shortbandCross1)):
if shortbandCross1[i] == True:
trend1.append(1)
elif longbandCross1[i] == True:
trend1.append(-1)
else:
trend1.append(trend1[i])
SlowAtrRsiTL = [longband1[i] if trend1[i] == 1 else shortband1[i] for i in range(len(trend1))]
return FastAtrRsiTL, SlowAtrRsiTL

Related

Pivot function results differ from TradingView

I'm using this code to calculate pivot points.
def pivots_low(osc, LBR, LBL):
pivots = []
for i in range(len(osc) - LBR):
pivots.append(0)
pivot = True
if i > LBL:
for j in range(1, LBR + 1):
if osc[i] >= osc[i + j]:
pivot = False
for j in range(1, LBL + 1):
if osc[i] > osc[i - j]:
pivot = False
if pivot is True:
pivots[len(pivots) - 1] = osc[i]
for i in range(LBR):
pivots.append(0)
return pivots
This returns an array with 0's where there's no pivots and the value of the pivot if there is one.
When Comparing the results to TradingView (downloaded csv with pivot points), the only time it matches exactly is when lookback left and right are both 5. Otherwise it deviates in the number of total pivots and the location of some.
But using this code to calculate pivot highs:
def pivots_high(osc, LBR, LBL):
pivots = []
for i in range(len(osc)-LBR):
pivots.append(0)
pivot = True
if i > LBL:
for j in range(1,LBL + 1):
if osc[i] < osc[i-j]:
pivot = False
for j in range(1,LBR + 1):
if osc[i] <= osc[i+j]:
pivot = False
if pivot is True:
pivots[len(pivots)-1] = osc[i]
for i in range(LBR):
pivots.append(0)
return pivots
the results are perfect regardless of lookback values. But the code is almost exactly the same besides comparison.
What is going wrong here? This is day 3 of having this problem and I just cant fix it
To Reproduce:
Load Data:
Full_Data = pd.read_csv(file)
use this simple function to check matches between calculated pivots and TradingView pivots.
def match_pivs(data, pivs_h, pivs_l): //Data is a DataFrame loaded from tradingview csv
global lblh
global lbrh
global lbll
global lbrl
start = lbrh
if lbrl > lbrh:
start = lbrl
match_h = 0
tot_hd = 0
tot_hp = 0
match_l = 0
tot_ld = 0
tot_lp = 0
for i in range(start, len(data)):
if data['PivHigh'][i] != 0 and pivs_h[i-lbrh] != 0:
match_h += 1
if data['PivLow'][i] != 0 and pivs_l[i-lbrl] != 0:
match_l += 1
if data['PivHigh'][i] != 0:
tot_hd += 1
if data['PivLow'][i] != 0:
tot_ld += 1
if pivs_h[i] != 0:
tot_hp += 1
if pivs_l[i] != 0:
tot_lp += 1
print('PivsLow ' + str(tot_lp))
print('DataLows ' + str(tot_ld))
print('MatchesL ' + str(match_l))
print('PivsHigh ' + str(tot_hp))
print('DataHighs ' + str(tot_hd))
print('MatchesH ' + str(match_h))
and to get csv from TradingView:
//#version=5
indicator("Data Script", overlay=true, max_labels_count=500)
leftLenL = input.int(title="Pivot Low", defval=10, minval=1, inline="Pivot Low", group=lengthGroupTitle)
rightLenL = input.int(title="/", defval=10, minval=1, inline="Pivot Low", group=lengthGroupTitle)
leftLenH = input.int(title="Pivot High", defval=10, minval=1, inline="Pivot High", group=lengthGroupTitle)
rightLenH = input.int(title="/", defval=10, minval=1, inline="Pivot High", group=lengthGroupTitle)
ph = ta.pivothigh(leftLenH, rightLenH)
pl = ta.pivotlow(leftLenL, rightLenL)
if not na(ph)
plth := ph
else
plth := 0.0
if not na(pl)
pltl := pl
else
pltl := 0.0
plot(plth, 'PivHigh')
plot(pltl, 'PivLow')
then just download csv with this script loaded.
Run program with these three lines:
pl = pivots_low(Full_Data['low'], lbll, lbrl)
ph = pivots_high(Full_Data['high'], lbrh, lblh)
match_pivs(Full_Data, ph, pl)
Finally found a way.
I still have no idea why that code does not work but I've made a different way that seems to be doing the job 100% to tradingview data.
def checkhl(data_back, data_forward, hl):
if hl == 'high' or hl == 'High':
ref = data_back[len(data_back)-1]
for i in range(len(data_back)-1):
if ref < data_back[i]:
return 0
for i in range(len(data_forward)):
if ref <= data_forward[i]:
return 0
return 1
if hl == 'low' or hl == 'Low':
ref = data_back[len(data_back)-1]
for i in range(len(data_back)-1):
if ref > data_back[i]:
return 0
for i in range(len(data_forward)):
if ref >= data_forward[i]:
return 0
return 1
def pivot(osc, LBL, LBR, highlow)
left = []
right = []
for i in range(len(osc)):
pivots.append(0.0)
if i < LBL + 1:
left.append(osc[i])
if i > LBL:
right.append(osc[i])
if i > LBL + LBR:
left.append(right[0])
left.pop(0)
right.pop(0)
if checkhl(left, right, highlow):
pivots[i - LBR] = osc[i - LBR]
return pivots
then just do:
pivots_low = pivot(data, lbl, lbr, 'low')
pivots_high = pivot(data, lbl, lbr, 'high')
All the pivots will be in the actual position that they occur, not lbr bars after, otherwise the value will be 0.0
I'm not sure if this is efficient or not but it seems to work.

Python - While trying to calculate RSI(Relative strength index - stock indicator) my results are "upside down" and shifted

I am trying to calculate RSI using simple functions.
The general formula for it is:
RSI = 100/(1+RS), where RS = Exponential Moving Average of gains / -||- of losses.
Here is what I am getting:
enter image description here
Here it is how should it look like:
enter image description here
I have everything double checked or even triple checked, but I can't find any mistake.
Thus I need your help, I know that the question is very simple though I need some help, I have no idea where I have made the mistake.
The general idea of RSI is that it should be low where the price is "low" and high, where the price is high, and generally no matter what I try I have it upside down.
def EMA(close_price_arr, n):
a = (2/n + 1)
EMA_n = np.empty((1, len(close_price_arr)))
for i in range(len(close_price_arr)):
if i < n:
# creating NaN values where it is impossible to calculate EMA to drop it later after connecting the whole database
EMA_n[0, i] = 'NaN'
if i >= n:
# Calaculating nominator and denominator of EMA
for j in range(n):
nominator_ema += close_price_arr[i - j] * a**(j)
denominator_ema += a**(j)
EMA_n[0, i] = nominator_ema / denominator_ema
nominator_ema = 0
denominator_ema = 0
return EMA_n
def gains(close_price_arr):
gain_arr = np.empty((len(close_price_arr) - 1))
for i in range(len(close_price_arr)):
if i == 0:
pass
if i >= 1:
if close_price_arr[i] > close_price_arr[i - 1]:
gain_arr[i - 1] = (close_price_arr[i] - close_price_arr[i-1])
else:
gain_arr[i - 1] = 0
return gain_arr
def losses(close_price_arr):
loss_arr = np.empty((len(close_price_arr) - 1))
for i in range(len(close_price_arr)):
if i == 0:
pass
if i >= 1:
if close_price_arr[i] < close_price_arr[i - 1]:
loss_arr[i - 1] = abs(close_price_arr[i] - close_price_arr[i - 1])
else:
loss_arr[i - 1] = 0
return loss_arr
def RSI(gain_arr, loss_arr, n):
EMA_u = EMA(gain_arr, n)
EMA_d = EMA(loss_arr, n)
EMA_diff = EMA_u / EMA_d
x,y = EMA_diff.shape
print(x, y)
RSI_n = np.empty((1, y))
for i in range(y):
if EMA_diff[0, i] == 'NaN':
RSI_n[0, i] = 'NaN'
print(i)
else:
RSI_n[0, i] = 100 / (1 + EMA_diff[0, i])
return RSI_n
#contextmanager
def show_complete_array():
oldoptions = np.get_printoptions()
np.set_printoptions(threshold=np.inf)
try:
yield
finally:
np.set_printoptions(**oldoptions)
np.set_printoptions(linewidth=3000)
pd.set_option('display.max_columns', None)
# Specyfying root folder, file folder and file
FILE = 'TVC_SILVER, 5.csv'
FOLDER = 'src'
PROJECT_ROOT_DIR = '.'
csv_path = os.path.join(PROJECT_ROOT_DIR, FOLDER, FILE)
# reading csv
price_data = pd.read_csv(csv_path, delimiter=',')
price_data_copy = price_data.copy()
price_data_nodate = price_data.copy().drop('time', axis=1)
price_data_np = price_data_nodate.to_numpy(dtype='float32')
close_price = price_data_np[:, 3]
EMA15 = EMA(close_price_arr=close_price, n=15)
EMA55 = EMA(close_price_arr=close_price, n=55)
gain = gains(close_price_arr=close_price)
loss = losses(close_price_arr=close_price)
RSI14 = RSI(gain_arr=gain, loss_arr=loss, n=14)
Try this:
"""dataset is a dataframe"""
def RSI(dataset, n=14):
delta = dataset.diff()
dUp, dDown = delta.copy(), delta.copy()
dUp[dUp < 0] = 0
dDown[dDown > 0] = 0
RolUp = pd.Series(dUp).rolling(window=n).mean()
RolDown = pd.Series(dDown).rolling(window=n).mean().abs()
RS = RolUp / RolDown
rsi= 100.0 - (100.0 / (1.0 + RS))
return rsi

TypeError: 'instancemethod' object is unsubscriptable in python

I'm working on my python script to get the list of buttons. I have got a problem with the code. When I pressed on the down arrow button of the keyboard, I get an error: TypeError: 'instancemethod' object is unsubscriptable
The error are jumping on this line:
for channel in channels[page_no*7:page_no*7+7]:
Here is the full code:
#get actioncodes from keyboard.xml
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
CHANNELS_PER_PAGE = 7
class MyClass(xbmcgui.WindowXML):
def __new__(cls):
return super(MyClass, cls).__new__(cls, 'script-tvguide-mainmenu.xml', ADDON.getAddonInfo('path'))
def __init__(self):
self._timel = []
self.thread = None
self.buttonList=[]
self.last_page = False
def All_Channels(self):
yellow_flag = True
global __killthread__
self.getControl(4202).setLabel("0%")
try:
# DOWNLOAD THE XML SOURCE HERE
url = ADDON.getSetting('allchannel.url')
data = ''
response = urllib2.urlopen(url)
meta = response.info()
file_size = int(meta.getheaders("Content-Length")[0])
file_size_dl = 0
block_size = 2048
while True and not __killthread__:
mbuffer = response.read(block_size)
if not mbuffer:
break
file_size_dl += len(mbuffer)
data += mbuffer
state = int(file_size_dl * 10.0 / file_size)
self.getControl(4202).setLabel(str(state) + '%')
else:
if __killthread__:
raise AbortDownload('downloading')
del response
# CREATE DATABASE
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))
if os.path.exists(profilePath):
os.remove(profilePath)
con = database.connect(profilePath)
cur = con.cursor()
cur.execute('CREATE TABLE programs(channel TEXT, title TEXT, start_date TIMESTAMP, stop_date TIMESTAMP, description TEXT)')
con.commit()
# Get the loaded data
total_count = data.count('programme')/2
tv_elem = ElementTree.parse(StringIO.StringIO(data)).getroot()
cur = con.cursor()
count = 1
channels = OrderedDict()
for channel in tv_elem.findall('channel'):
channel_name = channel.find('display-name').text
for program in channel.findall('programme'):
if __killthread__:
raise AbortDownload('filling')
title = program.find('title').text
start_time = program.get("start")
stop_time = program.get("stop")
cur.execute("INSERT INTO programs(channel, title, start_date, stop_date)" + " VALUES(?, ?, ?, ?)", [channel_name, title, start_time, stop_time])
status = 10 + int(float(count)/float(total_count) * 90.0)
self.getControl(4202).setLabel(str(status) + '%')
xbmc.sleep(10)
count += 1
con.commit()
print 'Channels have been successfully stored into the database!'
self.getControl(4202).setLabel('100%')
xbmc.sleep(3000)
# Set the date and time row
current_time = time.time() # now (in seconds)
half_hour = current_time + 60*30 # now + 30 minutes
one_hour = current_time + 60*60 # now + 60 minutes
for t in [current_time,half_hour,one_hour]:
if (0 <= datetime.datetime.now().minute <= 29):
self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':00' + time.strftime("%p"))
self.getControl(4205).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
self.getControl(4206).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)).lstrip("0"))
else:
self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
self.getControl(4205).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)).lstrip("0"))
self.getControl(4206).setLabel(time.strftime("%I" + ":30%p",time.localtime(t)).lstrip("0"))
#Pull the data from the database
channelList = list()
database_path = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', 'source.db'))
if os.path.exists(database_path):
#get the channels list
cur.execute('SELECT channel FROM programs WHERE channel GROUP BY channel')
for row in cur:
channels = row[0].encode('ascii')
channelList.append(channels)
# set the channels text
for index in range(0, CHANNELS_PER_PAGE):
channel = channelList[index]
channel_index = index
if channel is not None:
pass
#self.getControl(4207 + index).setLabel(channel)
#self.button.setLabel(channel, 'font14', '0xFFFFFFFF', '0xFFFF3300', '0xFF000000')
#get the programs list
cur.execute('SELECT channel, title, start_date, stop_date FROM programs WHERE channel=?', [channel])
programList = list()
programs = cur.fetchall()
start_pos = 368 # indent for first program
for row in programs:
program = row[1].encode('ascii'), str(row[2]), str(row[3])
title = row[1].encode('ascii')
program_start_date = str(row[2])
program_end_date = str(row[3])
#convert the date formats into minutes
minutes_start = self.parseDateTimeToMinutesSinceEpoch(program_start_date)
minutes_end = self.parseDateTimeToMinutesSinceEpoch(program_end_date)
minutes_length = minutes_end - minutes_start
program_length = minutes_length
program_notification = program
programs_top_backup = 0
programs_top = 315
program_height = 34.5
program_gap = 2.5
position_start = start_pos
position_top = programs_top + channel_index * (program_height + program_gap)
if 10 <= program_length < 60:
program_width = 342.5
elif 60 <= program_length < 90:
program_width = 690
elif 90 <= program_length < 105:
program_width = 1050
elif 105 <= program_length < 120:
program_width = 1400
elif 120 <= program_length < 150:
program_width = 1750
elif 150 <= program_length < 180:
program_width = 2100
elif 180 <= program_length < 210:
program_width = 2450
elif 210 <= program_length < 240:
program_width = 2800
elif 240 <= program_length < 270:
program_width = 3150
elif 270 <= program_length < 300:
program_width = 3500
elif 300 <= program_length < 330:
program_width = 3850
elif 330 <= program_length < 360:
program_width = 4200
elif 360 <= program_length < 390:
program_width = 3250
elif 390 <= program_length < 420:
program_width = 4550
elif 420 <= program_length < 450:
program_width = 4900
elif 450 <= program_length < 480:
program_width = 5250
start_pos += program_width + 2 * program_gap
if program_width > 1:
if yellow_flag:
if program_notification:
button_nofocus = 'changelang_yellow.png'
button_focus = 'channels_bar1.png'
else:
button_nofocus = 'changelang_yellow.png'
button_focus = 'channels_bar1.png'
yellow_flag = False
text_color = '0xFF000000'
else:
if program_notification:
button_nofocus = 'channels_bar1.png'
button_focus = 'channels_yellow.png'
else:
button_nofocus = 'channels_bar1.png'
button_focus = 'channels_yellow.png'
text_color = '0xFFFFFFFF'
if program_width < 1:
program_title = ''
else:
program_title = '[B]' + title + '[/B]'
def showepg(self, channels, page_no):
self.last_page = False
self.removeControls(self.buttonList)
self.buttonList = []
page_no = 0
self.button = [[0 for x in xrange(20)] for x in xrange(20)]
self.pdata = [[dict() for x in xrange(20)] for x in xrange(20)]
row = 0
for channel in channels[page_no*7:page_no*7+7]:
#get the list of buttons in array
print channel
self.pdata[row][0]['url'] = channel['url']
self.pdata[row][0]['cname'] = xbmcgui.ControlLabel(0, self.startPos + 17 + (row * row_height), 100, row_height,channel['callSign'])
self.pdata[row][0]['cicon'] = channel['thumbnail'].replace('\\','')
self.pdata[row][0]['cimage'] = xbmcgui.ControlImage(100, self.startPos + (row * row_height), logo_width, logo_width,self.pdata[row][0]['cicon'])
self.buttonList.append(self.pdata[row][0]['cimage'])
self.buttonList.append(self.pdata[row][0]['cname'])
events = channel['events']
col = 0
coffset = 0
for event in events:
try:
self.pdata[row][col]['desc'] = '%s - %s\n%s' % (event['startTimeDisplay'], event['endTimeDisplay'], str(event['program']['description']))
#except:
self.pdata[row][col]['desc'] = ""
self.pdata[row][col]['duration'] = str(event['duration'])
self.pdata[row][col]['eptitle'] = '%s - %s : %s' % (event['startTimeDisplay'], event['endTimeDisplay'], event['eptitle'])
cwidth = int((float(event['percentWidth']) / 100) * progs_width)
self.button[row][col] = xbmcgui.ControlButton(poffset + coffset, self.startPos + (row * row_height), cwidth, row_height, event['program']['title'])
self.buttonList.append(self.button[row][col])
coffset = coffset + cwidth
col = col + 1
row = row + 1
if row == MAXIMUMROW:
break
self.addControls(self.buttonList)
if row == 0:
self.current_page = 0
self.showepg(channels, 0) # hack to display first page after last page - could be problem for empty epg
return
elif row < MAXIMUMROW:
self.last_page = True
maxrow = row
for row in range(maxrow + 1):
for col in range(20):
if self.button[row][col] == 0:
break
else:
if row < maxrow-1:
self.button[row][col].controlDown(self.button[row+1][0])
if row == maxrow-1:
if maxrow == MAXIMUMROW:
self.button[row][col].controlDown(self.button[row][col])
if col > 0:
self.button[row][col].controlLeft(self.button[row][col-1])
self.button[row][col-1].controlRight(self.button[row][col])
if row > 0:
self.button[row][col].controlUp(self.button[row-1][0])
if row == 0:
self.button[row][col].controlUp(self.button[row][col])
self.topRow = True
self.bottomRow = False
control = self.button[0][0]
self.setFocus(control)
self.updateEpg(control)
def onAction(self, action):
self.current_page = 0
self.last_page = False
if action == ACTION_MOVE_DOWN:
if allchannels_enabled:
if self.last_page:
self.current_page = 0
else:
self.current_page += 1
self.showepg(self.All_Channels, self.current_page)
return
I don't understand what the error are means. I'm trying to defined the channels to get the button control using the self.All_Channels when pressed on the down arrow button.
Do anyone know why I get an error and how to fix this?
The error means you're using [] on something that doesn't support it, this can be reproduced with (for example): None[0].
Now, the specific problem in your code appears to be:
self.showepg(self.All_Channels, self.current_page)
That this does, is pass the function self.All_Channels to the self.showepg function. this is why you're seeing instancemethod in the error, what you probably want to do, is to add parenthesis here:
self.showepg(self.All_Channels(), self.current_page)

Triangulation with holes in python

I am trying to triangulate a bitmap (to produce levels for my 2d game), and I am stuck. I am using the Triangle library by Jonathan Shewchuk using this wrapper.
I start with an image,
then I detect edges and determine which vertices are holes. I picked every fourth for triangulation,
then I passed those points to triangulation, but I end up with something like this
where my hole has disappeared. What am I doing wrong?
Also, why am i getting somewhat convex hull instead of triangulated polygon?
Here is my code so far:
#here i am loading all data, that i will use later on but i had to insert that, just in case
mapfg = glob(path.join(pathtomapfolder, "Foreground.png"))[0] #Getting map foreground image
mapob = glob(path.join(pathtomapfolder, "Obstacles.png"))[0] #Getting map file
mappr = glob(path.join(pathtomapfolder, "Properties.txt"))[0] #Getting map info file
self.mapprops = [mapob, mapfg, mappr]
#getting ground and obstacles
obsbitmap = Image.open(self.mapprops[0])
lockBitmap = obsbitmap.load()
compareClr = (0, 0, 0)
for y in xrange(obsbitmap.size[1]):
tmp = []
for x in xrange(obsbitmap.size[0]):
if lockBitmap[x, y][0] == compareClr[0] and lockBitmap[x, y][6] == compareClr[1] and lockBitmap[x, y][7] == compareClr[2]:
tmp.append(1)
else:
tmp.append(0)
self.obs.append(tmp)
#detecting edges
for y in xrange(len(self.obs)):
tmphit = []
for x in xrange(len(self.obs[0])):
if (self.obs[y][x] == 0 and (self.obs[MinMax.NoOver(y - 1, len(self.obs) - 1, 0)][x] == 1 or self.obs[y][MinMax.NoOver(x - 1, len(self.obs[0]) - 1, 0)] == 1 or self.obs[y][MinMax.NoOver(x + 1, len(self.obs[0]) - 1, 0)] == 1 or self.obs[MinMax.NoOver(y + 1, len(self.obs) - 1, 0)][x] == 1)) or (self.obs[y][x] == 1 and (MinMax.WillOver(y - 1, len(self.obs) - 1, 0) or MinMax.WillOver(x - 1, len(self.obs[0]) - 1, 0) or MinMax.WillOver(x + 1, len(self.obs[0]) - 1, 0) or MinMax.WillOver(y + 1, len(self.obs) - 1, 0))):
tmphit.append(True)
else:
tmphit.append(False)
self.hit.append(tmphit)
#here it starts, first of all i search for vertice, then go CW or CCW and get all vertices from edge of one polygon, i also detect, whether it is hole or not and to which polygon is related to.
xcirc = ycirc = 0
coords = []
coordvalues = []
parentid = []
self.allverts = [coords, coordvalues, parentid]
polyID = 0
for y in xrange(len(self.obs)):
for x in xrange(len(self.obs[0])):
if self.hit[y][x] and not (x, y) in self.allverts[0]:
left = []
right = []
up = []
down = []
numobjects = numholes = 0
type = ""
parentid = -1
for v in xrange(len(self.allverts[0])):
if self.allverts[0][v][8] == y and self.allverts[0][v][0] < x: left.append(self.allverts[1][v])
if self.allverts[0][v][9] == y and self.allverts[0][v][0] > x: right.append(self.allverts[1][v])
if self.allverts[0][v][0] == x and self.allverts[0][v][10] < y: up.append(self.allverts[1][v])
if self.allverts[0][v][0] == x and self.allverts[0][v][11] > y: down.append(self.allverts[1][v])
for id in xrange(polyID):
if ("not hole", id) in left and ("not hole", id) in right and ("not hole", id) in up and ("not hole", id) in down:
numobjects += 1
parentid = id
elif ("hole", id) in left and ("hole", id) in right and ("hole", id) in up and ("hole", id) in down:
numholes += 1
if numobjects == 0 or numobjects == numholes: type = "not hole"
elif numobjects > numholes: type = "hole"
found = False
lastangle = -90
self.allverts[0].append((x, y))
self.allverts[1].append((type, polyID))
self.allverts[2].append(parentid)
v = 1
while not found:
angle = MinMax.Overflow(lastangle - 45, 180, -179)
lastangle = angle
xcirc = int(round(math.cos((math.pi / 180) * angle)))
ycirc = int(round(math.sin((math.pi / 180) * angle)))
if self.hit[MinMax.NoOver(self.allverts[0][-1][12] + ycirc, len(self.hit) - 1, 0)][MinMax.NoOver(self.allverts[0][-1][0] + xcirc, len(self.hit[0]) - 1, 0)] and (MinMax.WontOver(self.allverts[0][-1][13] + ycirc, len(self.hit) - 1, 0) and MinMax.WontOver(self.allverts[0][-1][0] + xcirc, len(self.hit[0]) - 1, 0)):
if not (self.allverts[0][-1][0] + xcirc, self.allverts[0][-1][14] + ycirc) in self.allverts[0]:
self.allverts[0].append((self.allverts[0][-1][0] + xcirc, self.allverts[0][-1][15] + ycirc))
self.allverts[1].append((type, polyID))
self.allverts[2].append(parentid)
v += 1
else:
#self.allverts.append((self.allverts[-1][0] + xcirc, self.allverts[-1][16] + ycirc))
found = True
if v < 4:
polyID -= 1
for d in xrange(v):
del self.allverts[0][-1]
del self.allverts[1][-1]
del self.allverts[2][-1]
lastangle = MinMax.Overflow(lastangle + 135, 180, -179)
polyID += 1
# now i have to convert that data structure to something i can pass to triangulate function
objects = []
objectpoints = []
idtoindexobj = []
holes = []
holepoints = []
holecoords = []
holeleft = len(self.hit[0])
holetop = len(self.hit)
holeright = holebottom = 0
idtoindexhole = []
prevvert = (self.allverts[0][0], self.allverts[1][0], self.allverts[2][0])
d = 0
for u in xrange(len(self.allverts[0])):
vert = (self.allverts[0][u], self.allverts[1][u], self.allverts[2][u])
if vert[1][17] != prevvert[1][18]:
d = 0
if prevvert[1][0] == "not hole":
objects.append(objectpoints)
objectpoints = []
idtoindexobj.append(prevvert[1][19])
else:
holes.append(holepoints)
holepoints = []
holecoords.append((holeleft + (MinMax.AminB(holeleft, holeright)/2), holetop + (MinMax.AminB(holetop, holebottom)/2)))
idtoindexhole.append(prevvert[2])
holeleft = len(self.hit[0])
holetop = len(self.hit)
holeright = holebottom = 0
if vert[1][0] == "not hole":
if d % 4 == 0:
objectpoints.append((vert[0][0], vert[0][20]))
else:
if d % 4 == 0:
holepoints.append((vert[0][0], vert[0][21]))
if vert[0][0] < holeleft: holeleft = vert[0][0]
if vert[0][0] > holeright: holeright = vert[0][0]
if vert[0][22] < holetop: holetop = vert[0][23]
if vert[0][24] > holebottom: holebottom = vert[0][25]
d+=1
prevvert = vert
if prevvert[1][0] == "not hole":
objects.append(objectpoints)
objectpoints = []
idtoindexobj.append(prevvert[1][26])
else:
holes.append(holepoints)
holepoints = []
holecoords.append((holeleft + (MinMax.AminB(holeleft, holeright)/2), holetop + (MinMax.AminB(holetop, holebottom)/2)))
idtoindexhole.append(prevvert[2])
holeleft = len(self.hit[0])
holetop = len(self.hit)
holeright = holebottom = 0
objectpoints.append((vert[0][0], vert[0][27]))
self.polygons = []
for ind, id in enumerate(idtoindexobj):
holecoordlist = []
segments = []
for k, l in enumerate(idtoindexhole):
if l == id:
holecoordlist.append(holecoords[k])
prevsegpart = False
for segpart in holes[k]:
if not prevsegpart:
prevsegpart = segpart
continue
segments.append((prevsegpart[0], prevsegpart[1], segpart[0], segpart[1]))
prevsegpart = segpart
segments.append((prevsegpart[0], prevsegpart[1], holes[k][0][0], holes[k][0][1]))
if segments:
self.polygons.append({"vertices":objects[ind], "segments":segments, "holes":holecoordlist})
else:
self.polygons.append({"vertices":objects[ind]})
indtripolylist = []
for pol in self.polygons:
#here i am calling that triangulate function
indtripolylist.append(triangle.triangulate(pol, opts="q"))
#and finally convert what has been returned to coordinates of triangles (because it returns list of vertices and touples of indexes pointing to vertices)
self.tripolylist = []
for po in indtripolylist:
tmptriangles = []
for tr in po["triangles"]:
tmptriangles.append((po["vertices"][tr[0]], po["vertices"][tr[1]], po["vertices"][tr[2]]))
self.tripolylist.append(tmptriangles)
Thank you for your help.
This had me scratching my head for a while, your comments helped me get it working.
to see an example of the data you need to pass:
triangle.get_data('face')
to stop a polygon being "filled in" and keep it concave you can pass along the segments like this
segments = []
for i in range(len(verts)-1):
segments.append([int(i),int(i+1)])
segments.append([int(i+1),int(0)])
A = {'vertices':array(verts), 'segments':array(segments)}
to add a hole, you need to mark the verts and segments seperatly (warning: untested code)
vertmarks = []
for i in range(len(verts)):
vertmarks.append([2])
for i in range(len(hole)):
vertmarks.append([4])
segmarks = []
for i in range(len(segments)):
segmarks.append([2])
for i in range(len(holesegments)):
segmarks.append([4])
A = {'vertices':array(verts), 'segments':array(segments),
'segment_markers':array(segmarks), 'vertex_markers':array(vertmarks)}
'holes' should also be passed as a list of [x,y] locations - one inside each hole

RAM full in numpy sagemath

I wrote the next code. In 1-2 hours of execution time the RAM of my laptop (8gb) is filled and the sistem crash:
from scipy.stats import uniform
import numpy as np
cant_de_cadenas =[700,800,900]
cantidad_de_cadenas=np.array([])
for kkkkk in cant_de_cadenas:
cantidad_de_cadenas=np.append(cantidad_de_cadenas,kkkkk)
cantidad_de_cadenas=np.transpose(cantidad_de_cadenas)
b=10
h=b
Longitud=1
numero_experimentos=100
densidad_de_cadenas =cantidad_de_cadenas/(b**2)
prob_perc=np.array([])
tiempos=np.array([])
S_int=np.array([])
S_medio=np.array([])
desviacion_standard=np.array([])
desviacion_standard_nuevo=np.array([])
anisotropia_macroscopica_porcentual=np.array([])
componente_y=np.array([])
componente_x=np.array([])
import time
for N in cant_de_cadenas:
empieza=time.clock()
PERCOLACION=np.array([])
size_medio_intuitivo = np.array([])
size_medio_nuevo = np.array([])
std_dev_size_medio_intuitivo = np.array([])
std_dev_size_medio_nuevo = np.array([])
comp_y = np.array([])
comp_x = np.array([])
for u in xrange(numero_experimentos):
perco = False
array_x1=uniform.rvs(loc=-b/2, scale=b, size=N)
array_y1=uniform.rvs(loc=-h/2, scale=h, size=N)
array_angle=uniform.rvs(loc=-0.5*(np.pi), scale=np.pi, size=N)
array_pendiente_x=1./np.tan(array_angle)
random=uniform.rvs(loc=-1, scale=2, size=N)
lambda_sign=np.zeros([N])
for t in xrange(N):
if random[t]<0:
lambda_sign[t]=-1
else:
lambda_sign[t]=1
array_lambdas=(lambda_sign*Longitud)/np.sqrt(1+array_pendiente_x**2)
array_x2= array_x1 + array_lambdas*array_pendiente_x
array_y2= array_y1 + array_lambdas*1
array_x1 = np.append(array_x1, [-b/2, b/2, -b/2, -b/2])
array_y1 = np.append(array_y1, [-h/2, -h/2, -h/2, h/2])
array_x2 = np.append(array_x2, [-b/2, b/2, b/2, b/2])
array_y2 = np.append(array_y2, [h/2, h/2, -h/2, h/2])
M = np.zeros([N+4,N+4])
for j in xrange(N+4):
if j>0:
x_A1B1 = array_x2[j]-array_x1[j]
y_A1B1 = array_y2[j]-array_y1[j]
x_A1A2 = array_x1[0:j]-array_x1[j]
y_A1A2 = array_y1[0:j]-array_y1[j]
x_A2A1 = -1*x_A1A2
y_A2A1 = -1*y_A1A2
x_A2B2 = array_x2[0:j]-array_x1[0:j]
y_A2B2 = array_y2[0:j]-array_y1[0:j]
x_A1B2 = array_x2[0:j]-array_x1[j]
y_A1B2 = array_y2[0:j]-array_y1[j]
x_A2B1 = array_x2[j]-array_x1[0:j]
y_A2B1 = array_y2[j]-array_y1[0:j]
p1 = x_A1B1*y_A1A2 - y_A1B1*x_A1A2
p2 = x_A1B1*y_A1B2 - y_A1B1*x_A1B2
p3 = x_A2B2*y_A2B1 - y_A2B2*x_A2B1
p4 = x_A2B2*y_A2A1 - y_A2B2*x_A2A1
condicion_1=p1*p2
condicion_2=p3*p4
for k in xrange (j):
if condicion_1[k]<=0 and condicion_2[k]<=0:
M[j,k]=1
del condicion_1
del condicion_2
if j+1<N+4:
x_A1B1 = array_x2[j]-array_x1[j]
y_A1B1 = array_y2[j]-array_y1[j]
x_A1A2 = array_x1[j+1:]-array_x1[j]
y_A1A2 = array_y1[j+1:]-array_y1[j]
x_A2A1 = -1*x_A1A2
y_A2A1 = -1*y_A1A2
x_A2B2 = array_x2[j+1:]-array_x1[j+1:]
y_A2B2 = array_y2[j+1:]-array_y1[j+1:]
x_A1B2 = array_x2[j+1:]-array_x1[j]
y_A1B2 = array_y2[j+1:]-array_y1[j]
x_A2B1 = array_x2[j]-array_x1[j+1:]
y_A2B1 = array_y2[j]-array_y1[j+1:]
p1 = x_A1B1*y_A1A2 - y_A1B1*x_A1A2
p2 = x_A1B1*y_A1B2 - y_A1B1*x_A1B2
p3 = x_A2B2*y_A2B1 - y_A2B2*x_A2B1
p4 = x_A2B2*y_A2A1 - y_A2B2*x_A2A1
condicion_1=p1*p2
condicion_2=p3*p4
for k in xrange ((N+4)-j-1):
if condicion_1[k]<=0 and condicion_2[k]<=0:
M[j,k+j+1]=1
del condicion_1
del condicion_2
M[N,N+2]=0
M[N,N+3]=0
M[N+1,N+2]=0
M[N+1,N+3]=0
M[N+2,N]=0
M[N+2,N+1]=0
M[N+3,N]=0
M[N+3,N+1]=0
CD=np.array([])
POPOPO=[]
for g in xrange(N):
lala=0
r=False
while lala<=len(POPOPO)-1:
esta= g in POPOPO[lala]
if esta is True:
lala=len(POPOPO)
r=True
else:
lala=lala+1
if r is False:
L=np.array([g])
for s in xrange(N):
if M[g,s] != 0:
L=np.append(L,s)
x=0
while x<= N:
for l in xrange(N):
z= l in L
d=L[x]
if z is False and M[d,l] != 0:
L=np.append(L,l)
if x+1<len(L):
x+=1
else:
x=N+1.
q= len (L)
CD=np.append(CD, q)
POPOPO.append(L)
M_horizontal=M.copy()
M_horizontal[:,N+2] = np.zeros(N+4)
M_horizontal[:,N+3] = np.zeros(N+4)
M_horizontal[N+2] = np.zeros(N+4)
M_horizontal[N+3] = np.zeros(N+4)
L=np.array([N])
for s in xrange(N+4):
if M_horizontal[N,s] != 0:
L=np.append(L,s)
x=0
while x<= N+4:
for l in xrange(N+4):
z= l in L
d=L[x]
if z is False and M_horizontal[d,l] != 0:
L=np.append(L,l)
if x+1<len(L):
x+=1
else:
x=(N+4)+1.
LV1_in_L = N in L
LV2_in_L= (N+1) in L
if LV1_in_L is True and LV2_in_L is True:
perc_horiz=True
else:
perc_horiz=False
M_vertical=M.copy()
M_vertical[:,N] = np.zeros(N+4)
M_vertical[:,N+1] = np.zeros(N+4)
M_vertical[N] = np.zeros(N+4)
M_vertical[N+1] = np.zeros(N+4)
L=np.array([N+2])
for s in xrange(N+4):
if M_vertical[N+2,s] != 0:
L=np.append(L,s)
x=0
while x<= N+4:
for l in xrange(N+4):
z= l in L
d=L[x]
if z is False and M_vertical[d,l] != 0:
L=np.append(L,l)
if x+1<len(L):
x+=1
else:
x=(N+4)+1.
LH1_in_L = (N+2) in L
LH2_in_L= (N+3) in L
if LH1_in_L is True and LH2_in_L is True:
perc_ver = True
else:
perc_ver = False
if perc_ver is True or perc_horiz is True:
PERCOLACION=np.append(PERCOLACION,1)
perco=True
D = np.array([])
W = np.array([])
for c in xrange (int(min(CD)), int(max(CD)+1),1):
D=np.append(D,c)
frec = sum (CD == c)
W = np.append(W,frec)
if perco is True:
posicion=np.argmax(D)
D=np.delete(D,posicion)
W=np.delete(W,posicion)
if len(D) == 0 and len(W)==0:
S_medio_intuitivo_exp_u=0
S_medio_nuevo_exp_u = 0
std_dev_exp_u = 0
std_dev_nuevo_exp_u = 0
else:
S_medio_intuitivo_exp_u = np.average (D,weights=W)
peso_nuevo=D*W
S_medio_nuevo_exp_u = np.average (D,weights=peso_nuevo)
tipos=sum(W)
X=W*((D-S_medio_intuitivo_exp_u)**2)
S=sum(X)
std_dev_exp_u = np.sqrt(S/(tipos-1.))
tipos_nuevo=sum(peso_nuevo)
X_nuevo=peso_nuevo*((D-S_medio_nuevo_exp_u)**2)
S_nuevo=sum(X_nuevo)
std_dev_nuevo_exp_u = np.sqrt(S_nuevo/(tipos_nuevo-1.))
componente_longitudinal=Longitud*np.abs(np.cos(array_angle))
comp_y=np.append(comp_y, sum(componente_longitudinal)/N)
componente_transversal=Longitud*np.abs(np.sin(array_angle))
comp_x=np.append(comp_x, sum(componente_transversal)/N)
std_dev_size_medio_intuitivo=np.append(std_dev_size_medio_intuitivo, std_dev_exp_u)
std_dev_size_medio_nuevo=np.append(std_dev_size_medio_nuevo, std_dev_nuevo_exp_u)
size_medio_intuitivo=np.append(size_medio_intuitivo, S_medio_intuitivo_exp_u)
size_medio_nuevo=np.append(size_medio_nuevo, S_medio_nuevo_exp_u)
percolation_probability=sum(PERCOLACION)/numero_experimentos
prob_perc=np.append(prob_perc, percolation_probability)
S_int = np.append (S_int, sum(size_medio_intuitivo)/numero_experimentos)
S_medio=np.append (S_medio, sum(size_medio_nuevo)/numero_experimentos)
desviacion_standard = np.append (desviacion_standard, sum(std_dev_size_medio_intuitivo)/numero_experimentos)
desviacion_standard_nuevo=np.append (desviacion_standard_nuevo, sum(std_dev_size_medio_nuevo)/numero_experimentos)
tiempos=np.append(tiempos, time.clock()-empieza)
componente_y=np.append(componente_y, sum(comp_y)/numero_experimentos)
componente_x=np.append(componente_x, sum(comp_x)/numero_experimentos)
anisotropia_macroscopica_porcentual=100*(1-(componente_y/componente_x))
I tryed with gc and gc.collect() and 'del'command for deleting arrays after his use and nothing work!
What am I doing wrong? Why the memory becomes full while running (starts with 10% of RAM used and in 1-2hour is totally full used)?
Lets take an array M with size 300MB. When this is overwritten (for example, in each iteration), have we 300MB occupated in RAM memory or just 300MB? In the case that we have just 300MB, there should be no problem, so why have I this RAM issue? In the case of the RAM is acumulated, how can I do for free RAM memory occupated for the 'old' array?
Please help me, I'm totally stuck!
Thanks a lot!

Categories