I'm trying to create a bounding box at a specific scale from a center coordinate. I'm trying to keep it within the aspect ratio of a 8.5x11inch piece of paper (612x792 pixels # 72dpi).
The code I'm using below mostly works, but the heigh seems a bit too tall for the aspect ratio of a letter. Am I not accounting for mercator projection? What am I missing here?
def bounding_box_from_point(center:, size:, scale_denominator:)
dpi = 72
inches_per_unit = 4374754
resolution = 1 / (scale_denominator * inches_per_unit * dpi)
half_width_deg = (size.width * resolution) / 2
half_height_deg = (size.height * resolution) / 2
BoundingBox.new(
north: center.lat + half_height_deg,
south: center.lat - half_height_deg,
east: center.lon + half_width_deg,
west: center.lon - half_width_deg
)
end
Calling bounding_box_from_point(center: center, size: size, scale_denominator: scale) with:
scale = 0.0008861342166177423 (i.e. 1/18055.955520)
center = Geometry::Location.new(lat: 37.806336, lon: -122.270625)
size.width = 612,
size.height = 792
It returns:
west: -122.27172131608657,
east: -122.26952868391342,
south: 37.804917238005615
north: 37.80775476199439
If you go to http://www.openstreetmap.org/export and enter those bounding box coordinates, you can see that the ratio does not match that of a 8.5x11in piece of paper...it's slightly too tall. What am I doing wrong here or not understanding?
This was my implementation that solved it!
def self.bounding_box_from_location(location:, scale:)
scale_meters_per_pixel = 0.0003
# scale.zoom is an integer between 0-19
# See http://wiki.openstreetmap.org/wiki/Zoom_levels for a description on `zoom`
# location.lat_rad is the latitude in radians, same for lon_rad
meters_per_pixel = EARTH_CIR * Math.cos(location.lat_rad) / (2 ** (scale.zoom + 8))
earth_meters_per_pictureMeters = meters_per_pixel / scale_meters_per_pixel
# height/width in meters is the height/width of the box you're applying this to
# In my case I'm using the heigh/width of a Letter of paper
# You can convert Pixels to meters (# 72dpi) with
# pixels * 0.00035277777777777776
meters_north = earth_meters_per_pictureMeters * scale.height_in_meters / 2
meters_east = earth_meters_per_pictureMeters * scale.width_in_meters / 2
meters_per_degree_lat = 111111.0
meters_per_degree_long = 111111.0 * Math.cos(location.lat_rad)
degrees_north = meters_north / meters_per_degree_lat
degrees_east = meters_east / meters_per_degree_long
BoundingBox.new(
north: (location.lat + degrees_north),
south: location.lat - degrees_north,
east: location.lon + degrees_east,
west: location.lon - degrees_east,
width: scale.width_in_pixels,
height: scale.height_in_pixels
)
end
Related
I am new to PowerApps. I have a Share Point List with a set of coordinates for various locations. What I need to figure out is when a user with PowerApps App on their phone are within a certain distance of those coordinates, using the Haversine formula. While the Haversine formula works in a test/simple way using hard-coded target location, I need the target locations from the Share Point List. Here is my code, which is inside a Timer End:
ForAll(
irfan_yard_locations,
With(
{
r: 6371000, p: (Pi() / 180), latA: location_lat, lonA: location_long, latB: Location.Latitude, lonB: Location.Longitude
},
Round((2 * r) * Asin(Sqrt(0.5 - Cos((latA - latB) * p)/2 + Cos(latB * p) * Cos(latA * p) * (1 - Cos((lonA - lonB) * p)) / 2)), 2 ));
) ;
irfan_yard_locations is the SP List which has location_lat and location_long coordinates. I am thinking something like in this example site: http://powerappsguide.com/blog/post/formula-how-to-use-the-if-and-switch-functions so that if the return from the with (), which would be a number, is less than 5 (it's in meters) then Navigate to another screen or do something. Just don't know the syntax. Or is there better approach?
Thanks!
Never mind. By putting in an If clause around the With function, I am able to catch if the current location is within 6 meters of one of the coordinate sets.
ForAll(
irfan_yard_locations,
If ( With(
{
r: 6371000, p: (Pi() / 180), latA: location_lat, lonA: location_long, latB: Location.Latitude, lonB: Location.Longitude
},
Round((2 * r) * Asin(Sqrt(0.5 - Cos((latA - latB) * p)/2 + Cos(latB * p) * Cos(latA * p) * (1 - Cos((lonA - lonB) * p)) / 2)), 2 )) < 6, Navigate(Screen2));
) ;
My problem has a single state and an infinite amount of actions on a certain interval (0,1). After quite some time of googling I found a few paper about an algorithm called zooming algorithm which can solve problems with a continous action space. However my implementation is bad at exploiting. Therefore I'm thinking about adding an epsilon-greedy kind of behavior.
Is it reasonable to combine different methods?
Do you know other approaches to my problem?
Code samples:
import portion as P
def choose_action(self, i_ph):
# Activation rule
not_covered = P.closed(lower=0, upper=1)
for arm in self.active_arms:
confidence_radius = calc_confidence_radius(i_ph, arm)
confidence_interval = P.closed(arm.norm_value - confidence_radius, arm.norm_value + confidence_radius)
not_covered = not_covered - confidence_interval
if not_covered != P.empty():
rans = []
height = 0
heights = []
for i in not_covered:
rans.append(np.random.uniform(i.lower, i.upper))
height += i.upper - i.lower
heights.append(i.upper - i.lower)
ran_n = np.random.uniform(0, height)
j = 0
ran = 0
for i in range(len(heights)):
if j < ran_n < j + heights[i]:
ran = rans[i]
j += heights[i]
self.active_arms.append(Arm(len(self.active_arms), ran * (self.sigma_square - lower) + lower, ran))
# Selection rule
max_index = float('-inf')
max_index_arm = None
for arm in self.active_arms:
confidence_radius = calc_confidence_radius(i_ph, arm)
# indexfunction from zooming algorithm
index = arm.avg_learning_reward + 2 * confidence_radius
if index > max_index:
max_index = index
max_index_arm = arm
action = max_index_arm.value
self.current_arm = max_index_arm
return action
def learn(self, action, reward):
arm = self.current_arm
arm.avg_reward = (arm.pulled * arm.avg_reward + reward) / (arm.pulled + 1)
if reward > self.max_profit:
self.max_profit = reward
elif reward < self.min_profit:
self.min_profit = reward
# normalize reward to [0, 1]
high = 100
low = -75
if reward >= high:
reward = 1
self.high_count += 1
elif reward <= low:
reward = 0
self.low_count += 1
else:
reward = (reward - low)/(high - low)
arm.avg_learning_reward = (arm.pulled * arm.avg_learning_reward + reward) / (arm.pulled + 1)
arm.pulled += 1
# zooming algorithm confidence radius
def calc_confidence_radius(i_ph, arm: Arm):
return math.sqrt((8 * i_ph)/(1 + arm.pulled))
You may find this useful, full algorithm description is here. They grid out the probes uniformly, informing this choice (e.g. normal centering on a reputed high energy arm) is also possible (but this might invalidate a few bounds I am not sure).
I found 2 scripts in tradingview and added them to my script, however, it didn't work. I lost a lot of time. Can someone help me convert them to version 4? Thank you. Have a nice day!!!
//#version=2
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 09/03/2018
// Linear Regression Intercept is one of the indicators calculated by using the
// Linear Regression technique. Linear regression indicates the value of the Y
// (generally the price) when the value of X (the time series) is 0. Linear
// Regression Intercept is used along with the Linear Regression Slope to create
// the Linear Regression Line. The Linear Regression Intercept along with the Slope
// creates the Regression line.
////////////////////////////////////////////////////////////
study(title="Line Regression Intercept", overlay = true)
Length = input(14, minval=1)
xSeria = input(title="Source", type=source, defval=close)
xX = Length * (Length - 1) * 0.5
xDivisor = xX * xX - Length * Length * (Length - 1) * (2 * Length - 1) / 6
xXY = 0
for i = 0 to Length-1
xXY := xXY + (i * xSeria[i])
xSlope = (Length * xXY - xX * sum(xSeria, Length)) / xDivisor
xLRI = (sum(xSeria, Length) - xSlope * xX) / Length
plot(xLRI, color=blue, title="LRI")
//Author - Rajandran R
//www.marketcalls.in
study("Supertrend V1.0 - Buy or Sell Signal", overlay = true)
Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? green : red
plot(Tsl, color = linecolor , style = line , linewidth = 2,title = "SuperTrend")
plotshape(cross(close,Tsl) and close>Tsl , "Up Arrow", shape.triangleup,location.belowbar,green,0,0)
plotshape(cross(Tsl,close) and close<Tsl , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")
plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=60, minheight=50, transp=0)
//#version=4
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 09/03/2018
// Linear Regression Intercept is one of the indicators calculated by using the
// Linear Regression technique. Linear regression indicates the value of the Y
// (generally the price) when the value of X (the time series) is 0. Linear
// Regression Intercept is used along with the Linear Regression Slope to create
// the Linear Regression Line. The Linear Regression Intercept along with the Slope
// creates the Regression line.
////////////////////////////////////////////////////////////
study(title="Line Regression Intercept", overlay=true)
Length = input(14, minval=1)
xSeria = input(title="Source", type=input.source, defval=close)
xX = Length * (Length - 1) * 0.5
xDivisor = xX * xX - Length * Length * (Length - 1) * (2 * Length - 1) / 6
xXY = 0.
for i = 0 to Length - 1 by 1
xXY := xXY + i * xSeria[i]
xXY
xSlope = (Length * xXY - xX * sum(xSeria, Length)) / xDivisor
xLRI = (sum(xSeria, Length) - xSlope * xX) / Length
plot(xLRI, color=color.blue, title="LRI")
//#version=4
//Author - Rajandran R
//www.marketcalls.in
study("Supertrend V1.0 - Buy or Sell Signal", overlay=true)
Factor = input(3, minval=1, maxval=100)
Pd = input(7, minval=1, maxval=100)
Up = hl2 - Factor * atr(Pd)
Dn = hl2 + Factor * atr(Pd)
TrendUp = Up
TrendUp := close[1] > TrendUp[1] ? max(Up, TrendUp[1]) : Up
TrendDown = Dn
TrendDown := close[1] < TrendDown[1] ? min(Dn, TrendDown[1]) : Dn
Trend = int(na)
Trend := close > TrendDown[1] ? 1 : close < TrendUp[1] ? -1 : nz(Trend[1], 1)
Tsl = Trend == 1 ? TrendUp : TrendDown
linecolor = Trend == 1 ? color.green : color.red
plot(Tsl, color=linecolor, style=plot.style_line, linewidth=2, title="SuperTrend")
plotshape(cross(close, Tsl) and close > Tsl, "Up Arrow", shape.triangleup, location.belowbar, color.green, 0, 0)
plotshape(cross(Tsl, close) and close < Tsl, "Down Arrow", shape.triangledown, location.abovebar, color.red, 0, 0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")
plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=color.lime, maxheight=60, minheight=50, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=color.red, maxheight=60, minheight=50, transp=0)
I'm using faceting heatmap on a spatial field which then returns a 2d array like this
"counts_ints2D",
[
null,
null,
null,
null,
[
0,
8,
4,
0,
0,
0,
0,
0,
0,
...
I want to locate those cluster on the map but the problem is that I don't know how to convert that 2d array in geo coordinates.
There's absolutely no documentation out there showing what to do with those integer.
Can somebody give some guidance ?
Going with the data you gave for Glasgow, and using the formula given in the comments, lets explore the coordinates in a python repl:
# setup
>>> minX = -180
>>> maxX = 180
>>> minY = -53.4375
>>> maxY = 74.53125
>>> columns = 256
>>> rows = 91
# calculate widths
>>> bucket_width = (maxX - minX) / columns
>>> bucket_width
1.40625
>>> bucket_height = (maxY - minY) / rows
>>> bucket_height
1.40625
# calculate area for bucket in heatmap facet for x = 124, y = 13
# point in lower left coordinate
>>> lower_left = {
... 'lat': maxY - (13 + 1) * bucket_height,
... 'lon': minX + 124 * bucket_width,
... }
>>> lower_left
{'lat': 54.84375, 'lon': -5.625}
# point in upper right
>>> upper_right = {
... 'lat': maxY - (13 + 1) * bucket_height + bucket_height,
... 'lon': minX + 124 * bucket_width + bucket_width,
... }
>>> upper_right
{'lat': 56.25, 'lon': -4.21875}
Let's graph these points on a map, courtesy of open street map. We generate a small CSV snippet we can import on umap (select the up arrow, choose 'csv' as the type and enter content into the text box). To our coordinates to show:
>>> bbox = [
... "lat,lon,description",
... str(lower_left['lat']) + "," + str(lower_left['lon']) + ",ll",
... str(upper_right['lat']) + "," + str(lower_left['lon']) + ",ul",
... str(upper_right['lat']) + "," + str(upper_right['lon']) + ",uu",
... str(lower_left['lat']) + "," + str(upper_right['lon']) + ",lu",
... ]
>>> print("\n".join(bbox))
lat,lon,description
54.84375,-5.625,ll
56.25,-5.625,ul
56.25,-4.21875,uu
54.84375,-4.21875,lu
After pasting these points into the import box creating the layer, we get this map:
Map based on Open Street Map data through uMap. This area encloses Glasgow as you expected.
Here's some code that takes 180th meridian (date line) wrapping into account:
$columns = $heatmap['columns'];
$rows = $heatmap['rows'];
$minX = $heatmap['minX'];
$maxX = $heatmap['maxX'];
$minY = $heatmap['minY'];
$maxY = $heatmap['maxY'];
$counts = $heatmap['counts_ints2D'];
// If our min longitude is greater than max longitude, we're crossing
// the 180th meridian (date line).
$crosses_meridian = $minX > $maxX;
// Bucket width needs to be calculated differently when crossing the
// meridian since it wraps.
$bucket_width = $crosses_meridian
? $bucket_width = (360 - abs($maxX - $minX)) / $columns
: $bucket_width = ($maxX - $minX) / $columns;
$bucket_height = ($maxY - $minY) / $rows;
$points = [];
foreach ($counts as $rowIndex => $row) {
if (!$row) continue;
foreach ($row as $columnIndex => $column) {
if (!$column) continue;
$point = []
$point['count'] = $column;
// Put the count in the middle of the bucket (adding a half height and width).
$point['lat'] = $maxY - (($rowIndex + 1) * $bucket_height) + ($bucket_height / 2);
$point['lng'] = $minX + ($columnIndex * $bucket_width) + ($bucket_width / 2);
// We crossed the meridian, so wrap back around to negative.
if ($point['lng'] > 180) {
$point['lng'] = -1 * (180 - ($point['lng'] % 180));
}
$points[] = $point;
}
}
I'm using SharpGL in a WPF window and have navigation and plotting of a survey point cloud with custom shaders for distance-based point size reduction. All working well but I've recently attempted to add the ability to select a point nearest to the ray cast by a mouse click. I used the steps 0 to 4 in this link: http://antongerdelan.net/opengl/raycasting.html
The problem I'm facing is that the ray seems to be very slightly shifted towards the camera vector causing me to miss the points I'm clicking on and only scrape their inside edge. I'm drawing the ray starting from the camera position too so initially the ray should appear as a dot before moving the camera (looking down the trajectory line) but I can see it clearly drawn to the middle of the screen. Here's a screenshot showing where the ray misses the point when I click on its center:
This is the code I'm using to calculate the ray start and end coordinates:
public void CreateVerticesForMouseCoord(OpenGL gl, float winx, float winy)
{
int[] viewport = new int[4];
gl.GetInteger(OpenGL.GL_VIEWPORT, viewport);
float window_width = viewport[2];
float window_height = viewport[3];
Console.WriteLine("Window size: " + window_width + "," + window_height);
vec4 clipPosition = new vec4(0.0f, 0.0f, 1.0f, 1.0f);
// Normalize the x and y coordinates
clipPosition.x = 2.0f * (winx / window_width) - 1.0f;
clipPosition.y = -2.0f * (winy / window_height) + 1.0f;
mat4 viewInv = glm.inverse(viewMatrix);
mat4 projInv = glm.inverse(projectionMatrix);
vec4 camPosition = projInv * clipPosition;
camPosition.w = 0;
camPosition.z = -1;
vec4 worldPosition = viewInv * camPosition;
vec4 camCamPos = new vec4(0.0f, 0.0f, 0.0f, 1.0f);
vec4 objCamPos = glm.inverse(viewMatrix) * camCamPos;
vec4 camCamDir = new vec4(0.0f, 0.0f, -1.0f, 0.0f);
vec4 objCamDir = glm.inverse(viewMatrix) * camCamDir;
float x1 = objCamPos.x + 30.0f * worldPosition.x;
float y1 = objCamPos.y + 30.0f * worldPosition.y;
float z1 = objCamPos.z + 30.0f * worldPosition.z;
float x2 = objCamPos.x - 0.0f * worldPosition.x;
float y2 = objCamPos.y - 0.0f * worldPosition.y;
float z2 = objCamPos.z - 0.0f * worldPosition.z;
Console.WriteLine("Screen coordinates: " + winx + ","+winy);
Console.WriteLine("Clip coordinates: " + clipPosition.x + "," + clipPosition.y + "," + clipPosition.z+ ","+ clipPosition.w);
Console.WriteLine("Camera coordinates: " + camPosition.x + "," + camPosition.y + "," + camPosition.z+","+ camPosition.w);
Console.WriteLine("World coordinates: " + worldPosition.x + "," + worldPosition.y + "," + worldPosition.z+","+ worldPosition.w);
Console.WriteLine("Camera Position: " + objCamPos.x + "," + objCamPos.y + "," + objCamPos.z + "," + objCamPos.w);
Console.WriteLine("Camera Direction: " + objCamDir.x + "," + objCamDir.y + "," + objCamDir.z + "," + objCamDir.w);
float[] mousePointArray = { x1, y1, z1, x2, y2, z2 };
The output looks like this:
Window size: 470,314
Screen coordinates: 316,184
Clip coordinates: 0.3446808,-0.1719745,1,1
Camera coordinates: 0.1877808,-0.06259361,-1,0
World coordinates: 0.1877808,-0.06259361,-1,0
Camera Position: 4,7,6,1
Camera Direction: 0,0,-1,0
The offset does appear to get bigger the further away from the center of the screen I click. Any help I can get diagnosing this would be much appreciated, I've spent two days reading articles and fiddling with the code to no avail.