-1

I am attempting to use python to calculate the distance and velocity between time ordered coordinates following the steps in the answer here. Towards the end of the code, I encounter an error which says the global name has not been defined but clearly it has.

This is a sample of my data

    ID  timestamp           latitude        longitude
0   72  20/01/2015 09:47    -6.646405565    71.35696828
1   72  20/01/2015 15:47    -6.642237759    71.36032005
2   72  20/01/2015 21:47    -6.639229675    71.36914769
3   73  21/01/2015 03:47    -6.648699053    71.37865551
4   73  21/01/2015 09:47    -6.65574147     71.37957366
5   74  21/01/2015 15:47    -6.660118996    71.37990588
6   74  21/01/2015 21:47    -6.666138734    71.38266541

So far I have been able to run the following code

import pandas as pd
df = pd.read_csv(filename)  

df['timestamp'] = pd.to_datetime(df['timestamp'], format='%d/%m/%Y %H:%M')

from math import sin, cos, sqrt, atan2, radians

def getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2):
    R = 6371 # Radius of the earth in km
    dLat = radians(lat2-lat1)
    dLon = radians(lon2-lon1)
    rLat1 = radians(lat1)
    rLat2 = radians(lat2)
    a = sin(dLat/2) * sin(dLat/2) + cos(rLat1) * cos(rLat2) * sin(dLon/2) * sin(dLon/2) 
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = R * c # Distance in km
    return d

def calc_velocity(dist_km, time_start, time_end):
    """Return 0 if time_start == time_end, avoid dividing by 0"""
    return dist_km / (time_end - time_start).seconds if time_end > time_start else 0

# First sort by ID and timestamp:
df = df.sort_values(by=['ID', 'timestamp'])

# Group the sorted dataframe by ID, and grab the initial value for lat, lon, and time.
df['lat0'] = df.groupby('ID')['latitude'].transform(lambda x: x.iat[0])
df['lon0'] = df.groupby('ID')['longitude'].transform(lambda x: x.iat[0])
df['t0'] = df.groupby('ID')['timestamp'].transform(lambda x: x.iat[0])

# create a new column for distance
df['dist_km'] = df.apply(
    lambda row: getDistanceFromLatLonInKm(
        lat1=row['latitude'],
        lon1=row['longitude'],
        lat2=row['lat0'],
        lon2=row['lon0']
    ),
    axis=1
)

At this point, I get an error which implies'getDistanceFromLatLonInKm' has not been defined although it has been. Below is the traceback and error

Traceback (most recent call last):
  File "<pyshell#36>", line 9, in <module>
    axis=1
  File "C:\Python27\ArcGIS10.6\lib\site-packages\pandas\core\frame.py", line 4061, in apply
    return self._apply_standard(f, axis, reduce=reduce)
  File "C:\Python27\ArcGIS10.6\lib\site-packages\pandas\core\frame.py", line 4157, in _apply_standard
    results[i] = func(v)
  File "<pyshell#36>", line 3, in <lambda>
    lambda row: getDistanceFromLatLonInKm(
NameError: ("global name 'getDistanceFromLatLonInKm' is not defined", u'occurred at index 0')

Where am I going wrong in this code?

Jo Harris
  • 98
  • 9
  • 1
    please post full trace back of your error – Nihal Mar 12 '19 at 12:02
  • My apologies, I have updated my question to include. – Jo Harris Mar 12 '19 at 12:10
  • 1
    you should save your code in file and run it. – Nihal Mar 12 '19 at 12:18
  • 2
    I see pyshell in the stack trace. Can you put everything in a python script and run it as 'python ' ? I was able to run your code without any errors using the csv file from the question you linked. – Manoj Mohan Mar 12 '19 at 13:24
  • @Manoj Mohan As I have admitted in a comment below, I haven't used python before so I am not sure what you mean. I know this is not a handholding service so I will say thank you and have a go at working it out. It is good to know the code works and it is just me that needs to learn how to use it. – Jo Harris Mar 12 '19 at 14:54
  • I created an answer with the code and steps to follow. Please check. – Manoj Mohan Mar 12 '19 at 15:08

1 Answers1

1

Please check this link if you need some background about different ways of executing Python code. https://realpython.com/run-python-scripts/

Copy paste the code below to a file and save the file as lat_long.py. Change only the csv filename 'lat_long.csv' as per your system. From the shell or command prompt, execute the command:

python lat_long.py.

The python interpreter will run the contents of the file lat_long.py and print the results if any.

import pandas as pd
from math import sin, cos, sqrt, atan2, radians

filename = 'lat_long.csv'
df = pd.read_csv(filename)


df['timestamp'] = pd.to_datetime(df['timestamp'], format='%d/%m/%Y %H:%M')


def getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2):
    R = 6371 # Radius of the earth in km
    dLat = radians(lat2-lat1)
    dLon = radians(lon2-lon1)
    rLat1 = radians(lat1)
    rLat2 = radians(lat2)
    a = sin(dLat/2) * sin(dLat/2) + cos(rLat1) * cos(rLat2) * sin(dLon/2) * sin(dLon/2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = R * c # Distance in km
    return d

def calc_velocity(dist_km, time_start, time_end):
    """Return 0 if time_start == time_end, avoid dividing by 0"""
    return dist_km / (time_end - time_start).seconds if time_end > time_start else 0

# First sort by ID and timestamp:
df = df.sort_values(by=['ID', 'timestamp'])

# Group the sorted dataframe by ID, and grab the initial value for lat, lon, and time.
df['lat0'] = df.groupby('ID')['latitude'].transform(lambda x: x.iat[0])
df['lon0'] = df.groupby('ID')['longitude'].transform(lambda x: x.iat[0])
df['t0'] = df.groupby('ID')['timestamp'].transform(lambda x: x.iat[0])

# create a new column for distance
df['dist_km'] = df.apply(
    lambda row: getDistanceFromLatLonInKm(
        lat1=row['latitude'],
        lon1=row['longitude'],
        lat2=row['lat0'],
        lon2=row['lon0']
    ),
    axis=1
)
print(df)
Manoj Mohan
  • 5,654
  • 1
  • 17
  • 21