Related
I want to use boost.python to use multi-index columns dataframe in c++.
※multi-index columns dataframe is like
I changed the type of multi-index columns dataframe into csv.
My csv file looks like this on spreadsheet
The reason why I want to use this data is for backtest. This is my backtest code in python that I want to translate to c++.
import pandas as pd
import numpy as np
from utils import load_data, load_list_csv, to_int
class No_Strategy():
def __init__(self, codes, unit, cash, position):
self.codes = codes
self.unit = unit
self.cash = cash
self.buy_signal = [0]*len(codes)
self.sell_signal = [0]*len(codes)
self.valid = 0
self.position = position
self.pass_st = 0 # 전략에 들어가지도 못한 경우
def set_data(self, prev_fs_row, fs_row, indi_row):
self.prev_fs = prev_fs_row
self.fs = fs_row # multi dimensional df
self.indi = indi_row
def _strat(self, prev_fs, curr_fs, curr_indi):
curr_rev = prev_rev = curr_ni = prev_ni = ni_growth = curr_asset = noncurr_asset = curr_asset_rat = 0
try:
prev_rev = int(prev_fs['매출액'].replace(",",""))
curr_rev = int(curr_fs['매출액'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
rev_growth=(curr_rev-prev_rev)/prev_rev
try:
prev_ni = int(prev_fs['당기순이익'].replace(",",""))
curr_ni = int(curr_fs['당기순이익'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
ni_growth=(curr_ni-prev_ni)/prev_ni
try:
curr_asset = int(curr_fs['유동자산'].replace(",",""))
noncurr_asset = int(curr_fs['비유동자산'].replace(",",""))
except:
self.pass_st += 1
return 0, 0
curr_asset_rat = curr_asset / noncurr_asset
#### this is the buy strategy! You can change the below ####
if (curr_indi.golden_cross) or (curr_indi.rsi_k < 0.65) :
return 1, 0
#### ************************************************** ####
#### this is the sell strategy! You can change the below ####
if (curr_indi.dead_cross):
return 0, 1
#### ************************************************** ####
return 0, 0
def run(self):
for i, code in enumerate(self.codes):
self.valid = 0
prev_fs = self.prev_fs[code]
curr_fs = self.fs[code]
curr_indi = self.indi[code]
prev_fs_cell = None
curr_fs_cell = None
try:
prev_fs_cell = prev_fs.iloc[0].replace(",","")
try:
curr_fs_cell = curr_fs.iloc[0].replace(",","")
except:
self.pass_st += 1
pass
except:
self.pass_st += 1
pass
if (curr_fs_cell != None) & (prev_fs_cell != None):
self.valid = 1
buy, sell = self._strat(prev_fs, curr_fs, curr_indi)
if self.valid == 0:
self.pass_st += 1
continue
else: # buy or sell signal get
price = curr_indi['close']
if buy:
if self.cash >= self.unit * price:
self.buy_signal[i] = self.unit
self.position[i] += self.unit
self.cash -= price * self.unit
elif sell:
if self.position[i] > 0 :
sell_num = self.position[i] - int(self.position[i]/2)
self.sell_signal[i] = sell_num
self.position[i] = int(self.position[i]/2) # 1-> 1 sell, 4 -> 2 sell ....
self.cash += price * sell_num
##title
class Broker():
def __init__(self, codes):
self.cash = 200000000 #2억
self.cash_df = None #pd.DataFrame(columns=['cash'])
self.position = [0]*len(codes)
self.position_df = None #pd.DataFrame(columns=codes) # for accumulated profit calculation
self.buy_signal = None #pd.DataFrame(columns=codes) # codes = KOSPI_stock_names
self.sell_signal = None #pd.DataFrame(columns=codes)
self.codes = codes # 012934, 3281, ...
self.unit = 1 # 주식 매매 단위
self.pass_st = 0
def set_strat(self, strategy):
self.strategy = strategy # class
def set_time(self, time_index): # time_index type: pd.Index / time range for indi df
self.buy_signal = pd.DataFrame(columns = self.codes, index = time_index) #set_index(time_index)
self.sell_signal = pd.DataFrame(columns = self.codes, index = time_index) #.set_index(time_index)
self.position_df = pd.DataFrame(columns = self.codes, index = time_index)
self.cash_df = pd.DataFrame(columns = ['cash'], index = time_index)#.set_index(time_index)
self.time_index = time_index
def set_data(self, fs, indi, price):
self.fs = fs # multi dimensional df / start: 0th - nth
self.indi = indi # multi dimensional df / start : 1th - nth
self.price = price # 2 dimensional (date X codes : close price)
def update_data(self, strategy, date):
self.cash = strategy.cash
self.cash_df.loc[date] = strategy.cash
self.position = strategy.position
self.position_df.loc[date] = strategy.position #list
self.buy_signal.loc[date] = strategy.buy_signal #list
self.sell_signal.loc[date] = strategy.sell_signal #list
self.pass_st += strategy.pass_st
def run(self):
for date in self.time_index: #아마 수정해야 할 확률 높음
if date.year == 2021:
break
else:
prev_fs_row = self.fs.loc[date.year-1] # ex: 2014
fs_row = self.fs.loc[date.year] # 2015
indi_row = self.indi.loc[date] # 2015
strategy = self.strategy(self.codes, self.unit, self.cash, self.position)
strategy.set_data(prev_fs_row, fs_row, indi_row)
strategy.run()
self.update_data(strategy, date)
def performance(self):
# !!!! 2020년까지의 결과만 성능 평가 ####
cash_df = self.cash_df[self.cash_df.index < '2021']
position_df = self.position_df[self.position_df.index < '2021']
price = self.price[self.price.index < '2021']
buy_signal = self.buy_signal[self.buy_signal.index < '2021']
sell_signal = self.sell_signal[self.sell_signal.index < '2021']
last_price = price.iloc[-1]
total_remain_num = self.position # last(2020) position data
total_buy = (price * buy_signal).sum(axis=1).sum()
total_sell = (price * sell_signal).sum(axis=1).sum()
total_remain = (last_price * total_remain_num).sum()
print(f'remain 개수: {total_remain_num}, total_remain: {total_remain} total_buy: {total_buy}, total_sell={total_sell}')
profit = total_sell + total_remain - total_buy
try:
return_mean = profit / total_buy
except:
print("no buy")
return
accum_df = (cash_df['cash'] + ((price.fillna(0) * position_df).sum(axis=1))).to_frame() # row sum
daily_return_df = (accum_df - accum_df.shift(1))/accum_df.shift(1)-1
SSE = ((daily_return_df - return_mean)**2).sum().item()
std = np.sqrt(SSE/(accum_df.shape[0]-1)) # route(sigma(x-x_bar)^2 / (n-1))
sharp = return_mean / std
self.return_mean = return_mean
self.sharp = sharp
print(f'return_mean: {return_mean}, sharp: {sharp}')
code_path = GDRIVE_DATA_PATH + 'codes.csv'
fs_path = GDRIVE_DATA_PATH + 'fs_total.csv'
indi_path = GDRIVE_DATA_PATH + 'indi_total.csv'
price_path = GDRIVE_DATA_PATH + 'prices.csv'
fs_total = load_data("fs_total.csv")
indi_total = load_data("indi_total.csv") # stock price and indicator(Golden cross, RSI, etc.)
prices = load_data("prices.csv") # stock close price data rows:date, cols: stock code.
time_index = indi_total.index # time index of indi_total multi-index columns
broker = Broker(codes)
broker.set_strat(No_Strategy)
broker.set_time(time_index)
broker.set_data(fs_total, indi_total, prices)
broker.run()
broker.performance()
I want to translate it not changing much in flow of the code.
But I cannot find how to get multi-index columns dataframe in c++, and transfer its row data to No_Strategy to decide whether invest into the stock.
※ I uploaded similar question before and get thankful answer, but it is too complicated for me so I question one more time with detail information.
look at https://github.com/hosseinmoein/DataFrame. It has about 95% of Pandas functionality in a much faster framework
I created an empty list, output every loop, adding just one object. Once finish adding all object to the list, then repeat the same process as shown below.
I'm not sure how to add all objects in one loop?
This is outputs:
[u'person_0']
[u'person_0', u'chair_0']
[u'person_0', u'chair_0', u'chair_1']
[u'person_0', u'chair_0', u'chair_1', u'book_0']
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']
I only need the last output:
[u'person_0', u'chair_0', u'chair_1', u'book_0', u'bottle_0']
This is full code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import numpy
import tf
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs import point_cloud2 as pc2
from sensor_msgs.msg import Image, PointCloud2
from dodo_detector.detection import SingleShotDetector
from dodo_detector_ros.msg import DetectedObject, DetectedObjectArray
import math
class Detector:
def __init__(self):
self._detector = SingleShotDetector('frozen_inference_graph.pb', 'mscoco_label_map.pbtxt', confidence=0.5)
self._global_frame = rospy.get_param('~global_frame', None)
self._tf_listener = tf.TransformListener()
self._bridge = CvBridge()
rospy.Subscriber("/camera/rgb/image_color", Image, self.image_callback)
rospy.Subscriber('/camera/depth/points', PointCloud2, self.pc_callback)
self._current_image = None
self._current_pc = None
self._imagepub = rospy.Publisher('~labeled_image', Image, queue_size=10)
self._publishers = {None: (None, rospy.Publisher('~detected', DetectedObjectArray, queue_size=10))}
self._tfpub = tf.TransformBroadcaster()
rospy.loginfo('Ready to detect!')
def image_callback(self, image):
"""Image callback"""
self._current_image = image
def pc_callback(self, pc):
"""Point cloud callback"""
self._current_pc = pc
def run(self):
while not rospy.is_shutdown():
if self._current_image is not None:
try:
if self._global_frame is not None:
(trans, _) = self._tf_listener.lookupTransform('/' + self._global_frame, '/camera_link', rospy.Time(0))
scene = self._bridge.imgmsg_to_cv2(self._current_image, 'rgb8')
marked_image, objects = self._detector.from_image(scene) # detect objects
self._imagepub.publish(self._bridge.cv2_to_imgmsg(marked_image, 'rgb8')) # publish detection results
msgs = {}
for key in self._publishers:
msgs[key] = DetectedObjectArray()
my_tf_id = []
my_dis =[]
for obj_class in objects:
rospy.logdebug('Found ' + str(len(objects[obj_class])) + ' object(s) of type ' + obj_class)
for obj_type_index, coordinates in enumerate(objects[obj_class]):
#
rospy.logdebug('...' + obj_class + ' ' + str(obj_type_index) + ' at ' + str(coordinates))
ymin, xmin, ymax, xmax = coordinates
y_center = ymax - ((ymax - ymin) / 2)
x_center = xmax - ((xmax - xmin) / 2)
detected_object = DetectedObject()
detected_object.type.data = obj_class
detected_object.image_x.data = xmin
detected_object.image_y.data = ymin
detected_object.image_width.data = xmax - xmin
detected_object.image_height.data = ymax - ymin
publish_tf = False
if self._current_pc is None:
rospy.loginfo('No point cloud information available to track current object in scene')
else:
pc_list = list(pc2.read_points(self._current_pc, skip_nans=True, field_names=('x', 'y', 'z'), uvs=[(x_center, y_center)]))
if len(pc_list) > 0:
publish_tf = True
tf_id = obj_class + '_' + str(obj_type_index) #object_number
my_tf_id.append(tf_id)
print my_tf_id
detected_object.tf_id.data = tf_id
point_x, point_y, point_z = pc_list[0] #point_z = x, point_x = y
if publish_tf:
object_tf = [point_z, -point_x, -point_y]
frame = 'cam_asus_link'
if self._global_frame is not None:
object_tf = numpy.array(trans) + object_tf
frame = self._global_frame
self._tfpub.sendTransform((object_tf), tf.transformations.quaternion_from_euler(0, 0, 0), rospy.Time.now(), tf_id, frame)
except CvBridgeError as e:
print(e)
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException) as e:
print(e)
if __name__ == '__main__':
rospy.init_node('dodo_detector_ros', log_level=rospy.INFO)
try:
Detector().run()
except KeyboardInterrupt:
rospy.loginfo('Shutting down')
Empty list line 82 (my_tf_id = []) and append to in it in line 119 (my_tf_id.append(tf_id)), finally use print my_tf_id in line 120
I am using python 2.7 , ROS, Opencv for detection of objects.
Please help me or make any suggestion.
Thank you in advance
You are printing the list inside the for loop. So everytime the loop iterates, it will print the list. Try to print my_tf_id outside the for loop
I'm trying to plot and compare the frequency spectrum of two .wav files. I wrote the following in python for that:
import pylab
import time
from scipy import fft, arange
from numpy import linspace
from scipy.io.wavfile import read
import gc
import sys
params = {'figure.figsize': (20, 15)}
pylab.rcParams.update(params)
def plotSpec(y, Fs):
n = len(y) # lungime semnal
k = arange(n)
T = n / Fs
frq = k / T # two sides frequency range
frq = frq[range(n / 2)] # one side frequency range
ff_valu = fft(y) / n # fft computing and normalization
ff_valu = ff_valu[range(n / 2)]
pylab.plot(frq, abs(ff_valu), 'r') # plotting the spectrum
pylab.tick_params(axis='x', labelsize=8)
pylab.tick_params(axis='y', labelsize=8)
pylab.tick_params()
pylab.xticks(rotation=45)
pylab.xlabel('Frequency')
pylab.ylabel('Power')
del frq, ff_valu, n, k, T, y
gc.collect()
return
def graph_plot(in_file, graph_loc, output_folder, count, func_type):
graph_loc = int(graph_loc)
rate = 0
data = 0
rate, data = read(in_file)
dlen = len(data)
print "dlen=", dlen
lungime = dlen
timp = dlen / rate
print "timp=", timp
t = linspace(0, timp, dlen)
pylab.subplot(3, 2, graph_loc)
pylab.plot(t, data)
fl = in_file.split('/')
file_name = fl[len(fl) - 1]
pylab.title(file_name)
pylab.tick_params(axis='x', labelsize=8)
pylab.tick_params(axis='y', labelsize=8)
pylab.xticks(rotation=45)
pylab.xlabel('Time')
pylab.ylabel('Numerical level')
pylab.subplot(3, 2, graph_loc + 2)
plotSpec(data, rate)
pylab.subplot(3, 2, graph_loc + 4)
if rate == 16000:
frq = 16
else:
frq = 8
pylab.specgram(data, NFFT=128, noverlap=0, Fs=frq)
pylab.tick_params(axis='x', labelsize=8)
pylab.tick_params(axis='y', labelsize=8)
pylab.xticks(rotation=45)
pylab.xlabel('Time')
pylab.ylabel('Frequency')
if graph_loc == 2:
name = in_file.split("/")
lnth = len(name)
name = in_file.split("/")[lnth - 1].split(".")[0]
print "File=", name
if func_type == 'a':
save_file = output_folder + 'RESULT_' + name + '.png'
else:
save_file = output_folder + 'RESULT_graph.png'
pylab.savefig(save_file)
pylab.gcf()
pylab.gca()
pylab.close('all')
del in_file, graph_loc, output_folder, count, t, rate, data, dlen, timp
gc.get_referrers()
gc.collect()
def result_plot(orig_file, rec_file, output_folder, seq):
graph_loc = 1
graph_plot(orig_file, graph_loc, output_folder, seq, 'a')
graph_loc = 2
graph_plot(rec_file, graph_loc, output_folder, seq, 'a')
sys.exit()
save_file="~/Documents/Output/"
o_file='~/Documents/audio/orig_8sec.wav'
#o_file='~/Documents/audio/orig_4sec.wav'
r_file='~/Documents/audio/rec_8sec.wav'
#r_file='~/Documents/audio/rec_4sec.wav'
print 10*"#"+"Start"+10*"#"
result_plot(o_file, r_file,save_file, 'a')
print 10*"#"+"End"+10*"#"
pylab.close('all')
With the above code, I see that the scale of y-axis appear different:
It clearly shows an automatically assigned scale. With this any amplification or attenuation with respect to the original file is difficult to be made obvious unless the person looks up the values.
Since I cannot really predict what would be the max amplitude among either files when I use multiple samples, how can I make both y-axis on each subplot set to the max of either so that the scale is the same and amplification is more clear?
I am adding my explanation you asked for in the comments above as an answer below. The idea is to selectively modify the x-axis limits for some particular subplots
fig, axes = plt.subplots(2,3,figsize=(16,8))
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
for i, row in enumerate(axes):
for j, col in enumerate(row):
col.plot(x, y)
col.set_title("Title here", fontsize=18)
if i == 1 and (j == 1 or j == 2):
col.set_xlim(0, np.pi)
plt.tight_layout()
Output
An alternative to setting the limits yourself is to create the figure and axes first using
fig, axes = plt.subplots(3, 2)
This has an optional argument sharex. From the docs
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of properties among x (sharex) or y (sharey) axes:
True or 'all': x- or y-axis will be shared among all subplots.
False or 'none': each subplot x- or y-axis will be independent.
'row': each subplot row will share an x- or y-axis.
'col': each subplot column will share an x- or y-axis.
Therefore, we can make sure the rows share the same x axis values as each other by using the argument sharex="row":
fig, axes = plt.subplots(3, 2, sharex="row")
If you want the y axis to be shared you can use sharey="row" instead/aswell.
Taking cues from other answers, I happened to make it work the following way:
import matplotlib.pyplot as pl
import time
from scipy import fft, arange
from numpy import linspace
from scipy.io.wavfile import read
import gc
import sys
def plotWavAmplLev(in_file, sub_graph):
print "Printing Signal graph (amplitude vs seconds)...."
rate, data = read(in_file)
dlen = len(data)
timp = dlen / rate
t = linspace(0,timp,dlen)
sub_graph.plot(t, data)
fl = in_file.split('/')
file_name = fl[len(fl) - 1]
sub_graph.set_title(file_name)
sub_graph.tick_params(axis='x', labelsize=10)
sub_graph.tick_params(axis='y', labelsize=10)
sub_graph.set_xlabel('Time')
sub_graph.set_ylabel('Numerical level')
def plotSpectralDensity(y, fs, sub_graph):
print "Printing Power Spectral Density (dB vs Hz)...."
n = len(y) # lungime semnal
k = arange(n)
T = n / fs
frq = k / T # two sides frequency range
frq = frq[range(n / 2)] # one side frequency range
ff_valu = fft(y) / n # fft computing and normalization
ff_valu = ff_valu[range(n / 2)]
sub_graph.plot(frq, abs(ff_valu), 'r') # plotting the spectrum
sub_graph.tick_params(axis='x', labelsize=10)
sub_graph.tick_params(axis='y', labelsize=10)
sub_graph.tick_params()
sub_graph.set_xlabel('Frequency')
sub_graph.set_ylabel('Power')
del frq, ff_valu, n, k, T, y
gc.collect()
return
def plotSpectrogram(rate, data, sub_graph):
print "Plotting Spectrogram (kHz vs seconds)...."
if rate == 16000:
frq = 16
else:
frq = 8
sub_graph.specgram(data, NFFT=128, noverlap=0, Fs=frq)
sub_graph.tick_params(axis='x', labelsize=10)
sub_graph.tick_params(axis='y', labelsize=10)
sub_graph.set_xlabel('Time')
sub_graph.set_ylabel('Frequency')
def graph_plot(in_file_list, output_folder, func_type):
orig_file = in_file_list[0]
rec_file = in_file_list[1]
g_index = 1
g_rows = 3
g_cols = 2
fig, axes = pl.subplots(g_rows, g_cols, figsize=(20,15), sharex="row", sharey="row")
for i, row in enumerate(axes):
for j, col in enumerate(row):
if i == 0 :
if j == 0:
print "Source file waveform is being plotted...."
rate, data = read(orig_file)
plotWavAmplLev(orig_file, col)
continue
elif j == 1:
print "Recorded file waveform is being plotted...."
rate, data = read(rec_file)
plotWavAmplLev(rec_file, col)
continue
elif i == 1:
if j == 0:
print "Source file PSD is being plotted...."
rate, data = read(orig_file)
plotSpectralDensity(data, rate, col)
continue
elif j == 1:
print "Recorded file PSD is being plotted...."
rate, data = read(rec_file)
plotSpectralDensity(data, rate, col)
continue
elif i == 2:
if j == 0:
print "Source file Spectrogram is being plotted...."
rate, data = read(orig_file)
plotSpectrogram(rate, data, col)
continue
elif j == 1:
print "Recorded file Spectrogram is being plotted...."
rate, data = read(rec_file)
plotSpectrogram(rate, data, col)
continue
pl.tight_layout()
name = in_file_list[1].split("/")
lnth = len(name)
name = in_file_list[1].split("/")[lnth - 1].split(".")[0]
print "File=", name
if func_type == 'a':
save_file = output_folder + 'RESULT_' + name + '.png'
else:
save_file = output_folder + 'RESULT_graph.png'
pl.savefig(save_file)
pl.gcf()
pl.gca()
pl.close('all')
del in_file_list, output_folder, rate, data
gc.get_referrers()
gc.collect()
def result_plot(orig_file, rec_file, output_folder, seq):
flist = [orig_file, rec_file]
graph_plot(flist, output_folder, 'a')
s_file="/<path>/Output/"
#o_file='/<path>/short_orig.wav'
o_file='/<path>/orig.wav'
#r_file='/<path>/short_rec.wav'
r_file='/<path>/rec.wav'
print 10*"#"+"Start"+10*"#"
result_plot(o_file, r_file,s_file, 'a')
print 10*"#"+"End"+10*"#"
pl.close('all')
Now, I got the y-axis scales fixed and get the output as follows:
This makes comparison a lot easier now.
I need to compare every plane (x,y) points. If x or y of American planes is close by 1 than a turn() will apply and change to route of the plane.
Any ideas of how to compare each plane and check if it is close by one?
import random
class CrazyPlane:
def __init__(self,x,y):
self.__x = x
self.__y = y
def update_position(self):
self.__x += random.randint(-1,1)
self.__y += random.randint(-1,1)
def get_position(self):
return self.__x,self.__y
def count_down(self):
for i in range(10,0,-1):
print i
def __eq__(self, other):
return self.value == other
def crash_check(planes):
x = 0
y = 1
flag = True
while (flag):
if (__eq__(planes[x], planes[y])):
print " BOOM!"
else:
y = y + 1
if y == 3:
x = x + 1
y = x + 1
if x == 3:
flag = false
return False
###AND!!!!!!!!!!!!!!!!!!!####
def main():
elal = CrazyPlane.CrazyPlane(1,2)
american = CrazyPlane.CrazyPlane(3,4)
british = CrazyPlane.CrazyPlane(5,6)
lufthansa = CrazyPlane.CrazyPlane(7,8)
planes = [elal,american,british,lufthansa]
flag = True
while (flag):
for plane in planes:
plane.update_position()
if crash_check(planes):
flag = False
print 'Crash'
main()
View on PasteBin
This is my code and when i try to run it and use it by entering numbers into the entry fields, an attribute error occurs when i try to call on the entry variable. This is the message that appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in call
return self.func(*args)
File "F:\HomeWork\Yr13\Extended Project\Notepad++\Python27\Programs\GUI{c} menu+check+gen+Nth.py", line 224, in OnGenButtonClick
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1845, in getattr
return getattr(self.tk, attr)
AttributeError: entryVariable5
any help would be greatly appreciated.
i have stuck on this problem for three days and have tried getting around the problem by using different functions and names and the error still occurs
import Tkinter
from Tkinter import *
import math
def SoS(limit):
numbers = range(3, limit+1, 2)
half = (limit)//2
initial = 4
for step in xrange(3, limit+1, 2):
for i in xrange(initial, half, step):
numbers[i-1] = 0
initial += 2*(step+1)
if initial > half:
plist = [2] + filter(None, numbers)
return plist
break
def S(m):
sieve = [True] * m
for i in xrange(3,(int(m**0.5)+1),2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((m-i*i-1)/(2*i)+1)
plist = [2] + [i for i in xrange(3,m,2) if sieve[i]]
return plist
def OTS(n):
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n/3)
for i in xrange(1,(int(n**0.5)/3)+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = [False] * ((n/6-k*k/6-1)/k+1)
sieve[k*(k-2*(i&1)+4)/3::2*k] = [False] * ((n/6-k*(k-2*(i&1)+4)/6-1)/k+1)
plist = [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
return plist
def is_prime(num):
if num <= 3:
if num <= 1:
return False
return True
if not num % 2 or not num % 3:
return False
for i in xrange(5, int(num ** 0.5) + 1, 6):
if not num % i or not num % (i + 2):
return False
return True
def is_prime_multiple(Lower,Upper):
NumberList = dict()
if Lower%2 == 1:
for i in xrange(Lower, Upper,2):
NumberList[i] = is_prime(i)
else:
for i in xrange(Lower-1,Upper,2):
NumberList[i] = is_prime(i)
NumberList[1] = False
return [i for i in NumberList if NumberList[i] == True]
def Prime_Generation(L,U):
Lower = int(L)
Upper = int(U)
if Lower == 1:
if Upper < 92:
print SoS(Upper)
if Upper >= 92 and Upper < 2250:
print S(Upper)
if Upper >= 2250 :
print OTS(Upper)
else:
print sorted(is_prime_multiple(Lower,Upper))
def factors(n):
f = 3
fs = []
while n % 2 == 0:
fs.append(2)
n /= 2
while f*f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += 2
if n > 1:
fs.append(n)
return fs
def Prime_Checker(N):
NStr = str(N)
N = int(N)
Nfs = factors(N)
for i in Nfs:
if i != N:
NfsStr = str(Nfs).strip('[]')
resultb = [NStr,' is not a prime. The prime factors of ',NStr,' are ',NfsStr]
return resultb.join()
else:
return N,' is a prime. The prime factors of ',N ,' are ',N
def PrimeFinderLamda(n,limit):
nums = range(3,limit,2)
for i in range(2, int(limit**0.5)):
nums = filter(lambda x: x == i or x % i, nums)
return [2]+nums
def NthPrime(N):
N = int(N)
Lower = 1
limit = N*N
if N == 1:
return 2
else:
return PrimeFinderLamda(N,limit)[N-1]
class Prime_app_tk(Tkinter.Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def Prime_Gen_Win(self):
Prime_Gen = Toplevel()
Prime_Gen.grid()
Prime_Gen.labelVariable3 = StringVar()
Title_label2 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable3,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label2.grid(column=0,row=0,columnspan=4)
Prime_Gen.labelVariable3.set(u"Please enter the upper and lower limits of the prime number generation")
Prime_Gen.labelVariable4 = StringVar()
SubTitle_label1 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable4,fg="black",bg="white")
SubTitle_label1.grid(column=0,row=1,columnspan=4)
Prime_Gen.labelVariable4.set(u"(Please enter values no greater than 10 million)")
Prime_Gen.entryVariable5 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable5)
Prime_Gen.entry.grid(column=0,row=4)
Prime_Gen.entryVariable5.set(u"Lower.")
Prime_Gen.entryVariable6 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable6)
Prime_Gen.entry.grid(column=0,row=5)
Prime_Gen.entryVariable6.set(u"Upper.")
Genbutton = Button(Prime_Gen,text=u"Generate !",command=self.OnGenButtonClick #placing and aesthetics of button
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=6)
scrollbar = Scrollbar(Prime_Gen)
scrollbar.grid(column=1,row=8,sticky="ns")
Prime_Gen.Result_label = Text(Prime_Gen, yscrollcommand=scrollbar.set
,fg="blue",bg="white",wrap=WORD
,width=100,relief = SUNKEN)
Prime_Gen.Result_label.grid(column=0,row=8,columnspan=2)
scrollbar.config(command=Prime_Gen.Result_label.yview)
Prime_Gen.labelVariable = StringVar()
SubTitle_label = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable,fg="black",bg="white")
SubTitle_label.grid(column=0,row=9,columnspan=4)
Prime_Gen.labelVariable.set(u"To see full list please click on the results\n and use the up and down arrows to scroll through the list")
Prime_Gen.grid_columnconfigure(0,weight=1)
Prime_Gen.resizable(True,True)
Prime_Gen.update()
Prime_Gen.geometry(Prime_Gen.geometry())
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def OnGenButtonClick(Prime_Gen):
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
Prime_Gen.Result_label.insert(END,"\nPrimes Found\n")
Prime_Gen.Result_label.insert(END,n)
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def Prime_Check_Win(self):
Prime_Check = Toplevel()
Prime_Check.grid()
Prime_Check.labelVariable8 = StringVar()
Title_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable8,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label3.grid(column=0,row=0,columnspan=4)
Prime_Check.labelVariable8.set(u"Please enter a Number to be checked for primality")
Prime_Check.labelVariable9 = StringVar()
SubTitle_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable9,fg="black",bg="white")
SubTitle_label3.grid(column=0,row=1,columnspan=4)
Prime_Check.labelVariable9.set(u"(Please enter values no greater than 10 million)")
Prime_Check.entryVariable = StringVar()
Prime_Check.entry = Entry(Prime_Check,textvariable=Prime_Check.entryVariable)
Prime_Check.entry.grid(column=0,row=2)
Prime_Check.entryVariable.set(u"Enter Number here.")
Checkbutton = Button(Prime_Check,text=u"Check !",command=self.OnCheckButtonClick
,bg="blue",fg="white",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Checkbutton.grid(column=0,row=4)
Prime_Check.labelVariable10 = StringVar()
Result_label2 = Message(Prime_Check,textvariable=Prime_Check.labelVariable10
,anchor="w",fg="blue",bg="white"
,width=500,relief = SUNKEN,padx=3,pady=3)
Result_label2.grid(column=0,row=5,columnspan=2,rowspan=100)
Prime_Check.labelVariable10.set(u"Hello")
Prime_Check.grid_columnconfigure(0,weight=1)
Prime_Check.resizable(True,False)
Prime_Check.update()
Prime_Check.geometry(Prime_Check.geometry())
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def OnCheckButtonClick(Prime_Check):
Prime_Check.labelVariable10.set(Prime_Checker(Prime_Check.entryVariable.get())) #Had to call on prime gen and display results
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def Nth_Prime_Win(self):
Nth_Prime = Toplevel()
Nth_Prime.grid()
Nth_Prime.labelVariable12 = StringVar()
Title_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable12,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label.grid(column=0,row=0,columnspan=4)
Nth_Prime.labelVariable12.set(u"Please enter the Nth prime you would like to find")
Nth_Prime.labelVariable13 = StringVar()
SubTitle_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable13,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
Nth_Prime.labelVariable13.set(u"(Please enter values no greater than 664579")
Nth_Prime.entryVariable = StringVar()
Nth_Prime.entry = Entry(Nth_Prime,textvariable=Nth_Prime.entryVariable)
Nth_Prime.entry.grid(column=0,row=4)
Nth_Prime.entryVariable.set(u"Enter Number here.")
Genbutton = Button(Nth_Prime,text=u"Generate !",command=self.OnButtonNthClick
,bg="green",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=5)
Nth_Prime.labelVariable14 = StringVar()
Result_label = Message(Nth_Prime,textvariable=Nth_Prime.labelVariable14
,anchor="w",fg="blue",bg="white"
,width=1000,relief = SUNKEN,justify=LEFT,padx=3,pady=3)
Result_label.grid(column=0,row=6,columnspan=2,rowspan=100)
Nth_Prime.labelVariable14.set(u"Hello")
Nth_Prime.grid_columnconfigure(0,weight=1)
Nth_Prime.resizable(False,False)
Nth_Prime.update()
Nth_Prime.geometry(Nth_Prime.geometry())
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def OnButtonNthClick(Nth_Prime):
Nth_Prime.labelVariable14.set(NthPrime(Nth_Prime.entryVariable.get()))
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def initialize(self):
self.grid()
self.labelVariable1 = StringVar()
Title_label1 = Label(self,textvariable=self.labelVariable1,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label1.grid(column=0,row=0,columnspan=4)
self.labelVariable1.set(u"Welcome to the Prime Program")
self.labelVariable2 = StringVar()
SubTitle_label = Label(self,textvariable=self.labelVariable2,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
self.labelVariable2.set(u"(Please select the function you would like to use)")
PrimeGenbutton = Button(self,text=u"Find Primes between 2 limits !",command=self.Prime_Gen_Win
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
PrimeGenbutton.grid(column=0,row=3)
PrimeCheckbutton = Button(self,text=u"Check if a number is prime !",command=self.Prime_Check_Win
,bg="blue",fg="white",relief=RAISED,padx=14,pady=10
,activebackground="red",activeforeground="white")
PrimeCheckbutton.grid(column=0,row=4)
NthPrimebutton = Button(self,text=u"Find the Nth prime !",command=self.Nth_Prime_Win
,bg="green",relief=RAISED,padx=35,pady=10
,activebackground="red",activeforeground="white")
NthPrimebutton.grid(column=0,row=5)
self.grid_columnconfigure(0,weight=1)
self.resizable(False,False)
self.update()
self.geometry(self.geometry())
if __name__ == "__main__":
app = Prime_app_tk(None)
app.title('Prime Program')
app.mainloop()
There's no quick fix for your code. It attempts to be object-oriented, but is doing so incorrectly. You need to properly define your methods, and should also adhere to PEP8 naming conventions -- specifically, methods and functions should start with a lowercase, and classes should start with an uppercase. Because you don't follow PEP8, and because of the odd way you use Prime_Gen to mean different things at different times, your code is incredibly hard to understand.
The crux of the problem is that inside OnGenButtonClick, Prime_Gen is not what you think it is. It is an instance of Prime_app_tk rather than the value that you set the local variable Prime_Gen to in Prime_Gen_Win. Thus, any attributes you assigned to the original Prime_Gen don't exist in this other Prime_Gen.
The reason is that the button is defined like this:
Genbutton = Button(..., command=self.OnGenButtonClick, ...)
In this context, self is the instance of Prime_app_tk, so that becomes the parameter passed to OnGenButtonClick. Inside that function you call the parameter Prime_Gen, in spite of the universal convention to name it self. This causes confusion in your code, because you also have a local variable named Prime_Gen in the code that creates the toplevel window.