From 360959dab103c7e88a094a9e03e1633f3c3974f3 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 11 Nov 2013 21:26:21 +0000 Subject: [PATCH] Added function to calculate the distance between systems. --- evesde/models/locations.py | 13 ++++++++++++- evesde/utils.py | 6 ++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 evesde/utils.py diff --git a/evesde/models/locations.py b/evesde/models/locations.py index 9a17619..8a2c430 100644 --- a/evesde/models/locations.py +++ b/evesde/models/locations.py @@ -1,5 +1,8 @@ +from math import sqrt from django.db import models -from .utils import InheritanceQuerySet +from evesde.utils import euclidean_distance +from evesde.app_defines import DISTANCE_LIGHT_YEAR +from evesde.models.utils import InheritanceQuerySet class LocationManager(models.Manager): @@ -132,6 +135,14 @@ class System(Location): def moons(self): return Moon.objects.filter(planet__in=self.planets.all()) + def distance_to(self, destination): + """Calculates the ly distance between the two systems""" + if not isinstance(destination, System): + raise ValueError('Provided destination is not a System.') + origin = (self.x, self.y, self.z) + destination = (destination.x, destination.y, destination.z) + return euclidean_distance(origin, destination) / DISTANCE_LIGHT_YEAR + class Meta: app_label = 'evesde' ordering = ['name'] diff --git a/evesde/utils.py b/evesde/utils.py new file mode 100644 index 0000000..ab4db39 --- /dev/null +++ b/evesde/utils.py @@ -0,0 +1,6 @@ +from math import sqrt + + +def euclidean_distance(origin, destination): + """Calculates the Euclidean distance of two sets of x/y/z tuples""" + return sqrt(sum((a - b)**2 for a, b in zip(origin, destination)))