I have a Seeed Studio XIAO SAMD21(Seeeduino XIAO) - Arduino Microcontroller. I want to have three pins put out a frequency using PWM. I am trying to use the below code. If I comment out one of DOut2, Dout3, or Dout4; the code runs and the two pins output the correct signal. However, when I have all three DOuts, I get the following error: RuntimeError: All timers in use. Any advice is appreciated.
#Seeeduino XIAO Program (to run on microcontroller)
import supervisor
import time
import board
import digitalio
import pwmio
import analogio
if __name__ == "__main__":
frequency = 25
DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
#DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
Works
DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
#DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
Works
#DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
Works
DOut2 = pwmio.PWMOut(board.D2, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut3 = pwmio.PWMOut(board.D3, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
DOut4 = pwmio.PWMOut(board.D4, duty_cycle = 32767, frequency = int(frequency), variable_frequency = True)
Gives 'RuntimeError: All timers in use'
Related
import copy
import math
class obj_kMeans:
def __init__(self,init_centroid,k):
self.k = k
self.clusters = None
self.centroids = np.empty((self.k,2))
self.initial_centroid = init_centroid
def distance(self,x,y):
return np.linalg.norm(y-x, ord=2)
def init_centroids(self, x):
centroids = self.centroids
centroids[0] = self.initial_centroid
for i in range(1, self.k):
d_max = 0
d_max_cen = centroids[0]
for x_i in x:
if x_i in centroids:
continue
xi_distance = sum([self.distance(x_i, prev) for prev in centroids]
if xi_distance > d_max:
d_max = xi_distance
d_max_cen = x_i
centroids[i] = d_max_cen
return centroids
def cost_function(self,clusters):
squared_errors = list()
for i in range(self.k):
points = clusters[i][1]
centroid = clusters[i][0]
errors = [self.distance(centroid,point)**2 for point in points]
total_error = sum(errors)
squared_errors.append(total_error)
return sum(squared_errors)
def cluster(self,x):
centroids = self.init_centroids(x)
clusters = {}
for i in range(self.k):
cluster_list = (centroids[i],list())
clusters[i] = cluster_list
itr = 0
while True:
for point in x:
dist_min = self.distance(centroids[0],point)
num = 0
cls_point = 0
for centroid in centroids:
d = self.distance(centroid,point)
if d < dist_min:
cls_point = num
dist_min = d
num +=1
clusters[cls_point][1].append(point)
self.clusters = copy.deepcopy(clusters)
centroids = list()
converges = True
for i in range(self.k):
dp = clusters[i][1]
dp.append(clusters[i][0])
centroid_p = np.mean(np.array(dp), axis=0)
if not ((centroid_p == clusters[i][0]).all()):
converges = False
centroids.append(centroid_p)
cluster_list = (centroid_p,list())
clusters[i] = cluster_list
itr +=1
if converges:
break
self.centroids = centroids
kMeans_implement1 = obj_kMeans(k=k1, init_centroid = i_point1)
kMeans_implement2 = obj_kMeans(k=k2, init_centroid = i_point2)
kMeans_implement1.cluster(data)
kMeans_implement2.cluster(data)
cost_val1 = kMeans_implement1.cost_function(kMeans_implement1.clusters)
cost_val2 = kMeans_implement2.cost_function(kMeans_implement2.clusters)
print("centroid 1", kMeans_implement1.centroids)
print("centroid 2", kMeans_implement2.centroids)
print("cost 1", cost_val1)
print("cost 2", cost_val2)
I am trying to simulate some planets and their moons around the sun but not getting scene opened up.`from vpython import*
def open_scene(breedte, hoogte):
global open_venster
c = canvas(width=breedte, height=hoogte, background=color.black)
c.center = vector(0,0,0)
c.range = breedte
c.autozoom = True
c.autoscale = False
c.userzoom = True
c.userspin = False
c.userpan = False
return c
open_scene(400, 400)
def solarsystem(n, dt):
He = planets_from_file("planeten.txt")
planets = []
sun = sphere(pos = vector(0,0,0), radius = He[0].straal_v_hemellichaam, color = kleuromzetting(He[0].kleur))
earth = sphere(pos = vector(-He[3].straal_vd_baan, 0, 0), radius= He[3].straal_v_hemellichaam*50, texture= textures.earth)
moon = sphere(pos = vector(-He[4].straal_vd_baan,0,0), radius = He[4].straal_v_hemellichaam, color = kleuromzetting(He[4].kleur))
mercurius = sphere(pos = vector(-He[1].straal_vd_baan,0,0), radius = He[1].straal_v_hemellichaam, color = kleuromzetting(He[1].kleur))
venus = sphere(pos = vector(-He[2].straal_vd_baan,0,0), radius = He[2].straal_v_hemellichaam, color = kleuromzetting(He[2].kleur))
mars = sphere(pos = vector(-He[5].straal_vd_baan,0,0), radius = He[5].straal_v_hemellichaam, color = kleuromzetting(He[5].kleur))
phobos = sphere(pos = vector(-He[6].straal_vd_baan-He[5].straal_vd_baan,0,0), radius = He[6].straal_v_hemellichaam, color = kleuromzetting(He[6].kleur))
deimos = sphere(pos = vector(-He[7].straal_vd_baan-He[5].straal_vd_baan,0,0), radius = He[7].straal_v_hemellichaam, color = kleuromzetting(He[7].kleur))
jupiter = sphere(pos = vector(-He[8].straal_vd_baan,0,0), radius = He[8].straal_v_hemellichaam, color = kleuromzetting(He[8].kleur))
io = sphere(pos = vector(-He[9].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[9].straal_v_hemellichaam, color = kleuromzetting(He[9].kleur))
europa = sphere(pos = vector(-He[10].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[10].straal_v_hemellichaam, color = kleuromzetting(He[10].kleur))
ganymede = sphere(pos = vector(-He[11].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[11].straal_v_hemellichaam, color = kleuromzetting(He[11].kleur))
callisto = sphere(pos = vector(-He[12].straal_vd_baan-He[8].straal_vd_baan,0,0), radius = He[12].straal_v_hemellichaam, color = kleuromzetting(He[12].kleur))
sun.velocity = vector(0, 0, 0)
earth.velocity = He[3].snelheid
moon.velocity = He[4].snelheid
mercury.velocity = He[1].snelheid
venus.velocity = He[2].snelheid
mars.velocity =He[5].snelheid
phobos.velocity = He[6].snelheid
deimos.velocity = He[7].snelheid
jupiter.velocity = He[8].snelheid
io.velocity = He[9].snelheid
europa.velocity = He[10].snelheid
ganymede.velocity = He[11].snelheid
callisto.velocity = He[12].snelheid
sun.massa = He[0].massa
earth.massa = He[3].massa
moon.massa = He[4].massa
mercury.massa = He[1].massa
venus.massa = He[2].massa
mars.massa =He[5].massa
phobos.massa = He[6].massa
deimos.massa = He[7].massa
jupiter.massa = He[8].massa
io.massa = He[9].massa
europa.massa = He[10].massa
ganymede.massa = He[11].massa
callisto.massa = He[12].massa
planets.extend((sun, earth, moon, mercurius, venus, mars, phobos, jupiter, io, europa, ganymede, calisto))
while True:
sleep(0.02)
for planet in planets:
a = calc_gravitational_acceleration(planet.massa, planet.pos)
planet.velocity -= a*dt
planet.pos += planet.velocity * dt`
I'm hoping to adjust the location of points and lines in a dumbbell plot to separate the bars rather than overlaying them, similar to position dodge or hjust/vjust in R.
The code below produces something close to what I'd like, but the barbells are overlayed.
urlfile <- 'https://raw.githubusercontent.com/charlottemcclintock/GenSquared/master/data.csv'
df <- read.csv(urlfile)
p <- plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~country, yend = ~country, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~country, name = "Mother", color = I("purple")) %>%
add_markers(x = ~daughter, y = ~country, name = "Daughter", color = I("pink")) %>%
add_segments(x = ~dad, xend = ~son, y = ~country, yend = ~country, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~country, name = "Father", color = I("navy")) %>%
add_markers(x = ~son, y = ~country, name = "Son", color = I("blue")) %>%
layout(
title = "Gender educational disparity",
xaxis = list(title = "Mean Years of Education"),
margin = list(l = 65)
)
p
By coercing the country names to a factor, I can get the ideal spacing but I lose the country labels which I'm hoping to keep. I tried using country and numeric factor index together but plotly doesn't allow discrete and continuous scales together.
df$cnum <- as.numeric(as.factor(df$country))
p <- plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~cnum+.2, yend = ~cnum+0.2, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~cnum+.2, name = "Mother", color = I("purple")) %>%
add_markers(x = ~daughter, y = ~cnum+.2, name = "Daughter", color = I("pink")) %>%
add_segments(x = ~dad, xend = ~son, y = ~cnum-.2, yend = ~cnum-.2, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~cnum-.2, name = "Father", color = I("navy")) %>%
add_markers(x = ~son, y = ~cnum-.2, name = "Son", color = I("blue")) %>%
layout(
title = "Gender educational disparity",
xaxis = list(title = "Mean Years of Education"),
margin = list(l = 65)
)
p
I would like it to look like this:
But with the country names on the y-axis.
Is there a way to adjust the vertical height relative to a discrete axis point?
Update: it's not elegant but I figured out a workaround by overwriting the y axis with a section y axis! Would still love a better answer, but this is a usable fix!
df$arb=15
plot_ly(df, color = I("gray80")) %>%
add_segments(x = ~mom, xend = ~daughter, y = ~cnum+.2, yend = ~cnum+.2, showlegend = FALSE) %>%
add_markers(x = ~mom, y = ~cnum+.2, name = "Mother", color = I("purple"), size=2) %>%
add_markers(x = ~daughter, y = ~cnum+.2, name = "Daughter", color = I("pink"), size=2) %>%
add_segments(x = ~dad, xend = ~son, y = ~cnum-.1, yend = ~cnum-.1, showlegend = FALSE) %>%
add_markers(x = ~dad, y = ~cnum-.1, name = "Father", color = I("navy"), size=2) %>%
add_markers(x = ~son, y = ~cnum-.1, name = "Son", color = I("blue"), size=2) %>%
add_markers(x = ~arb, y = ~country, name = " ", color = I("white"), yaxis = "y2") %>%
layout(
yaxis=list(title="", tickfont=list(color="white")),
yaxis2 = list(overlaying = "y", side = "left", title = ""))
)
I use a code that makes use of kalman filter to stabilize a video but I am not able to record a video to be saved. I thought about saving all the frames in a file and creating a video later.
If someone has a better idea, or how to modify the code to be possible to use cv2.videoWriter.
import cv2
import numpy as np
from matplotlib import pyplot as plt
ini = time.time()
class FrameInfo:
def __init__(self):
self.img = None
self.img_gray = None
self.features = []
self.number = 0
self.trajectory = Trajectory()
#property
def width(self):
return self.img_gray.shape[1]
#property
def height(self):
return self.img_gray.shape[0]
#property
def width_height(self):
return self.img_gray.shape[::-1]
videoInPath = "../data/MVI_5408.avi"
camera = cv2.VideoCapture(videoInPath)
videoOutPath = videoInPath +'sab.avi'
N_FRAMES = int(camera.get(cv2.CAP_PROP_FRAME_COUNT))
FPS = camera.get(cv2.CAP_PROP_FPS)
VID_WIDTH = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
VID_HEIGHT = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
print "N_FRAMES: " + str(N_FRAMES)
print "FPS: " + str(FPS)
frame = None
prev_frame = None
trajectory = Trajectory(0, 0, 0)
org_trajectories = []
stb_trajectories = []
crop = 40
crop_rate = crop / 20
filter = KalmanFilter(Trajectory(4e-2, 4e-2, 4e-2), Trajectory(crop_rate,
crop_rate, crop_rate), Trajectory(1, 1, 1))
#surf = cv2.SURF(4000)
prev_trans = None
frame_number = 0
frame_width = int(1336.0 / 2)
frame_height = int(768.0 / 2)
def resize(img):
return cv2.resize(img, (frame_width, frame_height),
interpolation=cv2.INTER_LANCZOS4)
lk_params = dict(winSize=(19, 19),
maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
feature_params = dict(maxCorners=100,
qualityLevel=0.01,
minDistance=8,
blockSize=19)
crop_rate = 0.9
limits = [int(frame_width * (1 - crop_rate)), int(frame_height * (1 -
crop_rate)), 0.05]
output_video = cv2.VideoWriter(videoOutPath,
cv2.VideoWriter_fourcc(*'XVID'), # -1, #
int(video.get(cv2.cv.CV_CAP_PROP_FOURCC)),
FPS,
(frame_width - 2*limits[0], frame_height - 2*limits[1])
)
feature_cont = 0
flow_cont = 0
ransac_cont = 0
kalman_cont = 0
features_quant = []
percent = 0
inliers_quant = []
ouliers_quant = []
compensate_count = 0
for k in range(N_FRAMES-1):
# Capture frame_img-by-frame_img
ret, frame_img = camera.read()
if frame_img is None:
break
if frame is not None:
prev_frame = frame
frame_number += 1
if frame_number < 220:
continue
frame = FrameInfo()
frame.number = frame_number
frame.img = frame_img
frame.img = cv2.resize(frame_img, (0, 0), fx=(1336.0 / frame_img.shape[1]) / 2.0,
fy=(768.0 / frame_img.shape[0]) / 2.0,
interpolation=cv2.INTER_LANCZOS4)
frame.img_gray = cv2.cvtColor(frame.img, cv2.COLOR_BGR2GRAY)
feature_time_ini = time.time()
frame.features = cv2.goodFeaturesToTrack(frame.img_gray, **feature_params)
#frame.features = sift.detect(frame.img_gray,None)
features_quant.append(len(frame.features))
if prev_frame is None:
continue
feature_time_fim = time.time()
feature_cont += feature_time_fim - feature_time_ini
feature_time_ini = 0
feature_time_fim = 0
flow_time_ini = time.time()
new_features, _, _ = cv2.calcOpticalFlowPyrLK(prev_frame.img, frame.img, prev_frame.features, None, **lk_params)
new_features_for_validation, _, _ = cv2.calcOpticalFlowPyrLK(frame.img, prev_frame.img, new_features, None,
**lk_params)
flow_time_fim = time.time()
flow_cont += flow_time_fim - flow_time_ini
flow_time_ini = 0
flow_time_fim = 0
d = abs(prev_frame.features - new_features_for_validation).reshape(-1, 2).max(-1)
good = d < 1
# Select good_features points
good_new = np.array([x for x, s in zip(new_features, good) if s], dtype=np.float32)
good_old = np.array([x for x, s in zip(prev_frame.features, good) if s], dtype=np.float32)
# trans = cv2.estimateRigidTransform(good_old, good_new, fullAffine=False)
ransac_time_ini = time.time()
trans, inliers_indices,outliers_indices = RansacMotionEstimator(40, 1.0).estimate(good_old, good_new)
ransac_time_fim = time.time()
ransac_cont += ransac_time_fim - ransac_time_ini
ransac_time_ini = 0
ransac_time_fim = 0
inliers_quant.append(len(inliers_indices))
ouliers_quant.append(len(outliers_indices))
if trans is None and prev_trans is None:
print ("wuf? trans is None and prev_trans is none too")
continue
if trans is None:
trans = prev_trans
print ("wut? trans is None")
delta = Trajectory(get_x(trans), get_y(trans), get_rad_angle(trans))
trajectory += delta
kalman_time_ini = time.time()
filter.put(trajectory)
diff = filter.get() - trajectory
new_delta = delta + diff
kalman_time_fim = time.time()
org_trajectories.append(trajectory)
stb_trajectories.append(filter.get())
kalman_cont += kalman_time_fim - kalman_time_ini
kalman_time_ini = 0
kalman_time_fim = 0
fill_mat(trans, new_delta.x, new_delta.y, new_delta.angle)
compensate_time_ini = time.time()
#out = cv2.warpAffine(frame.img, trans, frame.width_height, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT)
#out = cv2.warpAffine(frame_img, trans, frame.width_height, flags=cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_REFLECT)
#out = cv2.warpAffine(frame_img, trans, frame.width_height)
out = cv2.warpAffine(frame_img, trans, frame.width_height, flags=cv2.INTER_CUBIC,borderMode=cv2.BORDER_REPLICATE)
compensate_time_fim = time.time()
compensate_count += compensate_time_fim - compensate_time_ini
compensate_time_ini = 0
compensate_time_fim = 0
#out = cv2.warpAffine(frame_img, trans, frame.width_height, flags=cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_REFLECT)
#out = frame.img.copy()
prev_trans = trans.copy()
output_video.write(out)
camera.release()
output_video.release()
cv2.destroyAllWindows()
I am fairly new to bokeh(using jupyter) and I was trying to create a simple line and scatter graph with a drop-down button where I could select a set of values for x-axis and y-axis and see them being updated in real time but for some reason for the graph does not get updated correctly this is a portion of my code:
weight= [23,45,11,40]
velocity= [12,65,32,15]
momentum = [12,78,22,40]
p = figure(plot_height=300,plot_width=500,title="Graph line of DATA")
p.title.text_font_style = "bold"
r = p.line(weight,velocity, color="red", line_width=3)
tab1=Panel(child=p, title="line")
p1 = figure(plot_height=300,plot_width=500,title="Graph line of DATA")
r1 = p1.circle(weight,velocity, size=10, color="red", alpha=0.5)
p1.title.text_font_style = "bold"
tab2=Panel(child=p1, title="Circle")
def updatex(Xaxis):
if Xaxis == "Weight":
func = weight
p.xaxis.axis_label = "pounds"
p1.xaxis.axis_label = "pounds"
elif Xaxis == "Velocity":
func = velocity
p.xaxis.axis_label = "m/s"
p1.xaxis.axis_label = "m/s"
elif Xaxis == "Momemtum":
func = momentum
p.xaxis.axis_label = "lb-sec"
p1.xaxis.axis_label = "lb-sec"
r.data_source.data['x'] = func
r1.data_source.data['x'] = func
push_notebook()
def updatey(Yaxis):
if Yaxis == "Weight":
func = weight
p.xaxis.axis_label = "pounds"
p1.xaxis.axis_label = "pounds"
elif Yaxis == "Velocity":
func = velocity
p.xaxis.axis_label = "m/s"
p1.xaxis.axis_label = "m/s"
elif Xaxis == "Momemtum":
func = momentum
p.xaxis.axis_label = "lb-sec"
p1.xaxis.axis_label = "lb-sec"
r.data_source.data['y'] = func
r1.data_source.data['y'] = func
push_notebook()
# the following snippet would be in the following cell below:
interact(updatex,Xaxis=["Weight", "Velocity", "Momemtum"])
interact(updatey,Yaxis=["Weight","Velocity","Momemtum"])