Find all points below a line on a map
In order to draw a path between two points on a map with many points (almost two thousand), I use the following function:
def path_between_cities(self, cities_with_coordinates, from_to):
from matplotlib.lines import Line2D
# coordinates from chosen path
x = [int(from_to[0][2]), int(from_to[1][2])]
y = [int(from_to[0][1]), int(from_to[1][1])]
#create line
line = Line2D(x,y,linestyle='',color='k')
# create axis
x_ = np.array((0,2000))
y_ = np.array((0,6000))
plt.plot(x_,y_, 'o')
for item in cities_with_coordinates:
name = item[0]
y_coord = int(item[1])
x_coord = int(item[2])
plt.plot([x_coord], [y_coord], marker='o', markersize=1, color='blue')
plt.axes().add_line(line)
plt.axis('scaled')
plt.show()
My goal is to extract all points (coordinates) which are found below the drawn line.
I know that you can do this using the cross product of vectors
Given a large number of vectors, what would be the most efficient way of achieving this in the context above?
1 answer

Each cross product operation is still
O(1)
. You can run the below function for all the points and see which of them are below, bringing it to a linear time check.def ccw(a,b,c): """ Returns 1 if c is above directed line ab else returns 1""" return (b.x  a.x) * (c.y  a.y)  (c.x  a.x) * (b.y  a.y) #a and b are the vertices and c is the test point.
Unless you have some other information about the points, you would have to check each point to see if it below a particular line.
See also questions close to this topic

how to add non .py files into python egg
I have a flask app which looks like
myapp │ └── src │ └── python │ └── config │ └── app │── MANIFEST.in └── setup.py
The config folder is full of *.yaml files, I want to add all the static config files into my python egg after using
python setup.py install
My setup.py looks like
import os from setuptools import setup, find_packages path = os.path.dirname(os.path.abspath(__file__)) setup( name="app", version="1.0.0", author="Anna", description="", keywords=[], packages=find_packages(path + '/src/python'), package_dir={'': path + '/src/python'}, include_package_data=True )
I am trying the use the MANIFEST.in to add the config file However, it always give error
error: Error: setup script specifies an absolute path: /Users/Anna/Desktop/myapp/src/python/app setup() arguments must *always* be /separated paths relative to the setup.py directory, *never* absolute paths.
I have not used any absolute paths in my code, I've seen other posts trying to bypass this error, by removing
include_package_data=True
However, in my case, if i do this to avoid this error, all my yamls won't be added.
I was wondering if there are ways to fix this problem. Thanks

How to extract all functions and API calls used in a Python source code?
Let us consider the following Python source code;
def package_data(pkg, roots): data = [] for root in roots: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname, fname), pkg)) return {pkg: data}
From this source code, I want to extract all the functions and API calls. I found a similar question and solution. I ran the solution given here and it generates the output
[os.walk, data.append]
. But I am looking for the following output[os.walk, os.path.join, data.append, os.path.relpath, os.path.join]
.What I understood after analyzing the following solution code, this can visit the every node before the first bracket and drop rest of the things.
import ast class CallCollector(ast.NodeVisitor): def __init__(self): self.calls = [] self.current = None def visit_Call(self, node): # new call, trace the function expression self.current = '' self.visit(node.func) self.calls.append(self.current) self.current = None def generic_visit(self, node): if self.current is not None: print("warning: {} node in function expression not supported".format( node.__class__.__name__)) super(CallCollector, self).generic_visit(node) # record the func expression def visit_Name(self, node): if self.current is None: return self.current += node.id def visit_Attribute(self, node): if self.current is None: self.generic_visit(node) self.visit(node.value) self.current += '.' + node.attr tree = ast.parse(yoursource) cc = CallCollector() cc.visit(tree) print(cc.calls)
Can anyone please help me to modified this code so that this code can traverse the API calls inside the bracket?
N.B: This can be done using regex in python. But it requires a lot of manual labors to find out the appropriate API calls. So, I am looking something with help of Abstract Syntax Tree.

use correct version of 'pip' installed for your Python interpreter
I am using pycharm , i am having this error by adding any package , Click Here
i have tried lot of methods , but didn't succeed yet.
Info :
 python 3.6.2
 pip 10.0.1
 VirtualEnv

How do I get the slope of all contour paths from contours in matplotlib?
I am attempting to project data I have onto contours generated using matplotlib. Essentially, I am trying to align ocean current data with the direction of the underlying bathymetry. My goal is to calculate cell values of the contour generated from
contour(longitude, latitude, depth)
and do a vector projection of the current data onto those cells such that I have component velocities that are aligned with and perpendicular to the bathymetry.Is there a way to extract the slope of the contour lines generated with
contour()
? From there it would be pretty straightforward to calculate the angle with respect to due east the isobaths make and then do the vector projection. Thanks! 
Need help plotting 2D array in python. Im using Spyder(Python 3.6)
Output of my program is
[[['AB', 'CD', 'EF', 'GH', 'AB'], ['CD', 'EF', 'AB', 'AB', 'AB'], ['AB', 'CD', 'AB', 'GH', 'AB']]
AB CD EF GH AB CD EF AB AB AB AB CD AB GH AB
Can I plot this in python?
Please help!

Plotting 3d data distribution of a set of Images
I am working on Generative Adversarial Networks. I learned that GAN's learn to transform simple Gaussian distribution to Complex distribution similar to training data. I visualized how the Distribution of noise looks, but I want to visualize the distribution of my Training set, like in this image:
please tell me how I can do this in Python ?

smallest enclosing cylinder
Is there an algorithm for finding of an enclosing cylinder with the smallest radius for a 3D cloud of dots? I know that 2D case with the smallest enclosing circle is solved (for example this thread Smallest enclosing circle in Python, error in the code), but is there any working approach for 3D?
EDIT1: OBB. Below is an example of an arcshaped cloud of dots. The smallest enclosing circle was found by this tool https://www.nayuki.io/page/smallestenclosingcircle
Circle is defined by three dots of which two are lying almost on a diameter, so it is easy to estimate where the central axis is. "Boxing" of dots will yield a center of the box obviously much shifted from the true center.
I conclude, that OBB approach is not general.
EDIT2: PCA. Below is an example of PCA analysis of a tight dot cloud vs. dot cloud with outliers. For the tight dot cloud PCA predicts the cylinder direction satisfactorily. But if there is a small number of outliers, compared to the main cloud, than PCA will basically ignore them, yielding vectors which are very far from the true axis of an enclosing cylinder. In the example below the true geometrical axis of an enclosing cylinder is shown in black.
I conclude that PCA approach is not general.
EDIT3: OBB vs. PCA and OLS. A major difference  OBB relies only on a geometrical shape, while PCA and OLS are dependent from the overall number of points, including those in the middle of the set, which do not affect the shape. In order to make them more efficient, a data preparation step can be included. First, find the convex hull. Second, exclude all internal points. Then, points along the hull can be distributed unevenly. I'd suggest to remove all of them, leaving only the polygonal hull body, and cover it with mesh, where nodes will be new points. Application of PCA or OLS to this new cloud of points should provide much more accurate estimation of the cylinder axis.
All this can be unnecessary, if OBB provides an axis, as much parallel to the enclosing cylinder axis, as possible.
EDIT4: published approaches. @meowgoesthedog: paper by Michel Petitjean ("About the Algebraic Solutions of Smallest Enclosing Cylinders Problems") could help, but I'm insufficiently qualified to convert it to a working program. Author himself did it (module CYL here http://petitjeanmichel.free.fr/itoweb.petitjean.freeware.html). But at the conclusions in the paper he says: "and the present software, named CYL, downloadable for free at http://petitjeanmichel.free.fr/itoweb.petitjean.freeware.html, is neither claimed to offer the best possible implementations of the methods nor is claimed to work better than other cylinder computation softwares." Other phrases from the paper also makes an impression, that it is an experimental approach, which was not thoroughly validated. I'll try to use it, anyway.
@Ripi2: this paper by Timothy M. Chan is also a bit too complicated for me. I'm not an expert of that level in mathematics, to be able to convert to a tool.
@Helium_1s2: probably, it is a good suggestion, however, it is much less detailed compared to two papers above. Also, not validated.
EDIT5: reply for user1717828. Two most distant points vs. cylinder axis. A counter example  8 points in a shape of cube, fit in a cylinder. The biggest distance between two points  green diagonal. Obviously not parallel to cylinder axis.

Three.js rotate sphere, point A to B
I'm working on a 3d model of night sky map, I want to rotate my geometries in such way that zenith(green box) lies directly on the Y axis as highest point (0,+y,0).
image of what I'm trying to do
so far I've found possible solution:
function rotateSphere(long, lat){ var c = scene.rotation.y; var d = long * (Math.PI / 180)%(2 * Math.PI); var e = Math.PI / 2; scene.rotation.y = c % (2 * Math.PI); scene.rotation.x = lat * (Math.PI / 180) % Math.PI; scene.rotation.z = d+e; }
however, I don't really understand how it works and results in upside down position of what I'm trying to achieve. Any help much appreciated.

Creating new vertices at the wireframe subdivision in Three.js
I understand that the THREE.SubdivisionModifier will section a shape's wireframe, but as far as I understand this doesn't add any new vertices to the geometry. How can I add new vertices to the geometry representing the intersection points of the subdivisions? I'm trying to add noisy distortions to a convex hull, so I need to either add new vertices along the shapes'faces, bend each subdivision independently, or else copy the geometry into a new similar geometry with a higher "
resolution
" of vertices along its faces.Is any one of those options supported by Three.js? Thanks!

Counting pairs column elements with the same value in a data frame and shows in a matrix format
I was searching on internet for similar solution, but I was not able to find the specific one for my case. Let's say a have the following data frame:
a = c(1, 1, 1, 2, 2) b = c(2, 1, 1, 1, 2) c = c(2, 2, 1, 1, 1) d = c(1, 2, 2, 1, 1) df < data.frame(a = a, b = b, c = c, d = d)
and
df
looks like this:a b c d 1 1 2 2 1 2 1 1 2 2 3 1 1 1 2 4 2 1 1 1 5 2 2 1 1
Note: In this example I use
[1,2]
pair of values, but it could be a set of different values:[1,1]
or even more than two possible values:[1,1,2]
.Now I would like to have a matrix where each
[i,j]
element will represent the number of rows with the value1
for columni
andj
. For this particular case we have (showing the upper diagonal, because its symmetric):a b c d a 3 2 1 1 b 3 2 1 c 3 2 d 3
The diagonal should count the number of rows with
1
value at a given column. On this case all columns have the sames number of value1
. The format should be similar tocor()
function (Correlation Matrix).I was trying to use
table()
(and alsocrosstab
fromdescr
package) but it shows the information by pairs of columns.It can be done by computing manually the occurrence of
1
of each pair of columns (i.e.:nrow(df[df$a==1 & df$b==1,])=2
) and then putting into a matrix, but I was wondering if there is a builtin function that simplify the process. 
Binary Space Partition 3D Simple Mathematics
Let say we have 3 polygons with the following points:
A(40:100:100) B(20:0:100) C(60:5:100) polygon1 (black)
D(60:50:50) E(10:50:150) F(60:50:150) polygon2 (red)
G(40:20:0) H(30:10:0) I(50:10:0) polygon3 (green)
According to my understanding about BSP algorithm, the polygon started by polygon1 as the most top of the BSP tree. Then make a partition of polygon2 let say polygon 2A and 2B. And now polygon1 has polygon 2A as the left node and polygon 2B as the right node. Finally, polygon 2A has polygon3 as the left node. Therefore, the order of displaying the surfaces from back to front: 32A12B. It is easy to tell just by looking the picture and knowing from the point coordinate of the surface.
My question is, when the case of partitioning polygon begin mathematically? And how can we decide whether that polygon is in the left node or right node mathematically? My lecture said the following function is the answer.
normal = calculateVertexNormal(A, B, C) //cross product calculation Dim temp1, temp2, temp3 As TPoint Dim temp As Double = 0 temp1 = calculateVectorSubstraction(A, viewPoint) : temp2 = calculateVectorSubstraction(B, viewPoint) : temp3 = calculateVectorSubstraction(C, viewPoint) //AV as vector calculation(VA) a = calculateDotProductVector(temp1, normal) //return double b = calculateDotProductVector(temp2, normal) c = calculateDotProductVector(temp3, normal)
And the following function will determine which that polygon cases belong to:
If a < 0 And b < 0 And c < 0 Then insertPoly(LeftNode,Poly) ElseIf a > 0 And b > 0 And c > 0 Then insertPoly(RightNode, Poly) ElseIf a < 0 And b > 0 And c > 0 Then I1 = findIntersection(A,B,normal,viewPoint) I2 = findIntersection(A,C,normal,viewPoint) Poly1 = newPoly(B, C, I1) Poly2 = newPoly(C, I2, I1) Poly3 = newPoly(A, I1, I2) insertPoly(Left, Poly3) insertPoly(Right, Poly1) insertPoly(Right, Poly2) ElseIf a < 0 And b < 0 And c > 0 Then I1 = findIntersection(C,A,normal,viewPoint) I2 = findIntersection(C,B,normal,viewPoint) Poly1 = newPoly(A, B, I1) Poly2 = newPoly(C, I2, I1) Poly3 = newPoly(A, I1, I2) insertPoly(Left, Poly3) insertPoly(Left, Poly1) insertPoly(Right, Poly2) ElseIf a < 0 And isZero(b) And c > 0 Then // I don't know yet about this End If
But when I implemented the function above to the program it doesn't work. And I assumed that there must be something wrong with the algorithm above. Which part of the function above that I have to fix? Or is there any other solution?