├── .gitignore ├── .gitmodules ├── LICENSE.txt ├── README.md ├── Sketches ├── FishesSchooling │ ├── FishesSchooling.pyde │ ├── README.md │ ├── behaviors.py │ └── fish-schooling.png ├── GoogleStreetViewDemo │ ├── GoogleStreetView.pyde │ ├── data │ │ └── sample-locations.csv │ └── gsv.py ├── Graphics │ ├── Particles_Ribbons │ │ ├── Interaction.pde │ │ ├── Node.pde │ │ ├── Particles_Ribbons.pde │ │ └── README.md │ └── README.md ├── Intro │ ├── AltCsv │ │ ├── AltCsv.pyde │ │ ├── data │ │ │ └── quakes.csv │ │ └── sketch.properties │ ├── AltInteractCsv │ │ ├── AltInteractCsv.pyde │ │ ├── data │ │ │ └── quakes.csv │ │ └── sketch.properties │ ├── InteractCsv │ │ ├── InteractCsv.pyde │ │ ├── data │ │ │ └── quakes.csv │ │ └── sketch.properties │ ├── SimpleCsv │ │ ├── SimpleCsv.pyde │ │ ├── data │ │ │ └── quakes.csv │ │ └── sketch.properties │ ├── SimpleGoogleStreetView │ │ ├── SimpleGoogleStreetView.pyde │ │ └── locations.csv │ └── SimpleGoogleStreetView2 │ │ ├── SimpleGoogleStreetView2.pyde │ │ └── locationscsv.py ├── OpenStreetMap │ ├── OSMBicycleDemo │ │ ├── OSM-bicycles.png │ │ ├── OSMBicycleDemo.pyde │ │ └── README.md │ ├── OSMBuildingsDemo │ │ ├── OSM-buildings.png │ │ ├── OSMBuildingsDemo.pyde │ │ └── README.md │ └── OSMStreetsDemo │ │ ├── OSM-streets.png │ │ ├── OSMStreetsDemo.pyde │ │ └── README.md ├── README.md ├── RandomWalkSample │ ├── README.md │ ├── RandomWalkSample.pyde │ ├── procgui.py │ ├── randomwalkgenerator.py │ └── sketch.properties ├── Simulation │ ├── Biomimicry_Mitosis │ │ ├── Biomimicry_Mitosis.pde │ │ ├── Cell.pde │ │ ├── Interface.pde │ │ └── README.md │ ├── Biomimicry_MitosisFood │ │ ├── Biomimicry_MitosisFood.pde │ │ ├── Cell.pde │ │ ├── FoodSource.pde │ │ ├── Interface.pde │ │ └── README.md │ ├── Biomimicry_MitosisFoodPatterns │ │ ├── Biomimicry_MitosisFoodPatterns.pde │ │ ├── Cell.pde │ │ ├── FoodSource.pde │ │ ├── Interface.pde │ │ └── README.md │ └── README.md ├── SlippyMapperDemo │ ├── SlippyMapperDemo.pyde │ └── data │ │ ├── citibike.csv │ │ ├── earthquakes_all_day_20170921.geojson │ │ ├── location-history-sample.kml │ │ ├── route1762551746.geojson │ │ └── route1762551746.kml ├── SlippyMapperSubwayStations │ ├── SlippyMapperSubwayStations.pyde │ └── data │ │ ├── StationEntrances.csv │ │ ├── map-pin-10px.png │ │ ├── map-pin-15px.png │ │ └── map-pin-20px.png └── Visualization │ ├── Earthquakes │ ├── Data.pde │ ├── Earthquakes.pde │ ├── Globe.pde │ ├── Interaction.pde │ ├── Quake.pde │ ├── README.md │ ├── Transformation.pde │ └── data │ │ ├── earthquakes_2010_10.csv │ │ ├── earthquakes_2012_05.csv │ │ ├── earthquakes_2013_12.csv │ │ └── equirectangular_projection.jpg │ └── README.md ├── __init__.py ├── data ├── __init__.py ├── geojson │ ├── __init__.py │ ├── geojson.py │ └── slippylayer.py └── kml │ ├── __init__.py │ ├── kml.py │ └── slippylayer.py ├── google ├── __init__.py ├── directions │ ├── __init__.py │ ├── googledirections.py │ └── slippylayer.py └── streetview │ ├── __init__.py │ └── gsv.py ├── mapping ├── __init__.py ├── openstreetmap │ ├── __init__.py │ ├── openstreetmap.py │ └── slippylayer.py └── slippymapper │ ├── __init__.py │ ├── layer.py │ ├── marker.py │ ├── slippymapper.py │ └── tile_servers.py ├── path ├── __init__.py └── randomwalk.py ├── third_party └── __init__.py ├── ui ├── __init__.py ├── button.py ├── control.py ├── dropdown.py ├── interface.py ├── panner.py ├── text.py └── toggle.py └── util ├── __init__.py └── lazyimages.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/macos,python,processing 3 | 4 | ### macOS ### 5 | *.DS_Store 6 | .AppleDouble 7 | .LSOverride 8 | 9 | # Icon must end with two \r 10 | Icon 11 | 12 | # Thumbnails 13 | ._* 14 | 15 | # Files that might appear in the root of a volume 16 | .DocumentRevisions-V100 17 | .fseventsd 18 | .Spotlight-V100 19 | .TemporaryItems 20 | .Trashes 21 | .VolumeIcon.icns 22 | .com.apple.timemachine.donotpresent 23 | 24 | # Directories potentially created on remote AFP share 25 | .AppleDB 26 | .AppleDesktop 27 | Network Trash Folder 28 | Temporary Items 29 | .apdisk 30 | 31 | ### Processing ### 32 | .DS_Store 33 | applet 34 | application.linux32 35 | application.linux64 36 | application.windows32 37 | application.windows64 38 | application.macosx 39 | 40 | ### Python ### 41 | # Byte-compiled / optimized / DLL files 42 | __pycache__/ 43 | *.py[cod] 44 | *$py.class 45 | 46 | # C extensions 47 | *.so 48 | 49 | # Distribution / packaging 50 | .Python 51 | env/ 52 | build/ 53 | develop-eggs/ 54 | dist/ 55 | downloads/ 56 | eggs/ 57 | .eggs/ 58 | lib/ 59 | lib64/ 60 | parts/ 61 | sdist/ 62 | var/ 63 | wheels/ 64 | *.egg-info/ 65 | .installed.cfg 66 | *.egg 67 | 68 | # PyInstaller 69 | # Usually these files are written by a python script from a template 70 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 71 | *.manifest 72 | *.spec 73 | 74 | # Installer logs 75 | pip-log.txt 76 | pip-delete-this-directory.txt 77 | 78 | # Unit test / coverage reports 79 | htmlcov/ 80 | .tox/ 81 | .coverage 82 | .coverage.* 83 | .cache 84 | nosetests.xml 85 | coverage.xml 86 | *,cover 87 | .hypothesis/ 88 | 89 | # Translations 90 | *.mo 91 | *.pot 92 | 93 | # Django stuff: 94 | *.log 95 | local_settings.py 96 | 97 | # Flask stuff: 98 | instance/ 99 | .webassets-cache 100 | 101 | # Scrapy stuff: 102 | .scrapy 103 | 104 | # Sphinx documentation 105 | docs/_build/ 106 | 107 | # PyBuilder 108 | target/ 109 | 110 | # Jupyter Notebook 111 | .ipynb_checkpoints 112 | 113 | # pyenv 114 | .python-version 115 | 116 | # celery beat schedule file 117 | celerybeat-schedule 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # dotenv 123 | .env 124 | 125 | # virtualenv 126 | .venv 127 | venv/ 128 | ENV/ 129 | 130 | # Spyder project settings 131 | .spyderproject 132 | .spyproject 133 | 134 | # Rope project settings 135 | .ropeproject 136 | 137 | # mkdocs documentation 138 | /site 139 | 140 | # End of https://www.gitignore.io/api/macos,python,processing 141 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "third_party/googlemaps/services"] 2 | path = third_party/googlemaps/services 3 | url = https://github.com/googlemaps/google-maps-services-python 4 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Allan William Martin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spatial Pixel Code 2 | 3 | This repository hosts libraries and code for computational designers featured at [Spatial Pixel](http://spatialpixel.com). 4 | 5 | These sketches are written in Python and [Processing](http://processing.org) 3+, in both the Python and Java modes. Thanks to [Jonathan Feinberg](http://mrfeinberg.com) and his team for [processing.py](http://py.processing.org) and the [recent change to support site-packages](https://github.com/jdf/processing.py/commit/c8362cad7c1f565ea598b6b9d5f38d9ed3f8d45d). 6 | 7 | ## Using These Libraries 8 | 9 | 1. Ensure you have Python mode release 3027 or later. 10 | 2. It will create a `site-packages` folder in your `libraries` folder. This is where your Python dependencies can live (.py files) to be shared among all your Python mode sketches. 11 | 3. Download `spatialpixel.zip` from the [latest release](https://github.com/awmartin/spatialpixel/releases). Don't download the archives called "Source Code" as they won't include dependencies. 12 | 13 | Alternatively for step 3, you can clone this repository: 14 | 15 | $ cd libraries/site-packages 16 | $ git clone https://github.com/awmartin/spatialpixel --recursive 17 | 18 | The structure should look like this: 19 | 20 | YOUR SKETCHBOOK/ 21 | |- ... 22 | | 23 | |- libraries/ 24 | | |- site-packages/ 25 | | |- spatialpixel/ 26 | | |- ... 27 | | 28 | |- ... 29 | 30 | Start Processing in Python Mode and you should be able to import any of the modules included here. e.g. `import spatialpixel.mapping.slippymapper as slippymapper` 31 | 32 | ## Available Libraries and Components 33 | 34 | - data 35 | - kml 36 | - geojson 37 | - google 38 | - directions 39 | - streetview 40 | - mapping 41 | - openstreetmap 42 | - slippymapper 43 | - path 44 | - randomwalk 45 | - ui 46 | - button 47 | - control 48 | - interface 49 | - panner 50 | - text 51 | - toggle 52 | - util 53 | - lazyimages 54 | 55 | ## Other ways to use the code 56 | 57 | If you want to experiment with hacking at a library or component, one way is to copy/paste individual files into your sketches. You can also follow the contribution guidelines below and send pull requests. 58 | 59 | ## Contributing 60 | 61 | If you'd like to contribute, please fork the repo, create a new branch, and send a pull request with a descriptive message. Screenshots are very helpful. :) 62 | 63 | ## License 64 | 65 | MIT License for all the original code in this repo (see [LICENSE.txt](LICENSE.txt)). All dependencies maintain the licenses of their respective projects, all referenced in the `third_party` folder. 66 | -------------------------------------------------------------------------------- /Sketches/FishesSchooling/FishesSchooling.pyde: -------------------------------------------------------------------------------- 1 | """Demonstrates a simple simulation of schooling/swarming behavior. 2 | 3 | This simulates a school of fish that exhibit three bottom-up behaviors: 4 | 5 | - A fish wants to move towards the center of its neighbors. This encourages them to 6 | get cozy. 7 | - A fish wants to move away from any fish that's encroaching on its personal space. 8 | That is, don't get too cozy. 9 | - A fish wants to turn towards the average direction of its neighbors. This causes 10 | neighbors to swim in the same direction. 11 | """ 12 | 13 | import math 14 | import random 15 | from behaviors import * 16 | 17 | 18 | def setup(): 19 | size(800, 500) 20 | 21 | # How many fish you want in the simulation. 22 | number_of_fish = 100 23 | 24 | # Add all the fish behaviors and their parameters. 25 | global behaviors 26 | behaviors = ( 27 | MoveTowardsCenterOfNearbyFish(closeness=50.0, threshold=25.0, speedfactor=100.0, weight=20.0), 28 | TurnAwayFromClosestFish(threshold=15.0, speedfactor=5.0, weight=20.0), 29 | TurnToAverageDirection(closeness=50.0, weight=6.0), 30 | Swim(speedlimit=3.0, turnratelimit=math.pi / 20.0), 31 | WrapAroundWindowEdges(), 32 | ) 33 | 34 | # Make some fish! 35 | global allfishes 36 | allfishes = [] 37 | for i in xrange(0, number_of_fish): 38 | allfishes.append(Fish()) 39 | 40 | 41 | def draw(): 42 | background(24) 43 | for fish in allfishes: 44 | fish.move() 45 | fish.draw() 46 | 47 | 48 | class Fish(object): 49 | fishcolors = ( 50 | color(255, 145, 8), 51 | color(219, 69, 79), 52 | color(255) 53 | ) 54 | 55 | def __init__(self): 56 | self.position = [random.randrange(0, width), random.randrange(0, height)] 57 | self.speed = 1 58 | self.direction = random.random() * 2.0 * math.pi - math.pi 59 | self.turnrate = 0 60 | 61 | self.fishcolor = Fish.fishcolors[random.randrange(0, len(Fish.fishcolors))] 62 | 63 | def move(self): 64 | # TODO Globals... Yuck. 65 | global allfishes, behaviors 66 | 67 | state = {} 68 | 69 | # TODO Make this more efficient. 70 | for fish in allfishes: 71 | for behavior in behaviors: 72 | behavior.setup(self, fish, state) 73 | 74 | for behavior in behaviors: 75 | behavior.apply(self, state) 76 | # behavior.draw(self, state) 77 | 78 | def draw(self): 79 | pushMatrix() 80 | 81 | translate(*self.position) 82 | rotate(self.direction) 83 | 84 | stroke(self.fishcolor) 85 | noFill() 86 | bezier(0, 0, 10, 7, 15, 0, 25, 0) 87 | bezier(0, 0, 10, -7, 15, 0, 25, 0) 88 | line(7, 3, 12, 8) 89 | line(7, -3, 12, -8) 90 | 91 | popMatrix() 92 | -------------------------------------------------------------------------------- /Sketches/FishesSchooling/README.md: -------------------------------------------------------------------------------- 1 | Demonstrates a simple simulation of schooling/swarming behavior. 2 | 3 | ![](fish-schooling.png) 4 | 5 | This simulates a school of fish that exhibit three bottom-up behaviors: 6 | 7 | - A fish wants to move towards the center of its neighbors. This encourages them to 8 | get cozy. 9 | - A fish wants to move away from any fish that's encroaching on its personal space. 10 | That is, don't get too cozy. 11 | - A fish wants to turn towards the average direction of its neighbors. This causes 12 | neighbors to swim in the same direction. 13 | -------------------------------------------------------------------------------- /Sketches/FishesSchooling/behaviors.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Behavior(object): 4 | def __init__(self, **parameters): 5 | self.parameters = parameters 6 | 7 | def setup(self, fish, otherfish, state): 8 | pass 9 | 10 | def apply(self, fish, state): 11 | pass 12 | 13 | def draw(self, fish, state): 14 | pass 15 | 16 | 17 | class MoveTowardsCenterOfNearbyFish(Behavior): 18 | def setup(self, fish, otherfish, state): 19 | if fish is otherfish: 20 | return 21 | if 'closecount' not in state: 22 | state['closecount'] = 0.0 23 | if 'center' not in state: 24 | state['center'] = [0.0, 0.0] 25 | 26 | closeness = self.parameters['closeness'] 27 | distance_to_otherfish = dist( 28 | otherfish.position[0], otherfish.position[1], 29 | fish.position[0], fish.position[1] 30 | ) 31 | 32 | if distance_to_otherfish < closeness: 33 | if state['closecount'] == 0: 34 | state['center'] = otherfish.position 35 | state['closecount'] += 1.0 36 | else: 37 | state['center'][0] *= state['closecount'] 38 | state['center'][1] *= state['closecount'] 39 | 40 | # state['center'][0] += otherfish.position[0] 41 | # state['center'][1] += otherfish.position[1] 42 | state['center'] = [ 43 | state['center'][0] + otherfish.position[0], 44 | state['center'][1] + otherfish.position[1] 45 | ] 46 | 47 | state['closecount'] += 1.0 48 | 49 | state['center'][0] /= state['closecount'] 50 | state['center'][1] /= state['closecount'] 51 | 52 | def apply(self, fish, state): 53 | if state['closecount'] == 0: 54 | return 55 | 56 | center = state['center'] 57 | distance_to_center = dist( 58 | center[0], center[1], 59 | fish.position[0], fish.position[1] 60 | ) 61 | 62 | if distance_to_center > self.parameters['threshold']: 63 | angle_to_center = math.atan2( 64 | fish.position[1] - center[1], 65 | fish.position[0] - center[0] 66 | ) 67 | fish.turnrate += (angle_to_center - fish.direction) / self.parameters['weight'] 68 | fish.speed += distance_to_center / self.parameters['speedfactor'] 69 | 70 | def draw(self, fish, state): 71 | closeness = self.parameters['closeness'] 72 | stroke(200, 200, 255) 73 | noFill() 74 | ellipse(fish.position[0], fish.position[1], closeness * 2, closeness * 2) 75 | 76 | 77 | class TurnAwayFromClosestFish(Behavior): 78 | def setup(self, fish, otherfish, state): 79 | if fish is otherfish: 80 | return 81 | if 'closest_fish' not in state: 82 | state['closest_fish'] = None 83 | if 'distance_to_closest_fish' not in state: 84 | state['distance_to_closest_fish'] = 1000000 85 | 86 | distance_to_otherfish = dist( 87 | otherfish.position[0], otherfish.position[1], 88 | fish.position[0], fish.position[1] 89 | ) 90 | 91 | if distance_to_otherfish < state['distance_to_closest_fish']: 92 | state['distance_to_closest_fish'] = distance_to_otherfish 93 | state['closest_fish'] = otherfish 94 | 95 | def apply(self, fish, state): 96 | closest_fish = state['closest_fish'] 97 | if closest_fish is None: 98 | return 99 | 100 | distance_to_closest_fish = state['distance_to_closest_fish'] 101 | if distance_to_closest_fish < self.parameters['threshold']: 102 | angle_to_closest_fish = math.atan2( 103 | fish.position[1] - closest_fish.position[1], 104 | fish.position[0] - closest_fish.position[0] 105 | ) 106 | fish.turnrate -= (angle_to_closest_fish - fish.direction) / self.parameters['weight'] 107 | fish.speed += self.parameters['speedfactor'] / distance_to_closest_fish 108 | 109 | def draw(self, fish, state): 110 | stroke(100, 255, 100) 111 | closest = state['closest_fish'] 112 | line(fish.position[0], fish.position[1], closest.position[0], closest.position[1]) 113 | 114 | 115 | class TurnToAverageDirection(Behavior): 116 | def setup(self, fish, otherfish, state): 117 | if fish is otherfish: 118 | return 119 | if 'average_direction' not in state: 120 | state['average_direction'] = 0.0 121 | if 'closecount_for_avg' not in state: 122 | state['closecount_for_avg'] = 0.0 123 | 124 | distance_to_otherfish = dist( 125 | otherfish.position[0], otherfish.position[1], 126 | fish.position[0], fish.position[1] 127 | ) 128 | 129 | closeness = self.parameters['closeness'] 130 | if distance_to_otherfish < closeness: 131 | if state['closecount_for_avg'] == 0: 132 | state['average_direction'] = otherfish.direction 133 | state['closecount_for_avg'] += 1.0 134 | else: 135 | state['average_direction'] *= state['closecount_for_avg'] 136 | state['average_direction'] += otherfish.direction 137 | state['closecount_for_avg'] += 1.0 138 | state['average_direction'] /= state['closecount_for_avg'] 139 | 140 | def apply(self, fish, state): 141 | if state['closecount_for_avg'] == 0: 142 | return 143 | average_direction = state['average_direction'] 144 | fish.turnrate += (average_direction - fish.direction) / self.parameters['weight'] 145 | 146 | 147 | class Swim(Behavior): 148 | def setup(self, fish, otherfish, state): 149 | fish.speed = 1 150 | fish.turnrate = 0 151 | 152 | def apply(self, fish, state): 153 | # Move forward, but not too fast. 154 | if fish.speed > self.parameters['speedlimit']: 155 | fish.speed = self.parameters['speedlimit'] 156 | fish.position[0] -= math.cos(fish.direction) * fish.speed 157 | fish.position[1] -= math.sin(fish.direction) * fish.speed 158 | 159 | # Turn, but not too fast. 160 | if fish.turnrate > self.parameters['turnratelimit']: 161 | fish.turnrate = self.parameters['turnratelimit'] 162 | if fish.turnrate < -self.parameters['turnratelimit']: 163 | fish.turnrate = -self.parameters['turnratelimit'] 164 | fish.direction += fish.turnrate 165 | 166 | # Fix the angles. 167 | if fish.direction > math.pi: 168 | fish.direction -= 2 * math.pi 169 | if fish.direction < -math.pi: 170 | fish.direction += 2 * math.pi 171 | 172 | 173 | class WrapAroundWindowEdges(Behavior): 174 | def apply(self, fish, state): 175 | if fish.position[0] > width: 176 | fish.position[0] = 0 177 | if fish.position[0] < 0: 178 | fish.position[0] = width 179 | if fish.position[1] > height: 180 | fish.position[1] = 0 181 | if fish.position[1] < 0: 182 | fish.position[1] = height 183 | -------------------------------------------------------------------------------- /Sketches/FishesSchooling/fish-schooling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awmartin/spatialpixel/818f2a773ddde8a6d6d77d683093147c3e6a67af/Sketches/FishesSchooling/fish-schooling.png -------------------------------------------------------------------------------- /Sketches/GoogleStreetViewDemo/GoogleStreetView.pyde: -------------------------------------------------------------------------------- 1 | import gsv 2 | 3 | # --------------------------------------------------------------------------------------- 4 | # Parameters 5 | 6 | # The CSV file that contains the lat/lon locations. e.g. "locations2.csv" 7 | # 8 | # Latitude,Longitude 9 | # 40.744312,-73.994425 10 | locations_filename = "sample-locations.csv" 11 | 12 | # Create the filename we want to save as, e.g. streetview-2-90.jpg. 13 | # Just change the name before the "-{0}-{1}.jpg" 14 | output_template = "streetview-{0}-{1}.jpg" 15 | 16 | # Put your Google StreetView API key here. Should look like: AZzaSyAMw219rAW8zEjzQ2_Fz5FPpx9WIJ7D2H9 17 | api_key = "AZzaSyAMw219rAW8zEjzQ2_Fz5FPpx9WIJ7D2H9" 18 | 19 | # --------------------------------------------------------------------------------------- 20 | # Run the code! 21 | 22 | streetview = gsv.GoogleStreetViewPhotos(api_key) 23 | streetview.parseLocations(locations_filename) 24 | streetview.getPhotos(output_template) 25 | -------------------------------------------------------------------------------- /Sketches/GoogleStreetViewDemo/data/sample-locations.csv: -------------------------------------------------------------------------------- 1 | Latitude,Longitude 2 | 40.744312,-73.994425 3 | 40.744312,-73.994425 4 | 40.729919,-73.954635 5 | 40.716932,-74.006955 6 | 40.712042,-73.951064 7 | 40.729116,-73.989539 8 | 40.756632,-73.988681 9 | 40.761524,-73.973383 10 | 40.741084,-73.981912 11 | 40.720858,-73.987259 12 | 40.754993,-73.981952 13 | 40.757561,-73.980101 14 | 40.757561,-73.980101 15 | 40.809289,-73.953721 16 | 40.682913,-73.911017 17 | 40.74393,-73.986691 18 | 40.744634,-73.98773 19 | 40.721741,-73.988103 20 | 40.718108,-74.010427 21 | 40.714001,-73.998506 -------------------------------------------------------------------------------- /Sketches/GoogleStreetViewDemo/gsv.py: -------------------------------------------------------------------------------- 1 | """This script pulls Google StreetView images from their API given a CSV file of locations 2 | specified as latitude/longitude pairs. 3 | 4 | To use this, you'll need to sign up for a Google StreetView API key and provide it at the 5 | bottom of the file along with other parameters needed to run this script. 6 | 7 | You can also include this file as a module in other Processing sketches or Python scripts. 8 | 9 | """ 10 | 11 | import urllib 12 | import csv 13 | 14 | 15 | class GoogleStreetViewPhotos(object): 16 | def __init__(self, api_key): 17 | self.locations = [] 18 | self.api_key = api_key 19 | self.csvdialect = None 20 | self.has_header_row = False 21 | 22 | def addLatLon(self, lat, lon): 23 | self.locations.append((lat, lon)) 24 | 25 | def addLocation(self, location): 26 | self.locations.append(location) 27 | 28 | def provideLocations(self, locations): 29 | self.locations = locations 30 | 31 | def parseLocations(self, filename): 32 | # Open the file and parse it with the csv.reader method. 33 | with open(filename, 'rb') as csvfile: 34 | # Gather some information about the CSV file. 35 | csvsample = csvfile.read(1024) 36 | csvfile.seek(0) 37 | self.csvdialect = csv.Sniffer().sniff(csvsample) 38 | self.has_header_row = csv.Sniffer().has_header(csvsample) 39 | 40 | # Now, set up an object that will enable us to read the CSV file one row at a time. 41 | reader = csv.reader(csvfile, self.csvdialect) 42 | 43 | # Iterate over all the rows, converting the first elements of each row to floats. 44 | # If we're looking at the first row, and the CSV file has a header row, skip it for now. 45 | is_first_row = True 46 | for row in reader: 47 | if self.has_header_row and is_first_row: 48 | is_first_row = False 49 | continue 50 | 51 | # This assumes the first column is latitude and the second is longitude. 52 | lat, lon = float(row[0]), float(row[1]) 53 | 54 | # Store all the locations as tuples of (latitude, longitude) 55 | location = (lat, lon) 56 | self.addLocation(location) 57 | 58 | def getPhotos(self, template): 59 | if len(self.locations) == 0: 60 | print "This doesn't have any locations available. " + \ 61 | "You can either provide a file with parseLocations() or " + \ 62 | "add locations manually with addLocation()." 63 | return 64 | 65 | # Prepare the URL template. 66 | # TODO: Parameterize this. 67 | url_template = "https://maps.googleapis.com/maps/api/streetview" + \ 68 | "?size=640x400" + \ 69 | "&location={0},{1}" + \ 70 | "&fov=90" + \ 71 | "&heading={2}" + \ 72 | "&pitch=10" + \ 73 | "&key={3}" 74 | 75 | row = 2 if self.has_header_row else 1 76 | headings = [0, 90, 180, 270] 77 | 78 | # Loop over every location, and for each location, loop over all the possible headings. 79 | for location in self.locations: 80 | for dir in headings: 81 | # Create the URL for the request to Google. 82 | lat, lon = location 83 | url = url_template.format(lat, lon, dir, self.api_key) 84 | 85 | # Create the filename as well. 86 | filename = template.format(row, dir) 87 | 88 | # Use urllib.urlretrieve to send the request and save the response to a file. 89 | # TODO: Generalize this so a user can get a PImage or write the file or whatever. 90 | urllib.urlretrieve(url, filename) 91 | 92 | # Increment the row to correlate with the row number in the CSV file. 93 | row += 1 -------------------------------------------------------------------------------- /Sketches/Graphics/Particles_Ribbons/Interaction.pde: -------------------------------------------------------------------------------- 1 | 2 | boolean looping = true; 3 | void keyPressed(){ 4 | if( key == 'p' ){ 5 | // Toggle the animation on or off. 6 | if( looping ){ 7 | looping = false; 8 | noLoop(); 9 | } else { 10 | looping = true; 11 | loop(); 12 | } 13 | 14 | } 15 | else 16 | if (key == 'r'){ 17 | // Resets the entire simulation. 18 | initialize(); 19 | 20 | } 21 | else 22 | if (key == 'f'){ 23 | // Reverses the attractive/repulsive forces. 24 | flip(); 25 | } 26 | } 27 | 28 | /** 29 | * Reverses the attractive forces to become repulsive, and vice versa. 30 | */ 31 | void flip(){ 32 | for( int i=0; i nodes = new ArrayList(); 29 | 30 | 31 | // -------------------------------------------------------------------------------- 32 | 33 | void setup(){ 34 | size( 1200, 600 ); 35 | ps = new ParticleSystem( 0, DRAG ); 36 | 37 | smooth(); 38 | colorMode( HSB ); 39 | 40 | initialize(); 41 | } 42 | 43 | void draw(){ 44 | for( int i=0; i cells = new ArrayList(); 7 | 8 | 9 | void setup() { 10 | size(1100, 800); 11 | 12 | ps = new ParticleSystem(0, 1.5); 13 | 14 | initialize(); 15 | 16 | controls = new Interface(this); 17 | controls.addSlider("minDeathTime"); 18 | controls.addSlider("maxDeathTime"); 19 | controls.addSlider("minGrowthInterval"); 20 | controls.addSlider("maxGrowthInterval"); 21 | controls.addSlider("maxNodePopulation", 1, 300); 22 | controls.addSlider("systemDrag", 0.0, 2.5, 1.5); 23 | controls.addButton("reset"); 24 | 25 | noStroke(); 26 | fill(0); 27 | } 28 | 29 | void initialize() { 30 | cells.add(new Cell(width / 2, height / 2)); 31 | } 32 | 33 | void systemDrag(float newDrag) { 34 | ps.setDrag(newDrag); 35 | } 36 | 37 | void reset(float dummy) { 38 | cells.clear(); 39 | ps.clear(); 40 | initialize(); 41 | } 42 | 43 | void draw() { 44 | background(255); 45 | 46 | for (int i = 0; i < cells.size(); i ++) { 47 | Cell c = cells.get(i); 48 | c.tick(); 49 | c.draw(); 50 | } 51 | 52 | for (int i = 0; i < cells.size(); i ++) { 53 | Cell c = cells.get(i); 54 | c.checkForDeath(); 55 | } 56 | 57 | ps.tick(); 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_Mitosis/Cell.pde: -------------------------------------------------------------------------------- 1 | 2 | float CELL_RADIUS = 10; 3 | float CELL_PARTICLE_MASS = 1; 4 | float CELL_ATTRACTION = 20; 5 | float CELL_REPULSION = -30; 6 | 7 | int maxCellPopulation = 200; 8 | int minDeathTime = 30; 9 | int maxDeathTime = 80; 10 | int minGrowthInterval = 20; 11 | int maxGrowthInterval = 40; 12 | 13 | 14 | class Cell { 15 | Particle p; 16 | int timeToDie; 17 | int timeToReproduce; 18 | float radius; 19 | ArrayList attractions; 20 | boolean shouldDie; 21 | 22 | Cell(float x, float y) { 23 | this.p = ps.makeParticle(CELL_PARTICLE_MASS, x, y, 0.0); 24 | 25 | this.radius = CELL_RADIUS; 26 | this.attractions = new ArrayList(); 27 | this.shouldDie = false; 28 | 29 | this.timeToDie = int(random(minDeathTime, maxDeathTime)); 30 | resetReproductionTime(); 31 | } 32 | 33 | void resetReproductionTime() { 34 | this.timeToReproduce = int(random(minGrowthInterval, maxGrowthInterval)); 35 | } 36 | 37 | void reproduce(){ 38 | if (cells.size() > maxCellPopulation) return; 39 | 40 | float x = this.p.position().x(); 41 | float y = this.p.position().y(); 42 | 43 | Cell c = new Cell(x + random(-1, 1), y + random(-1, 1)); 44 | cells.add(c); 45 | 46 | for (int i = 0; i < cells.size(); i ++) { 47 | Cell other = cells.get(i); 48 | if (other.p != c.p) { 49 | // Attraction a1 = ps.makeAttraction(other.p, c.p, CELL_ATTRACTION, this.radius * 2); 50 | // other.attractions.add(a1); 51 | // c.attractions.add(a1); 52 | 53 | Attraction a2 = ps.makeAttraction(other.p, c.p, CELL_REPULSION, this.radius / 2); 54 | other.attractions.add(a2); 55 | c.attractions.add(a2); 56 | } 57 | } 58 | } 59 | 60 | void tick() { 61 | this.timeToDie--; 62 | this.timeToReproduce--; 63 | 64 | if (this.timeToDie == 0){ 65 | this.shouldDie = true; 66 | } 67 | else if (this.timeToReproduce == 0) { 68 | this.reproduce(); 69 | resetReproductionTime(); 70 | } 71 | 72 | } 73 | 74 | void checkForDeath() { 75 | if (this.shouldDie) die(); 76 | } 77 | 78 | void die() { 79 | for (int i = 0; i < this.attractions.size(); i ++ ) { 80 | Attraction a = this.attractions.get(i); 81 | ps.removeAttraction(a); 82 | } 83 | ps.removeParticle(this.p); 84 | cells.remove(this); 85 | } 86 | 87 | void draw() { 88 | float x = this.p.position().x(); 89 | float y = this.p.position().y(); 90 | ellipse(x, y, this.radius * 2, this.radius * 2); 91 | } 92 | 93 | } 94 | 95 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_Mitosis/Interface.pde: -------------------------------------------------------------------------------- 1 | import controlP5.*; 2 | 3 | class Interface { 4 | ControlP5 cp5; 5 | int currentHorizontalPosition; 6 | int currentVerticalPosition; 7 | 8 | Interface(PApplet parent) { 9 | this.cp5 = new ControlP5(parent); 10 | 11 | this.currentHorizontalPosition = 20; 12 | this.currentVerticalPosition = 40; 13 | } 14 | 15 | void addSlider(String sliderName){ 16 | int minValue = 0; 17 | int maxValue = 100; 18 | this.cp5.addSlider(sliderName) 19 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 20 | .setRange(minValue, maxValue) 21 | .setColorLabel(color(64)); 22 | this.currentVerticalPosition += 25; 23 | } 24 | 25 | void addSlider(String sliderName, float minValue, float maxValue) { 26 | this.cp5.addSlider(sliderName) 27 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 28 | .setRange(minValue, maxValue) 29 | .setColorLabel(color(64)); 30 | this.currentVerticalPosition += 25; 31 | } 32 | 33 | void addSlider(String sliderName, float minValue, float maxValue, float defaultValue) { 34 | this.cp5.addSlider(sliderName) 35 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 36 | .setRange(minValue, maxValue) 37 | .setColorLabel(color(64)) 38 | .setValue(defaultValue); 39 | this.currentVerticalPosition += 25; 40 | } 41 | 42 | void addButton(String buttonName){ 43 | this.cp5.addButton(buttonName) 44 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 45 | .setValue(0.0); 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_Mitosis/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Mitosis Simulation with Particle Systems 2 | 3 | This first sketch sets up the cell model and placeholder rules about when to "split" or "die." 4 | The growth patterns aren't sophisticated, but once an environment or inter-cellular rules are 5 | coded, it could get more interesting. 6 | 7 | ![](http://spatialpixel.com/wp-content/uploads/2014/01/Biomimicry_Mitosis_01.png) 8 | 9 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFood/Biomimicry_MitosisFood.pde: -------------------------------------------------------------------------------- 1 | import traer.physics.*; 2 | 3 | ParticleSystem ps; 4 | Interface controls; 5 | 6 | ArrayList cells = new ArrayList(); 7 | FoodSource food; 8 | 9 | boolean ENABLE_LIFESPAN = false; 10 | boolean ENABLE_COHESION = true; 11 | 12 | void initialize() { 13 | cells.add(new Cell(width / 2, height / 2)); 14 | } 15 | 16 | void setup() { 17 | size(1100, 800); 18 | colorMode(HSB, 1.0); 19 | 20 | food = new FoodSource(); 21 | ps = new ParticleSystem(0, 1.5); 22 | 23 | initialize(); 24 | 25 | controls = new Interface(this); 26 | 27 | if (ENABLE_LIFESPAN) { 28 | controls.addSlider("minLifespan"); 29 | controls.addSlider("maxLifespan"); 30 | } 31 | 32 | // controls.addSlider("minGrowthInterval"); 33 | // controls.addSlider("maxGrowthInterval"); 34 | 35 | controls.addSlider("maxCellPopulation", 1, 300); 36 | controls.addSlider("systemDrag", 0.0, 2.5, 1.5); 37 | controls.addSlider("eatRate", 0.0, 0.2, 0.01); 38 | controls.addSlider("reproduceAfterEating", 0.0, 0.75, 0.5); 39 | 40 | controls.addButton("reset"); 41 | 42 | noStroke(); 43 | fill(0); 44 | } 45 | 46 | void eatRate(float value){ 47 | for (int i = 0; i < cells.size(); i ++) { 48 | Cell c = cells.get(i); 49 | c.eatRate = value; 50 | } 51 | } 52 | 53 | void reproduceAfterEating(float value){ 54 | for (int i = 0; i < cells.size(); i ++) { 55 | Cell c = cells.get(i); 56 | c.reproduceAfterEating = value; 57 | } 58 | } 59 | 60 | void systemDrag(float newDrag) { 61 | ps.setDrag(newDrag); 62 | } 63 | 64 | void reset(float dummy) { 65 | cells.clear(); 66 | ps.clear(); 67 | food.reset(); 68 | initialize(); 69 | } 70 | 71 | void draw() { 72 | food.draw(); 73 | 74 | for (int i = 0; i < cells.size(); i ++) { 75 | Cell c = cells.get(i); 76 | c.tick(); 77 | c.draw(); 78 | } 79 | 80 | for (int i = 0; i < cells.size(); i ++) { 81 | Cell c = cells.get(i); 82 | c.checkForDeath(); 83 | } 84 | 85 | ps.tick(); 86 | } 87 | 88 | boolean looping = true; 89 | void keyPressed(){ 90 | 91 | if( key == 'p' ){ 92 | // Toggle the animation on or off. 93 | if (looping) { 94 | looping = false; 95 | noLoop(); 96 | } 97 | else { 98 | looping = true; 99 | loop(); 100 | } 101 | } 102 | 103 | if (key == 'r') 104 | reset(0.0); 105 | } 106 | 107 | 108 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFood/Cell.pde: -------------------------------------------------------------------------------- 1 | 2 | float CELL_RADIUS = 6; 3 | float CELL_PARTICLE_MASS = 1; 4 | float CELL_ATTRACTION = 20; 5 | float CELL_REPULSION = -30; 6 | 7 | int maxCellPopulation = 200; 8 | 9 | int minLifespan = 30; 10 | int maxLifespan = 80; 11 | 12 | //int minGrowthInterval = 20; 13 | //int maxGrowthInterval = 40; 14 | 15 | 16 | 17 | class Cell { 18 | Particle p; 19 | 20 | int lifespan; 21 | // int timeToReproduce; 22 | 23 | float radius; 24 | ArrayList attractions; 25 | boolean shouldDie; 26 | float eatRate; 27 | float reproduceAfterEating; 28 | float amountEaten; 29 | 30 | Cell(float x, float y) { 31 | this.p = ps.makeParticle(CELL_PARTICLE_MASS, x, y, 0.0); 32 | 33 | this.radius = CELL_RADIUS; 34 | this.attractions = new ArrayList(); 35 | this.shouldDie = false; 36 | 37 | this.eatRate = 0.01; 38 | this.amountEaten = 0.0; 39 | this.reproduceAfterEating = 0.5; 40 | 41 | if (ENABLE_LIFESPAN) 42 | this.lifespan = int(random(minLifespan, maxLifespan)); 43 | 44 | // resetReproductionTime(); 45 | } 46 | 47 | void resetReproductionTime() { 48 | // this.timeToReproduce = int(random(minGrowthInterval, maxGrowthInterval)); 49 | } 50 | 51 | void reproduce(){ 52 | if (cells.size() > maxCellPopulation) return; 53 | 54 | float x = this.p.position().x(); 55 | float y = this.p.position().y(); 56 | 57 | Cell c = new Cell(x + random(-1, 1), y + random(-1, 1)); 58 | cells.add(c); 59 | 60 | for (int i = 0; i < cells.size(); i ++) { 61 | Cell other = cells.get(i); 62 | if (other.p != c.p) { 63 | if (ENABLE_COHESION){ 64 | Attraction a1 = ps.makeAttraction(other.p, c.p, CELL_ATTRACTION, this.radius * 2); 65 | other.attractions.add(a1); 66 | c.attractions.add(a1); 67 | } 68 | 69 | Attraction a2 = ps.makeAttraction(other.p, c.p, CELL_REPULSION, this.radius / 2); 70 | other.attractions.add(a2); 71 | c.attractions.add(a2); 72 | } 73 | } 74 | } 75 | 76 | void tick() { 77 | if (ENABLE_LIFESPAN) 78 | this.lifespan--; 79 | 80 | // this.timeToReproduce--; 81 | 82 | float x = this.p.position().x(); 83 | float y = this.p.position().y(); 84 | 85 | // Adds a lifespan to the cell. After it lives this long, it dies. 86 | if (ENABLE_LIFESPAN && this.lifespan == 0){ 87 | this.shouldDie = true; 88 | } 89 | else 90 | if (food.getFoodAt(x, y) < 0.0001){ 91 | this.shouldDie = true; 92 | } 93 | // Adds a reproduction time to the Cell. After it lives this long, then it reproduces. 94 | // else if (this.timeToReproduce == 0) { 95 | // this.reproduce(); 96 | // resetReproductionTime(); 97 | // } 98 | else 99 | if (this.amountEaten > this.reproduceAfterEating) { 100 | this.reproduce(); 101 | this.amountEaten = 0.0; 102 | } 103 | 104 | this.amountEaten += this.eatRate; 105 | food.eatAt(x, y, this.eatRate); 106 | } 107 | 108 | void checkForDeath() { 109 | if (this.shouldDie) die(); 110 | } 111 | 112 | void die() { 113 | for (int i = 0; i < this.attractions.size(); i ++ ) { 114 | Attraction a = this.attractions.get(i); 115 | ps.removeAttraction(a); 116 | } 117 | ps.removeParticle(this.p); 118 | cells.remove(this); 119 | } 120 | 121 | void draw() { 122 | float x = this.p.position().x(); 123 | float y = this.p.position().y(); 124 | ellipse(x, y, this.radius * 2, this.radius * 2); 125 | } 126 | 127 | } 128 | 129 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFood/FoodSource.pde: -------------------------------------------------------------------------------- 1 | class FoodSource { 2 | float[] food; 3 | 4 | float[] eatPattern = { 5 | 0.0, 1.0, 1.0, 1.0, 0.0, 6 | 1.0, 1.0, 1.0, 1.0, 1.0, 7 | 1.0, 1.0, 1.0, 1.0, 1.0, 8 | 1.0, 1.0, 1.0, 1.0, 1.0, 9 | 0.0, 1.0, 1.0, 1.0, 0.0 10 | }; 11 | 12 | FoodSource() { 13 | this.food = new float[width * height]; 14 | reset(); 15 | } 16 | 17 | void reset(){ 18 | for (int i=0; i < width * height; i ++) 19 | this.food[i] = 1.0; 20 | } 21 | 22 | boolean isOnScreen(float x, float y){ 23 | return x >= 0 && y >= 0 && x < width && y < height; 24 | } 25 | 26 | float getFoodAt(float x, float y){ 27 | if (isOnScreen(x, y)) { 28 | int index = int(y) * width + int(x); 29 | return this.food[index]; 30 | } else { 31 | return 0.0; 32 | } 33 | } 34 | 35 | void eatAt(float x, float y, float eatRate){ 36 | if (this.getFoodAt(x, y) - eatRate < 0.0){ 37 | if (isOnScreen(x, y)){ 38 | int index = int(y) * width + int(x); 39 | this.food[index] = 0.0; 40 | } 41 | } else { 42 | for (int k=0; k < eatPattern.length; k ++){ 43 | int ex = int(k % 5) - 2; 44 | int ey = int(k / 5) - 2; 45 | if (isOnScreen(x + ex, y + ey)){ 46 | int index = int(y + ey) * width + int(x + ex); 47 | this.food[index] -= eatPattern[k] * eatRate; 48 | } 49 | } 50 | } 51 | } 52 | 53 | void draw(){ 54 | loadPixels(); 55 | for (int i=0; i < width * height; i ++){ 56 | pixels[i] = color(this.food[i], 0.8 * (1.0 - this.food[i]), 1.0); 57 | } 58 | updatePixels(); 59 | } 60 | 61 | } 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFood/Interface.pde: -------------------------------------------------------------------------------- 1 | import controlP5.*; 2 | 3 | class Interface { 4 | ControlP5 cp5; 5 | int currentHorizontalPosition; 6 | int currentVerticalPosition; 7 | 8 | Interface(PApplet parent) { 9 | this.cp5 = new ControlP5(parent); 10 | this.cp5.enableShortcuts(); 11 | 12 | this.currentHorizontalPosition = 20; 13 | this.currentVerticalPosition = 40; 14 | } 15 | 16 | void addSlider(String sliderName){ 17 | int minValue = 0; 18 | int maxValue = 100; 19 | this.cp5.addSlider(sliderName) 20 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 21 | .setRange(minValue, maxValue) 22 | .setColorLabel(color(64)); 23 | this.currentVerticalPosition += 25; 24 | } 25 | 26 | void addSlider(String sliderName, float minValue, float maxValue) { 27 | this.cp5.addSlider(sliderName) 28 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 29 | .setRange(minValue, maxValue) 30 | .setColorLabel(color(64)); 31 | this.currentVerticalPosition += 25; 32 | } 33 | 34 | void addSlider(String sliderName, float minValue, float maxValue, float defaultValue) { 35 | this.cp5.addSlider(sliderName) 36 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 37 | .setRange(minValue, maxValue) 38 | .setColorLabel(color(64)) 39 | .setValue(defaultValue); 40 | this.currentVerticalPosition += 25; 41 | } 42 | 43 | void addButton(String buttonName){ 44 | this.cp5.addButton(buttonName) 45 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 46 | .setValue(0.0); 47 | this.currentVerticalPosition += 40; 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFood/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Mitosis Simulation with Environmental Interaction 2 | 3 | In this simulation, growth is determined by the availablility of "food" in the environment around 4 | the cells. While there is no formal abstraction for "environment" yet, the food itself is modeled 5 | as an array of numbers. Cells eat and reproduce if they eat enough, and then die if they starve. 6 | 7 | ![](http://spatialpixel.com/wp-content/uploads/2014/01/Biomimicry_MitosisFood_01.png) 8 | 9 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFoodPatterns/Biomimicry_MitosisFoodPatterns.pde: -------------------------------------------------------------------------------- 1 | import traer.physics.*; 2 | 3 | ParticleSystem ps; 4 | Interface controls; 5 | 6 | ArrayList cells = new ArrayList(); 7 | FoodSource food; 8 | 9 | boolean ENABLE_LIFESPAN = false; 10 | boolean ENABLE_COHESION = true; 11 | 12 | void initialize() { 13 | cells.add(new Cell(width / 2, height / 2)); 14 | } 15 | 16 | void setup() { 17 | size(1100, 800); 18 | colorMode(HSB, 1.0); 19 | 20 | // food = new SpiralFood(); 21 | food = new CircularHoleFood(); 22 | ps = new ParticleSystem(0, 1.5); 23 | 24 | initialize(); 25 | 26 | controls = new Interface(this); 27 | 28 | if (ENABLE_LIFESPAN) { 29 | controls.addSlider("minLifespan"); 30 | controls.addSlider("maxLifespan"); 31 | } 32 | 33 | controls.addSlider("maxCellPopulation", 1, 300); 34 | controls.addSlider("systemDrag", 0.0, 2.5, 1.5); 35 | controls.addSlider("eatRate", 0.0, 0.2, 0.01); 36 | controls.addSlider("reproduceAfterEating", 0.0, 0.75, 0.5); 37 | 38 | controls.addButton("reset"); 39 | 40 | noStroke(); 41 | fill(0); 42 | } 43 | 44 | void eatRate(float value){ 45 | for (int i = 0; i < cells.size(); i ++) { 46 | Cell n = cells.get(i); 47 | n.eatRate = value; 48 | } 49 | } 50 | 51 | void reproduceAfterEating(float value){ 52 | for (int i = 0; i < cells.size(); i ++) { 53 | Cell n = cells.get(i); 54 | n.reproduceAfterEating = value; 55 | } 56 | } 57 | 58 | void systemDrag(float newDrag) { 59 | ps.setDrag(newDrag); 60 | } 61 | 62 | void reset(float dummy) { 63 | cells.clear(); 64 | ps.clear(); 65 | food.reset(); 66 | initialize(); 67 | } 68 | 69 | void draw() { 70 | food.beginDraw(); 71 | 72 | for (int i = 0; i < cells.size(); i ++) { 73 | Cell n = cells.get(i); 74 | n.tick(); 75 | } 76 | 77 | food.endDraw(); 78 | food.draw(); 79 | 80 | for (int i = 0; i < cells.size(); i ++) { 81 | Cell n = cells.get(i); 82 | n.checkForDeath(); 83 | } 84 | 85 | for (int i = 0; i < cells.size(); i ++) { 86 | Cell n = cells.get(i); 87 | n.draw(); 88 | } 89 | 90 | ps.tick(); 91 | } 92 | 93 | boolean looping = true; 94 | void keyPressed(){ 95 | 96 | if( key == 'p' ){ 97 | // Toggle the animation on or off. 98 | if (looping) { 99 | looping = false; 100 | noLoop(); 101 | } 102 | else { 103 | looping = true; 104 | loop(); 105 | } 106 | } 107 | 108 | if (key == 'r') 109 | reset(0.0); 110 | 111 | if (key == 's') 112 | saveFrame("Biomimicry-MitosisPatterns-####.png"); 113 | 114 | } 115 | 116 | 117 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFoodPatterns/Cell.pde: -------------------------------------------------------------------------------- 1 | 2 | float CELL_RADIUS = 6; 3 | float CELL_PARTICLE_MASS = 1; 4 | float CELL_ATTRACTION = 20; 5 | float CELL_REPULSION = -30; 6 | 7 | int maxCellPopulation = 200; 8 | 9 | int minLifespan = 30; 10 | int maxLifespan = 80; 11 | 12 | 13 | class Cell { 14 | Particle p; 15 | 16 | int lifespan; 17 | 18 | float radius; 19 | ArrayList attractions; 20 | boolean shouldDie; 21 | float eatRate; 22 | float reproduceAfterEating; 23 | float amountEaten; 24 | 25 | Cell(float x, float y) { 26 | this.p = ps.makeParticle(CELL_PARTICLE_MASS, x, y, 0.0); 27 | 28 | this.radius = CELL_RADIUS; 29 | this.attractions = new ArrayList(); 30 | this.shouldDie = false; 31 | 32 | this.eatRate = 0.01; 33 | this.amountEaten = 0.0; 34 | this.reproduceAfterEating = 0.5; 35 | 36 | if (ENABLE_LIFESPAN) 37 | this.lifespan = int(random(minLifespan, maxLifespan)); 38 | 39 | } 40 | 41 | void reproduce(){ 42 | if (cells.size() > maxCellPopulation) return; 43 | 44 | float x = this.p.position().x(); 45 | float y = this.p.position().y(); 46 | 47 | Cell c = new Cell(x + random(-1, 1), y + random(-1, 1)); 48 | cells.add(c); 49 | 50 | for (int i = 0; i < cells.size(); i ++) { 51 | Cell other = cells.get(i); 52 | if (other.p != c.p) { 53 | if (ENABLE_COHESION){ 54 | Attraction a1 = ps.makeAttraction(other.p, c.p, CELL_ATTRACTION, this.radius * 2); 55 | other.attractions.add(a1); 56 | c.attractions.add(a1); 57 | } 58 | 59 | Attraction a2 = ps.makeAttraction(other.p, c.p, CELL_REPULSION, this.radius / 2); 60 | other.attractions.add(a2); 61 | c.attractions.add(a2); 62 | } 63 | } 64 | } 65 | 66 | void tick() { 67 | if (ENABLE_LIFESPAN) 68 | this.lifespan--; 69 | 70 | float x = this.p.position().x(); 71 | float y = this.p.position().y(); 72 | 73 | // Adds a lifespan to the cell. After it lives this long, it dies. 74 | if (ENABLE_LIFESPAN && this.lifespan == 0){ 75 | this.shouldDie = true; 76 | } 77 | else 78 | if (food.getFoodAt(x, y) < 0.01){ 79 | this.shouldDie = true; 80 | } 81 | else 82 | if (this.amountEaten > this.reproduceAfterEating) { 83 | this.reproduce(); 84 | this.amountEaten = 0.0; 85 | } 86 | 87 | this.amountEaten += this.eatRate; 88 | food.eatAt(x, y, this.eatRate); 89 | } 90 | 91 | void checkForDeath() { 92 | if (this.shouldDie) die(); 93 | } 94 | 95 | void die() { 96 | for (int i = 0; i < this.attractions.size(); i ++ ) { 97 | Attraction a = this.attractions.get(i); 98 | ps.removeAttraction(a); 99 | } 100 | ps.removeParticle(this.p); 101 | cells.remove(this); 102 | } 103 | 104 | void draw() { 105 | float x = this.p.position().x(); 106 | float y = this.p.position().y(); 107 | ellipse(x, y, this.radius * 2, this.radius * 2); 108 | } 109 | 110 | } 111 | 112 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFoodPatterns/FoodSource.pde: -------------------------------------------------------------------------------- 1 | class SpiralFood extends FoodSource { 2 | SpiralFood() { 3 | this.food = createGraphics(width, height); 4 | reset(); 5 | } 6 | 7 | void setFood(){ 8 | 9 | this.food.background(0.5, 0, 0); 10 | this.food.blendMode(BLEND); 11 | this.food.fill(1.0); 12 | this.food.noStroke(); 13 | 14 | for (float r = 0; r < TWO_PI * 4; r += 0.01) { 15 | float x = 15 * r * cos(r) + width / 2; 16 | float y = 15 * r * sin(r) + height / 2; 17 | this.food.ellipse(x, y, 50, 50); 18 | } 19 | 20 | } 21 | } 22 | 23 | class CircularHoleFood extends FoodSource { 24 | CircularHoleFood() { 25 | this.food = createGraphics(width, height); 26 | reset(); 27 | } 28 | 29 | void setFood(){ 30 | this.food.background(1.0); 31 | this.food.blendMode(BLEND); 32 | this.food.fill(0.5, 0, 0); 33 | this.food.noStroke(); 34 | 35 | int holeSize = 100; 36 | this.food.ellipse(width / 2 - holeSize / 2, height / 2 - holeSize / 2, holeSize, holeSize); 37 | } 38 | } 39 | 40 | class FoodSource { 41 | PGraphics food; 42 | 43 | FoodSource() { 44 | this.food = createGraphics(width, height); 45 | reset(); 46 | } 47 | 48 | void setFood(){ 49 | this.food.background(1.0, 1.0, 1.0); 50 | } 51 | 52 | void reset(){ 53 | this.food.beginDraw(); 54 | this.food.colorMode(RGB, 1.0); 55 | this.food.noStroke(); 56 | 57 | this.setFood(); 58 | 59 | this.food.blendMode(DIFFERENCE); 60 | this.food.rectMode(CENTER); 61 | this.food.endDraw(); 62 | } 63 | 64 | boolean isOnScreen(float x, float y){ 65 | return x >= 0 && y >= 0 && x < width && y < height; 66 | } 67 | 68 | float getFoodAt(float x, float y){ 69 | if (isOnScreen(x, y)) { 70 | this.food.loadPixels(); 71 | color c = this.food.pixels[int(y) * width + int(x)]; 72 | float tr = green(c); 73 | return tr; 74 | } else { 75 | return 0.0; 76 | } 77 | } 78 | 79 | void beginDraw(){ 80 | this.food.beginDraw(); 81 | } 82 | 83 | void endDraw(){ 84 | this.food.endDraw(); 85 | } 86 | 87 | void eatAt(float x, float y, float eatRate){ 88 | this.food.fill(eatRate, eatRate, eatRate); 89 | this.food.ellipse(x, y, 5.0, 5.0); 90 | } 91 | 92 | void draw(){ 93 | loadPixels(); 94 | this.food.loadPixels(); 95 | System.arraycopy( this.food.pixels, 0, pixels, 0, pixels.length ); 96 | updatePixels(); 97 | } 98 | 99 | } 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFoodPatterns/Interface.pde: -------------------------------------------------------------------------------- 1 | import controlP5.*; 2 | 3 | class Interface { 4 | ControlP5 cp5; 5 | int currentHorizontalPosition; 6 | int currentVerticalPosition; 7 | 8 | Interface(PApplet parent) { 9 | this.cp5 = new ControlP5(parent); 10 | this.cp5.enableShortcuts(); 11 | 12 | this.currentHorizontalPosition = 20; 13 | this.currentVerticalPosition = 40; 14 | } 15 | 16 | void addSlider(String sliderName){ 17 | int minValue = 0; 18 | int maxValue = 100; 19 | this.cp5.addSlider(sliderName) 20 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 21 | .setRange(minValue, maxValue) 22 | .setColorLabel(color(64)); 23 | this.currentVerticalPosition += 25; 24 | } 25 | 26 | void addSlider(String sliderName, float minValue, float maxValue) { 27 | this.cp5.addSlider(sliderName) 28 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 29 | .setRange(minValue, maxValue) 30 | .setColorLabel(color(64)); 31 | this.currentVerticalPosition += 25; 32 | } 33 | 34 | void addSlider(String sliderName, float minValue, float maxValue, float defaultValue) { 35 | this.cp5.addSlider(sliderName) 36 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 37 | .setRange(minValue, maxValue) 38 | .setColorLabel(color(64)) 39 | .setValue(defaultValue); 40 | this.currentVerticalPosition += 25; 41 | } 42 | 43 | void addButton(String buttonName){ 44 | this.cp5.addButton(buttonName) 45 | .setPosition(this.currentHorizontalPosition, this.currentVerticalPosition) 46 | .setValue(0.0); 47 | this.currentVerticalPosition += 40; 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Sketches/Simulation/Biomimicry_MitosisFoodPatterns/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Mitosis Simulation with Patterns of Food 2 | 3 | In this simulation, the environment's food resource can be laid out. You can "draw" food onto 4 | the virtual petri dish, then watch as the cells grow around obstacles or down paths. 5 | 6 | ![](http://spatialpixel.com/wp-content/uploads/2014/01/Biomimicry-MitosisPatterns-3104.png) 7 | 8 | -------------------------------------------------------------------------------- /Sketches/Simulation/README.md: -------------------------------------------------------------------------------- 1 | # Simulation 2 | 3 | Sketches in this category all attempt to model some real-world phenomenon in a succinct and 4 | purposefully reductionist way. 5 | 6 | Some are frameworks for exploring differnet kinds of behaviors, like agent behavior under 7 | environmental conditions or constraints, or some to demonstrate emergent properties. 8 | 9 | -------------------------------------------------------------------------------- /Sketches/SlippyMapperDemo/SlippyMapperDemo.pyde: -------------------------------------------------------------------------------- 1 | import spatialpixel.mapping.slippymapper as slippymapper 2 | import spatialpixel.data.kml as kml 3 | import spatialpixel.data.geojson as geojson 4 | import spatialpixel.google.directions as directions 5 | 6 | import spatialpixel.ui.panner as panner 7 | import spatialpixel.ui.interface as interface 8 | import spatialpixel.ui.button as button 9 | import spatialpixel.ui.dropdown as dropdown 10 | 11 | import csv 12 | 13 | 14 | def setup(): 15 | size(1000, 800, P2D) 16 | 17 | # Create a new slippy map, centered at Lower Manhattan, at zoom level 12. 18 | # Make it twice the size of the sketch window. Pick a renderer. For more renders, check slippymapper.py. 19 | global slippy 20 | slippy = slippymapper.SlippyMapper(40.714728, -73.998672, 12, 'carto-light', width*2, height*2) 21 | 22 | # Adding simple text markers. 23 | slippy.addMarker(40.808238, -73.959277, "Avery GSAPP") 24 | slippy.addMarker(40.689220, -74.044359, "Statue of Liberty") 25 | slippy.addMarker(40.660212, -73.968962, "Prospect Park") 26 | 27 | # An example running route from mapmyrun.com. 28 | # slippy.addLayer(geojson.SlippyLayer("route1762551746.geojson")) 29 | 30 | # To view the earthquakes sample, try setting the map zoom above to 3. 31 | # slippy.addLayer(geojson.SlippyLayer("earthquakes_all_day_20170921.geojson")) 32 | 33 | # If you download your Location History from Google, you can export as KML and attempt to load it here. 34 | # It currently shows the locations it contains as points. 35 | # slippy.addLayer(kml.SlippyLayer("location-history-sample.kml")) 36 | 37 | 38 | # Render all the different ways you can get from point a to b. 39 | apiKey = '' 40 | a = (40.808238, -73.959277) 41 | b = (40.745530, -73.946631) 42 | trip = directions.SlippyLayer(apiKey) 43 | 44 | trip.addRoute(a, b, 'bicycling', strokeColor=color(0,255,0)) 45 | trip.addRoute(a, b, 'walking', strokeColor=color(0,0,255)) 46 | trip.addRoute(a, b, 'driving', strokeColor=color(255,0,0)) 47 | trip.addRoute(a, b, 'transit', strokeColor=color(0,255,255)) 48 | 49 | slippy.addLayer(trip) 50 | 51 | 52 | # Speculate on routes taken by actual Citibike customers. 53 | 54 | # citibike = directions.SlippyLayer(apiKey) 55 | # slippy.addLayer(citibike) 56 | # 57 | # with open('citibike.csv') as f: 58 | # reader = csv.reader(f) 59 | # header = reader.next() 60 | # 61 | # for row in reader: 62 | # start_lat = float(row[5]) 63 | # start_lon = float(row[6]) 64 | # a = (start_lat, start_lon) 65 | # 66 | # end_lat = float(row[9]) 67 | # end_lon = float(row[10]) 68 | # b = (end_lat, end_lon) 69 | # 70 | # citibike.addRoute(a, b, 'bicycling', strokeColor=color(255)) 71 | 72 | 73 | # Render the map. Since this is expensive, we should be explicit about when this happens. 74 | slippy.render() 75 | 76 | # Create a panner to provide a convenient panning interaction. 77 | # Offset the map such that the center of the slippy map shows up in the center of the sketch. 78 | global pan 79 | pan = panner.Panner(this, x=-(slippy.width - width)/2, y=-(slippy.height - height)/2) 80 | 81 | global ui 82 | ui = interface.Interface(this) 83 | ui.addControl(button.Button('zoomin', zoomIn, "+", (30, 30), (10, 40))) 84 | ui.addControl(button.Button('zoomout', zoomOut, "-", (30, 30), (10, 75))) 85 | ui.addControl(dropdown.DropDown("tileserver", slippymapper.tile_servers, 86 | getServer, setServer, 87 | size=(150, 20), position=(width-160, 10)) 88 | ) 89 | 90 | 91 | def draw(): 92 | background(255) 93 | 94 | pushMatrix() 95 | pan.pan() 96 | slippy.draw() 97 | # drawExample() 98 | popMatrix() 99 | 100 | drawGui() 101 | 102 | 103 | def drawExample(): 104 | # An example of how to draw something in the space of the map. 105 | stroke(255,0,0) 106 | noFill() 107 | 108 | # Calculate the coordinates of a point in pixel space. 109 | jfk_y = slippy.latToY(40.6413) 110 | jfk_x = slippy.lonToX(-73.7781) 111 | ellipse(jfk_x, jfk_y, 50, 50) 112 | 113 | lga_y = slippy.latToY(40.7769) 114 | lga_x = slippy.lonToX(-73.8740) 115 | ellipse(lga_x, lga_y, 50, 50) 116 | 117 | # Just draw a line between LGA and JFK for fun. 118 | line(lga_x, lga_y, jfk_x, jfk_y) 119 | 120 | 121 | # -------------------------------------------------------------------------------------- 122 | # Interaction 123 | 124 | def mouseClicked(): 125 | ui.click() 126 | 127 | def mouseDragged(): 128 | pan.drag() 129 | 130 | def keyPressed(): 131 | lat = slippy.yToLat(height / 2 - pan.panY) 132 | lon = slippy.xToLon(width / 2 - pan.panX) 133 | 134 | if key in ("=", "+"): 135 | zoomIn() 136 | 137 | elif key in ("-", "_"): 138 | zoomOut() 139 | 140 | elif key in ("r", " "): # Recenter the map 141 | slippy.setCenter(lat, lon) 142 | pan.reset() 143 | slippy.render() 144 | 145 | elif key == 'e': 146 | print "Exporting the entire map to output/slippymap.png..." 147 | slippy.save("output/slippymap.png") 148 | print "Done exporting." 149 | 150 | elif key == 'b': 151 | print "Exporting the basemap only to output/basemap.png..." 152 | slippy.baseMap.save("output/basemap.png") 153 | print "Done exporting." 154 | 155 | def zoomIn(): 156 | lat = slippy.yToLat(height / 2 - pan.panY) 157 | lon = slippy.xToLon(width / 2 - pan.panX) 158 | slippy.setCenter(lat, lon) 159 | slippy.setZoom(slippy.zoom + 1) 160 | pan.reset() 161 | slippy.render() 162 | 163 | def zoomOut(): 164 | lat = slippy.yToLat(height / 2 - pan.panY) 165 | lon = slippy.xToLon(width / 2 - pan.panX) 166 | slippy.setCenter(lat, lon) 167 | slippy.setZoom(slippy.zoom - 1) 168 | pan.reset() 169 | slippy.render() 170 | 171 | # -------------------------------------------------------------------------------------- 172 | # GUI 173 | 174 | def drawGui(): 175 | drawCoordinates() 176 | drawHelp() 177 | ui.draw(mousePressed) 178 | 179 | def drawCoordinates(): 180 | noStroke() 181 | fill(64) 182 | rect(10, 10, 300, 20) 183 | 184 | fill(255) 185 | lat = slippy.yToLat(mouseY - pan.panY) 186 | lon = slippy.xToLon(mouseX - pan.panX) 187 | 188 | text(str(lat) + " x " + str(lon), 15, 25) 189 | 190 | def drawHelp(): 191 | noStroke() 192 | fill(64) 193 | rect(10, height - 29, 400, 20) 194 | 195 | fill(255) 196 | text("+/- to zoom, r to recenter, e to export, b to export the basemap", 15, height - 15) 197 | 198 | def getServer(): 199 | return slippy.server 200 | 201 | def setServer(server): 202 | slippy.setServer(server) 203 | slippy.render() 204 | -------------------------------------------------------------------------------- /Sketches/SlippyMapperDemo/data/citibike.csv: -------------------------------------------------------------------------------- 1 | tripduration,starttime,stoptime,start station id,start station name,start station latitude,start station longitude,end station id,end station name,end station latitude,end station longitude,bikeid,usertype,birth year,gender 2 | 801,2/1/2015 0:00,2/1/2015 0:14,521,8 Ave & W 31 St,40.75044999,-73.99481051,423,W 54 St & 9 Ave,40.76584941,-73.98690506,17131,Subscriber,1978,2 3 | 379,2/1/2015 0:00,2/1/2015 0:07,497,E 17 St & Broadway,40.73704984,-73.99009296,504,1 Ave & E 15 St,40.73221853,-73.98165557,21289,Subscriber,1993,1 4 | 2474,2/1/2015 0:01,2/1/2015 0:42,281,Grand Army Plaza & Central Park S,40.7643971,-73.97371465,127,Barrow St & Hudson St,40.73172428,-74.00674436,18903,Subscriber,1969,2 5 | 818,2/1/2015 0:01,2/1/2015 0:15,2004,6 Ave & Broome St,40.724399,-74.004704,505,6 Ave & W 33 St,40.74901271,-73.98848395,21044,Subscriber,1985,2 6 | 544,2/1/2015 0:01,2/1/2015 0:10,323,Lawrence St & Willoughby St,40.69236178,-73.98631746,83,Atlantic Ave & Fort Greene Pl,40.68382604,-73.97632328,19868,Subscriber,1957,1 7 | 717,2/1/2015 0:02,2/1/2015 0:14,373,Willoughby Ave & Walworth St,40.69331716,-73.95381995,2002,Wythe Ave & Metropolitan Ave,40.716887,-73.963198,15854,Subscriber,1979,1 8 | 1306,2/1/2015 0:04,2/1/2015 0:26,352,W 56 St & 6 Ave,40.76340613,-73.97722479,504,1 Ave & E 15 St,40.73221853,-73.98165557,15173,Subscriber,1983,1 9 | 913,2/1/2015 0:04,2/1/2015 0:19,439,E 4 St & 2 Ave,40.7262807,-73.98978041,116,W 17 St & 8 Ave,40.74177603,-74.00149746,17862,Subscriber,1955,1 10 | 759,2/1/2015 0:04,2/1/2015 0:17,335,Washington Pl & Broadway,40.72903917,-73.99404649,2012,E 27 St & 1 Ave,40.739445,-73.976806,21183,Subscriber,1985,2 11 | 585,2/1/2015 0:05,2/1/2015 0:15,284,Greenwich Ave & 8 Ave,40.73901691,-74.00263761,444,Broadway & W 24 St,40.7423543,-73.98915076,14843,Subscriber,1982,1 12 | 581,2/1/2015 0:05,2/1/2015 0:15,284,Greenwich Ave & 8 Ave,40.73901691,-74.00263761,444,Broadway & W 24 St,40.7423543,-73.98915076,16936,Subscriber,1988,2 13 | 204,2/1/2015 0:05,2/1/2015 0:08,498,Broadway & W 32 St,40.74854862,-73.98808416,472,E 32 St & Park Ave,40.7457121,-73.98194829,21507,Subscriber,1991,2 14 | 1169,2/1/2015 0:07,2/1/2015 0:27,368,Carmine St & 6 Ave,40.73038599,-74.00214988,307,Canal St & Rutgers St,40.71427487,-73.98990025,17456,Subscriber,1982,2 15 | 419,2/1/2015 0:07,2/1/2015 0:14,326,E 11 St & 1 Ave,40.72953837,-73.98426726,2012,E 27 St & 1 Ave,40.739445,-73.976806,14679,Subscriber,1990,2 16 | 527,2/1/2015 0:09,2/1/2015 0:17,285,Broadway & E 14 St,40.73454567,-73.99074142,212,W 16 St & The High Line,40.74334935,-74.00681753,18978,Subscriber,1977,1 17 | 1013,2/1/2015 0:10,2/1/2015 0:27,368,Carmine St & 6 Ave,40.73038599,-74.00214988,488,W 39 St & 9 Ave,40.75645824,-73.99372222,16496,Subscriber,1968,1 18 | 587,2/1/2015 0:13,2/1/2015 0:23,394,E 9 St & Avenue C,40.72521311,-73.97768752,331,Pike St & Monroe St,40.71173107,-73.99193043,17107,Subscriber,1990,1 19 | 525,2/1/2015 0:13,2/1/2015 0:22,326,E 11 St & 1 Ave,40.72953837,-73.98426726,507,E 25 St & 2 Ave,40.73912601,-73.97973776,16984,Subscriber,1987,1 20 | 670,2/1/2015 0:14,2/1/2015 0:26,493,W 45 St & 6 Ave,40.7568001,-73.98291153,305,E 58 St & 3 Ave,40.76095756,-73.96724467,15997,Subscriber,1980,1 21 | -------------------------------------------------------------------------------- /Sketches/SlippyMapperDemo/data/location-history-sample.kml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1 6 | 7 | clampToGround 8 | 2016-05-25T01:37:15Z 9 | -73.95967759999999 40.799464799999996 0 10 | 2016-05-25T01:36:14Z 11 | -73.962249 40.7936604 0 12 | 2016-05-25T01:32:34Z 13 | -73.96849379999999 40.7859088 0 14 | 2016-05-25T01:30:04Z 15 | -73.9809827 40.770091699999995 0 16 | 2016-05-25T01:29:03Z 17 | -73.982652 40.767544400000006 0 18 | 2016-05-25T01:27:29Z 19 | -73.9798808 40.761291899999996 0 20 | 2016-05-25T01:26:57Z 21 | -73.9822092 40.7630313 0 22 | 2016-05-25T01:26:25Z 23 | -73.9811205 40.76297290000001 0 24 | 2016-05-25T01:24:42Z 25 | -73.9810746 40.759223299999995 0 26 | 2016-05-25T01:24:11Z 27 | -73.9815796 40.758484599999996 0 28 | 2016-05-25T01:21:06Z 29 | -73.9877346 40.7488528 0 30 | 2016-05-25T01:19:27Z 31 | -73.98809609999999 40.7486643 0 32 | 2016-05-25T01:18:27Z 33 | -73.9880957 40.748524499999995 0 34 | 2016-05-25T01:17:57Z 35 | -73.9880423 40.7485855 0 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Sketches/SlippyMapperSubwayStations/SlippyMapperSubwayStations.pyde: -------------------------------------------------------------------------------- 1 | import spatialpixel.mapping.slippymapper as slippymapper 2 | import csv 3 | 4 | 5 | def setup(): 6 | size(1000, 800, P2D) 7 | 8 | global pin 9 | pin = loadImage("https://s3.amazonaws.com/spatialpixel/maps/map-pin-10px.png") 10 | 11 | global nyc 12 | nyc = slippymapper.SlippyMapper(40.714728, -73.898672, 11, 'carto-dark', width, height) 13 | 14 | with open('StationEntrances.csv') as f: 15 | reader = csv.reader(f) 16 | header = reader.next() 17 | 18 | for row in reader: 19 | latitude = float(row[3]) 20 | longitude = float(row[4]) 21 | 22 | # Simple marker examples, prepackaged in slippymapper. 23 | # nyc.addMarker(latitude, longitude) 24 | 25 | # You can even add a PImage directly. 26 | nyc.addMarker(latitude, longitude, pin) 27 | 28 | # Create a marker object so you can customize them. 29 | # circle = slippymapper.CircleMarker(5) 30 | # circle.stroke(255, 0, 0) 31 | # circle.noFill() 32 | # nyc.addMarker(latitude, longitude, circle) 33 | 34 | # TextMarker class (and other markers) can accept a color directly in its constructor. 35 | # nyc.addMarker(latitude, longitude, slippymapper.TextMarker(row[2], color(255))) 36 | 37 | # There's also a class for an X-shaped marker. 38 | # nyc.addMarker(latitude, longitude, slippymapper.CrossMarker(3)) 39 | 40 | # Provide a function to draw an arbitrary marker. 41 | # nyc.addMarker(latitude, longitude, drawPin) 42 | 43 | # An interactive marker also drawn with a function. 44 | # nyc.addMarker(latitude, longitude, drawCross) 45 | 46 | # Custom interactive marker by subclassing DataMarker. Here, you can make a marker 47 | # by providing the data to the marker's constructor. 48 | # nyc.addMarker(latitude, longitude, StationMarker(row)) 49 | 50 | nyc.render() 51 | 52 | def draw(): 53 | background(255) 54 | nyc.draw() 55 | 56 | 57 | # Here are some marker drawing functions and classes used in some of the examples above. 58 | # 'marker' is a PGraphics object. 59 | 60 | def drawPin(x, y, marker): 61 | # The pin image we have places the pin's point at the bottom middle. So let's offset the 62 | # image to have x and y centered at the pin's bottom. 63 | marker.image(pin, x - pin.width / 2, y - pin.height) 64 | 65 | def drawCross(x, y, marker): 66 | if dist(x, y, mouseX, mouseY) < 5: 67 | marker.stroke(255, 0, 0) 68 | marker.strokeWeight(4) 69 | marker.line(x - 3, y - 3, x + 3, y + 3) 70 | marker.line(x - 3, y + 3, x + 3, y - 3) 71 | else: 72 | marker.stroke(0, 255, 0) 73 | marker.strokeWeight(1) 74 | marker.line(x - 3, y - 3, x + 3, y + 3) 75 | marker.line(x - 3, y + 3, x + 3, y - 3) 76 | 77 | 78 | class StationMarker(slippymapper.DataMarker): 79 | def drawMarker(self, x, y, marker): 80 | if dist(x, y, mouseX, mouseY) < 5 and mousePressed: 81 | marker.stroke(255, 0, 0) 82 | marker.strokeWeight(4) 83 | marker.line(x - 3, y - 3, x + 3, y + 3) 84 | marker.line(x - 3, y + 3, x + 3, y - 3) 85 | 86 | station_name = self.data[2] 87 | marker.text(station_name, x, y) 88 | else: 89 | marker.stroke(0, 255, 0) 90 | marker.strokeWeight(1) 91 | marker.line(x - 3, y - 3, x + 3, y + 3) 92 | marker.line(x - 3, y + 3, x + 3, y - 3) 93 | -------------------------------------------------------------------------------- /Sketches/SlippyMapperSubwayStations/data/map-pin-10px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awmartin/spatialpixel/818f2a773ddde8a6d6d77d683093147c3e6a67af/Sketches/SlippyMapperSubwayStations/data/map-pin-10px.png -------------------------------------------------------------------------------- /Sketches/SlippyMapperSubwayStations/data/map-pin-15px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awmartin/spatialpixel/818f2a773ddde8a6d6d77d683093147c3e6a67af/Sketches/SlippyMapperSubwayStations/data/map-pin-15px.png -------------------------------------------------------------------------------- /Sketches/SlippyMapperSubwayStations/data/map-pin-20px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awmartin/spatialpixel/818f2a773ddde8a6d6d77d683093147c3e6a67af/Sketches/SlippyMapperSubwayStations/data/map-pin-20px.png -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/Data.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * This module holds helpers that parse CSV data files and loads the Quakes. 3 | */ 4 | 5 | 6 | /** 7 | * Loads a list of earthquake events from a CSV file. 8 | */ 9 | void loadQuakesCSV(String filename){ 10 | String[] quakeStrings = loadStrings(filename); 11 | 12 | String headerRow = quakeStrings[0]; 13 | String[] headers = split(headerRow, ","); 14 | 15 | QuakeParseSchema schema = new QuakeParseSchema(headers); 16 | 17 | for(int i = 1; i < quakeStrings.length; i++){ 18 | String[] quakeData = split(quakeStrings[i], ","); 19 | 20 | quakes.add(new Quake(quakeData, schema)); 21 | } 22 | } 23 | 24 | /** 25 | * Return the index of a string in an array of strings. 26 | */ 27 | int indexOf(String[] haystack, String needle){ 28 | // Search linearly instead of using java.util for future compatibility with Processing.js. 29 | for (int i=0; i quakes = new ArrayList(); 43 | 44 | void drawQuakes(){ 45 | for(int i = 0; i < quakes.size(); i++){ 46 | Quake q = quakes.get(i); 47 | q.draw(); 48 | } 49 | } 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/Globe.pde: -------------------------------------------------------------------------------- 1 | 2 | 3 | // Known from the map size. Initialize here instead of deriving from the PImage 4 | // since the initialization order may not support it well. 5 | final int MAP_WIDTH = 2048; 6 | final int MAP_HEIGHT = 1024; 7 | // Known from looking at the image as well. 8 | final color OCEAN_COLOR = color(54, 140, 173); 9 | 10 | // Represents a single dot on the globe rendering. 11 | class GlobeDot { 12 | float x; 13 | float y; 14 | float colorOffset; 15 | 16 | int dotSize = 4; 17 | 18 | GlobeDot(float x, float y){ 19 | this.x = x; 20 | this.y = y; 21 | this.colorOffset = random(0, 180); 22 | } 23 | 24 | void draw(){ 25 | noStroke(); 26 | // Cycle the fill color. Adds a bit of animated flair. 27 | fill(128 + 64 * cos(this.colorOffset + frameCount/2.0)); 28 | 29 | pushMatrix(); 30 | transformToSphere(this.x, this.y); 31 | ellipse(0, 0, this.dotSize, this.dotSize); 32 | popMatrix(); 33 | } 34 | } 35 | 36 | // Draws a globe where land is represented by a series of dots. 37 | class Globe { 38 | 39 | int colorThreshold = 20; 40 | float dotSpacing = 8; 41 | 42 | boolean showThrough = false; 43 | 44 | PImage worldMap; 45 | ArrayList mapDots; 46 | 47 | float scalePixelsPerLongitude, scalePixelsPerLatitude; 48 | 49 | Globe(String mapFile) { 50 | this.worldMap = loadImage(mapFile); 51 | this.mapDots = new ArrayList(); 52 | 53 | this.scalePixelsPerLongitude = MAP_WIDTH / 360.0; 54 | this.scalePixelsPerLatitude = MAP_HEIGHT / 180.0; 55 | 56 | build(); 57 | } 58 | 59 | // Loop over the map and create a series of dots based on the colors in the world map. 60 | void build(){ 61 | mapDots.clear(); 62 | 63 | for (float y = this.dotSpacing / 2.0; y < MAP_HEIGHT; y += this.dotSpacing){ 64 | 65 | float lat = (y / MAP_HEIGHT) * 180.0 - 90.0; 66 | 67 | // Attempts to put fewer dots near the poles gradually. 68 | float xSpacing = int(abs(this.dotSpacing / cos(radians(abs(lat))))); 69 | 70 | for (float x = xSpacing / 2.0; x < MAP_WIDTH; x += xSpacing){ 71 | 72 | if (!this.isColorClose(worldMap.get(int(x), int(y)))){ 73 | mapDots.add(new GlobeDot(x, y)); 74 | } 75 | } 76 | } 77 | } 78 | 79 | void draw(){ 80 | 81 | // Show a black sphere to cover up the backface of the globe. 82 | if (!this.showThrough && isSphere()){ 83 | noStroke(); 84 | fill(0); 85 | sphere(sphereRadius - 1); 86 | } 87 | 88 | for (int i=0; i < mapDots.size(); i++){ 89 | GlobeDot gDot = mapDots.get(i); 90 | gDot.draw(); 91 | } 92 | } 93 | 94 | boolean isInInterval(float x, float interval){ 95 | return -interval < x && x < interval; 96 | } 97 | 98 | boolean isColorClose( color c ){ 99 | return ( 100 | isInInterval(red(c) - red(OCEAN_COLOR), colorThreshold) && 101 | isInInterval(blue(c) - blue(OCEAN_COLOR), colorThreshold) && 102 | isInInterval(green(c) - green(OCEAN_COLOR), colorThreshold) 103 | ); 104 | } 105 | 106 | void toggleShowThrough(){ 107 | this.showThrough = !this.showThrough; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/Interaction.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Holds Processing event handlers. 3 | * 4 | * +/- Changes the spacing between dots on the globe. 5 | * [space] Toggles the backface rendering of the globe. 6 | * t Toggles between a globe and flat map. 7 | * r Exports a PNG file of the current view. 8 | */ 9 | void keyPressed(){ 10 | if (key == '+' || key == '='){ 11 | globe.dotSpacing += 0.1; 12 | globe.build(); 13 | 14 | } else if (key == '-') { 15 | globe.dotSpacing -= 0.1; 16 | globe.build(); 17 | 18 | } else if (key == ' ') { 19 | globe.toggleShowThrough(); 20 | 21 | } else if (key == 't') { 22 | if (transformState == NOT_TRANSFORMING && isSphere()) { 23 | transformState = TO_FLAT; 24 | transformFrame = 0; 25 | 26 | } else if (transformState == NOT_TRANSFORMING && isFlat()) { 27 | transformState = TO_SPHERE; 28 | transformFrame = 0; 29 | 30 | } 31 | 32 | } else if (key == 'r') { 33 | saveFrame("earthquake-####.png"); 34 | 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/Quake.pde: -------------------------------------------------------------------------------- 1 | final int COLOR_SCALE = 192; 2 | 3 | class Quake { 4 | float latitude; 5 | float longitude; 6 | float magnitude; 7 | float depth; 8 | 9 | Quake(String[] event, QuakeParseSchema schema){ 10 | parseQuakeData(event, schema); 11 | } 12 | 13 | void parseQuakeData(String[] event, QuakeParseSchema schema){ 14 | 15 | this.latitude = schema.getLatitude(event); 16 | this.longitude = schema.getLongitude(event); 17 | this.magnitude = schema.getMagnitude(event); 18 | this.depth = schema.getDepth(event); 19 | 20 | } 21 | 22 | float x(){ 23 | return (this.longitude + 180) * globe.scalePixelsPerLongitude; 24 | } 25 | 26 | float y(){ 27 | return (-this.latitude + 90) * globe.scalePixelsPerLatitude; 28 | } 29 | 30 | void draw(){ 31 | stroke(COLOR_SCALE - this.magnitude / 10.0 * COLOR_SCALE, 255, 255); 32 | strokeWeight(this.magnitude / 10.0 + 1.0); 33 | 34 | pushMatrix(); 35 | transformToSphere(this.x(), this.y()); 36 | 37 | // Draw a line showing the magnitude of the Quake by length. 38 | line(0, 0, 0, 0, 0, pow(magnitude, 1.1) * 10); 39 | popMatrix(); 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/README.md: -------------------------------------------------------------------------------- 1 | # Earthquakes Visualization 2 | 3 | A simple interactive visualization of USGS earthquake data (CSV) found at [http://earthquake.usgs.gov/earthquakes/feed/](http://earthquake.usgs.gov/earthquakes/feed/). 4 | 5 | ![](http://spatialpixel.com/wp-content/uploads/2013/12/earthquakes05.png) 6 | 7 | See the full description on [Spatial Pixel](http://spatialpixel.com/2013/12/simple-earthquake-visualization/). 8 | 9 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/Transformation.pde: -------------------------------------------------------------------------------- 1 | 2 | // Hold some states by name for readability. 3 | final int NOT_TRANSFORMING = 0; 4 | final int TO_SPHERE = 1; 5 | final int TO_FLAT = 2; 6 | 7 | // Variables needed for the spherical-to-flattened animation. 8 | int transformState = NOT_TRANSFORMING; 9 | float transformFactor = 1.0; 10 | int transformFrame = 0; 11 | int framesToTransform = 20; 12 | 13 | int sphereRadius = 500; 14 | 15 | 16 | // Translates a given x and y pixel-space coordinate (2048px by 1024px) into a 17 | // set of transformations onto a sphere. 18 | void transformToSphere(float x, float y){ 19 | float theta = radians((x - MAP_WIDTH / 2) / MAP_WIDTH * 360); 20 | float phi = radians((y - MAP_HEIGHT / 2) / MAP_HEIGHT * 180); 21 | 22 | float xt = sphereRadius * cos(theta) * cos(phi); 23 | float yt = sphereRadius * sin(theta) * cos(phi); 24 | float zt = sphereRadius * sin(phi); 25 | 26 | float flatFactor = 1.0 - transformFactor; 27 | 28 | // Centers the map during the transition. 29 | translate(flatFactor * -MAP_WIDTH / 2, flatFactor * -MAP_HEIGHT / 2); 30 | translate( 31 | xt * transformFactor + flatFactor * x, 32 | yt * transformFactor + flatFactor * y, 33 | zt * transformFactor 34 | ); 35 | rotateZ((theta + HALF_PI) * transformFactor); 36 | rotateX((-phi + HALF_PI) * transformFactor); 37 | } 38 | 39 | boolean isSphere(){ 40 | return transformFactor >= 0.9999; 41 | } 42 | 43 | boolean isFlat(){ 44 | return transformFactor <= 0.0001; 45 | } 46 | 47 | // Handles the transformation from flattened to spherical form. 48 | void stepToSphere(){ 49 | transformFactor += 1.0 / framesToTransform; 50 | transformFrame++; 51 | } 52 | 53 | // Handles stepping the transformation from spherical to flattened form. 54 | void stepToFlat(){ 55 | transformFactor -= 1.0 / framesToTransform; 56 | transformFrame++; 57 | } 58 | 59 | // Handles the transformation from spherical to plane coordinates, and back again. 60 | void handleTransform(){ 61 | if (transformState == TO_SPHERE){ 62 | stepToSphere(); 63 | } else if (transformState == TO_FLAT) { 64 | stepToFlat(); 65 | } 66 | 67 | if (transformFrame >= framesToTransform) { 68 | if (transformState == TO_FLAT) { 69 | transformFactor = 0.0; 70 | } else if (transformState == TO_SPHERE) { 71 | transformFactor = 1.0; 72 | } 73 | transformState = NOT_TRANSFORMING; 74 | } 75 | } 76 | 77 | 78 | -------------------------------------------------------------------------------- /Sketches/Visualization/Earthquakes/data/equirectangular_projection.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awmartin/spatialpixel/818f2a773ddde8a6d6d77d683093147c3e6a67af/Sketches/Visualization/Earthquakes/data/equirectangular_projection.jpg -------------------------------------------------------------------------------- /Sketches/Visualization/README.md: -------------------------------------------------------------------------------- 1 | # Visualization 2 | 3 | Includes sketches that demonstrate basic techniques of data visualization, sometimes with an added twist. 4 | 5 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import data 2 | import google 3 | import mapping 4 | import path 5 | import ui 6 | import util 7 | -------------------------------------------------------------------------------- /data/__init__.py: -------------------------------------------------------------------------------- 1 | import geojson 2 | import kml 3 | -------------------------------------------------------------------------------- /data/geojson/__init__.py: -------------------------------------------------------------------------------- 1 | from geojson import RenderGeoJson 2 | from slippylayer import SlippyLayer 3 | -------------------------------------------------------------------------------- /data/geojson/geojson.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | class RenderGeoJson(object): 5 | def __init__(self, data): 6 | self.data = None 7 | 8 | if isinstance(data, str): 9 | # Hmm, this could be a filename or a string of JSON data. 10 | try: 11 | # Is this a filename? If so, attempt to open the file. 12 | with open(data, 'r') as f: 13 | self.data = json.load(f) 14 | except: 15 | # Attempt to load as a JSON string. 16 | self.data = json.loads(data) 17 | 18 | elif isinstance(data, file): 19 | # If handed a file object, just read it. 20 | self.data = json.load(data) 21 | 22 | elif isinstance(data, dict): 23 | # Assume this is raw GeoJSON. 24 | # TODO Validate GeoJSON format. 25 | self.data = data 26 | 27 | self._elts = [] 28 | self.parse() 29 | 30 | def add_element(self, elt): 31 | self._elts.append(elt) 32 | 33 | @property 34 | def elements(self): 35 | return self._elts or [] 36 | 37 | @property 38 | def features(self): 39 | if 'features' in self.data: 40 | return self.data['features'] or [] 41 | return [] 42 | 43 | def parse(self): 44 | for feature in self.features: # FeatureCollection 45 | geo_type = feature['geometry']['type'] 46 | coords = feature['geometry']['coordinates'] 47 | 48 | if geo_type == "Polygon": 49 | self.add_element(GeoJsonPolygon(coords, feature)) 50 | elif geo_type == "MultiPolygon": 51 | self.add_element(GeoJsonMultiPolygon(coords, feature)) 52 | elif geo_type == "LineString": 53 | self.add_element(GeoJsonLineString(coords, feature)) 54 | elif geo_type == "Point": 55 | self.add_element(GeoJsonPoint(coords, feature)) 56 | elif geo_type == "GeometryCollection": 57 | # TODO GeometryCollection 58 | pass 59 | 60 | def render(self, lonToX, latToY, pgraphics, styler=None): 61 | for elt in self._elts: 62 | shoulddraw = True 63 | 64 | if styler is not None: 65 | shoulddraw = styler(elt.data, pgraphics) 66 | if shoulddraw is None: 67 | shoulddraw = True 68 | 69 | if shoulddraw: 70 | elt.draw(lonToX, latToY, pgraphics) 71 | 72 | def draw(self, lonToX, latToY, styler=None): 73 | self.render(lonToX, latToY, this, styler) 74 | 75 | 76 | class GeoJsonObject(object): 77 | def __init__(self, pts, data=None): 78 | self.pts = pts 79 | self.data = data 80 | 81 | @property 82 | def centroid(self): 83 | return 0, 0 84 | 85 | def draw(self, lonToX, latToY, pgraphics): 86 | pass 87 | 88 | class GeoJsonMultiPolygon(GeoJsonObject): 89 | def __init__(self, coords, data=None): 90 | self.coords = coords 91 | self.data = data 92 | 93 | self.polygons = [] 94 | for pts in self.coords: 95 | polygon = GeoJsonPolygon(pts) 96 | self.polygons.append(polygon) 97 | 98 | @property 99 | def centroid(self): 100 | # return self.polygons[0].centroid 101 | return average([polygon.centroid for polygon in self.polygons]) 102 | 103 | def draw(self, lonToX, latToY, pgraphics): 104 | for polygon in self.polygons: 105 | polygon.draw(lonToX, latToY, pgraphics) 106 | 107 | class GeoJsonPolygon(GeoJsonObject): 108 | def __init__(self, coords, data=None): 109 | self.coords = coords 110 | self.data = data 111 | 112 | self.linestrings = [] 113 | for pts in self.coords: 114 | linestring = GeoJsonLineString(pts) 115 | self.linestrings.append(linestring) 116 | 117 | @property 118 | def centroid(self): 119 | # According to the spec, the first linestring must be the external outline. 120 | return self.linestrings[0].centroid 121 | 122 | def draw(self, lonToX, latToY, pgraphics): 123 | for linestring in self.linestrings: 124 | linestring.draw(lonToX, latToY, pgraphics) 125 | 126 | class GeoJsonLineString(GeoJsonObject): 127 | @property 128 | def centroid(self): 129 | return centroid(self.pts) 130 | 131 | def draw(self, lonToX, latToY, pgraphics): 132 | s = pgraphics.createShape() 133 | s.beginShape() 134 | 135 | for pt in self.pts: 136 | lon, lat = pt[0], pt[1] 137 | s.vertex(lonToX(lon), latToY(lat)) 138 | 139 | s.endShape() 140 | pgraphics.shape(s, 0, 0) 141 | 142 | class GeoJsonPoint(GeoJsonObject): 143 | @property 144 | def centroid(self): 145 | return self.pts 146 | 147 | def draw(self, lonToX, latToY, pgraphics): 148 | lon, lat = self.pts[0], self.pts[1] 149 | pgraphics.ellipse(lonToX(lon), latToY(lat), 3, 3) 150 | 151 | 152 | def average(pts): 153 | lon, lat = 0, 0 154 | for pt in pts: 155 | lon += pt[0] 156 | lat += pt[1] 157 | return lon / len(pts), lat / len(pts) 158 | 159 | # https://en.wikipedia.org/wiki/Centroid under "Centroid of a polygon" 160 | def centroid(pts): 161 | n = len(pts) 162 | if n == 1: 163 | return pts[0][0], pts[0][1] 164 | 165 | A = 0 166 | for i in xrange(0, n - 1): 167 | A += pts[i][0] * pts[i + 1][1] - pts[i + 1][0] * pts[i][1] 168 | A *= 0.5 169 | 170 | lon, lat = 0, 0 171 | for i in xrange(0, n - 1): 172 | b = (pts[i][0] * pts[i + 1][1] - pts[i + 1][0] * pts[i][1]) 173 | lon += (pts[i][0] + pts[i + 1][0]) * b 174 | lat += (pts[i][1] + pts[i + 1][1]) * b 175 | 176 | return lon / (6 * A), lat / (6 * A) 177 | -------------------------------------------------------------------------------- /data/geojson/slippylayer.py: -------------------------------------------------------------------------------- 1 | import geojson 2 | 3 | 4 | def defaultstyler(data, feature): 5 | feature.noFill() 6 | feature.stroke(255, 0, 0) 7 | 8 | class SlippyLayer(object): 9 | '''Creates a SlippyMapper layer for GeoJson objects. 10 | 11 | fileobj - instance of: 12 | str: contains a filename of the geojson file 13 | file: contains a file object for a geojson file 14 | RenderGeoJson: contains a RenderGeoJson instance 15 | ''' 16 | def __init__(self, source, styler=None): 17 | self.source = source 18 | if isinstance(source, geojson.RenderGeoJson): 19 | self.layerObject = source 20 | else: 21 | self.layerObject = geojson.RenderGeoJson(source) 22 | 23 | self.styler = styler if styler is not None else defaultstyler 24 | 25 | self.underlayMap = None 26 | 27 | def setUnderlayMap(self, m): 28 | self.underlayMap = m 29 | 30 | def render(self): 31 | self.layer = createGraphics(self.underlayMap.width, self.underlayMap.height) 32 | self.layer.beginDraw() 33 | self.layerObject.render(self.underlayMap.lonToX, self.underlayMap.latToY, self.layer, self.styler) 34 | self.layer.endDraw() 35 | 36 | def draw(self): 37 | image(self.layer, 0, 0) 38 | -------------------------------------------------------------------------------- /data/kml/__init__.py: -------------------------------------------------------------------------------- 1 | from kml import RenderKML 2 | from slippylayer import SlippyLayer 3 | -------------------------------------------------------------------------------- /data/kml/kml.py: -------------------------------------------------------------------------------- 1 | import xml.etree.ElementTree as ET 2 | 3 | 4 | def defaultkeyer(feature): 5 | return None 6 | 7 | def defaultstyler(key, feature): 8 | feature.noFill() 9 | feature.stroke(255, 0, 0) 10 | 11 | class RenderKML(object): 12 | @classmethod 13 | def open(self, filename, styler=None): 14 | with open(filename) as f: 15 | kml = RenderKML(f, styler=styler) 16 | kml.parse() 17 | return kml 18 | 19 | def __init__(self, xmlfile, styler=None): 20 | self.tree = ET.parse(xmlfile) 21 | self.styler = styler if styler is not None else defaultstyler 22 | self.placemarks = [] 23 | 24 | def render(self, lonToX, latToY, pgraphics): 25 | for placemark in self.placemarks: 26 | self.styler(placemark.placemark, pgraphics) 27 | placemark.draw(lonToX, latToY, pgraphics) 28 | 29 | def draw(self, lonToX, latToY): 30 | for placemark in self.placemarks: 31 | self.styler(placemark, pgraphics) 32 | placemark.draw(lonToX, latToY, this) 33 | 34 | def parse(self): 35 | root = self.tree.getroot() # 36 | for document in root: # 37 | for subitem in document: # subitem == or 38 | if subitem.tag.endswith("Placemark"): 39 | self.parse_placemark(subitem) 40 | elif subitem.tag.endswith("Folder"): 41 | for child in subitem: 42 | if child.tag.endswith("Placemark"): 43 | self.parse_placemark(child) 44 | 45 | # https://developers.google.com/kml/documentation/kmlreference#placemark 46 | def parse_placemark(self, placemark): 47 | self.placemarks.append(KmlPlacemark(placemark)) 48 | 49 | 50 | class KmlPlacemark(object): 51 | def __init__(self, placemark): 52 | self.placemark = placemark 53 | 54 | self.children = [] 55 | self.parse() 56 | 57 | def parse(self): 58 | for child in self.placemark: 59 | geometry = KmlGeometry.parse(child) 60 | if geometry is not None: 61 | self.children.append(geometry) 62 | 63 | def draw(self, lonToX, latToY, pgraphics): 64 | for child in self.children: 65 | child.draw(lonToX, latToY, pgraphics) 66 | 67 | 68 | # https://developers.google.com/kml/documentation/kmlreference#geometry 69 | class KmlGeometry(object): 70 | @classmethod 71 | def parse(self, geometry): 72 | if geometry.tag.endswith("Point"): 73 | return KmlPoint(geometry) 74 | 75 | elif geometry.tag.endswith("LineString"): 76 | return KmlLineString(geometry) 77 | 78 | elif geometry.tag.endswith("LinearRing"): 79 | return KmlLinearRing(geometry) 80 | 81 | elif geometry.tag.endswith("Polygon"): 82 | return KmlPolygon(geometry) 83 | 84 | elif geometry.tag.endswith("MultiGeometry"): 85 | return KmlMultiGeometry(geometry) 86 | 87 | elif geometry.tag.endswith("Track"): # gx:Track ?? 88 | return KmlTrack(geometry) 89 | 90 | return None 91 | 92 | 93 | class KmlPolygon(object): 94 | def __init__(self, element): 95 | self.element = element 96 | self.outer = [] 97 | self.inner = [] 98 | self.parse() 99 | 100 | def draw(self, lonToX, latToY, pgraphics): 101 | # TODO Make Polygon rendering do the right thing with holes. 102 | for child in self.outer: 103 | child.draw(lonToX, latToY, pgraphics) 104 | for child in self.inner: 105 | child.draw(lonToX, latToY, pgraphics) 106 | 107 | # https://developers.google.com/kml/documentation/kmlreference#polygon 108 | def parse(self): 109 | for child in self.element: 110 | if child.tag.endswith("outerBoundaryIs"): 111 | # https://developers.google.com/kml/documentation/kmlreference#outerboundaryis 112 | for subchild in child: 113 | geometry = KmlGeometry.parse(subchild) 114 | if geometry is not None: 115 | self.outer.append(geometry) 116 | elif child.tag.endswith("innerBoundaryIs"): # Can have multiple ones. 117 | # https://developers.google.com/kml/documentation/kmlreference#innerboundaryis 118 | for subchild in child: 119 | geometry = KmlGeometry.parse(child) 120 | if geometry is not None: 121 | self.inner.append(geometry) 122 | 123 | 124 | class KmlMultiGeometry(object): 125 | def __init__(self, element): 126 | self.element = element 127 | self.geometries = [] 128 | self.parse() 129 | 130 | def draw(self, lonToX, latToY, pgraphics): 131 | for geometry in self.geometries: 132 | geometry.draw(lonToX, latToY, pgraphics) 133 | 134 | def parse(self): 135 | for child in self.element: 136 | geometry = KmlGeometry.parse(child) 137 | if geometry is not None: 138 | self.geometries.append(geometry) 139 | 140 | 141 | class KmlLineString(object): 142 | def __init__(self, element): 143 | self.element = element 144 | self.points = [] 145 | self.parse() 146 | 147 | def draw(self, lonToX, latToY, pgraphics): 148 | s = pgraphics.createShape() 149 | s.beginShape() 150 | for pt in self.points: 151 | x = lonToX(pt[0]) 152 | y = latToY(pt[1]) 153 | s.vertex(x, y) 154 | s.endShape() 155 | pgraphics.shape(s, 0, 0) 156 | 157 | def parse(self): 158 | for subchild in self.element: 159 | if subchild.tag.endswith("coordinates"): 160 | coordinates_text = subchild.text 161 | self.points = parse_coordinates(coordinates_text) 162 | 163 | 164 | class KmlLinearRing(object): 165 | def __init__(self, element): 166 | self.element = element 167 | self.points = [] 168 | self.parse() 169 | 170 | def draw(self, lonToX, latToY, pgraphics): 171 | s = pgraphics.createShape() 172 | s.beginShape() 173 | for pt in self.points: 174 | x = lonToX(pt[0]) 175 | y = latToY(pt[1]) 176 | s.vertex(x, y) 177 | s.endShape(pgraphics.CLOSE) 178 | pgraphics.shape(s, 0, 0) 179 | 180 | def parse(self): 181 | for subchild in self.element: 182 | if subchild.tag.endswith("coordinates"): 183 | coordinates_text = subchild.text 184 | self.points = parse_coordinates(coordinates_text) 185 | 186 | 187 | class KmlTrack(object): 188 | def __init__(self, element): 189 | self.element = element 190 | self.waypoints = [] 191 | self.parse() 192 | 193 | def draw(self, lonToX, latToY, pgraphics): 194 | for waypoint in self.waypoints: 195 | waypoint.draw(lonToX, latToY, pgraphics) 196 | 197 | def parse(self): 198 | for entry in self.element: 199 | tag = entry.tag.strip() 200 | if tag.endswith("AltitudeMode"): 201 | pass 202 | elif tag.endswith("when"): 203 | pass 204 | elif tag.endswith("coord"): 205 | pt = parse_lonlat(entry.text, separator=" ") 206 | self.waypoints.append(KmlWayPoint(pt)) 207 | 208 | 209 | class KmlWayPoint(object): 210 | def __init__(self, lonlat): 211 | self.lonlat = lonlat 212 | 213 | def draw(self, lonToX, latToY, pgraphics): 214 | x = lonToX(self.lonlat[0]) 215 | y = latToY(self.lonlat[1]) 216 | pgraphics.ellipse(x, y, 5, 5) 217 | 218 | 219 | class KmlPoint(object): 220 | def __init__(self, element): 221 | self.element = element 222 | self.pt = None 223 | self.parse() 224 | 225 | def draw(self, lonToX, latToY, pgraphics): 226 | x = lonToX(self.pt[0]) 227 | y = latToY(self.pt[1]) 228 | pgraphics.ellipse(x, y, 5, 5) 229 | 230 | def parse(self): 231 | for child in self.element: 232 | if child.tag.endswith("coordinates"): 233 | points = parse_coordinates(child.text) 234 | self.pt = points[0] 235 | 236 | def parse_coordinates(coordinates_text): 237 | points_text = coordinates_text.strip().split(" ") 238 | return map(parse_lonlat, points_text) 239 | 240 | def parse_lonlat(point_text, separator=","): 241 | params = point_text.split(separator) 242 | return (float(params[0]), float(params[1])) 243 | -------------------------------------------------------------------------------- /data/kml/slippylayer.py: -------------------------------------------------------------------------------- 1 | import kml 2 | 3 | 4 | def defaultstyler(key, feature): 5 | feature.noFill() 6 | feature.stroke(255, 0, 0) 7 | 8 | class SlippyLayer(object): 9 | def __init__(self, filename, styler=None): 10 | self.filename = filename 11 | self.styler = styler if styler is not None else defaultstyler 12 | 13 | self.layerObject = kml.RenderKML.open(filename, styler=self.styler) 14 | self.underlayMap = None 15 | 16 | def setUnderlayMap(self, m): 17 | self.underlayMap = m 18 | 19 | def render(self): 20 | self.layer = createGraphics(self.underlayMap.width, self.underlayMap.height) 21 | self.layer.beginDraw() 22 | self.layerObject.render(self.underlayMap.lonToX, self.underlayMap.latToY, self.layer) 23 | self.layer.endDraw() 24 | 25 | def draw(self): 26 | image(self.layer, 0, 0) 27 | -------------------------------------------------------------------------------- /google/__init__.py: -------------------------------------------------------------------------------- 1 | import directions 2 | import streetview 3 | -------------------------------------------------------------------------------- /google/directions/__init__.py: -------------------------------------------------------------------------------- 1 | from googledirections import RenderGoogleDirections 2 | from slippylayer import SlippyLayer 3 | -------------------------------------------------------------------------------- /google/directions/googledirections.py: -------------------------------------------------------------------------------- 1 | import httplib 2 | import json 3 | import sys 4 | 5 | from ...third_party import googlemaps_convert 6 | 7 | 8 | class RenderGoogleDirections(object): 9 | def __init__(self, api_key): 10 | self.api_key = api_key 11 | 12 | self.locations = [] 13 | 14 | def request(self, start_location, end_location, mode="driving"): 15 | """Make a request to the API. locations are tuples of (lat, lon) format. 16 | 17 | Possible modes are 'driving', 'bicycling', 'walking', 'transit'. 18 | """ 19 | 20 | host = "maps.googleapis.com" 21 | 22 | start_param = str(start_location[0]) + "," + str(start_location[1]) 23 | end_param = str(end_location[0]) + "," + str(end_location[1]) 24 | 25 | api_url = "/maps/api/directions/json?origin={1}&destination={2}&mode={3}&key={0}" 26 | url = api_url.format(self.api_key, start_param, end_param, mode) 27 | 28 | # Assumes everything goes just peachy. 29 | 30 | conn = httplib.HTTPSConnection(host) 31 | conn.request("GET", url) 32 | res = conn.getresponse() 33 | response_data = res.read() 34 | 35 | self.data = json.loads(response_data) 36 | self.steps = [] 37 | 38 | try: 39 | # TOOD Ensure we're getting all the routes and legs if necessary. 40 | self.steps = self.data["routes"][0]["legs"][0]["steps"] 41 | except Exception as err: 42 | sys.stderr.write("Google driving directions didn't load properly for some reason. For now, just try again.") 43 | sys.stderr.write(err) 44 | sys.stderr.write(self.data) 45 | 46 | conn.close() 47 | 48 | self.get_locations() 49 | 50 | def render(self, lonToX, latToY, pgraphics): 51 | s = pgraphics.createShape() 52 | s.beginShape() 53 | 54 | def vertex(location): 55 | x = lonToX(float(location['lng'])) 56 | y = latToY(float(location['lat'])) 57 | s.vertex(x, y) 58 | 59 | for loc in self.locations: 60 | vertex(loc) 61 | 62 | s.endShape(LINES) 63 | pgraphics.shape(s, 0, 0) 64 | 65 | def draw(self): 66 | pass 67 | 68 | def get_locations(self): 69 | for step in self.steps: 70 | self.add_location(step['start_location']) 71 | 72 | # Decoded polyline here. 73 | if 'polyline' in step: 74 | polyline = step['polyline'] 75 | if 'points' in polyline: 76 | points_str = str(polyline['points']) 77 | if len(points_str) > 0: 78 | path = googlemaps_convert.decode_polyline(points_str) 79 | for loc in path: 80 | self.add_location(loc) 81 | 82 | self.add_location(step['end_location']) 83 | 84 | def add_location(self, loc): 85 | self.locations.append(loc) 86 | -------------------------------------------------------------------------------- /google/directions/slippylayer.py: -------------------------------------------------------------------------------- 1 | import googledirections 2 | 3 | 4 | class RenderableRoute(object): 5 | def __init__(self, route, strokeColor): 6 | self.route = route 7 | self.strokeColor = strokeColor 8 | 9 | def render(self, *args, **kwds): 10 | self.route.render(*args, **kwds) 11 | 12 | @property 13 | def locations(self): 14 | return self.route.locations 15 | 16 | 17 | class SlippyLayer(object): 18 | def __init__(self, apiKey, startLocation=None, endLocation=None, mode=None, strokeColor=None): 19 | self.apiKey = apiKey 20 | 21 | self.routes = [] 22 | self.underlayMap = None 23 | 24 | # Backwards compatibility. *Deprecated* 25 | if startLocation is not None and endLocation is not None: 26 | self.addRoute(startLocation, endLocation, mode=mode, strokeColor=strokeColor) 27 | 28 | def setUnderlayMap(self, m): 29 | self.underlayMap = m 30 | 31 | def addRoute(self, start, end, mode='driving', strokeColor=color(0)): 32 | route = googledirections.RenderGoogleDirections(self.apiKey) 33 | # TODO Send directions requests asynchronously, or at least on first render, or request() method. 34 | route.request(start, end, mode) 35 | self.routes.append(RenderableRoute(route, strokeColor)) 36 | 37 | def render(self): 38 | self.layer = createGraphics(self.underlayMap.width, self.underlayMap.height) 39 | self.layer.beginDraw() 40 | self.layer.noFill() 41 | 42 | for route in self.routes: 43 | self.layer.stroke(route.strokeColor) 44 | self.layer.strokeWeight(1.5) 45 | route.render(self.underlayMap.lonToX, self.underlayMap.latToY, self.layer) 46 | 47 | self.layer.endDraw() 48 | 49 | def draw(self): 50 | image(self.layer, 0, 0) 51 | -------------------------------------------------------------------------------- /google/streetview/__init__.py: -------------------------------------------------------------------------------- 1 | from gsv import GoogleStreetViewPhotos 2 | -------------------------------------------------------------------------------- /google/streetview/gsv.py: -------------------------------------------------------------------------------- 1 | """This script pulls Google StreetView images from their API given a CSV file of locations 2 | specified as latitude/longitude pairs. 3 | 4 | To use this, you'll need to sign up for a Google StreetView API key and provide it at the 5 | bottom of the file along with other parameters needed to run this script. 6 | 7 | You can also include this file as a module in other Processing sketches or Python scripts. 8 | 9 | """ 10 | 11 | import urllib 12 | import csv 13 | 14 | 15 | class GoogleStreetViewPhotos(object): 16 | def __init__(self, api_key): 17 | self.locations = [] 18 | self.api_key = api_key 19 | self.csvdialect = None 20 | self.has_header_row = False 21 | 22 | def addLatLon(self, lat, lon): 23 | self.locations.append((lat, lon)) 24 | 25 | def addLocation(self, location): 26 | self.locations.append(location) 27 | 28 | def provideLocations(self, locations): 29 | self.locations = locations 30 | 31 | def parseLocations(self, filename): 32 | # Open the file and parse it with the csv.reader method. 33 | with open(filename, 'rb') as csvfile: 34 | # Gather some information about the CSV file. 35 | csvsample = csvfile.read(1024) 36 | csvfile.seek(0) 37 | self.csvdialect = csv.Sniffer().sniff(csvsample) 38 | self.has_header_row = csv.Sniffer().has_header(csvsample) 39 | 40 | # Now, set up an object that will enable us to read the CSV file one row at a time. 41 | reader = csv.reader(csvfile, self.csvdialect) 42 | 43 | # Iterate over all the rows, converting the first elements of each row to floats. 44 | # If we're looking at the first row, and the CSV file has a header row, skip it for now. 45 | is_first_row = True 46 | for row in reader: 47 | if self.has_header_row and is_first_row: 48 | is_first_row = False 49 | continue 50 | 51 | # This assumes the first column is latitude and the second is longitude. 52 | lat, lon = float(row[0]), float(row[1]) 53 | 54 | # Store all the locations as tuples of (latitude, longitude) 55 | location = (lat, lon) 56 | self.addLocation(location) 57 | 58 | def getPhotos(self, template): 59 | if len(self.locations) == 0: 60 | print "This doesn't have any locations available. " + \ 61 | "You can either provide a file with parseLocations() or " + \ 62 | "add locations manually with addLocation()." 63 | return 64 | 65 | # Prepare the URL template. 66 | # TODO: Parameterize this. 67 | url_template = "https://maps.googleapis.com/maps/api/streetview" + \ 68 | "?size=640x400" + \ 69 | "&location={0},{1}" + \ 70 | "&fov=90" + \ 71 | "&heading={2}" + \ 72 | "&pitch=10" + \ 73 | "&key={3}" 74 | 75 | row = 2 if self.has_header_row else 1 76 | headings = [0, 90, 180, 270] 77 | 78 | # Loop over every location, and for each location, loop over all the possible headings. 79 | for location in self.locations: 80 | for dir in headings: 81 | # Create the URL for the request to Google. 82 | lat, lon = location 83 | url = url_template.format(lat, lon, dir, self.api_key) 84 | 85 | # Create the filename as well. 86 | filename = template.format(row, dir) 87 | 88 | # Use urllib.urlretrieve to send the request and save the response to a file. 89 | # TODO: Generalize this so a user can get a PImage or write the file or whatever. 90 | urllib.urlretrieve(url, filename) 91 | 92 | # Increment the row to correlate with the row number in the CSV file. 93 | row += 1 94 | -------------------------------------------------------------------------------- /mapping/__init__.py: -------------------------------------------------------------------------------- 1 | import slippymapper 2 | import openstreetmap -------------------------------------------------------------------------------- /mapping/openstreetmap/__init__.py: -------------------------------------------------------------------------------- 1 | from openstreetmap import * 2 | from slippylayer import SlippyLayer 3 | -------------------------------------------------------------------------------- /mapping/openstreetmap/openstreetmap.py: -------------------------------------------------------------------------------- 1 | """Provides a basic object to query and render OpenStreetMap data.""" 2 | 3 | import json 4 | import urllib 5 | import urllib2 6 | 7 | 8 | class OpenStreetMap(object): 9 | """Represents a query to the OpenStreetMap API.""" 10 | 11 | def __init__(self, query=None, bbox=None): 12 | self.query = query 13 | self.bbox = bbox 14 | 15 | self.data = None 16 | self.entities = None 17 | self.terms = [] 18 | 19 | def set_map(self, slippymap): 20 | self.set_bounding_box(*slippymap.bbox) 21 | 22 | def set_bounding_box(self, latsouth, lonwest, latnorth, loneast): 23 | self.bbox = (latsouth, lonwest, latnorth, loneast) 24 | 25 | def set_query(self, query): 26 | self.query = query 27 | 28 | @property 29 | def query_format(self): 30 | return "[out:json]" 31 | 32 | @property 33 | def query_bbox(self): 34 | return "[bbox:{:f},{:f},{:f},{:f}]".format(*self.bbox) 35 | 36 | def request(self): 37 | if self.query is None: 38 | if len(self.terms) > 0: 39 | self.query = "" 40 | for term in self.terms: 41 | self.query += term.term 42 | 43 | if self.query is None: 44 | return 45 | 46 | overpass_url = "http://overpass-api.de/api/interpreter" 47 | overpass_query = self.query_format + self.query_bbox + ";" 48 | overpass_query += """(%s); 49 | out body; 50 | >; 51 | out skel qt;""" % self.query 52 | 53 | params = {'data': overpass_query} 54 | data = urllib.urlencode(params) 55 | req = urllib2.Request(overpass_url, data) 56 | 57 | response = urllib2.urlopen(req) 58 | contents = response.read() 59 | 60 | self.data = json.loads(contents) 61 | self._parse() 62 | 63 | def _parse(self): 64 | if self.data is None: 65 | return 66 | 67 | # Gather all the nodes and ways into referenceable dictionaries. 68 | nodes = {} 69 | ways = {} 70 | for elt in self.data['elements']: 71 | if 'type' in elt: 72 | if elt['type'] == 'node': 73 | nodeid = elt['id'] 74 | nodes[nodeid] = elt 75 | elif elt['type'] == 'way': 76 | wayid = elt['id'] 77 | ways[wayid] = elt 78 | 79 | self.entities = {'nodes': nodes, 'ways': ways} 80 | 81 | def add(self, term): 82 | self.terms.append(term) 83 | 84 | 85 | class Query(object): 86 | def __init__(self): 87 | pass 88 | 89 | 90 | class QueryTerm(object): 91 | def __init__(self, tags=None): 92 | self.tags = [] 93 | 94 | if tags is not None: 95 | if isinstance(tags, str): 96 | self.tags.append(TagFilter(tags, None)) 97 | elif isinstance(tags, dict): 98 | for key, value in tags.iteritems(): 99 | self.tags.append(TagFilter(key, value)) 100 | 101 | def add_tag(self, key, value): 102 | self.tags.append(TagFilter(key, value)) 103 | 104 | @property 105 | def term(self): 106 | return "" 107 | 108 | def __str__(self): 109 | return "QueryTerm" 110 | 111 | 112 | class Relation(QueryTerm): 113 | @property 114 | def term(self): 115 | return "relation%s;" % "".join(map(str, self.tags)) 116 | 117 | 118 | class Way(QueryTerm): 119 | """Represents an OpenStreetMap query term for way[...];""" 120 | 121 | @property 122 | def term(self): 123 | return "way%s;" % "".join(map(str, self.tags)) 124 | 125 | 126 | class TagFilter(object): 127 | def __init__(self, key, value): 128 | self.key = key 129 | self.value = value 130 | 131 | def __str__(self): 132 | return self.term 133 | 134 | @property 135 | def term(self): 136 | if self.value is None and self.key is not None: 137 | return "[%s]" % self.key 138 | if isinstance(self.value, str): 139 | # If the value is a string, just place it. 140 | return "[%s=%s]" % (self.key, self.value) 141 | elif isinstance(self.value, list): 142 | # If the value is a list of strings, then insert as a regex. For example: 143 | # way[highway~"^(motorway|trunk|primary|secondary|tertiary|unclassified|residential)$"]; 144 | alternates = "|".join(map(str, self.value)) 145 | return """[%s~"(%s)$"]""" % (self.key, alternates) 146 | else: 147 | return "[]" 148 | 149 | 150 | class OpenStreetMapRender(object): 151 | pass 152 | 153 | -------------------------------------------------------------------------------- /mapping/openstreetmap/slippylayer.py: -------------------------------------------------------------------------------- 1 | """Enables rendering OpenStreetMap data in a SlippyMapper map.""" 2 | 3 | 4 | def defaultStyler(feature, graphics): 5 | if feature['type'] == 'way': 6 | graphics.noFill() 7 | graphics.stroke(255, 0, 0) 8 | return True 9 | 10 | elif feature['type'] == 'node': 11 | # graphics.stroke(255) 12 | # graphics.fill(255) 13 | return False 14 | 15 | else: 16 | graphics.stroke(0, 255, 0) 17 | return False 18 | 19 | 20 | class SlippyLayer(object): 21 | def __init__(self, osm, styler=None): 22 | self.source = osm 23 | self.styler = styler if styler is not None else defaultStyler 24 | 25 | self.underlayMap = None 26 | 27 | # TODO extend rendering to include relations, whatever those mean. 28 | 29 | @property 30 | def ways(self): 31 | return self.source.entities["ways"] 32 | 33 | @property 34 | def nodes(self): 35 | return self.source.entities["nodes"] 36 | 37 | def setUnderlayMap(self, m): 38 | self.underlayMap = m 39 | 40 | def render(self): 41 | self.layer = createGraphics(self.underlayMap.width, self.underlayMap.height) 42 | self.layer.beginDraw() 43 | self.renderLayer(self.underlayMap.lonToX, self.underlayMap.latToY, self.layer, self.styler) 44 | self.layer.endDraw() 45 | 46 | def draw(self): 47 | image(self.layer, 0, 0) 48 | 49 | def renderLayer(self, lonToX, latToY, pgraphics, styler=None): 50 | for wayid, way in self.ways.iteritems(): 51 | should_draw = True 52 | 53 | if styler is not None: 54 | should_draw = styler(way, pgraphics) 55 | if should_draw is None: 56 | should_draw = True 57 | 58 | if should_draw: 59 | s = pgraphics.createShape() 60 | s.beginShape() 61 | for nodeid in way['nodes']: 62 | node = self.nodes[nodeid] 63 | s.vertex(lonToX(node['lon']), latToY(node['lat'])) 64 | s.endShape() 65 | pgraphics.shape(s, 0, 0) 66 | 67 | for nodeid, node in self.nodes.iteritems(): 68 | should_draw = True 69 | 70 | if styler is not None: 71 | should_draw = styler(node, pgraphics) 72 | if should_draw is None: 73 | should_draw = True 74 | 75 | if should_draw: 76 | x, y = lonToX(node['lon']), latToY(node['lat']) 77 | pgraphics.ellipse(x, y, 4, 4) 78 | -------------------------------------------------------------------------------- /mapping/slippymapper/__init__.py: -------------------------------------------------------------------------------- 1 | from slippymapper import * 2 | from layer import SlippyLayer 3 | -------------------------------------------------------------------------------- /mapping/slippymapper/layer.py: -------------------------------------------------------------------------------- 1 | 2 | def defaultrenderer(layer, underlay): 3 | pass 4 | 5 | class SlippyLayer(object): 6 | '''Creates an arbitrary SlippyMapper layer, given a function that draws objects.''' 7 | 8 | def __init__(self, renderer=None): 9 | self.renderer = renderer if renderer is not None else defaultrenderer 10 | self.underlayMap = None 11 | 12 | def setUnderlayMap(self, m): 13 | self.underlayMap = m 14 | 15 | def render(self): 16 | self.layer = createGraphics(self.underlayMap.width, self.underlayMap.height) 17 | self.layer.beginDraw() 18 | self.renderer(self.layer, self.underlayMap) 19 | self.layer.endDraw() 20 | 21 | def draw(self): 22 | image(self.layer, 0, 0) 23 | -------------------------------------------------------------------------------- /mapping/slippymapper/marker.py: -------------------------------------------------------------------------------- 1 | """Defines classes used to draw markers on a SlippyMapper instance. 2 | 3 | There are several ways to add a marker to a SlippyMapper, all use the addMarker() 4 | method in the SlippyMapper class. 5 | 6 | 1. Provide a value: 7 | 8 | map.addMarker(40.71, -73.9) 9 | map.addMarker(40.71, -73.9, "New York City") 10 | map.addMarker(40.71, -73.9, 3) 11 | 12 | In the first and third above, the default shape is a circle. You can also provide a PImage object: 13 | 14 | pin = loadImage("map-pin.png") 15 | map.addMarker(40.71, -73.9, pin) 16 | 17 | 2. Provide a function: 18 | 19 | def cross(x, y, marker): 20 | marker.ellipse(x, y, 4, 4) 21 | map.addMarker(latitude, longitude, cross) 22 | 23 | With this, you can start marking the marker interactive. 24 | 25 | def hoverCross(x, y, marker): 26 | if dist(x, y, mouseX, mouseY) < 5: 27 | fill(255, 0, 0) 28 | else: 29 | fill(64) 30 | marker.ellipse(x, y, 4, 4) 31 | map.addMarker(latitude, longitude, hoverCross) 32 | 33 | 3. Provide an instance of a prepackaged class, derived from SimpleMarker: TextMarker, CrossMarker, etc. 34 | 35 | circle = slippymapper.CircleMarker(5, color(255, 255, 0)) 36 | marker.addMarker(latitude, longitude, circle) 37 | 38 | 4. Provide an instance fo a custom class, derived from DataMarker. Use when you need to bind 39 | data to a marker for more complex rendering. 40 | 41 | """ 42 | 43 | class SimpleMarker(object): 44 | def __init__(self, draw): 45 | self.drawMarker = draw 46 | 47 | self.latitude = None 48 | self.longitude = None 49 | self.underlayMap = None 50 | 51 | self.strokeColor = color(0) 52 | self.fillColor = color(255) 53 | 54 | self.offsetX = 0 55 | self.offsetY = 0 56 | 57 | def stroke(self, r=None, g=None, b=None, a=None): 58 | if g is None and b is None and a is None: 59 | self.strokeColor = color(r) 60 | elif b is None and a is None: 61 | self.strokeColor = color(r, g) 62 | elif a is None: 63 | self.strokeColor = color(r, g, b) 64 | else: 65 | self.strokeColor = color(r, g, b, a) 66 | 67 | def fill(self, r=None, g=None, b=None, a=None): 68 | if g is None and b is None and a is None: 69 | self.fillColor = color(r) 70 | elif b is None and a is None: 71 | self.fillColor = color(r, g) 72 | elif a is None: 73 | self.fillColor = color(r, g, b) 74 | else: 75 | self.fillColor = color(r, g, b, a) 76 | 77 | def noStroke(self): 78 | self.strokeColor = None 79 | 80 | def noFill(self): 81 | self.fillColor = None 82 | 83 | def setColors(self, pgraphics): 84 | if self.strokeColor is None: 85 | pgraphics.noStroke() 86 | else: 87 | pgraphics.stroke(self.strokeColor) 88 | 89 | if self.fillColor is None: 90 | pgraphics.noFill() 91 | else: 92 | pgraphics.fill(self.fillColor) 93 | 94 | def setLocation(self, latitude, longitude): 95 | self.latitude = latitude 96 | self.longitude = longitude 97 | 98 | def setUnderlayMap(self, m): 99 | self.underlayMap = m 100 | 101 | def setOffset(self, dx, dy): 102 | self.offsetx = dx 103 | self.offsety = dy 104 | 105 | def render(self, pgraphics): 106 | x = self.underlayMap.lonToX(self.longitude) + self.offsetX 107 | y = self.underlayMap.latToY(self.latitude) + self.offsetY 108 | 109 | self.setColors(pgraphics) 110 | self.drawMarker(x, y, pgraphics) 111 | 112 | def draw(self): 113 | x = self.underlayMap.lonToX(self.longitude) + self.offsetX 114 | y = self.underlayMap.latToY(self.latitude) + self.offsetY 115 | 116 | self.setColors(this) 117 | self.drawMarker(x, y, this) 118 | 119 | @property 120 | def latlon(self): 121 | return (self.latitude, self.longitude) 122 | @property 123 | def location(self): 124 | return self.latlon 125 | 126 | 127 | class CircleMarker(SimpleMarker): 128 | def __init__(self, diameter, color=None): 129 | self.diameter = diameter 130 | 131 | super(CircleMarker, self).__init__(self.drawCircle) 132 | 133 | if color is not None: 134 | self.stroke(color) 135 | self.fill(color) 136 | 137 | def drawCircle(self, x, y, pgraphics): 138 | pgraphics.ellipse(x, y, self.diameter, self.diameter) 139 | 140 | 141 | class TextMarker(SimpleMarker): 142 | def __init__(self, text, color=None): 143 | self.text = text 144 | self.color = color if color is not None else 0 145 | 146 | super(TextMarker, self).__init__(self.drawText) 147 | 148 | self.noStroke() 149 | self.fill(self.color) 150 | 151 | def drawText(self, x, y, pgraphics): 152 | pgraphics.text(self.text, x, y) 153 | 154 | 155 | class CrossMarker(SimpleMarker): 156 | def __init__(self, size, color=None): 157 | self.size = size 158 | 159 | super(CrossMarker, self).__init__(self.drawCross) 160 | 161 | if color is not None: 162 | self.stroke(color) 163 | self.noFill() 164 | 165 | def drawCross(self, x, y, pgraphics): 166 | pgraphics.line(x - self.size, y - self.size, x + self.size, y + self.size) 167 | pgraphics.line(x - self.size, y + self.size, x + self.size, y - self.size) 168 | 169 | 170 | class ImageMarker(SimpleMarker): 171 | def __init__(self, image): 172 | self.image = image 173 | 174 | super(ImageMarker, self).__init__(self.drawImage) 175 | 176 | # Adjust for the center of the image by default. 177 | self.offsetX = - self.image.width / 2 178 | self.offsetY = - self.image.height / 2 179 | 180 | def drawImage(self, x, y, pgraphics): 181 | pgraphics.image(self.image, x, y) 182 | 183 | 184 | class DataMarker(object): 185 | def __init__(self, data): 186 | self.data = data 187 | 188 | self.latitude = None 189 | self.longitude = None 190 | self.underlayMap = None 191 | 192 | def setLocation(self, latitude, longitude): 193 | self.latitude = latitude 194 | self.longitude = longitude 195 | 196 | def setUnderlayMap(self, m): 197 | self.underlayMap = m 198 | 199 | def drawMarker(self, x, y, marker): 200 | pass 201 | 202 | def render(self, pgraphics): 203 | x = self.underlayMap.lonToX(self.longitude) 204 | y = self.underlayMap.latToY(self.latitude) 205 | 206 | self.drawMarker(x, y, pgraphics) 207 | 208 | def draw(self): 209 | self.render(this) 210 | -------------------------------------------------------------------------------- /mapping/slippymapper/slippymapper.py: -------------------------------------------------------------------------------- 1 | import math 2 | from ...util import lazyimages 3 | from marker import * 4 | from tile_servers import tile_servers 5 | import sys 6 | 7 | # TODO Extract the processing-specific code. 8 | 9 | # Fundamental transformations. Reference: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames 10 | 11 | def lonToTile(lon, zoom): 12 | """Given a longitude and zoom value, return the X map tile index.""" 13 | n = 2.0 ** zoom 14 | return ((lon + 180.0) / 360.0) * n 15 | 16 | def latToTile(lat, zoom): 17 | """Given a latitude and zoom value, return the Y map tile index.""" 18 | n = 2.0 ** zoom 19 | lat_rad = math.radians(lat) 20 | return (1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n 21 | 22 | def tileToLon(tile, zoom): 23 | """Given a tile and zoom, give the longitude.""" 24 | n = 2.0 ** zoom 25 | return tile / n * 360.0 - 180.0 26 | 27 | def tileToLat(tile, zoom): 28 | """Given a tile and zoom, give the latitude.""" 29 | n = 2.0 ** zoom 30 | lat_rad = math.atan(math.sinh(math.pi * (1.0 - 2.0 * tile / n))) 31 | return math.degrees(lat_rad) 32 | 33 | 34 | class SlippyMapper(object): 35 | """SlippyMap will draw a map given a location, zoom, and public tile server.""" 36 | 37 | tile_size = 256.0 38 | 39 | def __init__(self, lat, lon, zoom=12, server='toner', width=512, height=512): 40 | self._width = width 41 | self._height = height 42 | self._basemap = None 43 | 44 | self.set_server(server) 45 | 46 | self.lat = lat 47 | self.lon = lon 48 | self.set_zoom(zoom) 49 | 50 | self.centerX = lonToTile(self.lon, self.zoom) 51 | self.centerY = latToTile(self.lat, self.zoom) 52 | self.offsetX = floor((floor(self.centerX) - self.centerX) * self.tile_size) 53 | self.offsetY = floor((floor(self.centerY) - self.centerY) * self.tile_size) 54 | 55 | self.lazyImageManager = lazyimages.LazyImageManager() 56 | self.layers = [] 57 | self.markers = [] 58 | 59 | def set_server_url(self, zxyurl): 60 | """Allows you to set a custom Z/X/Y server URL instead of picking an included one. 61 | 62 | If you look at tile_servers.py, you'll see what these URLs typically look like. 63 | Currently, slippymapper assumes you're targeting a Z/X/Y server. For example: 64 | 65 | mymap.setServerUrl("https://tile.server.org/%s/%s/%s.png") 66 | 67 | The "%s" interpolation is automatically filled out with the Z, X, and Y values, 68 | respectively. 69 | """ 70 | self.url = zxyurl 71 | self.server = 'custom' 72 | setServerUrl = set_server_url 73 | 74 | def set_server(self, server): 75 | """Set the current render server given the name of a predefined public server. 76 | 77 | See the tile_servers.py file for possible tile servers. All you need to do is provide 78 | the name of the server, like "carto-dark". This defaults to Stamen's "toner" server. 79 | 80 | Setting this after the map is rendered requires re-rendering the map by calling render(). 81 | """ 82 | if server in tile_servers: 83 | self.server = server 84 | self.url = tile_servers[server] 85 | 86 | elif server is None: 87 | # Don't render a map at all. 88 | self.server = None 89 | self.url = None 90 | 91 | else: 92 | sys.stderr.write("""Got %s as a tile server but that didn't exist. 93 | Available servers are %s. Falling back to 'toner'. 94 | You can also specify a custom ZXY URL with the setServerUrl() method.""" % \ 95 | (server, ", ".join(tile_servers.keys()))) 96 | self.server = 'toner' 97 | self.url = tile_servers['toner'] 98 | setServer = set_server 99 | 100 | def set_zoom(self, zoom): 101 | self.zoom = max(min(zoom, 18), 0) 102 | self.centerX = lonToTile(self.lon, self.zoom) 103 | self.centerY = latToTile(self.lat, self.zoom) 104 | setZoom = set_zoom 105 | 106 | def set_center(self, lat, lon): 107 | self.lat = lat 108 | self.lon = lon 109 | self.centerX = lonToTile(self.lon, self.zoom) 110 | self.centerY = latToTile(self.lat, self.zoom) 111 | setCenter = set_center 112 | 113 | @property 114 | def has_rendered(self): 115 | return self._basemap is not None 116 | hasRendered = has_rendered 117 | 118 | @property 119 | def width(self): 120 | return self._width 121 | 122 | @property 123 | def height(self): 124 | return self._height 125 | 126 | @property 127 | def bounding_box(self): 128 | lonwest = self.xToLon(0) 129 | loneast = self.xToLon(self.width) 130 | latnorth = self.yToLat(0) 131 | latsouth = self.yToLat(self.height) 132 | return (latsouth, lonwest, latnorth, loneast) 133 | boundingBox = bounding_box 134 | bbox = bounding_box 135 | 136 | def set_size(self, width, height): 137 | self._width = width 138 | self._height = height 139 | 140 | # The basemap is None until we render the first time. So if it's not rendered, rebuild the map. 141 | # Thus, setting the size will require re-rendering the map. 142 | if self.has_rendered: 143 | self._basemap = createGraphics(floor(self._width), floor(self._height)) 144 | setSize = set_size 145 | 146 | def clear(self): 147 | if self.has_rendered: 148 | self._basemap.beginDraw() 149 | self._basemap.background(255, 0) 150 | self._basemap.endDraw() 151 | 152 | @property 153 | def has_tile_server(self): 154 | return self.url is not None 155 | 156 | def get_tile_url(self, x, y): 157 | # Interpolate the URL for this particular tile. 158 | # e.g. .../12/1208/1541.png 159 | return self.url % (self.zoom, x, y) 160 | 161 | # Inspired by math contained in https://github.com/dfacts/staticmaplite/ 162 | def render(self): 163 | """Create the map by requesting tiles from the specified tile server.""" 164 | 165 | if not self.has_rendered: 166 | self._basemap = createGraphics(floor(self._width), floor(self._height)) 167 | 168 | self.clear() 169 | 170 | if self.has_tile_server: 171 | numColumns = self.width / self.tile_size 172 | numRows = self.height / self.tile_size 173 | 174 | tiles_start_x = floor(self.centerX - numColumns / 2.0) 175 | tiles_start_y = floor(self.centerY - numRows / 2.0) 176 | 177 | tiles_end_x = ceil(self.centerX + numColumns / 2.0) 178 | tiles_end_y = ceil(self.centerY + numRows / 2.0) 179 | 180 | self.offsetX = -floor((self.centerX - floor(self.centerX)) * self.tile_size) + \ 181 | floor(self.width / 2.0) + \ 182 | floor(tiles_start_x - floor(self.centerX)) * self.tile_size 183 | self.offsetY = -floor((self.centerY - floor(self.centerY)) * self.tile_size) + \ 184 | floor(self.height / 2.0) + \ 185 | floor(tiles_start_y - floor(self.centerY)) * self.tile_size 186 | 187 | def onTileLoaded(tile, meta): 188 | self._basemap.beginDraw() 189 | x = meta['destX'] 190 | y = meta['destY'] 191 | self._basemap.image(tile, x, y) 192 | self._basemap.endDraw() 193 | 194 | for x in xrange(tiles_start_x, tiles_end_x): 195 | for y in xrange(tiles_start_y, tiles_end_y): 196 | tile_url = self.get_tile_url(x, y) 197 | 198 | # Compute the x and y coordinates for where this tile will go on the map. 199 | destX = (x - tiles_start_x) * self.tile_size + self.offsetX 200 | destY = (y - tiles_start_y) * self.tile_size + self.offsetY 201 | 202 | # Attempts to load all the images lazily. 203 | meta = { 204 | 'url' : tile_url, 205 | 'destX' : destX, 206 | 'destY' : destY, 207 | 'x' : x, 208 | 'y' : y, 209 | } 210 | self.lazyImageManager.addLazyImage(tile_url, onTileLoaded, meta) 211 | 212 | # Kick off all the layer rendering. 213 | for layer in self.layers: 214 | layer.render() 215 | 216 | for marker in self.markers: 217 | marker.draw() 218 | 219 | # TODO Revisit map filters. 220 | # def makeGrayscale(self): 221 | # self._basemap.loadPixels() 222 | 223 | # for i in xrange(0, self._basemap.width * self._basemap.height): 224 | # b = self._basemap.brightness(self._basemap.pixels[i]) 225 | # self._basemap.pixels[i] = self._basemap.color(b, b, b) 226 | 227 | # self._basemap.updatePixels() 228 | 229 | # def makeFaded(self): 230 | # self._basemap.noStroke() 231 | # self._basemap.fill(255, 255, 255, 128) 232 | # self._basemap.rect(0, 0, width, height) 233 | 234 | def draw(self): 235 | """Draws the base map on the Processing sketch canvas.""" 236 | 237 | self.updateLazyImageLoading() 238 | 239 | if self.has_tile_server and self.has_rendered: 240 | image(self._basemap, 0, 0) 241 | 242 | for layer in self.layers: 243 | layer.draw() 244 | 245 | for marker in self.markers: 246 | marker.draw() 247 | 248 | def updateLazyImageLoading(self): 249 | if self.lazyImageManager.allLazyImagesLoaded: 250 | return 251 | self.lazyImageManager.request() 252 | 253 | def add_marker(self, latitude, longitude, marker=None): 254 | if marker is None: 255 | m = CircleMarker(6) 256 | 257 | elif callable(marker): 258 | # The case that marker is a function of: x, y, pgraphics. 259 | m = SimpleMarker(marker) 260 | 261 | elif isinstance(marker, str): 262 | m = TextMarker(marker) 263 | 264 | elif isinstance(marker, unicode): 265 | m = TextMarker(str(marker)) 266 | 267 | elif isinstance(marker, int) or isinstance(marker, float): 268 | m = CircleMarker(marker) 269 | 270 | elif isinstance(marker, PImage): 271 | m = ImageMarker(marker) 272 | 273 | else: 274 | m = marker 275 | 276 | m.setUnderlayMap(self) 277 | m.setLocation(latitude, longitude) 278 | 279 | self.markers.append(m) 280 | return m 281 | addMarker = add_marker 282 | 283 | def add_layer(self, layer): 284 | self.layers.append(layer) 285 | layer.setUnderlayMap(self) 286 | addLayer = add_layer 287 | 288 | def save(self, filename): 289 | self.flattened().save(filename) 290 | 291 | def flattened(self): 292 | export = createGraphics(self.width, self.height) 293 | export.beginDraw() 294 | 295 | if self.has_rendered and self.has_tile_server: 296 | export.image(self._basemap, 0, 0) 297 | 298 | for layer in self.layers: 299 | export.image(layer.layer, 0, 0) 300 | 301 | for marker in self.markers: 302 | marker.render(export) 303 | 304 | export.endDraw() 305 | return export 306 | 307 | def lonToX(self, lon): 308 | return (self.width / 2.0) - self.tile_size * (self.centerX - lonToTile(lon, self.zoom)) 309 | 310 | def latToY(self, lat): 311 | return (self.height / 2.0) - self.tile_size * (self.centerY - latToTile(lat, self.zoom)) 312 | 313 | def xToLon(self, x): 314 | tile = (x - (self.width / 2.0)) / self.tile_size + self.centerX 315 | return tileToLon(tile, self.zoom) 316 | 317 | def yToLat(self, y): 318 | tile = (y - (self.height / 2.0)) / self.tile_size + self.centerY 319 | return tileToLat(tile, self.zoom) 320 | 321 | def latlonToPixel(self, loc): 322 | return (self.lonToX(loc[0]), self.latToY(loc[1])) 323 | 324 | def pixelToLatLon(self, pixel): 325 | return (self.yToLat(pixel[1]), self.xToLon(pixel[0])) 326 | -------------------------------------------------------------------------------- /mapping/slippymapper/tile_servers.py: -------------------------------------------------------------------------------- 1 | 2 | # List of public map tile Z/X/Y map tile servers. 3 | tile_servers = { 4 | # http://maps.stamen.com/ 5 | 'toner' : "http://tile.stamen.com/toner/%s/%s/%s.png", 6 | 'toner-lines' : "http://tile.stamen.com/toner-lines/%s/%s/%s.png", 7 | 'toner-hybrid' : "http://tile.stamen.com/toner-hybrid/%s/%s/%s.png", 8 | 'toner-background' : "http://tile.stamen.com/toner-background/%s/%s/%s.png", 9 | 'toner-lite' : "http://tile.stamen.com/toner-lite/%s/%s/%s.png", 10 | 'terrain' : "http://tile.stamen.com/terrain/%s/%s/%s.png", 11 | 'terrain-lines' : "http://tile.stamen.com/terrain-lines/%s/%s/%s.png", 12 | 'terrain-background' : "http://tile.stamen.com/terrain-background/%s/%s/%s.png", 13 | 'watercolor' : "http://tile.stamen.com/watercolor/%s/%s/%s.png", 14 | 15 | # Found in https://github.com/dfacts/staticmaplite/blob/master/staticmap.php 16 | 'mapnik' : "http://tile.openstreetmap.org/%s/%s/%s.png", 17 | 'cycle' : "http://a.tile.opencyclemap.org/cycle/%s/%s/%s.png", 18 | 19 | # http://wiki.openstreetmap.org/wiki/Tile_servers 20 | 'openstreetmap' : "http://a.tile.openstreetmap.org/%s/%s/%s.png", # also http://b.* and https://c.* 21 | 'wikimedia' : "https://maps.wikimedia.org/osm-intl/%s/%s/%s.png", 22 | 'carto-light' : "http://a.basemaps.cartocdn.com/light_all/%s/%s/%s.png", 23 | 'carto-dark' : "http://a.basemaps.cartocdn.com/dark_all/%s/%s/%s.png", 24 | 'openptmap' : "http://www.openptmap.org/tiles/%s/%s/%s.png", 25 | 'hikebike' : "http://a.tiles.wmflabs.org/hikebike/%s/%s/%s.png", 26 | 27 | # https://carto.com/location-data-services/basemaps/ 28 | # Note: These seem to be really slow. 29 | 'carto-lightall' : "http://cartodb-basemaps-1.global.ssl.fastly.net/light_all/%s/%s/%s.png", 30 | 'carto-darkall' : "http://cartodb-basemaps-1.global.ssl.fastly.net/dark_all/%s/%s/%s.png", 31 | 'carto-lightnolabels': "http://cartodb-basemaps-1.global.ssl.fastly.net/light_nolabels/%s/%s/%s.png", 32 | 'carto-darknolabels' : "http://cartodb-basemaps-1.global.ssl.fastly.net/dark_nolabels/%s/%s/%s.png", 33 | } 34 | -------------------------------------------------------------------------------- /path/__init__.py: -------------------------------------------------------------------------------- 1 | import randomwalk 2 | -------------------------------------------------------------------------------- /path/randomwalk.py: -------------------------------------------------------------------------------- 1 | """RandomWalkGenerator 2 | 3 | Generates random walks in both 2D and 3D. 4 | 5 | The class generates paths as a list of 6 | 7 | """ 8 | 9 | import random 10 | 11 | class RandomWalkGenerator(object): 12 | """Generates 2D and 3D random walks, either those that can overlap themselves and those 13 | which can't. 14 | 15 | is3D : Boolean = specifies whether this should be a drawn 16 | """ 17 | 18 | def __init__(self, is3D=False, allowOverlap=True): 19 | self.is3D = is3D 20 | self.allowOverlap = allowOverlap 21 | self.path = [] 22 | self.history = [] 23 | 24 | # State 25 | self.path = [] 26 | self.history = [] 27 | self.currentStep = 0 28 | self.totalCount = 0 29 | self.numSteps = 0 30 | 31 | def getPossibleLocations(self, location): 32 | """Given a location, just give me the six possible directions I could go.""" 33 | 34 | if self.is3D: 35 | return set([ 36 | (location[0]+1, location[1], location[2]), 37 | (location[0]-1, location[1], location[2]), 38 | (location[0], location[1]+1, location[2]), 39 | (location[0], location[1]-1, location[2]), 40 | (location[0], location[1], location[2]+1), 41 | (location[0], location[1], location[2]-1), 42 | ]) 43 | else: 44 | return set([ 45 | (location[0]+1, location[1]), 46 | (location[0]-1, location[1]), 47 | (location[0], location[1]+1), 48 | (location[0], location[1]-1), 49 | ]) 50 | 51 | def getAvailableLocations(self, location, denied=None): 52 | """Given a location, return a set of locations I can go next, but not where I've been before.""" 53 | 54 | possibleLocations = self.getPossibleLocations(location) 55 | 56 | if self.allowOverlap: 57 | return list(possibleLocations) 58 | else: 59 | # Remove from the places I could go, the places where I can't go. 60 | if denied is None: 61 | return list(possibleLocations.difference(self.path)) 62 | else: 63 | return list(possibleLocations.difference(self.path).difference(denied)) 64 | 65 | def pickNextLocation(self, availableLocations): 66 | """From the given next available locations, pick one of them.""" 67 | 68 | numAvailableLocations = len(availableLocations) 69 | if not self.allowOverlap and numAvailableLocations == 0: 70 | return None 71 | 72 | pickedLocationIndex = random.randrange(0, numAvailableLocations) 73 | return availableLocations[pickedLocationIndex] 74 | 75 | def generate(self, startLocation, numSteps, seed=None, onStep=None): 76 | """Given a starting location, return a path with "numSteps" steps.""" 77 | 78 | self.start(startLocation, numSteps, seed=seed) 79 | 80 | while self.currentStep < self.numSteps: 81 | self.step(onStep) 82 | self.resetIfNecessary() 83 | 84 | return self.path 85 | 86 | def start(self, startLocation, numSteps, seed=None): 87 | random.seed(seed) 88 | 89 | self.path = [startLocation] 90 | self.history = [None] 91 | self.numSteps = numSteps 92 | self.totalCount = 0 93 | self.currentStep = 0 94 | 95 | def step(self, onStep=None): 96 | if self.currentStep < self.numSteps: 97 | i = self.currentStep 98 | 99 | currentLocation = self.path[i] 100 | knownBadMoves = self.history[i] 101 | 102 | availableLocations = self.getAvailableLocations(currentLocation, knownBadMoves) 103 | pickedNextLocation = self.pickNextLocation(availableLocations) 104 | 105 | if pickedNextLocation is None: 106 | # You know you've reached a dead end, so remember this for later as a bad move. 107 | if self.history[i - 1] is None: 108 | self.history[i - 1] = [currentLocation] 109 | else: 110 | self.history[i - 1].append(currentLocation) 111 | 112 | self.path.pop() 113 | self.history.pop() 114 | i -= 1 115 | else: 116 | self.path.append(pickedNextLocation) 117 | self.history.append(None) 118 | i += 1 119 | self.currentStep = i 120 | 121 | if onStep is not None: 122 | onStep(self.path) 123 | 124 | def resetIfNecessary(self): 125 | if self.currentStep < self.numSteps: 126 | # Behavior that takes big steps back when you take a long time. 127 | self.totalCount += 1 128 | 129 | if self.totalCount % (self.numSteps * 2) == 0: 130 | # print "hmm, taking a while", totalCount, i, numSteps 131 | # It's taking twice as long as the ideal, so take many steps back instead of just one. 132 | i = random.randrange(0, self.currentStep) 133 | self.path = self.path[:i+1] 134 | self.history = self.history[:i+1] 135 | self.currentStep = i 136 | 137 | 138 | if __name__ == "__main__": 139 | pathFinder = RandomWalkGenerator() 140 | path = pathFinder.generate((0, 0), 10) 141 | print path -------------------------------------------------------------------------------- /third_party/__init__.py: -------------------------------------------------------------------------------- 1 | # include the third-party libraries selectively 2 | import sys, os, imp 3 | separator = os.path.sep 4 | root = os.path.dirname(__file__) 5 | 6 | # Currently, the only function needed is decode_polyline from googlemaps.convert. 7 | # Importing like this sidesteps importing the "requests" library required by 8 | # googlemaps.client, which likely doesn't work with processing.py yet. 9 | libpath = os.path.join(root, "googlemaps", "services", "googlemaps", "convert.py") 10 | googlemaps_convert = imp.load_source("googlemaps_convert", libpath) 11 | import googlemaps_convert 12 | -------------------------------------------------------------------------------- /ui/__init__.py: -------------------------------------------------------------------------------- 1 | import button 2 | import control 3 | import dropdown 4 | import panner 5 | import text 6 | import toggle 7 | 8 | from interface import Interface 9 | -------------------------------------------------------------------------------- /ui/button.py: -------------------------------------------------------------------------------- 1 | from control import Control 2 | 3 | class Button(Control): 4 | def __init__(self, controlId, onClick=None, title=None, size=None, position=None): 5 | self.onClick = onClick 6 | super(Button, self).__init__(controlId, title=title, size=size, position=position) 7 | 8 | def draw(self, graphics): 9 | if not self.visible: 10 | return 11 | 12 | graphics.noStroke() 13 | if self.mouseHover: 14 | graphics.fill(0, 100, 150) 15 | if self.controller.mousePressed: 16 | graphics.fill(0, 150, 250) 17 | else: 18 | graphics.fill(0, 50, 100) 19 | graphics.rect(self.x, self.y, self.width, self.height) 20 | graphics.fill(255) 21 | graphics.text(self.title.upper(), self.x + 5, self.y + 15) 22 | 23 | def click(self): 24 | if self.mouseHover and self.onClick is not None: 25 | self.onClick() 26 | -------------------------------------------------------------------------------- /ui/control.py: -------------------------------------------------------------------------------- 1 | class Control(object): 2 | def __init__(self, controlId, title=None, size=None, position=None): 3 | self.controlId = controlId 4 | self.title = self.controlId if title is None else title 5 | self.size = (100, 20) if size is None else size 6 | self.position = (0, 0) if position is None else position 7 | self.controller = None 8 | self.visible = True 9 | 10 | @property 11 | def sketch(self): 12 | return self.controller.sketch 13 | @property 14 | def x(self): 15 | return self.position[0] 16 | @property 17 | def y(self): 18 | return self.position[1] 19 | @property 20 | def width(self): 21 | return self.size[0] 22 | @property 23 | def height(self): 24 | return self.size[1] 25 | @property 26 | def mouseHover(self): 27 | isBetweenX = self.x < self.sketch.mouseX and self.sketch.mouseX < self.x + self.width 28 | isBetweenY = self.y < self.sketch.mouseY and self.sketch.mouseY < self.y + self.height 29 | return isBetweenX and isBetweenY 30 | 31 | def click(self): 32 | pass 33 | 34 | def show(self): 35 | self.visible = True 36 | def hide(self): 37 | self.visible = False 38 | @property 39 | def isVisible(self): 40 | return self.visible 41 | 42 | def setController(self, controller): 43 | self.controller = controller 44 | -------------------------------------------------------------------------------- /ui/dropdown.py: -------------------------------------------------------------------------------- 1 | """Dropdown controls for spatialpixel.ui. 2 | 3 | Arguments: 4 | 5 | - controlId - an arbitrary string to uniquely identify the control 6 | - options - a dict or list of options, or a function that returns such a list or dict 7 | - getter - a function that will return the currently selected option 8 | - setter - a function called when a user selects an option, takes one argument 9 | - title - the default displayed title as a string 10 | - size - a tuple of (width, height) in pixels 11 | - position - a tuple of (x, y) in pixels of the upper-left corner of the control 12 | """ 13 | 14 | from control import Control 15 | import button 16 | 17 | class DropDown(Control): 18 | def __init__(self, controlId, options, getter, setter, title=None, size=None, position=None): 19 | self.options = options 20 | self.getter = getter 21 | self.setter = setter 22 | 23 | self.state = 'closed' 24 | 25 | super(DropDown, self).__init__(controlId, title=title, size=size, position=position) 26 | 27 | self.optionButtons = [] 28 | 29 | def setController(self, controller): 30 | super(DropDown, self).setController(controller) 31 | self.buildOptions() 32 | 33 | def buildOptions(self): 34 | pos = self.height + self.y 35 | 36 | for key in self.options: 37 | opt = button.Button( 38 | self.controlId + key, 39 | title=key, 40 | onClick=self.getClick(key), 41 | size=self.size, 42 | position=(self.x, pos) 43 | ) 44 | opt.hide() 45 | self.optionButtons.append(opt) 46 | self.controller.addControl(opt) 47 | 48 | pos += self.height 49 | 50 | def getClick(self, key): 51 | def optionClick(): 52 | self.setter(key) 53 | self.close() 54 | return optionClick 55 | 56 | def draw(self, graphics): 57 | if not self.visible: 58 | return 59 | 60 | graphics.noStroke() 61 | 62 | if self.mouseHover: 63 | graphics.fill(0, 100, 150) 64 | if self.controller.mousePressed: 65 | graphics.fill(0, 150, 250) 66 | else: 67 | graphics.fill(0, 50, 100) 68 | 69 | graphics.rect(self.x, self.y, self.width, self.height) 70 | graphics.fill(255) 71 | 72 | title = self.getter().upper() 73 | graphics.text(title, self.x + 5, self.y + 15) 74 | 75 | for opt in self.optionButtons: 76 | opt.draw(graphics) 77 | 78 | def click(self): 79 | if self.mouseHover: 80 | if self.state == 'open': 81 | self.close() 82 | elif self.state == 'closed': 83 | self.open() 84 | 85 | def open(self): 86 | self.state = 'open' 87 | for opt in self.optionButtons: 88 | opt.show() 89 | 90 | def close(self): 91 | self.state = 'closed' 92 | self.controller.clear() 93 | for opt in self.optionButtons: 94 | opt.hide() 95 | -------------------------------------------------------------------------------- /ui/interface.py: -------------------------------------------------------------------------------- 1 | """Build standard, boring user interfaces in processing.py. 2 | 3 | An Interface object can hold multiple Controls that represent standard 4 | UI elements, like buttons, dropdown menus, etc. 5 | 6 | To create an interface: 7 | 8 | import spatialpixel.ui as ui 9 | 10 | def setup(): 11 | global gui 12 | gui = ui.Interface(this) 13 | 14 | def draw(): 15 | global gui 16 | gui.draw(mousePressed) 17 | 18 | def mouseClicked(): 19 | global gui 20 | gui.click() 21 | """ 22 | 23 | class Interface(object): 24 | def __init__(self, sketch, fontName=None): 25 | self.sketch = sketch 26 | self.font = self.sketch.loadFont(fontName) if fontName is not None else None 27 | 28 | self.controls = {} 29 | self.graphics = self.sketch.createGraphics(self.sketch.width, self.sketch.height) 30 | 31 | def addControl(self, control): 32 | self.controls[control.controlId] = control 33 | control.setController(self) 34 | 35 | def draw(self, mousePressed): 36 | self.mousePressed = mousePressed 37 | 38 | self.graphics.beginDraw() 39 | 40 | if self.font is not None: 41 | self.graphics.textFont(self.font, 12) 42 | 43 | for control in self.controls.values(): 44 | control.draw(self.graphics) 45 | 46 | self.graphics.endDraw() 47 | 48 | self.sketch.image(self.graphics, 0, 0) 49 | 50 | def click(self): 51 | for control in self.controls.values(): 52 | if control.isVisible: 53 | control.click() 54 | 55 | def getControl(self, controlId): 56 | """Returns a Control instance given its id.""" 57 | 58 | if controlId in self.controls: 59 | return self.controls[controlId] 60 | return None 61 | 62 | def clear(self): 63 | self.graphics.beginDraw() 64 | self.graphics.background(self.graphics.color(0,0,0), 0) 65 | self.graphics.endDraw() 66 | -------------------------------------------------------------------------------- /ui/panner.py: -------------------------------------------------------------------------------- 1 | class Panner(object): 2 | def __init__(self, sketch, x=0, y=0): 3 | self.sketch = sketch 4 | self.originalPanX = x 5 | self.originalPanY = y 6 | self.panX = x 7 | self.panY = y 8 | self.zoomFactor = 1.0 9 | 10 | @property 11 | def x(self): 12 | return self.panX 13 | @property 14 | def y(self): 15 | return self.panY 16 | 17 | def reset(self): 18 | self.panX = self.originalPanX 19 | self.panY = self.originalPanY 20 | 21 | def pan(self): 22 | self.translate() 23 | 24 | def translate(self): 25 | self.sketch.translate(self.panX, self.panY) 26 | self.sketch.scale(self.zoomFactor) 27 | 28 | # Scaling affects the strokeWeight, so let's undo that so we're not rendering crap. 29 | self.sketch.strokeWeight(1.0 / self.zoomFactor) 30 | 31 | def drag(self): 32 | self.panX += (self.sketch.mouseX - self.sketch.pmouseX) 33 | self.panY += (self.sketch.mouseY - self.sketch.pmouseY) 34 | 35 | def zoom(self, event): 36 | origX, origY = self.sketch.width * self.zoomFactor, self.sketch.height * self.zoomFactor 37 | 38 | # Change the desired zoom value 39 | count = event.getCount() 40 | self.zoomFactor -= count / 100.0 41 | self.zoomFactor = max(self.zoomFactor, 0.01) 42 | 43 | # Adjust the pan of the map view to center around the center of the sketch window 44 | newX, newY = self.sketch.width * self.zoomFactor, self.sketch.height * self.zoomFactor 45 | self.panX += (origX - newX) 46 | self.panY += (origY - newY) 47 | -------------------------------------------------------------------------------- /ui/text.py: -------------------------------------------------------------------------------- 1 | from control import Control 2 | 3 | class Text(Control): 4 | def __init__(self, controlId, value=None, title=None, size=None, position=None): 5 | self.value = value 6 | super(Text, self).__init__(controlId, title=title, size=size, position=position) 7 | 8 | def draw(self, graphics): 9 | graphics.noStroke() 10 | 11 | graphics.fill(255) 12 | graphics.rect(self.x, self.y, self.width, self.height) 13 | 14 | graphics.fill(0, 50, 100) 15 | if self.value is not None: 16 | graphics.text(self.title.upper() + " " + str(self.value()), self.x + 5, self.y + 15) 17 | else: 18 | graphics.text(self.title.upper(), self.x + 5, self.y + 15) 19 | -------------------------------------------------------------------------------- /ui/toggle.py: -------------------------------------------------------------------------------- 1 | from control import Control 2 | 3 | class Toggle(Control): 4 | def __init__(self, controlId, onToggle=None, state=False, title=None, size=None, position=None): 5 | self.on = state 6 | self.onToggle = onToggle 7 | super(Toggle, self).__init__(controlId, title=title, size=size, position=position) 8 | 9 | def draw(self, graphics): 10 | graphics.noStroke() 11 | 12 | if self.mouseHover: 13 | if self.on: 14 | graphics.fill(150, 100, 0) 15 | else: 16 | graphics.fill(0, 100, 150) 17 | 18 | if self.controller.mousePressed: 19 | graphics.fill(0, 150, 250) 20 | else: 21 | if self.on: 22 | graphics.fill(100, 50, 0) 23 | else: 24 | graphics.fill(0, 50, 100) 25 | 26 | graphics.rect(self.x, self.y, self.width, self.height) 27 | 28 | graphics.fill(255) 29 | graphics.text(self.title.upper(), self.x + 5, self.y + 15) 30 | 31 | def click(self): 32 | if self.mouseHover: 33 | self.on = not self.on 34 | if self.onToggle is not None: 35 | self.onToggle() 36 | 37 | @property 38 | def value(self): 39 | return self.on 40 | -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- 1 | from lazyimages import LazyImageManager 2 | -------------------------------------------------------------------------------- /util/lazyimages.py: -------------------------------------------------------------------------------- 1 | """Classes for loading images in lazy fashion. 2 | 3 | The challenge when using requestImage() from Processing is that it doesn't have a proper 4 | async callback mechanism. You need to use the draw() loop to continually poll to see if 5 | the image has successfully loaded. 6 | 7 | The other challenge is loading images in small batches to not send too many requests. 8 | 9 | These classes help with both problems. 10 | 11 | """ 12 | 13 | class LazyImageManager(object): 14 | def __init__(self, maxInFlight=3): 15 | self.maxInFlight = maxInFlight 16 | 17 | self._allImages = [] 18 | 19 | def addLazyImage(self, *args, **kwds): 20 | self.add(LazyImage(*args, **kwds)) 21 | 22 | def add(self, lazyImage): 23 | self._allImages.append(lazyImage) 24 | 25 | def request(self): 26 | """Continue the loading process.""" 27 | 28 | if self.numInFlight < self.maxInFlight and self.numInQueue > 0: 29 | self._requestNextImage() 30 | 31 | for lazyImage in self.allImages: 32 | lazyImage.check() 33 | 34 | def _requestNextImage(self): 35 | if self.numInQueue == 0: 36 | return 37 | nextImage = self.lazyImageQueue[0] 38 | nextImage.request() 39 | 40 | @property 41 | def allLazyImagesLoaded(self): 42 | return self.numTotal > 0 and self.numTotal == self.numLoaded 43 | 44 | @property 45 | def allImages(self): 46 | return self._allImages 47 | @property 48 | def numTotal(self): 49 | return len(self.allImages) 50 | 51 | @property 52 | def lazyImageQueue(self): 53 | return filter(lambda img: img.pending, self.allImages) 54 | @property 55 | def numInQueue(self): 56 | return len(self.lazyImageQueue) 57 | 58 | @property 59 | def imagesInFlight(self): 60 | return filter(lambda img: img.requesting, self.allImages) 61 | @property 62 | def numInFlight(self): 63 | return len(self.imagesInFlight) 64 | 65 | @property 66 | def imagesLoaded(self): 67 | return filter(lambda img: img.loaded, self.allImages) 68 | @property 69 | def numLoaded(self): 70 | return len(self.imagesLoaded) 71 | 72 | 73 | class LazyImage(object): 74 | """Class to load images lazily using the dumb Processing.py requestImage() function. 75 | 76 | The problem is that Processing.py doesn't yet support Pythonic patterns, like providing 77 | callback functions to complete aynchronous operations. 78 | """ 79 | 80 | def __init__(self, url, callback, meta={}): 81 | self.url = url 82 | self.callback = callback # What to do when the image is loaded. 83 | self.meta = meta 84 | 85 | self.img = None # PImage 86 | self._done = False 87 | 88 | def request(self): 89 | if self.img is not None: 90 | return 91 | self.img = requestImage(self.url) 92 | 93 | def check(self): 94 | if self._done: 95 | return True 96 | 97 | if self.pending: 98 | return False 99 | if self.requesting: 100 | return False 101 | if self.error: 102 | # Error 103 | return True # We're still done though. 104 | if not self._done: 105 | # Success! 106 | self._done = True 107 | self.callback(self.img, self.meta) 108 | return True 109 | 110 | @property 111 | def loaded(self): 112 | if self.img is None: 113 | return False 114 | return self.img.width != 0 and self._done 115 | @property 116 | def requesting(self): 117 | if self.img is None: 118 | return False 119 | return self.img.width == 0 120 | @property 121 | def error(self): 122 | if self.img is None: 123 | return False 124 | return self.img.width == -1 125 | @property 126 | def pending(self): 127 | return self.img is None 128 | --------------------------------------------------------------------------------