Skip to content

Commit

Permalink
Add City, Country, Duration, Distance and Velocity
Browse files Browse the repository at this point in the history
  • Loading branch information
gorkarevilla committed Apr 25, 2017
1 parent 0369fd3 commit edc061e
Show file tree
Hide file tree
Showing 21 changed files with 205 additions and 27 deletions.
Binary file modified behaviour/forms.pyc
Binary file not shown.
38 changes: 38 additions & 0 deletions behaviour/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-25 09:33
from __future__ import unicode_literals

from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Trips',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('device_id', models.CharField(max_length=4)),
('firsttimestamp', models.DateTimeField()),
('lasttimestamp', models.DateTimeField()),
('firstpointlatitude', models.FloatField()),
('firstpointlongitude', models.FloatField()),
('lastpointlatitude', models.FloatField()),
('lastpointlongitude', models.FloatField()),
('geom', django.contrib.gis.db.models.fields.LineStringField(srid=4326)),
('city', models.CharField(max_length=20)),
('country', models.CharField(max_length=20)),
('continent', models.CharField(max_length=20)),
('username', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Binary file added behaviour/migrations/0001_initial.pyc
Binary file not shown.
19 changes: 19 additions & 0 deletions behaviour/migrations/0002_remove_trips_continent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-25 10:07
from __future__ import unicode_literals

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('behaviour', '0001_initial'),
]

operations = [
migrations.RemoveField(
model_name='trips',
name='continent',
),
]
Binary file added behaviour/migrations/0002_remove_trips_continent.pyc
Binary file not shown.
20 changes: 20 additions & 0 deletions behaviour/migrations/0003_trips_duration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-25 13:21
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('behaviour', '0002_remove_trips_continent'),
]

operations = [
migrations.AddField(
model_name='trips',
name='duration',
field=models.FloatField(blank=True, default=None, null=True),
),
]
Binary file added behaviour/migrations/0003_trips_duration.pyc
Binary file not shown.
20 changes: 20 additions & 0 deletions behaviour/migrations/0004_trips_distance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-25 13:49
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('behaviour', '0003_trips_duration'),
]

operations = [
migrations.AddField(
model_name='trips',
name='distance',
field=models.FloatField(blank=True, default=None, null=True),
),
]
Binary file added behaviour/migrations/0004_trips_distance.pyc
Binary file not shown.
20 changes: 20 additions & 0 deletions behaviour/migrations/0005_trips_velocity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-25 14:19
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('behaviour', '0004_trips_distance'),
]

operations = [
migrations.AddField(
model_name='trips',
name='velocity',
field=models.FloatField(blank=True, default=None, null=True),
),
]
Binary file added behaviour/migrations/0005_trips_velocity.pyc
Binary file not shown.
Empty file.
Binary file added behaviour/migrations/__init__.pyc
Binary file not shown.
8 changes: 7 additions & 1 deletion behaviour/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,14 @@ class Trips(models.Model):
geom = gismodels.LineStringField() # geom is the Field to be drawn (all the points)

#Calculated fields
city = models.CharField(max_length=20)
country = models.CharField(max_length=20)

duration = models.FloatField(default=None, blank=True, null=True)
distance = models.FloatField(default=None, blank=True, null=True)
velocity = models.FloatField(default=None, blank=True, null=True)


# Returns the string representation of the model.
def __unicode__(self): # __str__ on Python !=2
return str(self.username) + " : " + str(self.device_id) + " @ "+ str(self.firsttimestamp) + " - " + str(self.lasttimestamp)
return str(self.username) + " : " + str(self.device_id) + " @ "+ str(self.firsttimestamp) + " - " + str(self.lasttimestamp) + " - " + str(self.duration)
Binary file modified behaviour/models.pyc
Binary file not shown.
12 changes: 7 additions & 5 deletions behaviour/templates/base.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{% load staticfiles %}
{% load static %}
{% load crispy_forms_tags %}
{% load bootstrap3 %}
<! DOCTYPE html>
<html>
<head>
Expand Down Expand Up @@ -78,19 +79,20 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/behaviour/">Smart Mobility</a>
<a class="navbar-brand" href="/">Smart Mobility</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
{% if not user.is_authenticated %}
<form class="navbar-form navbar-right" role="form">

<div class="form-group">
{{ user_form|crispy }}
{{ userform.username | as_crispy_field }}
{% csrf_token %}
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<div class="form-group">
{{ userform.password | as_crispy_field }}
{% csrf_token %}
</div>
<button type="submit" class="btn btn-success">Sign in</button>
<button type="submit" class="btn btn-info">Sign up</button>
</form>
Expand Down
91 changes: 71 additions & 20 deletions behaviour/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,32 @@
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.http import require_http_methods

from .forms import UploadFileForm
from .forms import LoginForm, UploadFileForm

import csv
import json
from datetime import datetime
from datetime import timedelta

from .models import Trips
from django.contrib.gis.geos import LineString, Point

from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
from geopy.distance import vincenty

# Create your views here.


@require_http_methods(["GET"])
def index(request):
return render (request, 'behaviour/index.html')
userform = LoginForm()
return render (request, 'behaviour/index.html', {'userform': userform})

@require_http_methods(["GET"])
def maposm(request):
return render (request, 'behaviour/maposm.html')
userform = LoginForm()
return render (request, 'behaviour/maposm.html', {'userform': userform})

def upload(request):
if request.method == 'POST':
Expand All @@ -45,18 +54,21 @@ def upload(request):
messages.error(request,"Error Uploading the File")
return HttpResponseRedirect('upload.html')
else:
userform = LoginForm()
formupload = UploadFileForm()
return render(request, 'behaviour/upload.html', {'formupload': formupload})
return render(request, 'behaviour/upload.html', {'formupload': formupload, 'userform': userform})

@require_http_methods(["GET"])
def display(request):
return render (request, 'behaviour/display.html')
userform = LoginForm()
return render (request, 'behaviour/display.html', {'userform': userform})


@require_http_methods(["GET"])
def user_logout(request):
logout(request)
messages.add_message(request, messages.SUCCESS, 'You have successfully loged out!')
return HttpResponseRedirect('behaviour/')
return HttpResponseRedirect('/')

#Process the file
#Format:
Expand Down Expand Up @@ -184,6 +196,8 @@ def insert_trips(request,trips):
firsttimestamp = None
lasttimestamp = None
point = None
city = None
country = None

for t in trips:

Expand All @@ -204,17 +218,26 @@ def insert_trips(request,trips):
firstpointlongitude = t[4]
device_id = t[2]
firsttimestamp = t[1]

#Calculated values
# City and Country
try:
geolocator = Nominatim()
location = geolocator.reverse(str(firstpointlatitude) + ", "+ str(firstpointlongitude))
locjson = json.loads(json.dumps(location.raw))
city = locjson['address']['city']
except GeocoderTimedOut:
print("Error: Geocode time out")
except KeyError:
city = "Unknown"
try:
country = locjson['address']['country']
except KeyError:
country = "Unknown"
else:

# Save in the model
print "Adding: "+ device_id + " FT: " + str(firsttimestamp) + " FP: " + str(firstpointlatitude)
Trips( username=request.user, device_id=device_id,
firsttimestamp=firsttimestamp, lasttimestamp=lasttimestamp,
firstpointlatitude=firstpointlatitude, firstpointlongitude=firstpointlongitude,
lastpointlatitude=lastpointlatitude, lastpointlongitude=firstpointlongitude,
geom=LineString(listpoints)).save()

insert_ddbb(request,device_id,firsttimestamp,lasttimestamp,
firstpointlatitude,firstpointlongitude,lastpointlatitude,lastpointlongitude,
listpoints,city,country)
# Clear the temporary list
listpoints = []

Expand All @@ -229,21 +252,49 @@ def insert_trips(request,trips):
firstpointlongitude = t[4]
device_id = t[2]
firsttimestamp = t[1]
#Calculated values
# City and Country
try:
geolocator = Nominatim()
location = geolocator.reverse(str(firstpointlatitude) + ", "+ str(firstpointlongitude))
locjson = json.loads(json.dumps(location.raw))
city = locjson['address']['city']
except GeocoderTimedOut:
print("Error: Geocode time out")
except KeyError:
city = "Unknown"
try:
country = locjson['address']['country']
except KeyError:
country = "Unknown"


tripNumber = t[0]

# Finally insert the remaining list
insert_ddbb(request,device_id,firsttimestamp,lasttimestamp,
firstpointlatitude,firstpointlongitude,lastpointlatitude,lastpointlongitude,
listpoints,city,country)


def insert_ddbb(request,device_id,firsttimestamp,lasttimestamp,
firstpointlatitude,firstpointlongitude,lastpointlatitude,lastpointlongitude,
listpoints,city,country):

duration = timedifference(datetime.strptime(firsttimestamp, '%Y-%m-%d %H:%M:%S'),datetime.strptime(lasttimestamp, '%Y-%m-%d %H:%M:%S')).total_seconds()
distance = vincenty( (firstpointlatitude,firstpointlongitude), (lastpointlatitude,lastpointlongitude) ).meters
velocity = (3.6)*(distance/duration)

print "Adding: "+ device_id + " FT: " + str(firsttimestamp) + " FP: " + str(firstpointlatitude)

Trips( username=request.user, device_id=device_id,
firsttimestamp=firsttimestamp, lasttimestamp=lasttimestamp,
firstpointlatitude=firstpointlatitude, firstpointlongitude=firstpointlongitude,
lastpointlatitude=lastpointlatitude, lastpointlongitude=firstpointlongitude,
geom=LineString(listpoints)).save()




geom=LineString(listpoints),
city=city, country=country,
duration=duration, distance=distance, velocity=velocity
).save()



Expand Down
Binary file modified behaviour/views.pyc
Binary file not shown.
4 changes: 3 additions & 1 deletion smartmobility/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
'djgeojson',
'behaviour',
'crispy_forms',
'leaflet'
'leaflet',
'bootstrap3',
'geopy'
]

LEAFLET_CONFIG = {
Expand Down
Binary file modified smartmobility/settings.pyc
Binary file not shown.
Binary file modified spatial.db
Binary file not shown.

0 comments on commit edc061e

Please sign in to comment.