OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Calculate Distance to the nearest object

  • Thread starter Thread starter Kekkerino_taco
  • Start date Start date
K

Kekkerino_taco

Guest
I need to make a map of distances to the nearest object. I have a solution where i am looping over every point of a map, and every object, calculating the distance to all of them, and then leaving only minimum distance. The problem here is that if i am woking with real data, the map can easily contain 10s of millions of points, and there can be more than 100 objects. Is there any better code implementation for solving this problem?

Loading packages​


Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

Generate synthetic map​


Code:
coord_dict = {"X": [],
              "Y": []}

for x_value in range(0, 10000, 50):    
    for y_value in range(0, 5000, 50):
        coord_dict["X"].append(x_value)
        coord_dict["Y"].append(y_value)

map_df = pd.DataFrame(coord_dict)

Generate points to calculate distance from​


Code:
well_points_dict = {"X": [500, 1500, 4000, 5500, 6250, 7500, 8000, 9000], 
                    "Y": [500, 4000, 2000, 1500, 500, 5000, 100, 2500]}

wells_df = pd.DataFrame(well_points_dict)

Calculate distances​


Code:
calculations_count = 0
distance_map = np.zeros(map_df.shape)

for i in range(map_df.shape[0]):
    d = []
    for j in range(wells_df.shape[0]):
        d.append(((map_df["X"].iloc[i]-wells_df["X"][j])**2 + (map_df["Y"].iloc[i]-      wells_df["Y"][j])**2)**0.5)
        calculations_count += 1
    dd = min(d)
    distance_map[i,1] = dd
    # print(calculations_count)

Print resulting map​


Code:
plt.figure(figsize=(10,10))
plt.scatter(x=map_df["X"],y=map_df["Y"],c=distance_map[:,1],s=1,cmap='terrain')
for i in range(len(wells_df)):
    plt.plot(wells_df["X"][i],wells_df["Y"][i], color='black', marker='o',markersize=3)
plt.title('Calculated map')
plt.xlabel('X')
plt.ylabel('Y')
plt.axis('scaled')
plt.tight_layout()
plt.colorbar(shrink=0.25)

Result map example
<p>I need to make a map of distances to the nearest object.
I have a solution where i am looping over every point of a map, and every object, calculating the distance to all of them, and then leaving only minimum distance.
The problem here is that if i am woking with real data, the map can easily contain 10s of millions of points, and there can be more than 100 objects.
Is there any better code implementation for solving this problem?</p>
<h3>Loading packages</h3>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
</code></pre>
<h3>Generate synthetic map</h3>
<pre><code>coord_dict = {"X": [],
"Y": []}

for x_value in range(0, 10000, 50):
for y_value in range(0, 5000, 50):
coord_dict["X"].append(x_value)
coord_dict["Y"].append(y_value)

map_df = pd.DataFrame(coord_dict)
</code></pre>
<h3>Generate points to calculate distance from</h3>
<pre><code>well_points_dict = {"X": [500, 1500, 4000, 5500, 6250, 7500, 8000, 9000],
"Y": [500, 4000, 2000, 1500, 500, 5000, 100, 2500]}

wells_df = pd.DataFrame(well_points_dict)
</code></pre>
<h3>Calculate distances</h3>
<pre><code>calculations_count = 0
distance_map = np.zeros(map_df.shape)

for i in range(map_df.shape[0]):
d = []
for j in range(wells_df.shape[0]):
d.append(((map_df["X"].iloc-wells_df["X"][j])**2 + (map_df["Y"].iloc- wells_df["Y"][j])**2)**0.5)
calculations_count += 1
dd = min(d)
distance_map[i,1] = dd
# print(calculations_count)
</code></pre>
<h3>Print resulting map</h3>
<pre><code>plt.figure(figsize=(10,10))
plt.scatter(x=map_df["X"],y=map_df["Y"],c=distance_map[:,1],s=1,cmap='terrain')
for i in range(len(wells_df)):
plt.plot(wells_df["X"],wells_df["Y"], color='black', marker='o',markersize=3)
plt.title('Calculated map')
plt.xlabel('X')
plt.ylabel('Y')
plt.axis('scaled')
plt.tight_layout()
plt.colorbar(shrink=0.25)
</code></pre>
<p><a href="https://i.sstatic.net/25spfWM6.png" rel="nofollow noreferrer">Result map example</a></p>
 

Latest posts

L
Replies
0
Views
1
lagnaoui jihane
L
E
Replies
0
Views
1
Eduard Dubilyer
E
Top