Related
I import technicals.py into bot.py and want to reuse the variable sl and tp from the class instance process_candles.
If a constant number is given to sl and tp in bot.py, the script is able to work. However, the desired result is to get variable sl and tp which is calculated in the class instance process_candles. from technicals.py.
snippet technicals.py as below:
df['PAIR'] = self.pair
decision = NONE
tp = 0
sl = 0
if c[-2]>o[-2]:
if ca[-1]>h[-2]+0.0010:
decision = BUY
tp = ca[-1]+0.010
sl = l[-2]-0.010
elif o[-2]>c[-2]:
if cb[-1]<l[-2]-0.0010:
decision = SELL
tp = cb[-1]-0.010
sl = h[-2]+0.010
else:
decision = NONE
snippet bot.py
def process_pairs(self):
trades_to_make = []
for pair in self.trade_pairs:
if self.timings[pair].ready == True:
self.log_message(f"Ready to trade {pair}")
techs = Technicals(self.settings[pair], self.api, pair, GRANULARITY, log=self.tech_log)
decision = techs.get_trade_decision(self.timings[pair].last_candle)
print ("process decision")
print (decision)
units = decision * self.settings[pair].units
#tp = "154"
#sl = "153"
if units != 0:
trades_to_make.append({'pair': pair, 'units': units,'take_profit':tp, 'stop_loss':sl})
Full script are as below:
technicals.py
import pandas as pd
import numpy as np
from defs import BUY, SELL, NONE
class Technicals():
def __init__(self, settings, api, pair, granularity, log=None):
self.settings = settings
self.log = log
self.api = api
self.pair = pair
self.granularity = granularity
def log_message(self, msg):
if self.log is not None:
self.log.logger.debug(msg)
def fetch_candles(self, row_count, candle_time):
status_code, df = self.api.fetch_candles(self.pair, count=row_count, granularity=self.granularity)
if df is None:
self.log_message(f"Error fetching candles for pair:{self.pair} {candle_time}, df None")
return None
elif df.iloc[-1].time != candle_time:
self.log_message(f"Error fetching candles for pair:{self.pair} {candle_time} vs {df.iloc[-1].time}")
return None
else:
return df
def process_candles(self, df):
open = df.mid_o
o = np.array(open,dtype='float')
#print (o)
high = df.mid_h
h = np.array(high,dtype='float')
#print (h)
low = df.mid_l
l = np.array(low,dtype='float')
#print (l)
close = df.mid_c
c = np.array(close,dtype='float')
print (c)
close_ask = df.ask_c
ca = np.array(close_ask,dtype='float')
print (ca)
close_bid = df.bid_c
cb = np.array(close_bid,dtype='float')
print (cb)
df['PAIR'] = self.pair
decision = NONE
tp = 0
sl = 0
if c[-2]>o[-2]:
if ca[-1]>h[-2]+0.0010:
decision = BUY
tp = ca[-1]+0.010
sl = l[-2]-0.010
elif o[-2]>c[-2]:
if cb[-1]<l[-2]-0.0010:
decision = SELL
tp = cb[-1]-0.010
sl = h[-2]+0.010
else:
decision = NONE
log_cols = ['time','volume','PAIR','bid_c','ask_c','mid_o','mid_h','mid_l','mid_c']
self.log_message(f"Processed_df\n{df[log_cols].tail(3)}")
self.log_message(f"Trade_decision:{decision}")
self.log_message("")
return decision
def get_trade_decision(self, candle_time):
max_rows = self.settings.long_ma + 2
self.log_message("")
self.log_message(f"get_trade_decision() pair:{self.pair} max_rows:{max_rows}")
df = self.fetch_candles(max_rows, candle_time)
print ("xxxx")
print (df)
if df is not None:
return self.process_candles(df)
print("get trade decision")
print(self.process_candles(df))
return NONE
bot.py
import pprint
import time
from settings import Settings
from log_wrapper import LogWrapper
from timing import Timing
from oanda_api import OandaAPI
from technicals import Technicals
from defs import NONE, BUY, SELL
from trade_manager import TradeManager
GRANULARITY = "M1"
SLEEP = 10.0
class TradingBot():
def __init__(self):
self.log = LogWrapper("Bot")
self.tech_log = LogWrapper("Technicals")
self.trade_log = LogWrapper("Trade")
self.trade_pairs = Settings.get_pairs()
self.settings = Settings.load_settings()
self.api = OandaAPI()
self.trade_manager = TradeManager(self.api, self.settings, self.trade_log)
self.timings = { p: Timing(self.api.last_complete_candle(p, GRANULARITY)) for p in self.trade_pairs }
self.log_message(f"Bot started with\n{pprint.pformat(self.settings)}")
self.log_message(f"Bot Timings\n{pprint.pformat(self.timings)}")
print (self.api)
def log_message(self, msg):
self.log.logger.debug(msg)
def update_timings(self):
for pair in self.trade_pairs:
current = self.api.last_complete_candle(pair, GRANULARITY)
self.timings[pair].ready = False
if current > self.timings[pair].last_candle:
self.timings[pair].ready = True
self.timings[pair].last_candle = current
self.log_message(f"{pair} new candle {current}")
def process_pairs(self):
trades_to_make = []
for pair in self.trade_pairs:
if self.timings[pair].ready == True:
self.log_message(f"Ready to trade {pair}")
techs = Technicals(self.settings[pair], self.api, pair, GRANULARITY, log=self.tech_log)
decision = techs.get_trade_decision(self.timings[pair].last_candle)
print ("process decision")
print (decision)
units = decision * self.settings[pair].units
#tp = "154"
#sl = "153"
if units != 0:
trades_to_make.append({'pair': pair, 'units': units,'take_profit':tp, 'stop_loss':sl})
if len(trades_to_make) > 0:
print("bot")
print(trades_to_make)
self.trade_manager.place_trades(trades_to_make)
def run(self):
while True:
self.update_timings()
self.process_pairs()
time.sleep(SLEEP)
if __name__ == "__main__":
b = TradingBot()
b.run()
defs.py
API_KEY = "xxxx"
ACCOUNT_ID = "xyz"
OANDA_URL = 'https://api-fxpractice.oanda.com/v3'
SECURE_HEADER = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
BUY = 1
SELL = -1
NONE = 0
Instead of just returning the decision, also return the take profit and stop loss values:
return decision, tp, sl
Then you can unpack the tuple in process_pairs:
decision, tp, sl = techs.get_trade_decision(self.timings[pair].last_candle)
You can define your tp and sl as class variables of Technicals.
class Technicals(object):
tp: int = 0
sl: int = 0
and use them within Technicals as:
cls.tp = ... # if you are inside class-method
self.tp = ... # if you are inside instance-method
And in the TradingBot you can then simple import Technicals and use the class-Vars like:
tp = Technicals.tp # you can use the class
tp = techs.tp # or the instance you already have
My current GUI is to show target tracking from a TI processor to PC via UART. Sometimes, GUI crashes due to UART performance. But everytime I want to reset GUI, I also have to reset my TI device. So I want to modify python code so as to only re-open GUI, enter COM port without having to reset device whenever GUI crashes.
Currently, each time GUI crashes, even though I re-opened GUI but didn't reset device (power off & on), I can not continue tracking.
I put python code for GUI below.In this GUI python program, we have 2 blanks & button to enter UART COM port, 2 buttons to select & send configuration to device. Then it can begin tracking.
I'm considering to modify the part of sendCfg(self), but still not sure how to make it work as my purpose due to my lack of experience in Python & GUI design. Please help me with sample code for this task.
class Window(QDialog):
def __init__(self, parent=None, size=[]):
super(Window, self).__init__(parent)
#when running Gree Demo
self.Gree = 1
# set window toolbar options, and title. #deb_gp
self.setWindowFlags(
Qt.Window |
Qt.CustomizeWindowHint |
Qt.WindowTitleHint |
Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint |
Qt.WindowCloseButtonHint
)
self.setWindowTitle("mmWave People Counting")
print('Python is ', struct.calcsize("P")*8, ' bit')
print('Python version: ', sys.version_info)
gridlay = QGridLayout()
gridlay.addWidget(self.comBox, 0,0,1,1)
gridlay.addWidget(self.statBox, 1,0,1,1)
gridlay.addWidget(self.configBox,2,0,1,1)
gridlay.addWidget(self.plotControlBox,3,0,1,1)
gridlay.addWidget(self.boxTab,4,0,1,1)
gridlay.addWidget(self.spBox,5,0,1,1)
gridlay.addWidget(self.graphTabs,0,1,6,1)
gridlay.addWidget(self.gw, 0, 2, 6, 1)
#gridlay.addWidget(self.demoData, 0,3,1,2)
#gridlay.addWidget(self.hPlot,1,3,4,2)
gridlay.setColumnStretch(0,1)
gridlay.setColumnStretch(1,3)
self.setLayout(gridlay)
#
# left side pane layout
#
def setConnectionLayout(self):
self.comBox = QGroupBox('Connect to Com Ports')
self.uartCom = QLineEdit('') #deb_gp
self.dataCom = QLineEdit('') #deb_gp
self.uartLabel = QLabel('UART COM:')
self.dataLabel = QLabel('DATA COM:')
self.connectStatus = QLabel('Not Connected')
self.connectButton = QPushButton('Connect')
self.connectButton.clicked.connect(self.connectCom)
self.configLabel = QLabel('Config Type:')
self.configType = QComboBox()
self.configType.addItems(["3D People Counting", "SDK Out of Box Demo", "Long Range People Detection", "Indoor False Detection Mitigation", "(Legacy) 2D People Counting", "(Legacy): Overhead People Counting"])
self.comLayout = QGridLayout()
self.comLayout.addWidget(self.uartLabel,0,0)
self.comLayout.addWidget(self.uartCom,0,1)
self.comLayout.addWidget(self.dataLabel,1,0)
self.comLayout.addWidget(self.dataCom,1,1)
self.comLayout.addWidget(self.configLabel,2,0)
self.comLayout.addWidget(self.configType,2,1)
self.comLayout.addWidget(self.connectButton,3,0)
self.comLayout.addWidget(self.connectStatus,3,1)
self.comBox.setLayout(self.comLayout)
def setConfigLayout(self):
self.configBox = QGroupBox('Configuration')
self.selectConfig = QPushButton('Select Configuration')
self.sendConfig = QPushButton('Send Configuration')
self.selectConfig.clicked.connect(self.selectCfg)
self.sendConfig.clicked.connect(self.sendCfg)
self.configTable = QTableWidget(5,2)
#set parameter names
self.configTable.setItem(0,0,QTableWidgetItem('Radar Parameter'))
self.configTable.setItem(0,1,QTableWidgetItem('Value'))
self.configTable.setItem(1,0,QTableWidgetItem('Max Range'))
self.configTable.setItem(2,0,QTableWidgetItem('Range Resolution'))
self.configTable.setItem(3,0,QTableWidgetItem('Max Velocity'))
self.configTable.setItem(4,0,QTableWidgetItem('Velcoity Resolution'))
self.configLayout = QVBoxLayout()
self.configLayout.addWidget(self.selectConfig)
self.configLayout.addWidget(self.sendConfig)
self.configLayout.addWidget(self.configTable)
#self.configLayout.addStretch(1)
self.configBox.setLayout(self.configLayout)
def updateGraph(self, parsedData):
updateStart = int(round(time.time()*1000))
self.useFilter = 0
classifierOutput = []
pointCloud = parsedData[0]
targets = parsedData[1]
indexes = parsedData[2]
numPoints = parsedData[3]
numTargets = parsedData[4]
self.frameNum = parsedData[5]
fail = parsedData[6]
classifierOutput = parsedData[7]
fallDetEn = 0
indicesIn = []
if (fail != 1):
#left side
pointstr = 'Points: '+str(numPoints)
targetstr = 'Targets: '+str(numTargets)
self.numPointsDisplay.setText(pointstr)
self.numTargetsDisplay.setText(targetstr)
#right side fall detection
peopleStr = 'Number of Detected People: '+str(numTargets)
if (numTargets == 0):
fdestr = 'Fall Detection Disabled - No People Detected'
elif (numTargets == 1):
fdestr = 'Fall Detection Enabled'
fallDetEn = 1
elif (numTargets > 1):
fdestr = 'Fall Detected Disabled - Too Many People'
#self.numDetPeople.setText(peopleStr)
#self.fallDetEnabled.setText(fdestr)
if (len(targets) < 13):
targets = []
classifierOutput = []
if (fail):
return
#remove static points
if (self.configType.currentText() == '3D People Counting'):
if (not self.staticclutter.isChecked()):
statics = np.where(pointCloud[3,:] == 0)
try:
firstZ = statics[0][0]
numPoints = firstZ
pointCloud = pointCloud[:,:firstZ]
indexes = indexes[:,:self.previousFirstZ]
self.previousFirstZ = firstZ
except:
firstZ = -1
#point cloud persistence
fNum = self.frameNum%10
if (numPoints):
self.previousCloud[:5,:numPoints,fNum] = pointCloud[:5,:numPoints]
self.previousCloud[5,:len(indexes),fNum] = indexes
self.previousPointCount[fNum]=numPoints
#plotting 3D - get correct point cloud (persistent points and synchronize the frame)
if (self.configType.currentText() == 'SDK3xPeopleCount'):
pointIn = pointCloud
else:
totalPoints = 0
persistentFrames = int(self.persistentFramesInput.currentText())
#allocate new array for all the points
for i in range(1,persistentFrames+1):
totalPoints += self.previousPointCount[fNum-i]
pointIn = np.zeros((5,int(totalPoints)))
indicesIn = np.ones((1, int(totalPoints)))*255
totalPoints = 0
#fill array
for i in range(1,persistentFrames+1):
prevCount = int(self.previousPointCount[fNum-i])
pointIn[:,totalPoints:totalPoints+prevCount] = self.previousCloud[:5,:prevCount,fNum-i]
if (numTargets > 0):
indicesIn[0,totalPoints:totalPoints+prevCount] = self.previousCloud[5,:prevCount,fNum-i]
totalPoints+=prevCount
if (self.graphFin):
self.plotstart = int(round(time.time()*1000))
self.graphFin = 0
if (self.threeD):
try:
indicesIn = indicesIn[0,:]
except:
indicesIn = []
self.get_thread = updateQTTargetThread3D(pointIn, targets, indicesIn, self.scatter, self.pcplot, numTargets, self.ellipsoids, self.coordStr, classifierOutput, self.zRange, self.gw, self.plotByIndex.isChecked(), self.plotTracks.isChecked(), self.bbox,self.boundaryBoxes[0]['checkEnable'].isChecked())
self.get_thread.done.connect(self.graphDone)
self.get_thread.start(priority=QThread.HighestPriority-1)
else:
npc = pointIn[0:2,:]
print (np.shape(npc))
self.legacyThread = update2DQTGraphThread(npc, targets, numTargets, indexes, numPoints, self.trailData, self.activeTrail, self.trails, self.scatter2D, self.gatingScatter)
self.legacyThread.done.connect(self.graphDone)
self.legacyThread.start(priority=QThread.HighestPriority-1)
else:
return
#pointIn = self.previousCloud[:,:int(self.previousPointCount[fNum-1]),fNum-1]
#state tracking
if (numTargets > 0):
self.lastFrameHadTargets = True
else:
self.lastFrameHadTargets = False
if (numTargets):
self.lastTID = targets[0,:]
else:
self.lastTID = []
def graphDone(self):
plotend = int(round(time.time()*1000))
plotime = plotend - self.plotstart
try:
if (self.frameNum > 1):
self.averagePlot = (plotime*1/self.frameNum) + (self.averagePlot*(self.frameNum-1)/(self.frameNum))
else:
self.averagePlot = plotime
except:
self.averagePlot = plotime
self.graphFin = 1
pltstr = 'Average Plot time: '+str(plotime)[:5] + ' ms'
fnstr = 'Frame: '+str(self.frameNum)
self.frameNumDisplay.setText(fnstr)
self.plotTimeDisplay.setText(pltstr)
def resetFallText(self):
self.fallAlert.setText('Standing')
self.fallPic.setPixmap(self.standingPicture)
self.fallResetTimerOn = 0
def updateFallThresh(self):
try:
newThresh = float(self.fallThreshInput.text())
self.fallThresh = newThresh
self.fallThreshMarker.setPos(self.fallThresh)
except:
print('No numberical threshold')
def connectCom(self):
#get parser
self.parser = uartParserSDK(type=self.configType.currentText())
self.parser.frameTime = self.frameTime
print('Parser type: ',self.configType.currentText())
#init threads and timers
self.uart_thread = parseUartThread(self.parser)
if (self.configType.currentText() != 'Replay'):
self.uart_thread.fin.connect(self.parseData)
self.uart_thread.fin.connect(self.updateGraph)
self.parseTimer = QTimer()
self.parseTimer.setSingleShot(False)
self.parseTimer.timeout.connect(self.parseData)
try:
uart = "COM"+ self.uartCom.text() #deb_gp
data = "COM"+ self.dataCom.text() #deb_gp
#TODO: find the serial ports automatically.
self.parser.connectComPorts(uart, data)
self.connectStatus.setText('Connected') #deb_gp
self.connectButton.setText('Disconnect') #deb_gp
#TODO: create the disconnect button action
except:
self.connectStatus.setText('Unable to Connect')
if (self.configType.currentText() == "Replay"):
self.connectStatus.setText('Replay')
if (self.configType.currentText() == "Long Range People Detection"):
self.frameTime = 400
#
# Select and parse the configuration file
# TODO select the cfgfile automatically based on the profile.
def selectCfg(self):
try:
self.parseCfg(self.selectFile())
except:
print('No cfg file selected!')
def selectFile(self):
fd = QFileDialog()
filt = "cfg(*.cfg)"
filename = fd.getOpenFileName(directory='./../chirp_configs',filter=filt) #deb_gp - added folder name
return filename[0]
def parseCfg(self, fname):
cfg_file = open(fname, 'r')
self.cfg = cfg_file.readlines()
counter = 0
chirpCount = 0
for line in self.cfg:
args = line.split()
if (len(args) > 0):
if (args[0] == 'cfarCfg'):
zy = 4
#self.cfarConfig = {args[10], args[11], '1'}
elif (args[0] == 'AllocationParam'):
zy=3
#self.allocConfig = tuple(args[1:6])
elif (args[0] == 'GatingParam'):
zy=2
#self.gatingConfig = tuple(args[1:4])
elif (args[0] == 'SceneryParam' or args[0] == 'boundaryBox'):
self.boundaryLine = counter
self.profile['leftX'] = float(args[1])
self.profile['rightX'] = float(args[2])
self.profile['nearY'] = float(args[3])
self.profile['farY'] = float(args[4])
self.setBoundaryTextVals(self.profile)
self.boundaryBoxes[0]['checkEnable'].setChecked(True)
elif (args[0] == 'staticBoundaryBox'):
self.staticLine = counter
elif (args[0] == 'profileCfg'):
self.profile['startFreq'] = float(args[2])
self.profile['idle'] = float(args[3])
self.profile['adcStart'] = float(args[4])
self.profile['rampEnd'] = float(args[5])
self.profile['slope'] = float(args[8])
self.profile['samples'] = float(args[10])
self.profile['sampleRate'] = float(args[11])
print(self.profile)
elif (args[0] == 'frameCfg'):
self.profile['numLoops'] = float(args[3])
self.profile['numTx'] = float(args[2])+1
elif (args[0] == 'chirpCfg'):
chirpCount += 1
elif (args[0] == 'sensorPosition'):
self.profile['sensorHeight'] = float(args[1])
self.profile['az_tilt'] = float(args[2])
self.profile['elev_tilt'] = float(args[3])
counter += 1
maxRange = self.profile['sampleRate']*1e3*0.9*3e8/(2*self.profile['slope']*1e12)
#update boundary box
self.drawBoundaryGrid(maxRange)
#update chirp table values
bw = self.profile['samples']/(self.profile['sampleRate']*1e3)*self.profile['slope']*1e12
rangeRes = 3e8/(2*bw)
Tc = (self.profile['idle']*1e-6 + self.profile['rampEnd']*1e-6)*chirpCount
lda = 3e8/(self.profile['startFreq']*1e9)
maxVelocity = lda/(4*Tc)
velocityRes = lda/(2*Tc*self.profile['numLoops']*self.profile['numTx'])
self.configTable.setItem(1,1,QTableWidgetItem(str(maxRange)[:5]))
self.configTable.setItem(2,1,QTableWidgetItem(str(rangeRes)[:5]))
self.configTable.setItem(3,1,QTableWidgetItem(str(maxVelocity)[:5]))
self.configTable.setItem(4,1,QTableWidgetItem(str(velocityRes)[:5]))
#update sensor position
self.az_tilt.setText(str(self.profile['az_tilt']))
self.elev_tilt.setText(str(self.profile['elev_tilt']))
self.s_height.setText(str(self.profile['sensorHeight']))
def sendCfg(self):
try:
if (self.configType.currentText() != "Replay"):
self.parser.sendCfg(self.cfg)
self.configSent = 1
self.parseTimer.start(self.frameTime)
except:
print ('No cfg file selected!')
# Needed ?? deb_gp
# def setParser(self, uParser):
# self.parser = uParser
def parseData(self):
self.uart_thread.start(priority=QThread.HighestPriority)
def whoVisible(self):
if (self.threeD):
self.threeD = 0
else:
self.threeD = 1
print('3d: ', self.threeD)
if __name__ == '__main__':
if (compileGui):
appctxt = ApplicationContext()
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
exit_code = appctxt.app.exec_()
sys.exit(exit_code)
else:
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
main = Window(size=size)
main.show()
sys.exit(app.exec_())
I tried to use flopy, so I could try running some optimization procedures with python and modflow. Modflow requires a number of data to work with and we provide that info using different files.
We provide the input and flopy runs modflow
My trouble is that, flopy seems to disregard the input files and gives the same result, no matter what input I give.
Here's the code:
nper = 10
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(1, 71, 24)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(1, 71, 24)
class Modflow:
def __init__(self):
self.modelname = 'outs/gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name=r'G:\Program Files (x86)\Visual MODFLOW\mf2005.exe')
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf)
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound, strt=basreader.head)
self.prev_headdata = basreader.head
wel = flopy.modflow.ModflowWel(self.mf, stress_period_data=WellProvider(nper).wells)
fname = 'inps/yo.evt'
fhandle = open(fname, 'r')
packages = []
ext_unit_dict = {22: flopy.utils.mfreadnam.NamData('EVT', fname, fhandle, packages)}
evt = flopy.modflow.ModflowEvt.load(fhandle, self.mf, ext_unit_dict=ext_unit_dict)
fhandle.close()
rech = {}
for x in range(nper):
rech[x] = 1.44e-5
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
stress_period_data = {}
for kper in range(nper):
for kstp in range(int(nper/10)):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf, stress_period_data=stress_period_data, compact=True)
chd = flopy.modflow.ModflowChd.load("inps/yo.chd", self.mf)
lpf = flopy.modflow.ModflowLpf(self.mf, hk=14.44, vka=14.44, ipakcb=53, sy=0.22)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
headobj = bf.HeadFile(self.modelname + '.hds')
newheaddata = headobj.get_alldata()[-1][0]
return newheaddata
mdflw = Modflow()
mdflw.run()
Now, even if I change the EVT, RCH or WEL info, the results are same.
I even tried to not include the above files, still the results were same.
Any pointers?
This revision of your script results in different head results (since different groundwater recharge values are used). I used the bcf2ss MODFLOW-2005 input files as base files in the revised example.
Not entirely sure why your script wasn't working since your input files weren't available.
import os
import numpy as np
import flopy
class BASreader:
def __init__(self):
self.ibound = None
self.head = None
with open("inps/bas/ibound", "r") as f:
data = f.read().replace("-", " -").split()
data = [int(x) for x in data]
data = np.array(data).reshape(2, 10, 15)
self.ibound = data
with open("inps/bas/head", "r") as f:
data = f.read().split()
data = [float(x) for x in data]
self.head = np.array(data).reshape(2, 10, 15)
class Modflow:
def __init__(self, ws='outs', rech_val=.0040, wel_data=None):
self.model_ws = ws
self.modelname = 'gen1'
self.mf = flopy.modflow.Modflow(self.modelname, exe_name='mf2005',
model_ws=self.model_ws)
dis = flopy.modflow.ModflowDis.load("inps/yo.dis", self.mf, check=False)
nper = dis.nper
nstp = dis.nstp.array
basreader = BASreader()
bas = flopy.modflow.ModflowBas(self.mf, ibound=basreader.ibound,
strt=basreader.head)
self.prev_headdata = basreader.head
bcf = flopy.modflow.ModflowBcf.load("inps/yo.bc6", self.mf)
if wel_data is None:
wel_data = [[1, 2, 3, -35000.],
[1, 7, 3, -35000.]]
wel_spd = {1: wel_data}
wel = flopy.modflow.ModflowWel(self.mf,
stress_period_data=wel_spd)
riv = flopy.modflow.ModflowRiv.load('inps/yo.riv', self.mf, check=False)
rech = {}
for x in range(nper):
rech[x] = rech_val
rch = flopy.modflow.ModflowRch(self.mf, rech=rech)
pcg = flopy.modflow.ModflowPcg.load('inps/yo.pcg', self.mf)
stress_period_data = {}
for kper in range(nper):
for kstp in range(nstp[kper]):
stress_period_data[(kper, kstp)] = ['save head',
'save drawdown',
'save budget',
'print head',
'print drawdown',
'print budget']
oc = flopy.modflow.ModflowOc(self.mf,
stress_period_data=stress_period_data,
compact=True)
self.mf.write_input()
def run(self):
success, buff = self.mf.run_model(silent=True)
fpth = os.path.join(self.model_ws, self.modelname + '.hds')
headobj = flopy.utils.HeadFile(fpth)
newheaddata = headobj.get_data(idx=1)
return newheaddata
if __name__ == "__main__":
m1 = Modflow()
h1 = m1.run()
m2 = Modflow(rech_val=.0041)
h2 = m2.run()
assert np.array_equal(h1, h2), 'h1 does not equal h2'
i first use PyQT4 .
i'm create a QTableWidget to show runing message...
when my program run, it ill crash Within ten minutes.
i try diable my TableUpdate function , and it's don't crash again.
there is my code please help me
class table_work(QThread):
TableDataSignal = pyqtSignal()
def __init__(self,main_self):
# QThread.__init__(self)
super(table_work, self).__init__(main_self)
self.main_self = main_self
self.table_update_list = list()
#pyqtSlot(dict)
def update_table_thread_o(self,work):
try:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
del work
except:
pass
def update_table_thread(self):
main_self = self.main_self
table_work_list = self.table_update_list
while 1:
for work in self.table_update_list:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
time.sleep(0.5)
def run(self):
self.update_table_thread()
this's update table message
def update_table(self,address,change_obj=None,tabe_name='auto_card'):
sample_dict = dict()
table_key_sort = list()
now_table_sort = 0
if tabe_name == "auto_bot":
this_table = self.auto_bot_procc_table
table_data_list = self.auto_bot_procc_table_list
now_table_sort = self.auto_bot_now_table_sort
sample_dict['address'] = address
sample_dict['money'] = 0
sample_dict['run_time'] = 0
sample_dict['item_cd'] = u"60分鐘後"
sample_dict['stat'] = "Ready..."
sample_dict['sort'] = now_table_sort
table_key_sort.append('address')
table_key_sort.append('money')
table_key_sort.append('run_time')
table_key_sort.append('item_cd')
table_key_sort.append('stat')
if tabe_name == "auto_card":
this_table = self.process_table
table_data_list = self.now_procc_table_list
now_table_sort = self.now_table_sort
sample_dict['address'] = address
sample_dict['done_num'] = 0
sample_dict['pre_item'] = ""
sample_dict['procc'] = "Ready"
sample_dict['mission_procc'] = u"待命.."
sample_dict['mission_num'] = 0
sample_dict['mission_line'] = 0
sample_dict['update_time'] = db.get_time()
sample_dict['sort'] = now_table_sort
sample_dict['option'] = ""
table_key_sort.append('address')
table_key_sort.append('done_num')
table_key_sort.append('pre_item')
table_key_sort.append('mission_procc')
table_key_sort.append('procc')
table_key_sort.append('mission_num')
table_key_sort.append('mission_line')
table_key_sort.append('update_time')
if address not in table_data_list:
this_table.insertRow(sample_dict['sort'])
table_data_list[address] = sample_dict
sample_dict['sort'] = self.auto_bot_now_table_sort
self.auto_bot_now_table_sort += 1
acc_data = table_data_list[address]
if change_obj != None:
key = change_obj['key']
val = change_obj['val']
if key in acc_data:
acc_data[key] = val
acc_data['update_time'] = db.get_time()
rowPosition = acc_data['sort']
temp = dict()
temp['row_position'] = rowPosition
temp['data'] = acc_data
temp['key_sort'] = table_key_sort
temp['table'] = this_table
self.TableDataSignal.emit(temp)
del temp
Some time i get a ANS.
i'm a PYQT newbie , After this period of various projects experience.
I understand if you don't use Main Thread to Change UI, Always use sign/emit
even your code is worked,but always use sign/emit, Otherwise there will be a series of disasters.
you just like
class sample(QtCore.QThread):
table_data_change = QtCore.pyqtSignal(dict)
def __init__(self,main_win):
self.main = main_win
self.table_data_change.connect(self.main.change_fn)
def test(self):
data = dict()
data['btn'] = .....
data['val'] = .....
self.table_data_change.emit(data)
Save your time !
I research Python internals and write GUI Generic windows use Windows API.
# -*- coding: utf-8 -*-
import time
import threading
import logging
import uuid
import ctypes
import ctypes.wintypes
import const
INT = ctypes.wintypes.c_int
LPVOID = ctypes.wintypes.c_void_p
HCURSOR = ctypes.wintypes.HANDLE
LRESULT = ctypes.wintypes.LPARAM
COLORREF = ctypes.wintypes.DWORD
PVOID = ctypes.wintypes.c_void_p
WCHAR = ctypes.wintypes.c_wchar
BCHAR = ctypes.wintypes.c_wchar
LPRECT = ctypes.wintypes.POINTER(ctypes.wintypes.RECT)
LPPOINT = ctypes.wintypes.POINTER(ctypes.wintypes.POINT)
LPMSG = ctypes.wintypes.POINTER(ctypes.wintypes.MSG)
UINT_PTR = ctypes.wintypes.HANDLE
LONG_PTR = ctypes.wintypes.HANDLE
#WNDPROC = ctypes.wintypes.WINFUNCTYPE(ctypes.c_long, ctypes.wintypes.HWND, ctypes.wintypes.UINT, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)
WNDPROC = ctypes.wintypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int)
SW_SHOWNORMAL = 1
SW_SHOW = 5
CS_HREDRAW = 2
CS_VREDRAW = 1
CW_USEDEFAULT = 0x80000000
WM_DESTROY = 2
class WNDCLASSEX(ctypes.wintypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.UINT),
("style", ctypes.wintypes.UINT),
("lpfnWndProc", WNDPROC),
("cbClsExtra", ctypes.wintypes.INT),
("cbWndExtra", ctypes.wintypes.INT),
("hInstance", ctypes.wintypes.HANDLE),
("hIcon", ctypes.wintypes.HANDLE),
("hCursor", ctypes.wintypes.HANDLE),
("hBrush", ctypes.wintypes.HANDLE),
("lpszMenuName", ctypes.wintypes.LPCWSTR),
("lpszClassName", ctypes.wintypes.LPCWSTR),
("hIconSm", ctypes.wintypes.HANDLE)]
class Window(object):
def __init__(self, app, wclassName=None, wname=u"Custom Title"):
self.__app = app
#
self.__log = logging.getLogger("win_ui.window")
#
self.__hInst = app.getInstance()
self.__hWnd = None
#
if wclassName is None:
wclassName = u"NewWindowClass-{uid}".format(uid=uuid.uuid4().hex)
#
self.__wclassName = wclassName
self.__wname = wname
#
#self.__event_dispatcher = EventDispatcher(app=app)
#self.__event_dispatcher.start()
#
self.__has_exit = threading.Condition()
#
self._create()
def wnd_proc(self, hWnd, Msg, wParam, lParam):
self.__log.debug("WndProc: hWnd={hWnd!r}, Msg={Msg!r}, wParam={wParam!r}, lParam={lParam!r}".format(hWnd=hWnd, Msg=Msg, wParam=wParam, lParam=lParam))
#self.__event_dispatcher.push((hWnd, Msg, wParam, lParam))
#
result = None
#
self.__has_exit.acquire()
self.__has_exit.wait(0.1)
#
if Msg == WM_DESTROY:
self.__app.loadLibrary("user32").PostQuitMessage(0)
result = 0
#
if result is None:
result = self.__app.loadLibrary("user32").DefWindowProcW(hWnd, Msg, wParam, lParam)
#
self.__has_exit.release()
#
return result
def _create(self):
WndProc = WNDPROC(self.wnd_proc)
hBrush = self.__app.loadLibrary("gdi32").GetStockObject(const.LTGRAY_BRUSH)
print hBrush
wndClass = WNDCLASSEX()
wndClass.cbSize = ctypes.sizeof(WNDCLASSEX)
wndClass.style = CS_HREDRAW | CS_VREDRAW
wndClass.lpfnWndProc = WndProc
wndClass.cbClsExtra = 0
wndClass.cbWndExtra = 0
wndClass.hInstance = self.__hInst
wndClass.hIcon = 0 #self.__app.loadIcon()
wndClass.hCursor = 0 #self.__app.loadCursor()
wndClass.hBrush = hBrush
wndClass.lpszMenuName = None
wndClass.lpszClassName = ctypes.c_wchar_p(self.__wclassName)
wndClass.hIconSm = 0 #self.__app.loadCursor()
self.__log.debug("wndClass.cbSize = {cbSize!r}".format(cbSize=wndClass.cbSize))
self.__log.debug("wndClass.lpfnWndProc = {lpfnWndProc!r}".format(lpfnWndProc=wndClass.lpfnWndProc))
self.__log.debug("wndClass.hInstance = {hInst!r}".format(hInst=wndClass.hInstance))
self.__log.debug("wndClass.lpszClassName = {lpszClassName!r}".format(lpszClassName=wndClass.lpszClassName))
result = self.__app.loadLibrary("user32").RegisterClassExW(ctypes.byref(wndClass))
self.__log.debug("0x0{result:x} = RegisterClassExW(...)".format(result=result))
#
self.__x = CW_USEDEFAULT
self.__y = CW_USEDEFAULT
self.__width = 300
self.__height = 300
#
exStyle = 0
#exStyle = const.WS_EX_APPWINDOW
style = const.WS_OVERLAPPEDWINDOW
#style = const.WS_OVERLAPPEDWINDOW | const.WS_CAPTION | const.WS_VISIBLE
wclassName = ctypes.c_wchar_p(self.__wclassName)
wname = ctypes.c_wchar_p(self.__wname)
print wname
#
self.__app.loadLibrary("user32").CreateWindowExW.restype = ctypes.wintypes.HWND
self.__app.loadLibrary("user32").CreateWindowExW.argtypes = [ctypes.wintypes.DWORD, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.wintypes.DWORD, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.wintypes.HWND, ctypes.wintypes.HMENU, ctypes.wintypes.HINSTANCE, ctypes.wintypes.LPVOID]
#
self.__hWnd = self.__app.loadLibrary("user32").CreateWindowExW(exStyle, wclassName, wname, style, self.__x, self.__y, self.__width, self.__height, 0, None, self.__hInst, 0)
self.__log.debug("0x0{hWnd!r} = CreateWindowExW(...)".format(hWnd=self.__hWnd))
if not self.__hWnd:
print self.__app.getLastError()
raise WindowsError("Failed to create window")
self.__log.debug("ShowWindow(hWnd=0x{hWnd:x})".format(hWnd=self.__hWnd))
result = self.__app.loadLibrary("user32").ShowWindow(self.__hWnd, SW_SHOW)
self.__log.debug('0x0{result:x} = ShowWindow(...)'.format(result=result))
self.__log.debug('UpdateWindow(hWnd=0x{hWnd:x})'.format(hWnd=self.__hWnd))
result = self.__app.loadLibrary("user32").UpdateWindow(self.__hWnd)
self.__log.debug('0x0{result:x} = UpdateWindow(...)'.format(result=result))
GUI generic window create but cause exception "WidnowsError: access violation 000001" on DispatchMessageW in EventLoop.
# -*- coding: utf-8 -*-
import logging
import uuid
import ctypes
import ctypes.wintypes
import const
class Application(object):
def __init__(self):
self.__log = logging.getLogger("win_ui.application")
self.__libs = {}
#
self._event_thread = self.loadLibrary("kernel32").GetCurrentThreadId()
def loadLibrary(self, name):
if name in self.__libs:
result = self.__libs[name]
else:
module = getattr(ctypes.windll, name)
result = self.__libs[name] = module
return result
def getInstance(self, hModule=None):
self.__log.debug('GetModuleHandleW(hModule={hModule!r})'.format(hModule=hModule))
result = self.loadLibrary("kernel32").GetModuleHandleW(None)
self.__log.debug('0x0{result:x} = GetModuleHandleW(...)'.format(result=result))
return result
def loadIcon(self, iconName=None):
if iconName is None:
iconName = const.IDI_APPLICATION
hInst = self.getInstance()
result = self.loadLibrary("user32").LoadIconW(hInst, iconName)
return result
def loadCursor(self, v=None):
if v is None:
v = const.IDI_APPLICATION
hInst = self.getInstance()
result = self.loadLibrary("user32").LoadCursorW(hInst, v)
return result
def getLastError(self):
self.__log.debug('GetLastError()')
result = self.loadLibrary("kernel32").GetLastError()
#print result
#rs = self.loadLibrary("kernel32").FormatMessageW(result)
#print rs
self.__log.debug('0x0{result:x} = GetLastError()'.format(result=result))
return result
def check(self):
if self._event_thread != self.loadLibrary("kernel32").GetCurrentThreadId():
raise RuntimeError("Thread?")
def run(self):
self.check()
msg = ctypes.wintypes.MSG()
lpmsg = ctypes.pointer(msg)
self.__log.debug('Entering message loop')
#
user32 = self.loadLibrary("user32")
while user32.GetMessageW(lpmsg, 0, 0, 0) != 0:
#while self.loadLibrary("user32").PeekMessageW(ctypes.byref(msg), 0, 0, 0, const.PM_REMOVE):
user32.TranslateMessage(lpmsg)
print lpmsg
user32.DispatchMessageW(lpmsg)
#
self.__log.debug('done.')
When I refactoring and calls RegisterWindowEx and CreateWindowEx on separate Python method CreateWindowEx start return 0x0 and GetLastError retrun 0x0. What problem there?