How to draw a radar scanning animation in osmdroid - osmdroid

I use polygon and set its fillpaint with RadialGradient,but it doesn't work!
val polygon = Polygon()
val pp = polygon.fillPaint
val xx = mapView.projection.toPixels(pointCenter, null).x
val yy = mapView.projection.toPixels(pointCenter, null).y
pp.shader = RadialGradient(xx.toFloat(), yy.toFloat(), radius.toFloat(), Color.GREEN, Color.RED, Shader.TileMode.MIRROR)
polygon.points = points
mapView.overlayManager.add(polygon)

Related

'for' loop and 'lists' in plotly - R

I want to add some shapes to my chart:
p <- p %>% layout(shapes = list(list(type = "rect", fillcolor = kolorrecesji, line = list(color = kolorrecesji), opacity = op_1, x0 = x0_1, x1 = x1_1, xref = "x", y0 = min_y, y1 = max_y, yref = "y"),
list(type = "rect", fillcolor = kolorrecesji, line = list(color = kolorrecesji), opacity = op_2, x0 = x0_2, x1 = x1_2, xref = "x", y0 = min_y, y1 = max_y, yref = "y"),
list(type = "rect", fillcolor = kolorrecesji, line = list(color = kolorrecesji), opacity = op_3, x0 = x0_3, x1 = x1_3, xref = "x", y0 = min_y, y1 = max_y, yref = "y"),
list(type = "rect", fillcolor = kolorrecesji, line = list(color = kolorrecesji), opacity = op_4, x0 = x0_4, x1 = x1_4, xref = "x", y0 = min_y, y1 = max_y, yref = "y"),
...
Can I have dynamic number od these shapes?
I prefer to have shapes in data frame with different x0, x1, fillcolor and opacity (or parameter permitting to draw or not) and use for ... loop rather than list them one by one like above?
rgds & thks
Grzegorz

What's the equivalent of np.delete in libtorch?

It seems we don't have an np.delete equivalent in libtorch yet, so how can we emulate its behavior? For example I'm trying to rewrite the following bit of code in libtorch:
ids = np.delete( ids, np.concatenate([[last], np.where(overlap > overlap_threshold)[0]] ) )
How should I go about this? I thought about slicing, but I'm not sure if there are implications involved that I'm not aware of. This is what I came up with:
neg = torch.where(overlap < overlap_threshold)[0]
ids = ids[neg].clone()
libtorch:
auto neg = torch::where(overlap <over_threshold)[0];
ids.index_put_({Slice()}, ids.index({neg}));
//or simply
ids = ids.index({neg}).clone();
And this is an example demo to test out their result is the same:
x1 = np.asarray([125.,152., 155., 155., 202.])
y1 = np.asarray( [52., 72., 92., 95., 95.])
x2 = np.asarray( [145., 172., 175., 175., 222.])
y2 = np.asarray( [ 72., 92., 112., 115., 115.])
score = np.asarray([0.60711509, 0.63444906, 0.85604602, 0.60021192, 0.70115328])
area = (x2 - x1 + 1.0) * (y2 - y1 + 1.0)
ids = np.argsort(score)
overlap_threshold = 0.5
mode = 'union'
while len(ids) > 0:
# grab index of the largest value
last = len(ids) - 1
i = ids[last]
# left top corner of intersection boxes
ix1 = np.maximum(x1[i], x1[ids[:last]])
iy1 = np.maximum(y1[i], y1[ids[:last]])
# right bottom corner of intersection boxes
ix2 = np.minimum(x2[i], x2[ids[:last]])
iy2 = np.minimum(y2[i], y2[ids[:last]])
# width and height of intersection boxes
w = np.maximum(0.0, ix2 - ix1 + 1.0)
h = np.maximum(0.0, iy2 - iy1 + 1.0)
# intersections' areas
inter = w * h
if mode == 'min':
overlap = inter / np.minimum(area[i], area[ids[:last]])
elif mode == 'union':
# intersection over union (IoU)
overlap = inter / (area[i] + area[ids[:last]] - inter)
# delete all boxes where overlap is too big
# ids = np.delete(ids,np.concatenate([[last], np.where(overlap > overlap_threshold)[0]]))
neg = np.where(overlap <= overlap_threshold)[0]
ids = ids[neg]
print(f'ids: {ids}')
And here is the cpp counter part in libtorch:
void test5()
{
auto x1 = torch::tensor({ 125., 152., 155., 155., 202. });
auto y1 = torch::tensor({ 52., 72., 92., 95., 95. });
auto x2 = torch::tensor({ 145., 172., 175., 175., 222. });
auto y2 = torch::tensor({ 72., 92., 112., 115., 115. });
auto score = torch::tensor({ 0.60711509, 0.63444906, 0.85604602, 0.60021192, 0.70115328 });
auto area = (x2 - x1 + 1.0) * (y2 - y1 + 1.0);
auto ids = torch::argsort(score);
auto overlap_threshold = 0.5;
auto mode = "union";
while (ids.sizes()[0] > 0)
{
//# grab index of the largest value
auto last = ids.sizes()[0] - 1;
auto i = ids[last];
//# left top corner of intersection boxes
auto ix1 = torch::max(x1[i], x1.index({ ids.index({ Slice(None,last) }) }));
auto iy1 = torch::max(y1[i], y1.index({ ids.index({ Slice(None,last) }) }));
//# right bottom corner of intersection boxes
auto ix2 = torch::min(x2[i], x2.index({ ids.index({Slice(None,last)}) }));
auto iy2 = torch::min(y2[i], y2.index({ ids.index({Slice(None,last)}) }));
//# width and height of intersection boxes
auto w = torch::max(torch::tensor(0.0), ix2 - ix1 + 1.0);
auto h = torch::max(torch::tensor(0.0), iy2 - iy1 + 1.0);
//# intersections' areas
auto inter = w * h;
torch::Tensor overlap;
if (mode == "min")
{
overlap = inter / torch::min(area[i], area.index({ ids.index({Slice(None,last)}) }));
}
else if (mode == "union")
{ //# intersection over union (IoU)
overlap = inter / (area[i] + area.index({ ids.index({Slice(None,last)}) }) - inter);
}
//# delete all boxes where overlap is too big
//# ids = np.delete(ids, np.concatenate([[last], np.where(overlap > overlap_threshold)[0]] ))
auto neg = torch::where(overlap < overlap_threshold)[0];
ids = ids.index({ neg });
std::cout << "ids: " << ids << std::endl;
}
}
Both of them print the same output, so is there something that I'm missing here or this is actually the reasonable way of implementing delete in libtorch?
What other possibly more efficient ways do I have to implement/emulate np.delete()?
It seems this is the reasonable way of doing it as pointed out in the comments. That is to reverse the condition and only filter out based on the new condition.
I also would like to fix a slight issue in my original post.
the correct form that would be equivalent to the Pythons :
ids = np.delete(ids, np.concatenate([[last], np.where(overlap > overlap_threshold)[0]] ))
would be :
auto neg = torch::where(overlap <= overlap_threshold)[0];
ids = ids.index({ neg });
mind the <=!

Python auto select color bar

I want to set color bar "green" when data direction1 = 005.
How to make it auto select color bar in Python 2.7 from these case?:
direction1=['200','250','180','200','300','270','005','080']
time1=['0000','0030','0100','0130','0200','0230','0300','0300']
Current script as follows :
ind = np.arange(len(time1))
width = 0.50
rects1 = plt.bar(ind, direction1, width, color='r')
for x in range(0,len(direction1)):
if x in direction1==005:
rects1[x].set_color('g')
This is the answer for sharing:
values=np.array(direction1)
searchval = '005'
location = np.where(values == searchval)[0]
print location
rects1 = plt.bar(ind, direction1, width, color='r')
for x in location:
rects1[x].set_color('g')
Cheers!!!...

How to modify a variable when a while loop is running Python

I am using wx.python along with VPython to make an orbit simulator, however i'm having trouble trying to get the sliders in the GUI to effect the simulation, I assume it's because I am trying to get the number associated with the slider button to go into a while loop when it is running.
So my question is, how do i get the function SetRate to update in the while loop located at the bottom of the code? (I have checked to see that the slider is retuning values)
Here is my code for reference:
Value = 1.0
dt = 100.0
def InputValue(Value):
dt = Value
def SetRate(evt):
global Value
Value = SpeedOfSimulation.GetValue()
return Value
w = window(menus=True, title="Planetary Orbits",x=0, y=0, width = 1000, height = 1000)
Screen = display(window = w, x = 30, y = 30, width = 700, height = 500)
gdisplay(window = w, x = 80, y = 80 , width = 40, height = 20)
p = w.panel # Refers to the full region of the window in which to place widgets
SpeedOfSimulation = wx.Slider(p, pos=(800,10), size=(200,100), minValue=0, maxValue=1000)
SpeedOfSimulation.Bind(wx.EVT_SCROLL, SetRate)
TestData = [2, 0, 0, 0, 6371e3, 5.98e24, 0, 0, 0, 384400e3, 0, 0, 1737e3, 7.35e22, 0, 1e3, 0]
Nstars = TestData[0] # change this to have more or fewer stars
G = 6.7e-11 # Universal gravitational constant
# Typical values
Msun = 2E30
Rsun = 2E9
vsun = 0.8*sqrt(G*Msun/Rsun)
Stars = []
colors = [color.red, color.green, color.blue,
color.yellow, color.cyan, color.magenta]
PositionList = []
MomentumList = []
MassList = []
RadiusList = []
for i in range(0,Nstars):
s=i*8
x = TestData[s+1]
y = TestData[s+2]
z = TestData[s+3]
Radius = TestData[s+4]
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
Mass = TestData[s+5]
SpeedX = TestData[s+6]
SpeedY = TestData[s+7]
SpeedZ = TestData[s+8]
px = Mass*(SpeedX)
py = Mass*(SpeedY)
pz = Mass*(SpeedZ)
PositionList.append((x,y,z))
MomentumList.append((px,py,pz))
MassList.append(Mass)
RadiusList.append(Radius)
pos = array(PositionList)
Momentum = array(MomentumList)
Mass = array(MassList)
Mass.shape = (Nstars,1) # Numeric Python: (1 by Nstars) vs. (Nstars by 1)
Radii = array(RadiusList)
vcm = sum(Momentum)/sum(Mass) # velocity of center of mass
Momentum = Momentum-Mass*vcm # make total initial momentum equal zero
Nsteps = 0
time = clock()
Nhits = 0
while True:
InputValue(Value) #Reprensents the change in time
rate(100000) #No more than 100 loops per second on fast computers
# Compute all forces on all stars
r = pos-pos[:,newaxis] # all pairs of star-to-star vectors (Where r is the Relative Position Vector
for n in range(Nstars):
r[n,n] = 1e6 # otherwise the self-forces are infinite
rmag = sqrt(sum(square(r),-1)) # star-to-star scalar distances
hit = less_equal(rmag,Radii+Radii[:,newaxis])-identity(Nstars)
hitlist = sort(nonzero(hit.flat)[0]).tolist() # 1,2 encoded as 1*Nstars+2
F = G*Mass*Mass[:,newaxis]*r/rmag[:,:,newaxis]**3 # all force pairs
for n in range(Nstars):
F[n,n] = 0 # no self-forces
Momentum = Momentum+sum(F,1)*dt
# Having updated all momenta, now update all positions
pos = pos+(Momentum/Mass)*dt
# Update positions of display objects; add trail
for i in range(Nstars):
Stars[i].pos = pos[i]
I know nothing about vpython but in a normal wxPython app, you will use wx.Timer instead of while loop.
here is an example of wx.Timer modified from https://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/
You will want to separate the while loop part from your SetRate class method and put it in update.
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Timer Tutorial 1",
size=(500,500))
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
SpeedOfSimulation = wx.Slider(p, pos=(800,10), size=(200,100), minValue=0, maxValue=1000)
SpeedOfSimulation.Bind(wx.EVT_SCROLL, SetRate)
self.SpeedOfSimulation = SpeedOfSimulation
def update(self, event):
# Compute all forces on all stars
SpeedOfSimulation = self.SpeedOfSimulation.GetValue()

Any RaphaelJS Guru knows how to draw this image?

Any Raphael JS guru (or any genius who doesn't know Raphael JS) knows how to simply draw this?
the solid yellow color is 4.2 / 10 of part of the circle.
First approach using svg's elliptical arc curve command
Demo: http://jsbin.com/iwuqe3/edit
Raphael.fn.zeroToTenArc = function (x, y, r, value) {
var set = this.set();
var pi = Math.PI;
var cos = Math.cos;
var sin = Math.sin;
var maxValue = 10;
var t = (pi/2) * 3; //translate
var rad = (pi*2 * (maxValue-value)) / maxValue + t;
var colors = ["#F79518", "#FCE6BF", "#FFF"];
set.push(this.circle(x, y, r).attr({ fill : colors[+!value], stroke : 0 }));
var p = [
"M", x, y,
"l", r * cos(t), r * sin(t),
"A", r, r, 0, +(rad > pi + t), 1, x + r * cos(rad), y + r * sin(rad),
"z"
];
set.push(this.path(p).attr({ fill : colors[1], stroke : 0 }));
set.push(this.circle(x, y, r*0.7).attr({ fill : colors[2], stroke : 0 }));
return set;
};
var canvas = Raphael("hello", 300, 300);
var arc = canvas.zeroToTenArc(150, 150, 30, 4.2);
.
Second approach using (a lot of) svg's lineto commands
Demo: http://jsbin.com/usotu5/edit
Raphael.fn.zeroToTenArc = function (x, y, radius, value) {
var angle = 0;
var endAngle = (value*360)/10;
var path = "";
var clockwise = -1;
var translate = Math.PI/2;
while(angle <= endAngle) {
var radians= (angle/180) * Math.PI + translate;
var cx = x + Math.cos(radians) * radius;
var cy = y + Math.sin(radians) * radius * clockwise;
path += (angle === 0) ? "M" : "L";
path += [cx,cy];
angle += 1;
}
return this.path(path);
};
var canvas = Raphael("hello", 200, 200);
canvas.zeroToTenArc(50, 50, 30, 10).attr({ stroke : "#FCE6BF", "stroke-width" : 12 });
canvas.zeroToTenArc(50, 50, 30, 4.2).attr({ stroke : "#F79518", "stroke-width" : 12 });