I'm a beginner in Python and have a trouble in running a python module in Rhino3D Grasshopper. The code in a Python module is shown as below.
An instance of Agent alone is working well but when I try to dla.update() with Timer in a next python module(which is simply executing dla.update()), I got the message saying that there is something wrong in self.pos = rs.EvaluateCurve(cirCrv, rndNum) and self.curAgent = Agent(self.cirCrv, self.cenPt, self.walkDist).
Is there a way to make this working ?
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
import ghpythonlib.components as gh
import random as rnd
class Agent :
def __init__(self, cirCrv, cenPt, walkDist):
self.cenPt = cenPt
self.walkDist = walkDist
rndNum = rnd.random()
self.pos = rs.EvaluateCurve(cirCrv, rndNum)
def randWalk(self) :
v = rs.VectorSubtract(rs.AddPoint(0,0,0), self.pos)
v1 = rs.VectorUnitize(v)
v2 = rs.VectorScale(v1, self.walkDist)
v3 = rs.VectorSubtract(self.pos, rs.AddPoint(0,0,0))
v4 = rs.VectorAdd(v3, gh.UnitZ(1))
rotAxis = rs.VectorSubtract(v4, v3)
newV1 = rs.VectorRotate(v2, rnd.uniform(-70, 70), rotAxis)
self.pos = rs.VectorAdd(self.pos, newV1)
def checkDist(self):
dist1 = rs.Distance(self.pos, rs.AddPoint(0,0,0))
return dist1
class dla :
def __init__(self, cirCrv, cenPt, walkDist):
self.Agents = []
self.cirCrv = cirCrv
self.cenPt = cenPt
self.walkDist = walkDist
self.curAgent = Agent(self.cirCrv, self.cenPt, self.walkDist)
self.pos =self.curAgent.pos
def update(self):
if self.curAgent.checkDist() < 1:
self.Agents.append(self.curAgent)
self.curAgent = Agent(self.cirCrv, self.cenPt, self.walkDist)
else:
self.curAgent.randWalk()
a = dla(cirCrv,cenPt,walkDist)
Related
I can't make graph with qt6 beacouse when I set values it gives me error: numpy.core._exceptions._UFuncNoLoopError: ufunc 'fmin' did not contain a loop with signature matching types (dtype('<U1'), dtype('<U1')) -> None
Theres my code:
import sys
from PySide6.QtWidgets import QApplication
from PySide6 import *
import pyqtgraph as pg
uiclass, baseclass = pg.Qt.loadUiType("mainwindow.ui")
class MainWindow(uiclass, baseclass):
def __init__(self):
super().__init__()
self.setupUi(self)
self.plot([1,2,3,4,5,6,7,8,9,10], [20,20,20,20,20,20,20,20,20,20])
self.pushButton.clicked.connect(lambda: self.changeColorTeeth1())
self.pushButton_2.clicked.connect(lambda: self.changeColorTeeth2())
self.pushButton_3.clicked.connect(lambda: self.changeColorTeeth3())
self.pushButton_4.clicked.connect(lambda: self.changeColorTeeth4())
self.pushButton_5.clicked.connect(lambda: self.changeColorTeeth5())
self.pushButton_6.clicked.connect(lambda: self.changeColorTeeth6())
self.SaveGraphButton.clicked.connect(lambda: self.Save())
def plot(self, teethsize, height):
self.graphWidget.plot(teethsize, height)
self.graphWidget_2.plot(teethsize, height)
def Save(self):
print("Save runned!")
Teeth1 = self.Teeth1.toPlainText()
Teeth2 = self.Teeth2.toPlainText()
Teeth3 = self.Teeth3.toPlainText()
Teeth4 = self.Teeth4.toPlainText()
Teeth5 = self.Teeth5.toPlainText()
Teeth6 = self.Teeth6.toPlainText()
Teeth7 = self.Teeth7.toPlainText()
Teeth8 = self.Teeth8.toPlainText()
Teeth9 = self.Teeth9.toPlainText()
Teeth10 = self.Teeth10.toPlainText()
Teeth11 = self.Teeth11.toPlainText()
Teeth12 = self.Teeth12.toPlainText()
Teeth13 = self.Teeth13.toPlainText()
Teeth14 = self.Teeth14.toPlainText()
self.plot([Teeth1,Teeth2,Teeth3,Teeth4,Teeth5,Teeth6,Teeth7,Teeth8,Teeth9,Teeth10,Teeth11,Teeth12,Teeth13,Teeth14], [20,20,20,20,20,20,20,20,20,20,20,20,20,20])
def changeColorTeeth1(self):
g = open('config.txt', 'r')
buttonClicked = int(g.read())
print("Button State:", buttonClicked)
g.close()
f = open('config.txt', 'w')
if buttonClicked == 0:
self.pushButton.setStyleSheet(f"background-color : orange;")
buttonClicked = 1
elif buttonClicked == 1:
self.pushButton.setStyleSheet(f"background-color : red;")
buttonClicked = 2
elif buttonClicked == 2:
self.pushButton.setStyleSheet(f"background-color : white;")
buttonClicked = 0
b = f.write(str(buttonClicked))
f.close()
...
I tried to add str and int but it still doesn't worked!
This is my current project (Python 3.8). Your supposed to be able to draw things on your screen. This is not my full version. Its just for explanation purposes. The problem is that if you run run.py it doesn't clear the screen. Shouldn't the new Frame just push the old one out of frame? Do you know what my problem is?
main.py:
import os
import time
from datetime import datetime
import logging
import ctypes
class ConsoleGameEngine:
def __init__(self, windowWidth, windowHeight):
logging.basicConfig(filename=f'debug\{datetime.now().strftime("%H-%M-%S")}-main.log',level=logging.DEBUG)
self.screenWidth = windowWidth
self.screenHeight = windowHeight
self.var = ""
self.pixel = u"\u2591"#u"\u25A1"
self.lightShade = u"\u2591"
self.mediumShade = u"\u2592"
self.darkShade = u"\u2593"
os.system(f'mode con: cols={self.windowWidth} lines={self.windowHeight}')
"""
SCREEN ACCESS:
self.screen[y][x]
"""
self.clearScreenVar = [[" " for w in range(self.screenWidth)] for h in range(self.screenHeight)]
self.screen = self.clearScreenVar
def clearScreen(self):
"""
for y in range(self.windowHeight):
for x in range(self.windowHeight):
self.screen[y][x] = " "
"""
self.screen = self.clearScreenVar
def drawPixel(self,x,y,shade=u"\u2591"):
try:
self.screen[y][x] = shade
except Exception as e:
logging.warning(datetime.now().strftime("%H:%M:%S~")+str(e)+f"~Failed drawing pixel at x: {x} and/or y: {y}")
def sleep(self, t = 1):
time.sleep(t)
def printScreen(self):
print("".join(["".join(x) for x in self.screen]))
run.py:
from main import ConsoleGameEngine
win = ConsoleGameEngine(120, 40)
x = 0
while True:
win.drawPixel(x,20)
win.printScreen()
win.sleep(0.1)
win.clearScreen()
x += 1
I am trying to add UserControl to a WinForm using PythonNet but not having any luck. For testing, I added a button and that shows up but not the UserControl and I am not sure what I a doing wrong.
All the code can be placed into one py file. I broke into a few sections hoping it will be easier to read.
USER CONTROL
class Field(WinForms.UserControl):
def __init__(self):
self.InitializeComponents()
pass
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.label = WinForms.Label()
self.textBox = WinForms.Label()
## Label
# self.label.Anchor = ((WinForms.AnchorStyles)(
# ((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)))
self.label.AutoSize = True
self.label.Location = System.Drawing.Point(3, 7)
self.label.Name = "label"
self.label.Size = System.Drawing.Size(29, 13)
self.label.TabIndex = 0
self.label.Text = "label"
## TextBox
# self.textBox.Anchor = ((WinForms.AnchorStyles)(
# (((WinForms.AnchorStyles.Top | WinForms.AnchorStyles.Bottom)
# | WinForms.AnchorStyles.Left)
# | WinForms.AnchorStyles.Right)))
# self.textBox.Location = System.Drawing.Point(115, 3)
self.textBox.Name = "textBox"
self.textBox.Size = System.Drawing.Size(260, 20)
self.textBox.TabIndex = 1
## Control
self.AutoScaleMode = WinForms.AutoScaleMode.Font
self.Controls.Add(self.textBox)
self.Controls.Add(self.label)
self.Name = "Field"
self.Size = System.Drawing.Size(378, 26)
# self.PerformLayout()
PARENT FORM
class ParentForm(WinForms.Form):
def __init__(self):
self.InitializeComponents()
# region Form Design
def InitializeComponents(self):
self.components = System.ComponentModel.Container()
self.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
self.ClientSize = System.Drawing.Size(385, 180)
self.Name = "ParentForm"
self.Text = "Parent Form"
self.field1 = Field()
self.field1.Location = Point(13, 13)
self.field1.Name = "field1"
self.field1.Size = Size(378, 26)
self.field1.TabIndex = 1
self.Controls.Add(self.field1)
self.button1 = WinForms.Button()
self.button1.Location = Point(13, 50)
self.button1.Size = Size(50, 20)
self.button1.Text = "Button1"
self.Controls.Add(self.button1)
pass
def Dispose(self):
self.components.Dispose()
WinForms.Form.Dispose(self)
ENTRY POINT AND IMPORTS
import clr
import System
import System.Windows.Forms as WinForms
from System.IO import File
from System.Text import Encoding
from System.Drawing import Color, Point, Size
from System.Threading import ApartmentState, Thread, ThreadStart
def appThread():
app = ParentForm()
WinForms.Application.Run(app)
app.Dispose()
def appEntry():
thread = Thread(ThreadStart(appThread))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()
if __name__ == '__main__':
appEntry()
I am using code in wxPython to show images.
I created a screen with 2 panels, one left and right.
In one of the panels (randomly chosen), I want do display an image for exactly 150ms.
How can I program this? I am relatively new to Python, and I don't find any clear way on the internet.
My code for now (without the 150ms):
import wxversion
wxversion.select("3.0")
import wx
import random
import timeclass Screen_1(wx.Dialog):
ri = 0
def __init__(self,parent,id,title):
wx.Dialog.__init__(self,parent,id,title,size=(400,300))
self.randomImage = random.randrange(1,3)
self.randomSlot = random.randrange(1,3)
Screen_1.ri = self.randomImage
if(self.randomSlot == 1):
self.side = 'Left'
else:
self.side = 'Right'
file = open('User.txt','a')
panel_left = wx.Panel(self,11,(-1,-1),(200,200))
self.picture_left = wx.StaticBitmap(panel_left)
font = wx.Font(13,wx.DEFAULT,wx.NORMAL,wx.BOLD)
panel_centre = wx.Panel(self,12,(200,70),(10,100))
msg = wx.StaticText(panel_centre,-1,'+',size=(10,100))
msg.SetFont(font)
panel_right = wx.Panel(self,13,(210,0),(200,200))
self.picture_right = wx.StaticBitmap(panel_right)
**self.imageName = 'im_'+str(self.randomImage)+'.png'**
if self.randomSlot == 1:
self.picture_left.SetBitmap(wx.Bitmap(self.imageName))
else:
self.picture_right.SetBitmap(wx.Bitmap(self.imageName))
wx.FutureCall(1000,self.Destroy)
self.Centre()
self.ShowModal()
def OnClick(self,event):
self.Close()
Thanks a lot!
def OnTimeUp(self,e):
#change images
self.timer.Start(15,oneShot=True) # if you want to call it again in 15 ms
def StartTimer(self):
self.timer = wx.Timer()
self.timer.Bind(wx.EVT_TIMER,self.OnTimeUp)
self.timer.Start(15,oneShot=True)
something like that ... although 15ms is very fast ...
I encountered this error when running a testbench, together with a synchronizer built on two existing D-FFs.
File "/home/runner/design.py", line 28, in Sync
#always_seq(clk.posedge, reset=reset)
File "/usr/share/myhdl-0.8/lib/python/myhdl/_always_seq.py", line 76, in _always_seq_decorator
raise AlwaysSeqError(_error.ArgType)
myhdl.AlwaysError: decorated object should be a classic (non-generator) function
My testbench is outlined as follows
from myhdl import *
from random import randrange
HALF_PERIOD = delay(10) ### This makes a 20-ns clock signal
ACTIVE_HIGH = 1
G_DELAY = delay(15)
def Main():
### Signal declaration
clk, d, dout = [Signal(intbv(0)) for i in range(3)]
reset = ResetSignal(1,active=ACTIVE_HIGH,async=True)
### Module Instantiation
S1 = Sync(dout, d, clk,reset)
### Clk generator
#always(HALF_PERIOD)
def ClkGen():
clk.next = not clk
### TB def
#instance
def Driver():
yield(HALF_PERIOD)
reset.next = 0
for i in range(4):
yield(G_DELAY)
d.next = not d
raise StopSimulation
return ClkGen, Driver, S1
m1 = traceSignals(Main)
sim = Simulation(m1)
sim.run()
And my synchronizer is coded as follows.
from myhdl import *
from DFF import *
def Sync(dout,din,clk,reset):
""" The module consists of two FFs with one internal signal
External signals
dout : output
din : input
clk : input
Internal signal:
F2F : output-to-input signal that connects two FFs together
"""
### Connectivity
F2F = Signal(intbv(0))
F1 = DFF(F2F,din,clk,reset)
F2 = DFF(dout,F2F,clk,reset)
### Function
#always_seq(clk.posedge,reset=reset)
def SyncLogic():
if reset:
F2F.next = 0
dout.next = 0
else:
F2F.next = din
yield(WIRE_DELAY)
dout.next = F2F
return SyncLogic
and the FF prototype is coded as follows.
from myhdl import *
def DFF(dout,din,clk,reset):
#always_seq(clk.posedge, reset=reset)
def Flogic():
if reset:
dout.next = 0
else:
dout.next = din
return Flogic
The testbench did work with the similar testbench I coded earlier(with slight modification), but it didn't work when combining two modules together. Please clarify. Thank you.
To model a wire delay, use the "delay" argument in the Signal.
change
#always_seq(clk.posedge,reset=reset)
def SyncLogic():
if reset:
F2F.next = 0
dout.next = 0
else:
F2F.next = din
yield(WIRE_DELAY)
dout.next = F2F
return SyncLogic
to:
dout = Signal(<type>, delay=WIRE_DELAY)
# ...
#always_seq(clk.posedge, reset=reset)
def synclogic():
dout.next = din
With the "always_seq" don't define the reset (it is automatically added). If you want to explicitly define the reset use "#always(clock.posedge, reset.negedge)".