Skip to content

Assignment 11 Submission #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# Ignore the temp folder
tmp/

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
50 changes: 50 additions & 0 deletions PlotWindow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random


class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)

# a figure instance to plot on
#self.figure = plt.figure()

self.fig, self.ax = plt.subplots()

# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.fig)

# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)

# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)



def plot(self, x, y, label, color):
''' plot some random stuff '''
# create an axis
#ax = self.figure.add_subplot(111)

# discards the old graph
#ax.hold(False)

# plot data
self.ax.plot(x, y, label=label, color=color)

# refresh canvas
self.canvas.draw()

self.ax.legend(loc=0)
194 changes: 194 additions & 0 deletions PointPatternAnalysis.ipynb

Large diffs are not rendered by default.

95 changes: 95 additions & 0 deletions Untitled.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Starting\n",
"OrderedDict([(0.0, 0.0), (0.00052949131190439043, 0.8293349529304586), (0.0010589826238087809, 0.9416945034922563), (0.0015884739357131714, 0.9793501366535075), (0.0021179652476175617, 0.9921044640145764), (0.0026474565595219521, 0.9975706043121774), (0.0031769478714263428, 0.998177953234133), (0.0037064391833307331, 0.9990889766170665), (0.0042359304952351235, 0.9993926510780443), (0.0047654218071395138, 0.9996963255390222)])\n",
"Finishing\n"
]
}
],
"source": [
"%matplotlib inline\n",
"\n",
"from src.point_pattern import PointPattern\n",
"from src.point import Point\n",
"import pysal as ps\n",
"import matplotlib\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"print(\"Starting\")\n",
"\n",
"shapefile = ps.open(ps.examples.get_path('new_haven_merged.shp'))\n",
"dbf = ps.open(ps.examples.get_path('new_haven_merged.dbf'))\n",
"\n",
"points= []\n",
"i = 0\n",
"for geometry, attributes in zip(shapefile, dbf):\n",
" i += 1\n",
" points.append(Point(\n",
" geometry[0], \n",
" geometry[1], \n",
" date=attributes[0],\n",
" problem=attributes[1],\n",
" address=attributes[2],\n",
" location=attributes[3],\n",
" time=attributes[4]))\n",
" '''\n",
" # Uncommenting this section displays the first 50 items in the files.\n",
" print(geometry, attributes)\n",
" if i == 50:\n",
" break\n",
" '''\n",
" \n",
"point_pattern = PointPattern()\n",
"for point in points:\n",
" point_pattern.add_point(point)\n",
"\n",
"dict = point_pattern.compute_g(10)\n",
"print(dict)\n",
"#print(sorted(dict))\n",
"print(\"Finishing\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Binary file added exit-24.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added openFolder.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added src/__init__.py
Empty file.
108 changes: 108 additions & 0 deletions src/analytics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
from . import utils


def find_largest_city(gj):
"""
Iterate through a geojson feature collection and
find the largest city. Assume that the key
to access the maximum population is 'pop_max'.

Parameters
----------
gj : dict
A GeoJSON file read in as a Python dictionary

Returns
-------
city : str
The largest city

population : int
The population of the largest city
"""
city = None
max_population = 0
for item in gj["features"]:
props = item["properties"]
if props["pop_max"] > max_population:
max_population = props["pop_max"]
city = props["adm1name"]

return city, max_population


def average_nearest_neighbor_distance(points_list, mark = None):
"""
Given a set of points, compute the average nearest neighbor.

Parameters
----------
points_list : list
A list of Point objects.
mark : str
An optional string to filter the inputs by a certain color.

Returns
-------
mean_d : float
Average nearest neighbor distance

References
----------
Clark and Evan (1954 Distance to Nearest Neighbor as a
Measure of Spatial Relationships in Populations. Ecology. 35(4)
p. 445-453.
"""
points = None
if mark is None:
# User passed in no mark, we will use the entire points_list.
points = points_list
else:
points = list(filter(lambda current_point: current_point.mark['color'] == mark, points_list))

mean_d = 0
temp_nearest_neighbor = None
# Average the nearest neighbor distance of all points.
for i, point in enumerate(points):
# Find the nearest neighbor to this point.
for j, otherPoint in enumerate(points):
# You are not your own neighbor.
if i == j:
continue
# To avoid multiple calculations, we'll cache the result.
current_distance = utils.euclidean_distance((point.x, point.y), (otherPoint.x, otherPoint.y))
# nearest neighbor will be None if this is the first neighbor we have iterated over.
if temp_nearest_neighbor is None:
temp_nearest_neighbor = current_distance
elif temp_nearest_neighbor > current_distance:
temp_nearest_neighbor = current_distance
# At this point, we've found point's nearest neighbor distance.
# Add in that distance.
mean_d += temp_nearest_neighbor
temp_nearest_neighbor = None

# Divide by number of points.
mean_d /= len(points)

return mean_d


def permutations(p=99, mark=None):
n = 100
to_return = []
for i in range(p):
to_return.append(
average_nearest_neighbor_distance(
utils.create_random(n),
mark
)
)
return to_return


def compute_critical(p):
"""
Calculates the critical points (lowest distance and greatest distance) in a set of
randomly generated permutations (created using permutations(p)).
"""
return min(p), max(p)
28 changes: 28 additions & 0 deletions src/io_geojson.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import json


def read_geojson(input_file):
"""
Read a geojson file

Parameters
----------
input_file : str
The PATH to the data to be read

Returns
-------
gj : dict
An in memory version of the geojson
"""
# Please use the python json module (imported above)
# to solve this one.
with open(input_file, 'r') as fp:
gj = json.load(fp)
return gj


def read_tweets(tweet_file):
with open(tweet_file, 'r') as fp:
to_return = json.load(fp)
return to_return
35 changes: 35 additions & 0 deletions src/point.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from . import utils
import random


class Point(object):
def __init__(self, x, y, **mark):
self.x = x
self.y = y
self.mark = mark

def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

def __radd__(self, other):
return self.__add__(self, other)

def __str__(self):
return "({0}, {1})".format(self.x, self.y)

def __neg__(self):
return Point(-self.x, -self.y)

def is_coincident(self, other_point):
return utils.check_coincident((self.x, self.y), (other_point.x, other_point.y))

def shift_point(self, delta_x, delta_y):
result = utils.shift_point((self.x, self.y), delta_x, delta_y)
self.x = utils.getx(result)
self.y = utils.gety(result)

def get_array(self):
return [self.x, self.y]

def euclidean_distance(self, other_point):
return utils.euclidean_distance([self.x, self.y], [other_point.x, other_point.y])
Loading