├── data ├── geoJSON.zip └── 100k_US_cities.csv ├── requirements.txt ├── alembic ├── script.py.mako ├── versions │ ├── f78c5b7d4a52_add_osm_solar_node_table.py │ ├── d9ccb1fc3ced_add_centroid_distance_index.py │ ├── e49f0ac2240d_add_positive_clusters.py │ └── a8825815024c_add_columns_and_ON_CONFLICT_primary_key.py └── env.py ├── setup ├── Dockerfile.base ├── Dockerfile ├── environment_cpu.yml ├── environment_gpu.yml └── build_docker_images.sh ├── alembic.ini ├── .gitignore ├── gather_city_shapes.py ├── run_entire_process.py ├── maproulette.py ├── README.md ├── run_inference.py ├── imagery.py ├── solardb.py ├── process_city_shapes.py └── LICENSE /data/geoJSON.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brubsby/SolarPanelDataWrangler/HEAD/data/geoJSON.zip -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scikit-image 2 | certifi 3 | chardet 4 | geojson 5 | idna 6 | numpy 7 | requests 8 | Shapely 9 | urllib3 10 | sqlalchemy 11 | geojsonio 12 | geopandas 13 | alembic 14 | mapbox 15 | overpy 16 | # rtree also needs https://libspatialindex.org/#download, only necessary if running maproulette.py with filtering 17 | rtree -------------------------------------------------------------------------------- /alembic/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | ${imports if imports else ""} 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = ${repr(up_revision)} 14 | down_revision = ${repr(down_revision)} 15 | branch_labels = ${repr(branch_labels)} 16 | depends_on = ${repr(depends_on)} 17 | 18 | 19 | def upgrade(): 20 | ${upgrades if upgrades else "pass"} 21 | 22 | 23 | def downgrade(): 24 | ${downgrades if downgrades else "pass"} 25 | -------------------------------------------------------------------------------- /alembic/versions/f78c5b7d4a52_add_osm_solar_node_table.py: -------------------------------------------------------------------------------- 1 | """add osm solar node table 2 | 3 | Revision ID: f78c5b7d4a52 4 | Revises: a8825815024c 5 | Create Date: 2019-03-28 22:02:12.405302 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = 'f78c5b7d4a52' 14 | down_revision = 'a8825815024c' 15 | branch_labels = None 16 | depends_on = None 17 | 18 | 19 | def upgrade(): 20 | # ### commands auto generated by Alembic - please adjust! ### 21 | op.drop_table('solar_nodes') 22 | # ### end Alembic commands ### 23 | 24 | 25 | def downgrade(): 26 | # ### commands auto generated by Alembic - please adjust! ### 27 | op.create_table('solar_nodes', 28 | sa.Column('longitude', sa.FLOAT(), nullable=False), 29 | sa.Column('latitude', sa.FLOAT(), nullable=False), 30 | sa.PrimaryKeyConstraint('longitude', 'latitude', sqlite_on_conflict='IGNORE') 31 | ) 32 | # ### end Alembic commands ### 33 | -------------------------------------------------------------------------------- /alembic/versions/d9ccb1fc3ced_add_centroid_distance_index.py: -------------------------------------------------------------------------------- 1 | """add centroid distance index 2 | 3 | Revision ID: d9ccb1fc3ced 4 | Revises: f78c5b7d4a52 5 | Create Date: 2019-03-29 08:57:01.226643 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = 'd9ccb1fc3ced' 14 | down_revision = 'f78c5b7d4a52' 15 | branch_labels = None 16 | depends_on = None 17 | 18 | 19 | def upgrade(): 20 | # ### commands auto generated by Alembic - please adjust! ### 21 | with op.batch_alter_table('slippy_tiles', schema=None) as batch_op: 22 | batch_op.create_index('centroid_index', ['polygon_name', 'centroid_distance'], unique=False) 23 | 24 | # ### end Alembic commands ### 25 | 26 | 27 | def downgrade(): 28 | # ### commands auto generated by Alembic - please adjust! ### 29 | with op.batch_alter_table('slippy_tiles', schema=None) as batch_op: 30 | batch_op.drop_index('centroid_index') 31 | 32 | # ### end Alembic commands ### 33 | -------------------------------------------------------------------------------- /setup/Dockerfile.base: -------------------------------------------------------------------------------- 1 | ARG base_image=ubuntu:16.04 2 | FROM ${base_image} 3 | LABEL maintainer="Sean Sall " 4 | 5 | ARG conda_version 6 | ARG user 7 | 8 | ENV CONDA_DIRPATH /opt/conda 9 | ENV PATH $CONDA_DIRPATH/bin:$PATH 10 | ENV USER_UID 1000 11 | 12 | RUN apt-get update && apt-get install -y \ 13 | bzip2 \ 14 | cmake \ 15 | g++ \ 16 | git \ 17 | graphviz \ 18 | libgl1-mesa-glx \ 19 | libhdf5-dev \ 20 | rtorrent \ 21 | sudo \ 22 | tmux \ 23 | vim \ 24 | wget 25 | 26 | RUN mkdir -p $CONDA_DIRPATH && \ 27 | cd $CONDA_DIRPATH && \ 28 | wget https://repo.continuum.io/miniconda/Miniconda3-${conda_version}-Linux-x86_64.sh && \ 29 | chmod u+x Miniconda3-${conda_version}-Linux-x86_64.sh && \ 30 | ./Miniconda3-${conda_version}-Linux-x86_64.sh -b -f -p $CONDA_DIRPATH && \ 31 | conda install conda=4.6.11 && \ 32 | conda install python=3.6.8 && \ 33 | rm Miniconda3-${conda_version}-Linux-x86_64.sh 34 | 35 | RUN useradd -m -s /bin/bash -N -u $USER_UID $user && \ 36 | echo "$user:$user" | chpasswd && adduser $user sudo && \ 37 | chown -R $user $CONDA_DIRPATH && \ 38 | echo "$user ALL=NOPASSWD: ALL" > /etc/sudoers.d/$user && \ 39 | echo ". /opt/conda/etc/profile.d/conda.sh" >> /home/$user/.bashrc 40 | 41 | WORKDIR /home/$user 42 | USER $user 43 | -------------------------------------------------------------------------------- /setup/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM spdw/base 2 | LABEL maintainer="Sean Sall " 3 | 4 | ARG fname_environment_yml 5 | ARG conda_version 6 | ARG user 7 | ARG branch 8 | 9 | USER $user 10 | 11 | RUN mkdir $HOME/repos && \ 12 | cd $HOME/repos && \ 13 | git clone https://github.com/typicalTYLER/SolarPanelDataWrangler.git && \ 14 | git clone https://github.com/typicalTYLER/DeepSolar.git 15 | 16 | USER root 17 | RUN cd /opt && \ 18 | wget http://download.osgeo.org/libspatialindex/spatialindex-src-1.8.5.tar.gz && \ 19 | tar -xvf spatialindex-src-1.8.5.tar.gz && \ 20 | cd spatialindex-src-1.8.5 && \ 21 | ./configure; make; make install 22 | 23 | USER $user 24 | RUN cd $HOME/repos/SolarPanelDataWrangler &&\ 25 | git checkout $branch && \ 26 | cd $HOME/repos/SolarPanelDataWrangler/setup && \ 27 | conda install conda=$conda_version && \ 28 | conda env create -f $fname_environment_yml && \ 29 | cd $HOME 30 | 31 | RUN mkdir -p ~/.config/matplotlib && \ 32 | echo "backend: Agg" > ~/.config/matplotlib/matplotlibrc 33 | 34 | RUN cd $HOME/repos/DeepSolar && \ 35 | mkdir ckpt && \ 36 | cd ckpt && \ 37 | wget https://s3-us-west-1.amazonaws.com/roofsolar/inception_classification.tar.gz && \ 38 | wget https://s3-us-west-1.amazonaws.com/roofsolar/inception_segmentation.tar.gz && \ 39 | tar xzf inception_classification.tar.gz && \ 40 | tar xzf inception_segmentation.tar.gz 41 | -------------------------------------------------------------------------------- /alembic/versions/e49f0ac2240d_add_positive_clusters.py: -------------------------------------------------------------------------------- 1 | """add positive clusters 2 | 3 | Revision ID: e49f0ac2240d 4 | Revises: d9ccb1fc3ced 5 | Create Date: 2019-04-06 21:13:17.289431 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = 'e49f0ac2240d' 14 | down_revision = 'd9ccb1fc3ced' 15 | branch_labels = None 16 | depends_on = None 17 | 18 | 19 | naming_convention = { 20 | "fk": 21 | "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", 22 | } 23 | 24 | 25 | def upgrade(): 26 | # ### commands auto generated by Alembic - please adjust! ### 27 | with op.batch_alter_table('slippy_tiles', naming_convention=naming_convention, schema=None) as batch_op: 28 | batch_op.add_column(sa.Column('cluster_id', sa.String(), nullable=True)) 29 | batch_op.create_foreign_key('fk_slippy_tiles_cluster_id_positive_clusters', 'positive_clusters', ['cluster_id'], 30 | ['id']) 31 | 32 | # ### end Alembic commands ### 33 | 34 | 35 | def downgrade(): 36 | # ### commands auto generated by Alembic - please adjust! ### 37 | with op.batch_alter_table('slippy_tiles', naming_convention=naming_convention, schema=None) as batch_op: 38 | batch_op.drop_constraint('fk_slippy_tiles_cluster_id_positive_clusters', type_='foreignkey') 39 | batch_op.drop_column('cluster_id') 40 | 41 | # ### end Alembic commands ### 42 | -------------------------------------------------------------------------------- /alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # path to migration scripts 5 | script_location = alembic 6 | 7 | # template used to generate migration files 8 | # file_template = %%(rev)s_%%(slug)s 9 | 10 | # timezone to use when rendering the date 11 | # within the migration file as well as the filename. 12 | # string value is passed to dateutil.tz.gettz() 13 | # leave blank for localtime 14 | # timezone = 15 | 16 | # max length of characters to apply to the 17 | # "slug" field 18 | #truncate_slug_length = 40 19 | 20 | # set to 'true' to run the environment during 21 | # the 'revision' command, regardless of autogenerate 22 | # revision_environment = false 23 | 24 | # set to 'true' to allow .pyc and .pyo files without 25 | # a source .py file to be detected as revisions in the 26 | # versions/ directory 27 | # sourceless = false 28 | 29 | # version location specification; this defaults 30 | # to alembic/versions. When using multiple version 31 | # directories, initial revisions must be specified with --version-path 32 | # version_locations = %(here)s/bar %(here)s/bat alembic/versions 33 | 34 | # the output encoding used when revision files 35 | # are written from script.py.mako 36 | # output_encoding = utf-8 37 | 38 | sqlalchemy.url = sqlite:///data/solar.db 39 | 40 | 41 | # Logging configuration 42 | [loggers] 43 | keys = root,sqlalchemy,alembic 44 | 45 | [handlers] 46 | keys = console 47 | 48 | [formatters] 49 | keys = generic 50 | 51 | [logger_root] 52 | level = WARN 53 | handlers = console 54 | qualname = 55 | 56 | [logger_sqlalchemy] 57 | level = WARN 58 | handlers = 59 | qualname = sqlalchemy.engine 60 | 61 | [logger_alembic] 62 | level = INFO 63 | handlers = 64 | qualname = alembic 65 | 66 | [handler_console] 67 | class = StreamHandler 68 | args = (sys.stderr,) 69 | level = NOTSET 70 | formatter = generic 71 | 72 | [formatter_generic] 73 | format = %(levelname)-5.5s [%(name)s] %(message)s 74 | datefmt = %H:%M:%S 75 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | 125 | ## repository specific 126 | /data/imagery 127 | /data/solar.db 128 | -------------------------------------------------------------------------------- /alembic/env.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | 3 | import os 4 | import sys 5 | from logging.config import fileConfig 6 | 7 | from sqlalchemy import engine_from_config 8 | from sqlalchemy import pool 9 | 10 | from alembic import context 11 | 12 | 13 | sys.path.append(os.getcwd()) 14 | 15 | import solardb 16 | 17 | # this is the Alembic Config object, which provides 18 | # access to the values within the .ini file in use. 19 | config = context.config 20 | 21 | # Interpret the config file for Python logging. 22 | # This line sets up loggers basically. 23 | fileConfig(config.config_file_name) 24 | 25 | # add your model's MetaData object here 26 | # for 'autogenerate' support 27 | # from myapp import mymodel 28 | # target_metadata = mymodel.Base.metadata 29 | target_metadata = solardb.Base.metadata 30 | 31 | # other values from the config, defined by the needs of env.py, 32 | # can be acquired: 33 | # my_important_option = config.get_main_option("my_important_option") 34 | # ... etc. 35 | 36 | 37 | def run_migrations_offline(): 38 | """Run migrations in 'offline' mode. 39 | 40 | This configures the context with just a URL 41 | and not an Engine, though an Engine is acceptable 42 | here as well. By skipping the Engine creation 43 | we don't even need a DBAPI to be available. 44 | 45 | Calls to context.execute() here emit the given string to the 46 | script output. 47 | 48 | """ 49 | url = config.get_main_option("sqlalchemy.url") 50 | context.configure( 51 | url=url, target_metadata=target_metadata, literal_binds=True, render_as_batch=True 52 | ) 53 | 54 | with context.begin_transaction(): 55 | context.run_migrations() 56 | 57 | 58 | def run_migrations_online(): 59 | """Run migrations in 'online' mode. 60 | 61 | In this scenario we need to create an Engine 62 | and associate a connection with the context. 63 | 64 | """ 65 | connectable = engine_from_config( 66 | config.get_section(config.config_ini_section), 67 | prefix="sqlalchemy.", 68 | poolclass=pool.NullPool, 69 | ) 70 | 71 | with connectable.connect() as connection: 72 | context.configure( 73 | connection=connection, target_metadata=target_metadata, render_as_batch=True 74 | ) 75 | 76 | with context.begin_transaction(): 77 | context.run_migrations() 78 | 79 | 80 | if context.is_offline_mode(): 81 | run_migrations_offline() 82 | else: 83 | run_migrations_online() 84 | -------------------------------------------------------------------------------- /gather_city_shapes.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import csv 3 | import json 4 | import os 5 | 6 | import requests 7 | 8 | 9 | def get_filename(city, state): 10 | return city.replace(' ', '_') + '.' + state.replace(' ', '_') + '.json' 11 | 12 | 13 | def get_city_state_tuples(csvpath): 14 | with open(csvpath, 'r') as csvfile: 15 | reader = csv.reader(csvfile, skipinitialspace=True) 16 | for row in reader: 17 | city = row[0] 18 | state = row[1] 19 | yield city, state 20 | 21 | 22 | def get_city_state_filepaths(csvpath): 23 | for city, state in get_city_state_tuples(csvpath): 24 | yield city, state, os.path.join('data', 'geoJSON', get_filename(city, state)) 25 | 26 | 27 | def gather(csvpath): 28 | for city, state, filepath in get_city_state_filepaths(csvpath): 29 | if not os.path.isfile(filepath): 30 | with open(filepath, 'w') as outfile: 31 | json.dump(query_nominatim_for_geojson(city, state), outfile) 32 | 33 | 34 | def query_nominatim_for_geojson(city=None, state=None, county=None, country=None): 35 | url = "https://nominatim.openstreetmap.org/search?" 36 | if city: 37 | url += "city=" + city + "&" 38 | if state: 39 | url += "state=" + state + "&" 40 | if county: 41 | url += "county=" + county + "&" 42 | if country: 43 | url += "country=" + country + "&" 44 | url += "polygon_geojson=1&format=json" 45 | response = requests.get( 46 | url) 47 | if response.ok: 48 | response_json = response.json() 49 | for single_json in response_json: 50 | feature_type = single_json.get('geojson').get('type') 51 | if feature_type == 'Polygon' or feature_type == 'MultiPolygon': 52 | return single_json['geojson'] 53 | raise ValueError("No suitable polygons found for url: {}".format(url)) 54 | else: 55 | raise ConnectionError(response.content) 56 | 57 | 58 | # These cities are hard to programmatically get for some reason or another, so you have to use the method here to fix 59 | # your data by hand: 60 | # https://gis.stackexchange.com/questions/183248/getting-polygon-boundaries-of-city-in-json-from-google-maps-api 61 | def get_degenerate_cities(csvpath): 62 | for city, state, filepath in get_city_state_filepaths(csvpath): 63 | if os.path.isfile(filepath): 64 | with open(filepath, 'r') as infile: 65 | json_dict = json.load(infile) 66 | if json_dict['type'] != 'Polygon' and json_dict['type'] != 'MultiPolygon': 67 | yield city, state 68 | 69 | 70 | if __name__ == '__main__': 71 | parser = argparse.ArgumentParser(description='Gather and process shapes of cities from OSM') 72 | parser.add_argument('--input_csv', dest='csvpath', default=os.path.join('data', '100k_US_cities.csv'), 73 | help='specify the csv list of city and state names to gather geoJSON for') 74 | parser.add_argument('--gather', dest='gather', action='store_const', 75 | const=True, default=False, 76 | help='Run the gather portion of this script, which uses the csv input to gather geoJSON shapes' 77 | 'from OSM for each city/state pair') 78 | args = parser.parse_args() 79 | 80 | if args.gather: 81 | gather(args.csvpath) 82 | -------------------------------------------------------------------------------- /alembic/versions/a8825815024c_add_columns_and_ON_CONFLICT_primary_key.py: -------------------------------------------------------------------------------- 1 | """add columns and ON CONFLICT primary key 2 | 3 | Wasn't able to get this migrate working in sqlite due to altering a primary key, 4 | just did the migrate by hand via this method: https://stackoverflow.com/a/14353595/3586848 5 | I've left my notes/attempt here commented out just in case someone wants to try and do it 6 | 7 | Revision ID: a8825815024c 8 | Revises: 9 | Create Date: 2019-03-25 15:45:05.011747 10 | 11 | """ 12 | import sqlalchemy as sa 13 | from alembic import op 14 | from sqlalchemy import Column, Integer, String, Float, ForeignKey, Boolean, PrimaryKeyConstraint, orm 15 | 16 | # revision identifiers, used by Alembic. 17 | from sqlalchemy.ext.declarative import declarative_base 18 | from sqlalchemy.orm import relationship 19 | from sqlalchemy.sql import expression 20 | 21 | revision = 'a8825815024c' 22 | down_revision = None 23 | branch_labels = None 24 | depends_on = None 25 | 26 | Base1 = declarative_base() 27 | Base2 = declarative_base() 28 | 29 | 30 | class SlippyTileOld(Base1): 31 | __tablename__ = 'slippy_tiles' 32 | 33 | row = Column(Integer, nullable=False, primary_key=True) 34 | column = Column(Integer, nullable=False, primary_key=True) 35 | zoom = Column(Integer, nullable=False, primary_key=True) 36 | centroid_distance = Column(Float) 37 | polygon_name = Column(String, ForeignKey('search_polygons.name')) 38 | polygon = relationship("SearchPolygon") 39 | has_image = Column(Boolean, nullable=False, server_default=expression.false()) 40 | inference_ran = Column(Boolean, nullable=False, server_default=expression.false()) 41 | inference_timestamp = Column(Integer, nullable=True) # UNIX EPOCH 42 | 43 | 44 | class SlippyTileNew(Base2): 45 | __tablename__ = 'slippy_tiles' 46 | 47 | row = Column(Integer, nullable=False) 48 | column = Column(Integer, nullable=False) 49 | zoom = Column(Integer, nullable=False) 50 | centroid_distance = Column(Float) 51 | polygon_name = Column(String, ForeignKey('search_polygons.name')) 52 | polygon = relationship("SearchPolygon") 53 | has_image = Column(Boolean, nullable=False, server_default=expression.false()) 54 | inference_ran = Column(Boolean, nullable=False, server_default=expression.false()) 55 | inference_timestamp = Column(Integer, nullable=True) # UNIX EPOCH 56 | panel_softmax = Column(Float, nullable=True) 57 | panel_seen_by_human = Column(Boolean, nullable=True, server_default=expression.false()) 58 | panel_verified = Column(Boolean, nullable=True, server_default=expression.false()) 59 | 60 | __table_args__ = ( 61 | PrimaryKeyConstraint(row, column, zoom, sqlite_on_conflict='IGNORE'), 62 | ) 63 | 64 | 65 | def upgrade(): 66 | pass 67 | # bind = op.get_bind() 68 | # session = orm.Session(bind=bind) 69 | # old_tiles = session.query(SlippyTileOld).all() 70 | # 71 | # SlippyTileOld.__table__.drop(bind) 72 | # session.commit() 73 | # 74 | # SlippyTileNew.__table__.create(bind) 75 | # new_tiles = [SlippyTileNew(old_tile) for old_tile in old_tiles] 76 | # session.add_all(new_tiles) 77 | # session.commit() 78 | # session.close() 79 | 80 | 81 | def downgrade(): 82 | pass 83 | # bind = op.get_bind() 84 | # session = orm.Session(bind=bind) 85 | # old_tiles = session.query(SlippyTileNew).all() 86 | # 87 | # SlippyTileNew.__table__.drop(bind) 88 | # session.commit() 89 | # 90 | # SlippyTileOld.__table__.create(bind) 91 | # old_tiles = [SlippyTileNew(new_tile) for new_tile in old_tiles] 92 | # session.add_all(old_tiles) 93 | -------------------------------------------------------------------------------- /run_entire_process.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | import geopandas 5 | from geojsonio import geojsonio 6 | from shapely.geometry import shape 7 | 8 | import gather_city_shapes 9 | import maproulette 10 | import process_city_shapes 11 | import run_inference 12 | import solardb 13 | 14 | ZOOM = 21 15 | BATCHES_BETWEEN_DELETE = 100 16 | 17 | parser = argparse.ArgumentParser(description='Give the search parameters to find a location (usually city/state ' 18 | 'sufficient), and this script will attempt to find all the solar panels in' 19 | ' that area (given enough time)') 20 | parser.add_argument('--city', dest='city', help='city parameter to pass to nominatim') 21 | parser.add_argument('--county', dest='county', help='county parameter to pass to nominatim') 22 | parser.add_argument('--state', dest='state', help='state parameter to pass to nominatim') 23 | parser.add_argument('--country', dest='country', help='country parameter to pass to nominatim') 24 | parser.add_argument('-q', '--no-geojsonio', dest='no_geojsonio', action='store_const', const=True, default=False, 25 | help='don\'t open geojson windows') 26 | parser.add_argument('--classification-checkpoint', dest='classification_checkpoint', 27 | default=os.path.join('..', 'DeepSolar', 'ckpt', 'inception_classification'), 28 | help='Path to DeepSolar classification checkpoint.') 29 | parser.add_argument('--segmentation-checkpoint', dest='segmentation_checkpoint', 30 | default=os.path.join('..', 'DeepSolar', 'ckpt', 'inception_segmentation'), 31 | help='Path to DeepSolar segmentation checkpoint.') 32 | 33 | args = parser.parse_args() 34 | 35 | polygon_name_params = [args.city, args.county, args.state, args.country] 36 | polygon_name = ', '.join([polygon_name_param for polygon_name_param in polygon_name_params if polygon_name_param]) 37 | 38 | print("Searching OSM for a polygon for: {}".format(polygon_name)) 39 | # Get a polygon from nomanatim for the given area parameters https://wiki.openstreetmap.org/wiki/Nominatim 40 | polygon = gather_city_shapes.query_nominatim_for_geojson(city=args.city, county=args.county, state=args.state, 41 | country=args.country) 42 | 43 | print("Checking if this search polygon is already tracked in the database.") 44 | # If inner coords have been calculated for this polygon, we can skip to later 45 | names = solardb.get_inner_coords_calculated_polygon_names() 46 | if polygon_name not in names: 47 | 48 | print("Found a polygon, simplifying it.") 49 | # Make it simpler (makes calculation of inner grid quicker) 50 | polygon = process_city_shapes.simplify_polygon(polygon) 51 | 52 | if not args.no_geojsonio: 53 | # Create a link to geojsonio for the polygon to double check correctness 54 | print(geojsonio.make_url(geopandas.GeoSeries([polygon]).to_json())) 55 | input("A geojson.io link has been created with your simplified search polygon, press enter to continue if it " 56 | "looks okay. If it doesn't, implement a way to edit your polygon and feed it directly to this script :)") 57 | 58 | print("Calculating the coordinates of the imagery grid contained within this polygon.") 59 | # This step is necessary so we know what images to query in this polygon, it also persists these in the db 60 | process_city_shapes.calculate_inner_coordinates([polygon_name], [polygon], zoom=ZOOM) 61 | 62 | print("Calculating the distance to the search polygon's centroid from each point if it hasn't been done before.") 63 | # This step is just so we have an order for which coordinates to search first (outwards from the middle) 64 | solardb.compute_centroid_distances() 65 | 66 | print("Running classification on every tile in the search polygon that hasn't had inference ran yet.") 67 | # You should be able to SIGINT at this point if it's taking forever and it should pick up where it left off if you do 68 | run_inference.run_classification(args.classification_checkpoint, args.segmentation_checkpoint, BATCHES_BETWEEN_DELETE) 69 | 70 | print("Querying OpenStreetMap for existing solar panels in this search polygon.") 71 | # This will requery every time, but it's good because you want your task to filter the newly added panels out. 72 | solardb.query_and_persist_osm_solar([shape(polygon)]) 73 | 74 | print("Detecting clusters of positive classification tiles.") 75 | run_inference.detect_clusters() 76 | 77 | print("Generating line-by-line geoJSON file that represents a MapRoulette challenge where each task is a cluster of " 78 | "found panels containing no existing OSM solar nodes or ways, saved as ./data/{}" 79 | .format(maproulette.get_maproulette_geojson_filename(polygon_name))) 80 | maproulette.create_clustered_maproulette_geojson(polygon_name=polygon_name, filter_existing_osm_panels=True) 81 | 82 | -------------------------------------------------------------------------------- /maproulette.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import os 3 | from collections import defaultdict 4 | 5 | from rtree import index 6 | from shapely import geometry 7 | from shapely.ops import cascaded_union 8 | 9 | import solardb 10 | from process_city_shapes import num2deg 11 | 12 | GEOJSON_STRING = \ 13 | '{{"type": "FeatureCollection", "features": [{{"type": "Feature", "properties": {{"prediction_confidence": ' \ 14 | '{confidence}}}, "geometry": {{"type": "Polygon", "coordinates": [{points}]}}}}]}}\n' 15 | 16 | 17 | def create_simple_maproulette_geojson(threshold=0.25, polygon_name=None): 18 | tiles = solardb.query_tiles_over_threshold(threshold=threshold, polygon_name=polygon_name) 19 | with open(os.path.join("data", (polygon_name or "") + "maproulette.geojson"), "w") as the_file: 20 | for tile in tiles: 21 | bounding_polygon_slippy_coordinates = [ 22 | (tile.column, tile.row), 23 | (tile.column + 1, tile.row), 24 | (tile.column + 1, tile.row + 1), 25 | (tile.column, tile.row + 1), 26 | (tile.column, tile.row) 27 | ] 28 | bounding_polygon_lon_lat_coordinates = \ 29 | map(functools.partial(num2deg, center=False), bounding_polygon_slippy_coordinates) 30 | 31 | points = str([list(coordinates) for coordinates in bounding_polygon_lon_lat_coordinates]) 32 | confidence = tile.panel_softmax 33 | the_file.write(GEOJSON_STRING.format(points=points, confidence=confidence)) 34 | 35 | 36 | def get_clustered_positive_polygon_dicts(threshold=0.25, polygon_name=None): 37 | tiles = solardb.query_tiles_over_threshold(threshold=threshold, polygon_name=polygon_name) 38 | cluster_to_tile_map = defaultdict(list) 39 | for tile in tiles: 40 | cluster_to_tile_map[tile.cluster_id].append(tile) 41 | polygon_dicts = [] 42 | for cluster_id, tiles in cluster_to_tile_map.items(): 43 | bounding_polygons_slippy_coordinates = [] 44 | for tile in tiles: 45 | bounding_polygon_slippy_coordinates = [ 46 | (tile.column, tile.row), 47 | (tile.column + 1, tile.row), 48 | (tile.column + 1, tile.row + 1), 49 | (tile.column, tile.row + 1), 50 | (tile.column, tile.row) 51 | ] 52 | bounding_polygons_slippy_coordinates.append( 53 | geometry.Polygon([[p[0], p[1]] for p in bounding_polygon_slippy_coordinates])) 54 | unioned_slippy_coordinate_polygon = cascaded_union(bounding_polygons_slippy_coordinates) 55 | slippy_coordinate_bounding_polygon_coordinates = \ 56 | zip(*unioned_slippy_coordinate_polygon.exterior.xy) 57 | bounding_polygon_lon_lat_coordinates = \ 58 | list(map(functools.partial(num2deg, center=False), slippy_coordinate_bounding_polygon_coordinates)) 59 | string_points = str([list(coordinates) for coordinates in bounding_polygon_lon_lat_coordinates]) 60 | confidence = max(tile.panel_softmax for tile in tiles) 61 | polygon_dicts.append({ 62 | "bounding_polygon_lon_lat_coordinates": bounding_polygon_lon_lat_coordinates, 63 | "string_points": string_points, 64 | "confidence": confidence 65 | }) 66 | return polygon_dicts 67 | 68 | 69 | def filter_polygon_dicts_based_off_osm_panels(polygon_dicts): 70 | panel_nodes = solardb.get_osm_pv_nodes() 71 | polygon_dict_map = {} 72 | for i, polygon_dict in enumerate(polygon_dicts): 73 | polygon_dict_map[i] = polygon_dict 74 | polygon_enumeration = [] 75 | for i, polygon_dict in polygon_dict_map.items(): 76 | polygon_enumeration.append((i, geometry.Polygon(polygon_dict["bounding_polygon_lon_lat_coordinates"]))) 77 | spatial_index = index.Index(polygon_rtree_generator(polygon_enumeration)) 78 | for node_lon_lat_tuple in panel_nodes: 79 | for intersecting_item in spatial_index.intersection(node_lon_lat_tuple + node_lon_lat_tuple, objects=True): 80 | if intersecting_item.object.contains(geometry.Point(node_lon_lat_tuple)): 81 | spatial_index.delete(intersecting_item.id, intersecting_item.bounds) 82 | polygon_dict_map.pop(intersecting_item.id, None) 83 | return polygon_dict_map.values() 84 | 85 | 86 | def polygon_rtree_generator(polygon_enumeration): 87 | for i, polygon in polygon_enumeration: 88 | yield (i, polygon.bounds, polygon) 89 | 90 | 91 | def create_clustered_maproulette_geojson(threshold=0.25, polygon_name=None, filter_existing_osm_panels=True): 92 | polygon_dicts = get_clustered_positive_polygon_dicts(threshold=threshold, polygon_name=polygon_name) 93 | if filter_existing_osm_panels: 94 | polygon_dicts = filter_polygon_dicts_based_off_osm_panels(polygon_dicts) 95 | with open(os.path.join("data", get_maproulette_geojson_filename(polygon_name)), "w") as the_file: 96 | for polygon_dict in polygon_dicts: 97 | the_file.write(GEOJSON_STRING.format(points=polygon_dict["string_points"], 98 | confidence=polygon_dict["confidence"])) 99 | 100 | 101 | def get_maproulette_geojson_filename(polygon_name): 102 | if not polygon_name: 103 | return "maproulette.geojson" 104 | return polygon_name.replace(', ', '_') + "_maproulette.geojson" 105 | 106 | 107 | if __name__ == "__main__": 108 | create_clustered_maproulette_geojson() 109 | -------------------------------------------------------------------------------- /setup/environment_cpu.yml: -------------------------------------------------------------------------------- 1 | name: spdw 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - _tflow_select=2.3.0=mkl 7 | - absl-py=0.7.0=py36_0 8 | - alembic=1.0.8=py_0 9 | - asn1crypto=0.24.0=py36_0 10 | - astor=0.7.1=py36_0 11 | - attrs=19.1.0=py36_1 12 | - backcall=0.1.0=py36_0 13 | - blas=1.0=mkl 14 | - bzip2=1.0.6=h14c3975_5 15 | - c-ares=1.15.0=h7b6447c_1 16 | - ca-certificates=2019.1.23=0 17 | - cairo=1.14.12=h8948797_3 18 | - certifi=2019.3.9=py36_0 19 | - cffi=1.12.2=py36h2e261b9_1 20 | - chardet=3.0.4=py36_1 21 | - click=7.0=py36_0 22 | - click-plugins=1.0.4=py36_0 23 | - cligj=0.5.0=py36_0 24 | - cloudpickle=0.8.0=py36_0 25 | - cryptography=2.6.1=py36h1ba5d50_0 26 | - curl=7.64.0=hbc83047_2 27 | - cycler=0.10.0=py36_0 28 | - cytoolz=0.9.0.1=py36h14c3975_1 29 | - dask-core=1.1.4=py36_1 30 | - dbus=1.13.6=h746ee38_0 31 | - decorator=4.4.0=py36_1 32 | - descartes=1.1.0=py36_0 33 | - expat=2.2.6=he6710b0_0 34 | - fiona=1.8.4=py36hc38cc03_0 35 | - fontconfig=2.13.0=h9420a91_0 36 | - freetype=2.9.1=h8a8886c_1 37 | - freexl=1.0.5=h14c3975_0 38 | - gast=0.2.2=py36_0 39 | - gdal=2.3.3=py36hbb2a789_0 40 | - geojson=2.4.1=py_0 41 | - geojsonio=0.0.3=py_0 42 | - geopandas=0.4.1=py_0 43 | - geos=3.7.1=he6710b0_0 44 | - giflib=5.1.4=h14c3975_1 45 | - github3.py=1.3.0=py_0 46 | - glib=2.56.2=hd408876_0 47 | - grpcio=1.16.1=py36hf8bcb03_1 48 | - gst-plugins-base=1.14.0=hbbd80ab_1 49 | - gstreamer=1.14.0=hb453b48_1 50 | - h5py=2.9.0=py36h7918eee_0 51 | - hdf4=4.2.13=h3ca952b_2 52 | - hdf5=1.10.4=hb1b8bf9_0 53 | - icu=58.2=h9c2bf20_1 54 | - idna=2.8=py36_0 55 | - imageio=2.5.0=py36_0 56 | - intel-openmp=2019.3=199 57 | - ipython=7.4.0=py36h39e3cac_0 58 | - ipython_genutils=0.2.0=py36_0 59 | - jedi=0.13.3=py36_0 60 | - jpeg=9b=h024ee3a_2 61 | - json-c=0.13.1=h1bed415_0 62 | - jwcrypto=0.6.0=py_0 63 | - kealib=1.4.7=hd0c454d_6 64 | - keras-applications=1.0.7=py_0 65 | - keras-preprocessing=1.0.9=py_0 66 | - kiwisolver=1.0.1=py36hf484d3e_0 67 | - krb5=1.16.1=h173b8e3_7 68 | - libboost=1.67.0=h46d08c1_4 69 | - libcurl=7.64.0=h20c2e04_2 70 | - libdap4=3.19.1=h6ec2957_0 71 | - libedit=3.1.20181209=hc058e9b_0 72 | - libffi=3.2.1=hd88cf55_4 73 | - libgcc-ng=8.2.0=hdf63c60_1 74 | - libgdal=2.3.3=h2e7e64b_0 75 | - libgfortran-ng=7.3.0=hdf63c60_0 76 | - libkml=1.3.0=h590aaf7_4 77 | - libnetcdf=4.6.1=h11d0813_2 78 | - libpng=1.6.36=hbc83047_0 79 | - libpq=11.2=h20c2e04_0 80 | - libprotobuf=3.6.1=hd408876_0 81 | - libspatialindex=1.8.5=h20b78c2_2 82 | - libspatialite=4.3.0a=hb08deb6_19 83 | - libssh2=1.8.0=h1ba5d50_4 84 | - libstdcxx-ng=8.2.0=hdf63c60_1 85 | - libtiff=4.0.10=h2733197_2 86 | - libuuid=1.0.3=h1bed415_2 87 | - libxcb=1.13=h1bed415_1 88 | - libxml2=2.9.9=he19cac6_0 89 | - mapclassify=2.0.1=py_0 90 | - markdown=3.0.1=py36_0 91 | - markupsafe=1.1.1=py36h7b6447c_0 92 | - matplotlib=3.0.3=py36h5429711_0 93 | - mkl=2019.3=199 94 | - mkl_fft=1.0.10=py36ha843d7b_0 95 | - mkl_random=1.0.2=py36hd81dba3_0 96 | - munch=2.3.2=py36_0 97 | - ncurses=6.1=he6710b0_1 98 | - ndg-httpsclient=0.5.1=py_1 99 | - networkx=2.2=py36_1 100 | - numpy=1.16.2=py36h7e9f1db_0 101 | - numpy-base=1.16.2=py36hde5b4d6_0 102 | - olefile=0.46=py36_0 103 | - openjpeg=2.3.0=h05c96fa_1 104 | - openssl=1.1.1b=h7b6447c_1 105 | - overpy=0.4=py_0 106 | - pandas=0.24.2=py36he6710b0_0 107 | - parso=0.3.4=py36_0 108 | - pcre=8.43=he6710b0_0 109 | - pexpect=4.6.0=py36_0 110 | - pickleshare=0.7.5=py36_0 111 | - pillow=5.4.1=py36h34e0f95_0 112 | - pip=19.0.3=py36_0 113 | - pixman=0.38.0=h7b6447c_0 114 | - poppler=0.65.0=h581218d_1 115 | - poppler-data=0.4.9=0 116 | - proj4=5.2.0=he6710b0_1 117 | - prompt_toolkit=2.0.9=py36_0 118 | - protobuf=3.6.1=py36he6710b0_0 119 | - psycopg2=2.7.6.1=py36h1ba5d50_0 120 | - ptyprocess=0.6.0=py36_0 121 | - pyasn1=0.4.4=py_1 122 | - pycparser=2.19=py36_0 123 | - pygments=2.3.1=py36_0 124 | - pyopenssl=19.0.0=py36_0 125 | - pyparsing=2.3.1=py36_0 126 | - pyproj=1.9.6=py36h14380d9_0 127 | - pyqt=5.9.2=py36h05f1152_2 128 | - pysocks=1.6.8=py36_0 129 | - python=3.6.8=h0371630_0 130 | - python-dateutil=2.8.0=py36_0 131 | - python-editor=1.0.4=py_0 132 | - pytz=2018.9=py36_0 133 | - pywavelets=1.0.2=py36hdd07704_0 134 | - qt=5.9.7=h5867ecd_1 135 | - readline=7.0=h7b6447c_5 136 | - requests=2.21.0=py36_0 137 | - rtree=0.8.3=py36_0 138 | - scikit-image=0.14.2=py36he6710b0_0 139 | - scipy=1.2.1=py36h7c811a0_0 140 | - setuptools=40.8.0=py36_0 141 | - shapely=1.6.4=py36h86c5351_0 142 | - sip=4.19.8=py36hf484d3e_0 143 | - six=1.12.0=py36_0 144 | - sqlalchemy=1.3.1=py36h7b6447c_0 145 | - sqlite=3.27.2=h7b6447c_0 146 | - tensorboard=1.12.2=py36he6710b0_0 147 | - tensorflow=1.12.0=mkl_py36h69b6ba0_0 148 | - tensorflow-base=1.12.0=mkl_py36h3c3e929_0 149 | - termcolor=1.1.0=py36_1 150 | - tk=8.6.8=hbc83047_0 151 | - toolz=0.9.0=py36_0 152 | - tornado=6.0.2=py36h7b6447c_0 153 | - traitlets=4.3.2=py36_0 154 | - uritemplate.py=3.0.2=py_1 155 | - urllib3=1.24.1=py36_0 156 | - wcwidth=0.1.7=py36_0 157 | - werkzeug=0.14.1=py36_0 158 | - wheel=0.33.1=py36_0 159 | - xerces-c=3.2.2=h780794e_0 160 | - xz=5.2.4=h14c3975_4 161 | - zlib=1.2.11=h7b6447c_3 162 | - zstd=1.3.7=h0b5b093_0 163 | - pip: 164 | - boto3==1.9.130 165 | - botocore==1.12.130 166 | - cachecontrol==0.12.5 167 | - docutils==0.14 168 | - iso3166==1.0 169 | - jmespath==0.9.4 170 | - mako==1.0.7 171 | - mapbox==0.18.0 172 | - msgpack==0.6.1 173 | - polyline==1.3.2 174 | - s3transfer==0.2.0 175 | -------------------------------------------------------------------------------- /setup/environment_gpu.yml: -------------------------------------------------------------------------------- 1 | name: spdw 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - _tflow_select==2.1.0=gpu 7 | - absl-py=0.7.0=py36_0 8 | - alembic=1.0.8=py_0 9 | - asn1crypto=0.24.0=py36_0 10 | - astor=0.7.1=py36_0 11 | - attrs=19.1.0=py36_1 12 | - backcall=0.1.0=py36_0 13 | - blas=1.0=mkl 14 | - bzip2=1.0.6=h14c3975_5 15 | - c-ares=1.15.0=h7b6447c_1 16 | - ca-certificates=2019.1.23=0 17 | - cairo=1.14.12=h8948797_3 18 | - certifi=2019.3.9=py36_0 19 | - cffi=1.12.2=py36h2e261b9_1 20 | - chardet=3.0.4=py36_1 21 | - click=7.0=py36_0 22 | - click-plugins=1.0.4=py36_0 23 | - cligj=0.5.0=py36_0 24 | - cloudpickle=0.8.0=py36_0 25 | - cryptography=2.6.1=py36h1ba5d50_0 26 | - curl=7.64.0=hbc83047_2 27 | - cycler=0.10.0=py36_0 28 | - cytoolz=0.9.0.1=py36h14c3975_1 29 | - dask-core=1.1.4=py36_1 30 | - dbus=1.13.6=h746ee38_0 31 | - decorator=4.4.0=py36_1 32 | - descartes=1.1.0=py36_0 33 | - expat=2.2.6=he6710b0_0 34 | - fiona=1.8.4=py36hc38cc03_0 35 | - fontconfig=2.13.0=h9420a91_0 36 | - freetype=2.9.1=h8a8886c_1 37 | - freexl=1.0.5=h14c3975_0 38 | - gast=0.2.2=py36_0 39 | - gdal=2.3.3=py36hbb2a789_0 40 | - geojson=2.4.1=py_0 41 | - geojsonio=0.0.3=py_0 42 | - geopandas=0.4.1=py_0 43 | - geos=3.7.1=he6710b0_0 44 | - giflib=5.1.4=h14c3975_1 45 | - github3.py=1.3.0=py_0 46 | - glib=2.56.2=hd408876_0 47 | - grpcio=1.16.1=py36hf8bcb03_1 48 | - gst-plugins-base=1.14.0=hbbd80ab_1 49 | - gstreamer=1.14.0=hb453b48_1 50 | - h5py=2.9.0=py36h7918eee_0 51 | - hdf4=4.2.13=h3ca952b_2 52 | - hdf5=1.10.4=hb1b8bf9_0 53 | - icu=58.2=h9c2bf20_1 54 | - idna=2.8=py36_0 55 | - imageio=2.5.0=py36_0 56 | - intel-openmp=2019.3=199 57 | - ipython=7.4.0=py36h39e3cac_0 58 | - ipython_genutils=0.2.0=py36_0 59 | - jedi=0.13.3=py36_0 60 | - jpeg=9b=h024ee3a_2 61 | - json-c=0.13.1=h1bed415_0 62 | - jwcrypto=0.6.0=py_0 63 | - kealib=1.4.7=hd0c454d_6 64 | - keras-applications=1.0.7=py_0 65 | - keras-preprocessing=1.0.9=py_0 66 | - kiwisolver=1.0.1=py36hf484d3e_0 67 | - krb5=1.16.1=h173b8e3_7 68 | - libboost=1.67.0=h46d08c1_4 69 | - libcurl=7.64.0=h20c2e04_2 70 | - libdap4=3.19.1=h6ec2957_0 71 | - libedit=3.1.20181209=hc058e9b_0 72 | - libffi=3.2.1=hd88cf55_4 73 | - libgcc-ng=8.2.0=hdf63c60_1 74 | - libgdal=2.3.3=h2e7e64b_0 75 | - libgfortran-ng=7.3.0=hdf63c60_0 76 | - libkml=1.3.0=h590aaf7_4 77 | - libnetcdf=4.6.1=h11d0813_2 78 | - libpng=1.6.36=hbc83047_0 79 | - libpq=11.2=h20c2e04_0 80 | - libprotobuf=3.6.1=hd408876_0 81 | - libspatialindex=1.8.5=h20b78c2_2 82 | - libspatialite=4.3.0a=hb08deb6_19 83 | - libssh2=1.8.0=h1ba5d50_4 84 | - libstdcxx-ng=8.2.0=hdf63c60_1 85 | - libtiff=4.0.10=h2733197_2 86 | - libuuid=1.0.3=h1bed415_2 87 | - libxcb=1.13=h1bed415_1 88 | - libxml2=2.9.9=he19cac6_0 89 | - mapclassify=2.0.1=py_0 90 | - markdown=3.0.1=py36_0 91 | - markupsafe=1.1.1=py36h7b6447c_0 92 | - matplotlib=3.0.3=py36h5429711_0 93 | - mkl=2019.3=199 94 | - mkl_fft=1.0.10=py36ha843d7b_0 95 | - mkl_random=1.0.2=py36hd81dba3_0 96 | - munch=2.3.2=py36_0 97 | - ncurses=6.1=he6710b0_1 98 | - ndg-httpsclient=0.5.1=py_1 99 | - networkx=2.2=py36_1 100 | - numpy=1.16.2=py36h7e9f1db_0 101 | - numpy-base=1.16.2=py36hde5b4d6_0 102 | - olefile=0.46=py36_0 103 | - openjpeg=2.3.0=h05c96fa_1 104 | - openssl=1.1.1b=h7b6447c_1 105 | - overpy=0.4=py_0 106 | - pandas=0.24.2=py36he6710b0_0 107 | - parso=0.3.4=py36_0 108 | - pcre=8.43=he6710b0_0 109 | - pexpect=4.6.0=py36_0 110 | - pickleshare=0.7.5=py36_0 111 | - pillow=5.4.1=py36h34e0f95_0 112 | - pip=19.0.3=py36_0 113 | - pixman=0.38.0=h7b6447c_0 114 | - poppler=0.65.0=h581218d_1 115 | - poppler-data=0.4.9=0 116 | - proj4=5.2.0=he6710b0_1 117 | - prompt_toolkit=2.0.9=py36_0 118 | - protobuf=3.6.1=py36he6710b0_0 119 | - psycopg2=2.7.6.1=py36h1ba5d50_0 120 | - ptyprocess=0.6.0=py36_0 121 | - pyasn1=0.4.4=py_1 122 | - pycparser=2.19=py36_0 123 | - pygments=2.3.1=py36_0 124 | - pyopenssl=19.0.0=py36_0 125 | - pyparsing=2.3.1=py36_0 126 | - pyproj=1.9.6=py36h14380d9_0 127 | - pyqt=5.9.2=py36h05f1152_2 128 | - pysocks=1.6.8=py36_0 129 | - python=3.6.8=h0371630_0 130 | - python-dateutil=2.8.0=py36_0 131 | - python-editor=1.0.4=py_0 132 | - pytz=2018.9=py36_0 133 | - pywavelets=1.0.2=py36hdd07704_0 134 | - qt=5.9.7=h5867ecd_1 135 | - readline=7.0=h7b6447c_5 136 | - requests=2.21.0=py36_0 137 | - rtree=0.8.3=py36_0 138 | - scikit-image=0.14.2=py36he6710b0_0 139 | - scipy=1.2.1=py36h7c811a0_0 140 | - setuptools=40.8.0=py36_0 141 | - shapely=1.6.4=py36h86c5351_0 142 | - sip=4.19.8=py36hf484d3e_0 143 | - six=1.12.0=py36_0 144 | - sqlalchemy=1.3.1=py36h7b6447c_0 145 | - sqlite=3.27.2=h7b6447c_0 146 | - tensorboard=1.12.2=py36he6710b0_0 147 | - tensorflow=1.12.0=gpu_py36he74679b_0 148 | - tensorflow-base=1.12.0=gpu_py36had579c0_0 149 | - tensorflow-gpu=1.12.0=h0d30ee6_0 150 | - termcolor=1.1.0=py36_1 151 | - tk=8.6.8=hbc83047_0 152 | - toolz=0.9.0=py36_0 153 | - tornado=6.0.2=py36h7b6447c_0 154 | - traitlets=4.3.2=py36_0 155 | - uritemplate.py=3.0.2=py_1 156 | - urllib3=1.24.1=py36_0 157 | - wcwidth=0.1.7=py36_0 158 | - werkzeug=0.14.1=py36_0 159 | - wheel=0.33.1=py36_0 160 | - xerces-c=3.2.2=h780794e_0 161 | - xz=5.2.4=h14c3975_4 162 | - zlib=1.2.11=h7b6447c_3 163 | - zstd=1.3.7=h0b5b093_0 164 | - pip: 165 | - boto3==1.9.130 166 | - botocore==1.12.130 167 | - cachecontrol==0.12.5 168 | - docutils==0.14 169 | - iso3166==1.0 170 | - jmespath==0.9.4 171 | - mako==1.0.7 172 | - mapbox==0.18.0 173 | - msgpack==0.6.1 174 | - polyline==1.3.2 175 | - s3transfer==0.2.0 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SolarPanelDataWrangler 2 | 3 | ![image](https://i.imgur.com/zahiUaU.png) 4 | 5 | This project contains scripts used to manipulate data having to do with finding solar panels with machine learning and adding their locations to OpenStreetMap; as part of the efforts around [OpenClimateFix](https://openclimatefix.github.io/) 6 | 7 | You can see the results of the whole process via the [MapRoulette project](https://maproulette.org/project/3749/leaderboard) 8 | 9 | ## Design 10 | I've chosen to use SQLite and SQLAlchemy for persisting the search locations and panel confidences, just so the process can be restartable, rapidly prototypeable, and doesn't need to be hosted (so other people can pick up the torch where I may leave off). In the future, if this needs to be turned into a long standing service, using SQLAlchemy should hopefully lessen the work required to switch to a more robust RDMS like PostgreSQL or something. 11 | 12 | # Quickstart 13 | 14 | If you'd like to build and work out of the pre-existing Docker container, jump to the Docker container section just below. Regardless of the setup method, once you're all done you should be able to run: 15 | 16 | `python run_entire_process.py --city --state ` 17 | 18 | And the whole suite of scripts should run, eventually outputting a MapRoulette challenge geoJSON for your city. (And leaving you with a sqlite database of these locations) 19 | 20 | Please create an [issue](https://github.com/typicalTYLER/SolarPanelDataWrangler/issues/new) if you have any trouble with this quickstart! 21 | 22 | ## Manual Setup 23 | 24 | ### Conda Environment 25 | 26 | One of the requirements is rtree, which requires you to install libspatialindex, instructions [here](http://toblerity.org/rtree/install.html). 27 | 28 | To install the environment, choose either the `setup/environment_cpu.yml` and `setup/environment_gpu.yml`. If you have a GPU that you intend to use, you'll need to setup the relevant packages / drivers (e.g. cuDNN / CUDA, NVIDIA diver, etc.) before installing the conda environment. Once you've chosen a YML file, you can create the environment via something like the following: 29 | 30 | ``` 31 | conda create --name spdw --file setup/environment_cpu.yml 32 | ``` 33 | 34 | *Note*: These environments are built on `conda=4.6.11`, `python=3.6.8`, and `tensorflow=1.12.0`. 35 | 36 | ### DeepSolar repository 37 | 38 | Currently, [this DeepSolar repo](https://github.com/typicalTYLER/DeepSolar) must be present at ../DeepSolar (relative to this repo) and pre-trained weights must be present in the `ckpt` directory inside of the `DeepSolar` repository. 39 | 40 | ### MapBox Token 41 | 42 | Your Mapbox API key must be in your environment variables as MAPBOX_ACCESS_TOKEN="MY_ACCESS_TOKEN". 43 | 44 | ## Docker Setup 45 | 46 | Within the `setup` directory is a `build_docker_images.sh` script that can be used to automatically setup a docker container to develop out of. 47 | 48 | ### No GPU Build 49 | 50 | To build a docker image that uses the no GPU conda environment, first install docker. Next, choose a username that you would like to use inside the container, and from **within the setup directory**, run: 51 | 52 | ``` 53 | bash build_docker_images.sh --docker_user [specify username here] 54 | ``` 55 | 56 | Once the image is built, you should be able to work inside a container created from the image just as if you were logged into a remote instance. 57 | 58 | ### GPU Build 59 | 60 | To build a docker image that uses the GPU conda environment, first install nvidia-docker (version 2.0). Next, make sure that you have the appropriate GPU driver installed for your system and for the version of tensorflow that will be used (`1.12.0`) as well as the versions of CUDA and cuDNN (CUDA 9.0 and cuDNN7. Once that is done, choose a username that you would like to use inside the container, and from **within the setup directory**, run: 61 | 62 | ``` 63 | bash build_docker_images.sh --docker_user [specify username here] --gpu_build 64 | ``` 65 | 66 | Once the image is built, you should be able to work inside a container created from the image just as if you were logged into a remote instance. 67 | 68 | # Overview 69 | 70 | There are several scripts to aid in the pipeline of turning names of cities into a database of coordinates and whether or not those coordinates contain solar panels. 71 | 72 | First, gather_city_shapes.py is used to query OSM with a csv of city, state rows for the boundaries of cities. There are also some tools to help detect incorrect shapes (OSM doesn't always return the correct relation first with my query scheme). 73 | If you don't want to query the data yourself (and have to manually fix it yourself) simply unzip geoJSON.zip in place to get 311 polygons of 100k population US cities. 74 | 75 | Next, process_city_shapes.py contains a number of ways to perform operations on these polygons, mainly reducing their complexity, calculating statistics about the shapes, and calculating a grid (and persisting) of coordinates that fall in all of these polygons. The persisting and calculating of these coordinates is currently very slow, so I've made sure to make the operation restartable. 76 | 77 | solardb.py contains an ORM for the database object that is currently SQLite, along with some helper functions to aid persistence. I also have started tracking data migrates via alembic, and I'm not sure how well my migrates work for new users, so please leave an issue if you're having trouble with the configuration and I'll try to help. 78 | 79 | imagery.py contains code to query and preprocess satellite data (currently only from MapBox, but this is where you'd add more services if you wanted). 80 | 81 | run_inference.py downloads, preprocesses, and runs inference on all the computed points in the database that don't have an estimation of whether they contain a solar panel. 82 | 83 | maproulette.py contains functionality to turn positive classifications (above a certainty threshold) into a line-by-line geoJSON that can be turned into a MapRoulette class 84 | 85 | # Contributing 86 | 87 | Feel free to sign up for and submit pull requests for one of the [existing issues](https://github.com/typicalTYLER/SolarPanelDataWrangler/issues) if you want to contribute! I'm also down to add other Open Climate Fix collaborators as collaborators on this repo. Also feel free to create issues if you are having trouble with anything in this repo. 88 | -------------------------------------------------------------------------------- /setup/build_docker_images.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # build_docker_images.sh builds the necessary docker images for setting up the 4 | # spdw environment and repository, using the Dockerfile.base and Dockerfile 5 | # files in this directory. 6 | 7 | function usage { 8 | echo "Usage: build_docker_image.sh [--branch] [--conda_version version] [--docker_user username]" 9 | echo " [--fpath_custom_dockerfile fpath] [--gpu_build] " 10 | echo " [--rebuild_image (base|final|custom)]" 11 | echo "" 12 | echo " --branch Branch to use when building, defaults to master." 13 | echo " --conda_version Conda version for the Docker images - defaults " 14 | echo " to 4.5.11, which is compatible with the repository " 15 | echo " YMLs." 16 | echo "" 17 | echo " --docker_user Username for the Docker images. " 18 | echo "" 19 | echo " --fpath_custom_dockerfile fpath: Build a custom Docker image from a provided " 20 | echo " Dockerfile after the Dockerfile.base and " 21 | echo " Dockerfile image builds, meant to allow for " 22 | echo " further customization of a user's environment. " 23 | echo " This Dockerfile must use setup/Dockerfile as " 24 | echo " the base image." 25 | echo "" 26 | echo " --gpu_build Build the base image (setup/Dockerfile.base) using " 27 | echo " nvidia/cuda9.0-cudnn7-runtime-ubuntu16.04 as the " 28 | echo " base image, instead of ubuntu:16.04 (the default)." 29 | echo "" 30 | echo " --rebuild_image Rebuild this image and any subsequent images that " 31 | echo " use this one as base. Useful if you know that " 32 | echo " something inside has changed (e.g. the conda " 33 | echo " environment) but Docker won't be able to register " 34 | echo " that change. Valid options are (base, final, custom)." 35 | exit 1 36 | } 37 | 38 | while [ ! $# -eq 0 ] 39 | do 40 | case "$1" in 41 | --branch) 42 | BRANCH=$2 43 | shift 2 44 | ;; 45 | --conda_version) 46 | CONDA_VERSION=$2 47 | shift 2 48 | ;; 49 | --docker_user) 50 | DOCKER_USER=$2 51 | shift 2 52 | ;; 53 | --fpath_custom_dockerfile) 54 | FPATH_CUSTOM_DOCKERFILE=$2 55 | shift 2 56 | ;; 57 | --gpu_build) 58 | GPU_BUILD=true 59 | shift 1 60 | ;; 61 | --rebuild_image) 62 | REBUILD_IMAGE=$2 63 | shift 2 64 | ;; 65 | --help) 66 | usage 67 | shift 68 | ;; 69 | esac 70 | done 71 | 72 | if [ -z "$DOCKER_USER" ]; then 73 | echo "--docker_user flag must be specified!" 74 | exit 1 75 | fi 76 | 77 | if [ -z "$BRANCH" ]; then 78 | echo "--branch not specified, using the default of master." 79 | BRANCH=master 80 | fi 81 | 82 | if [ -z "$CONDA_VERSION" ]; then 83 | echo "--conda_version not specified, using the default of 4.5.11." 84 | CONDA_VERSION=4.5.11 85 | fi 86 | 87 | if [ ! -z "$REBUILD_IMAGE" ]; then 88 | if ! [[ "$REBUILD_IMAGE" =~ ^(base|final|custom)$ ]]; then 89 | echo "--rebuild_image option \"$REBUILD_IMAGE\" is not one of the " 90 | echo "accepted options (base, final, or custom). If you'd like to " 91 | echo "delete and remove one of the images, please specify one of " 92 | echo "these options." 93 | exit 1 94 | fi 95 | 96 | if [[ "$REBUILD_IMAGE" == "base" ]]; then 97 | echo "--rebuild_image equal to \"base\"... will delete any existing, " 98 | echo "spdw/base, spdw/final, and " 99 | echo "spdw/custom images to build them anew." 100 | DELETE_BASE=true 101 | DELETE_FINAL=true 102 | DELETE_CUSTOM=true 103 | elif [[ "$REBUILD_IMAGE" == "final" ]]; then 104 | echo "--rebuild_image equal to \"final\"... will delete any existing, " 105 | echo "spdw/final and spdw/custom images to build " 106 | echo "them anew." 107 | DELETE_FINAL=true 108 | DELETE_CUSTOM=true 109 | elif [[ "$REBUILD_IMAGE" == "custom" ]]; then 110 | echo "--rebuild_image equal to \"custom\"... will delete the " 111 | echo "spdw/custom image to build it anew." 112 | DELETE_CUSTOM=true 113 | fi 114 | 115 | BASE_IMAGE_EXISTS=$(docker images -q spdw/base) 116 | FINAL_IMAGE_EXISTS=$(docker images -q spdw/final) 117 | CUSTOM_IMAGE_EXISTS=$(docker images -q spdw/custom) 118 | 119 | if [[ "$DELETE_BASE" == "true" ]] && [[ ! -z $BASE_IMAGE_EXISTS ]]; then 120 | docker image rm spdw/base 121 | fi 122 | if [[ "$DELETE_FINAL" == "true" ]] && [[ ! -z $FINAL_IMAGE_EXISTS ]]; then 123 | docker image rm spdw/final 124 | fi 125 | if [[ "$DELETE_CUSTOM" == "true" ]] && [[ ! -z $CUSTOM_IMAGE_EXISTS ]]; then 126 | docker image rm spdw/custom 127 | fi 128 | fi 129 | 130 | BASE_IMAGE="ubuntu:16.04" 131 | FNAME_ENVIRONMENT_YML="environment_cpu.yml" 132 | if [[ ! -z "$GPU_BUILD" ]]; then 133 | BASE_IMAGE="nvidia/cuda:9.0-cudnn7-runtime-ubuntu16.04" 134 | FNAME_ENVIRONMENT_YML="environment_gpu.yml" 135 | fi 136 | 137 | echo "Creating images with docker username $DOCKER_USER and miniconda " 138 | echo "version $CONDA_VERSION..." 139 | 140 | docker build --build-arg user=$DOCKER_USER \ 141 | --build-arg conda_version=$CONDA_VERSION \ 142 | --build-arg base_image=$BASE_IMAGE \ 143 | -t spdw/base --file ./Dockerfile.base ./ 144 | 145 | docker build --build-arg user=$DOCKER_USER \ 146 | --build-arg branch=$BRANCH \ 147 | --build-arg conda_version=$CONDA_VERSION \ 148 | --build-arg fname_environment_yml=$FNAME_ENVIRONMENT_YML \ 149 | -t spdw/final --file ./Dockerfile ./ 150 | 151 | if [ ! -z "$FPATH_CUSTOM_DOCKERFILE" ]; then 152 | echo "Building custom Docker image based off of " 153 | echo "$FPATH_CUSTOM_DOCKERFILE ..." 154 | docker build --build-arg user=$DOCKER_USER \ 155 | -t spdw/custom --file $FPATH_CUSTOM_DOCKERFILE ./ 156 | fi 157 | -------------------------------------------------------------------------------- /run_inference.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import itertools 3 | import os 4 | import time 5 | 6 | import numpy as np 7 | import skimage 8 | 9 | import imagery 10 | import solardb 11 | 12 | from os import path 13 | import sys 14 | sys.path.append(path.abspath('../DeepSolar')) 15 | 16 | from inception.predictor import Predictor 17 | 18 | IMAGE_SIZE = 299 19 | 20 | 21 | def detect_clusters(): 22 | polygon_names = solardb.get_polygon_names() 23 | print("Starting clustering recursion") 24 | for polygon_name in polygon_names: 25 | print("Querying tiles for {polygon_name}".format(polygon_name=polygon_name)) 26 | tiles = {} 27 | coordinates_to_iterate_through = set() 28 | for tile in solardb.query_tiles_over_threshold(polygon_name=polygon_name, filter_clustered=True): 29 | coordinate_tuple = (tile.column, tile.row, tile.zoom) 30 | tiles[coordinate_tuple] = tile 31 | coordinates_to_iterate_through.add(coordinate_tuple) 32 | total_iterations = len(coordinates_to_iterate_through) 33 | print("Starting clustering recursion") 34 | while coordinates_to_iterate_through: 35 | print("{0:.0%}".format(((total_iterations - len(coordinates_to_iterate_through)) / total_iterations)), 36 | end='\r') 37 | tile = coordinates_to_iterate_through.pop() 38 | cluster = {tile} 39 | positive_cluster_id = solardb.get_new_positive_cluster_id() 40 | detect_clusters_recursive_helper(cluster, coordinates_to_iterate_through, tile) 41 | for coordinate_tuple in cluster: 42 | slippy_tile = tiles[coordinate_tuple] 43 | slippy_tile.cluster_id = positive_cluster_id 44 | solardb.update_tiles(tiles.values()) 45 | 46 | 47 | def detect_clusters_recursive_helper(cluster, coordinates_to_iterate_through, tile, no_check_direction=None): 48 | north_tuple = (tile[0], tile[1] - 1, tile[2]) 49 | east_tuple = (tile[0] + 1, tile[1], tile[2]) 50 | south_tuple = (tile[0], tile[1] + 1, tile[2]) 51 | west_tuple = (tile[0] - 1, tile[1], tile[2]) 52 | neighbors = [north_tuple, east_tuple, south_tuple, west_tuple] 53 | for i, coord_tuple in enumerate(neighbors): 54 | # little bit of optimization to not call the "coord_tuple in coords_to_iterate_through" for the coordinate that 55 | # just called this method and will never be in the remaining coordinates 56 | if not (no_check_direction and no_check_direction == i) \ 57 | and coord_tuple in coordinates_to_iterate_through: 58 | cluster.add(coord_tuple) 59 | coordinates_to_iterate_through.remove(coord_tuple) 60 | detect_clusters_recursive_helper(cluster, coordinates_to_iterate_through, coord_tuple, (i + 2) % 4) 61 | 62 | 63 | def batch_delete_extra_imagery(): 64 | print("Starting extraneous imagery cleanup/deletion") 65 | polygon_names = solardb.get_polygon_names() 66 | for polygon_name in polygon_names: 67 | tiles_above_threshold = solardb.query_tiles_over_threshold(polygon_name=polygon_name) 68 | expanded_coords_above_threshold = set() 69 | for tile in tiles_above_threshold: 70 | for column in range(tile.column - 1, tile.column + 2): 71 | for row in range(tile.row - 1, tile.row + 2): 72 | expanded_coords_above_threshold.add((column, row, tile.zoom)) 73 | print("Calculation for expanded positive coords for {polygon_name} completed".format(polygon_name=polygon_name)) 74 | while True: 75 | tile_batch = solardb.query_tile_batch(polygon_name=polygon_name) 76 | to_delete = [] 77 | if not tile_batch: 78 | break 79 | for tile in tile_batch: 80 | tile_tuple = (tile.column, tile.row, tile.zoom) 81 | if tile_tuple not in expanded_coords_above_threshold: 82 | tile.has_image = False 83 | to_delete.append(tile_tuple) 84 | solardb.update_tiles(tile_batch) 85 | imagery.delete_images(to_delete) 86 | print("Deleted {num} non-solar panel containing imagery tiles for {polygon_name}".format( 87 | num=len(to_delete), polygon_name=polygon_name)) 88 | # if no tiles got deleted in the batch it's probably done 89 | # if the number of expanded coords is larger than the batch size, this could theoretically return early 90 | if not to_delete: 91 | break 92 | print("Deletion finished") 93 | 94 | 95 | def run_classification(classification_checkpoint, segmentation_checkpoint=None, delete_every=None): 96 | predictor = Predictor( 97 | dirpath_classification_checkpoint=classification_checkpoint, 98 | dirpath_segmentation_checkpoint=segmentation_checkpoint 99 | ) 100 | avg_tiles_per_sec = 0.0 101 | for i in itertools.count(0): 102 | if delete_every and i % delete_every == 0: 103 | batch_delete_extra_imagery() 104 | start_time = time.time() 105 | tiles = solardb.query_tile_batch_for_inference() 106 | if not tiles: 107 | print("No viable coordinates left to run inference on. Either provide more polygons or compute centroid " 108 | "distances. Attempting to detect clusters now.") 109 | detect_clusters() 110 | break 111 | 112 | for tile in tiles: 113 | image = np.array(imagery.stitch_image_at_coordinate((tile.column, tile.row))) 114 | 115 | resized_image = skimage.transform.resize(image, (IMAGE_SIZE, IMAGE_SIZE)) 116 | if resized_image.shape[2] != 3: 117 | resized_image = resized_image[:, :, 0:3] 118 | resized_image = resized_image[None, ...] 119 | 120 | tile.panel_softmax = predictor.classify(resized_image) 121 | tile.inference_ran = True 122 | tile.inference_timestamp = time.time() 123 | 124 | solardb.update_tiles(tiles) 125 | 126 | tiles_per_sec = len(tiles) / (time.time() - start_time) 127 | avg_tiles_per_sec = ((avg_tiles_per_sec * i) + tiles_per_sec) / (i + 1) 128 | print("{0:.2f} tiles/s | {1:.2f} avg tiles/s".format(tiles_per_sec, avg_tiles_per_sec)) 129 | 130 | 131 | DEFAULT_DELETE_EVERY = 100 132 | 133 | if __name__ == '__main__': 134 | parser = argparse.ArgumentParser(description='Run inference for slippy tiles stored in database') 135 | parser.add_argument('--classification-checkpoint', dest='classification_checkpoint', 136 | default=os.path.join('..', 'DeepSolar', 'ckpt', 'inception_classification'), 137 | help='Path to DeepSolar classification checkpoint.') 138 | parser.add_argument('--segmentation-checkpoint', dest='segmentation_checkpoint', 139 | default=os.path.join('..', 'DeepSolar', 'ckpt', 'inception_segmentation'), 140 | help='Path to DeepSolar segmentation checkpoint.') 141 | parser.add_argument('--delete_every', dest='delete_every', default=DEFAULT_DELETE_EVERY, 142 | help='Deletes extra imagery every x inference batches, default {}'.format(DEFAULT_DELETE_EVERY)) 143 | args = parser.parse_args() 144 | 145 | run_classification(args.classification_checkpoint, args.segmentation_checkpoint, delete_every=args.delete_every) 146 | -------------------------------------------------------------------------------- /data/100k_US_cities.csv: -------------------------------------------------------------------------------- 1 | Cambridge, Massachusetts 2 | Daly City, California 3 | Paterson, New Jersey 4 | Inglewood, California 5 | El Monte, California 6 | Norwalk, California 7 | Berkeley, California 8 | San Mateo, California 9 | Elizabeth, New Jersey 10 | Downey, California 11 | Lowell, Massachusetts 12 | El Cajon, California 13 | Jersey City, New Jersey 14 | Alexandria, Virginia 15 | Costa Mesa, California 16 | West Covina, California 17 | Bridgeport, Connecticut 18 | Hartford, Connecticut 19 | Burbank, California 20 | Allentown, Pennsylvania 21 | Yonkers, New York 22 | Garden Grove, California 23 | Miami Gardens, Florida 24 | Providence, Rhode Island 25 | Santa Clara, California 26 | New Haven, Connecticut 27 | Vista, California 28 | Torrance, California 29 | Hialeah, Florida 30 | Ventura, California 31 | Sunnyvale, California 32 | Rialto, California 33 | Fullerton, California 34 | Santa Maria, California 35 | Pomona, California 36 | Pasadena, California 37 | Gresham, Oregon 38 | Woodbridge, New Jersey 39 | Renton, Washington 40 | Salinas, California 41 | Coral Springs, Florida 42 | Pompano Beach, Florida 43 | Newark, New Jersey 44 | Clovis, California 45 | Lakewood, New Jersey 46 | Boulder, Colorado 47 | Syracuse, New York 48 | Hillsboro, Oregon 49 | Orange, California 50 | Clearwater, Florida 51 | Oxnard, California 52 | Huntington Beach, California 53 | Santa Ana, California 54 | Allen, Texas 55 | Hollywood, Florida 56 | Ann Arbor, Michigan 57 | Clinton, Michigan 58 | Waterbury, Connecticut 59 | Richardson, Texas 60 | Vacaville, California 61 | Miramar, Florida 62 | Antioch, California 63 | Centennial, Colorado 64 | Richmond, California 65 | Edison, New Jersey 66 | Glendale, California 67 | Concord, California 68 | Vallejo, California 69 | Westminster, Colorado 70 | Springfield, Massachusetts 71 | West Jordan, Utah 72 | Pembroke Pines, Florida 73 | Manchester, New Hampshire 74 | Everett, Washington 75 | Bellevue, Washington 76 | Murrieta, California 77 | Kent, Washington 78 | Warren, Michigan 79 | Fort Lauderdale, Florida 80 | Davie, Florida 81 | West Valley City, Utah 82 | Round Rock, Texas 83 | Thornton, Colorado 84 | Rochester, New York 85 | Sparks, Nevada 86 | Miami, Florida 87 | Carrollton, Texas 88 | Sterling Heights, Michigan 89 | Lewisville, Texas 90 | Escondido, California 91 | Temecula, California 92 | Worcester, Massachusetts 93 | Elgin, Illinois 94 | Visalia, California 95 | Stamford, Connecticut 96 | Carlsbad, California 97 | Sandy Springs, Georgia 98 | Arvada, Colorado 99 | Naperville, Illinois 100 | Lansing, Michigan 101 | Corona, California 102 | Tempe, Arizona 103 | Rancho Cucamonga, California 104 | Buffalo, New York 105 | Fairfield, California 106 | Oceanside, California 107 | Santa Rosa, California 108 | South Bend, Indiana 109 | Simi Valley, California 110 | Provo, Utah 111 | Elk Grove, California 112 | Lakewood, Colorado 113 | Jurupa Valley, California 114 | Modesto, California 115 | Fontana, California 116 | Roseville, California 117 | Pasadena, Texas 118 | Billings, Montana 119 | Eugene, Oregon 120 | Grand Rapids, Michigan 121 | Aurora, Illinois 122 | Odessa, Texas 123 | Green Bay, Wisconsin 124 | Hayward, California 125 | Pearland, Texas 126 | San Francisco, California 127 | Vancouver, Washington 128 | Mesquite, Texas 129 | Evansville, Indiana 130 | Greeley, Colorado 131 | Peoria, Illinois 132 | Boston, Massachusetts 133 | Salem, Oregon 134 | Fargo, North Dakota 135 | Chula Vista, California 136 | Tacoma, Washington 137 | Ontario, California 138 | Anaheim, California 139 | Long Beach, California 140 | College Station, Texas 141 | League City, Texas 142 | Moreno Valley, California 143 | Hampton, Virginia 144 | Wilmington, North Carolina 145 | Saint Paul, Minnesota 146 | Santa Clarita, California 147 | Norfolk, Virginia 148 | Killeen, Texas 149 | Pueblo, Colorado 150 | Lafayette, Louisiana 151 | Minneapolis, Minnesota 152 | Rochester, Minnesota 153 | West Palm Beach, Florida 154 | Thousand Oaks, California 155 | High Point, North Carolina 156 | Pittsburgh, Pennsylvania 157 | Dayton, Ohio 158 | Fort Collins, Colorado 159 | Oakland, California 160 | Murfreesboro, Tennessee 161 | Cary, North Carolina 162 | Tyler, Texas 163 | Garland, Texas 164 | McAllen, Texas 165 | Glendale, Arizona 166 | Richmond, Virginia 167 | San Angelo, Texas 168 | Springfield, Illinois 169 | Honolulu, Hawaii 170 | Olathe, Kansas 171 | Washington, District of Columbia 172 | San Bernardino, California 173 | Topeka, Kansas 174 | Stockton, California 175 | Broken Arrow, Oklahoma 176 | St. Petersburg, Florida 177 | St. Louis, Missouri 178 | Akron, Ohio 179 | Gainesville, Florida 180 | Davenport, Iowa 181 | McKinney, Texas 182 | Rockford, Illinois 183 | Joliet, Illinois 184 | Chandler, Arizona 185 | Columbia, Missouri 186 | Irvine, California 187 | Palm Bay, Florida 188 | Lakeland, Florida 189 | Irving, Texas 190 | Frisco, Texas 191 | Gilbert, Arizona 192 | Spokane, Washington 193 | Newport News, Virginia 194 | Cedar Rapids, Iowa 195 | Plano, Texas 196 | Tuscaloosa, Alabama 197 | Wichita Falls, Texas 198 | Grand Prairie, Texas 199 | Victorville, California 200 | North Charleston, South Carolina 201 | Midland, Texas 202 | Overland Park, Kansas 203 | Sioux Falls, South Dakota 204 | Las Cruces, New Mexico 205 | Madison, Wisconsin 206 | Cincinnati, Ohio 207 | Fremont, California 208 | Cleveland, Ohio 209 | Independence, Missouri 210 | Toledo, Ohio 211 | Baltimore, Maryland 212 | Riverside, California 213 | Boise, Idaho 214 | Beaumont, Texas 215 | Springfield, Missouri 216 | Seattle, Washington 217 | Baton Rouge, Louisiana 218 | Des Moines, Iowa 219 | Waco, Texas 220 | Lincoln, Nebraska 221 | Denton, Texas 222 | Lancaster, California 223 | Arlington, Texas 224 | Milwaukee, Wisconsin 225 | Sacramento, California 226 | North Las Vegas, Nevada 227 | Clarksville, Tennessee 228 | Knoxville, Tennessee 229 | Tallahassee, Florida 230 | Laredo, Texas 231 | Amarillo, Texas 232 | Savannah, Georgia 233 | Henderson, Nevada 234 | Orlando, Florida 235 | Cape Coral, Florida 236 | Palmdale, California 237 | Abilene, Texas 238 | Shreveport, Louisiana 239 | Reno, Nevada 240 | Surprise, Arizona 241 | Charleston, South Carolina 242 | Durham, North Carolina 243 | Fort Wayne, Indiana 244 | Jackson, Mississippi 245 | Salt Lake City, Utah 246 | Tampa, Florida 247 | Fresno, California 248 | Athens, Georgia 249 | Little Rock, Arkansas 250 | Port St. Lucie, Florida 251 | Lubbock, Texas 252 | Kansas City, Kansas 253 | Greensboro, North Carolina 254 | Winston-Salem, North Carolina 255 | Brownsville, Texas 256 | Omaha, Nebraska 257 | Portland, Oregon 258 | Atlanta, Georgia 259 | Columbia, South Carolina 260 | Philadelphia, Pennsylvania 261 | Las Vegas, Nevada 262 | Mesa, Arizona 263 | Detroit, Michigan 264 | Mobile, Alabama 265 | Chattanooga, Tennessee 266 | Raleigh, North Carolina 267 | Birmingham, Alabama 268 | Fayetteville, North Carolina 269 | Bakersfield, California 270 | Denver, Colorado 271 | Aurora, Colorado 272 | Montgomery, Alabama 273 | Wichita, Kansas 274 | New Orleans, Louisiana 275 | Corpus Christi, Texas 276 | Peoria, Arizona 277 | San Jose, California 278 | Norman, Oklahoma 279 | Scottsdale, Arizona 280 | Albuquerque, New Mexico 281 | Colorado Springs, Colorado 282 | Tulsa, Oklahoma 283 | Huntsville, Alabama 284 | Columbus, Georgia 285 | Columbus, Ohio 286 | Chicago, Illinois 287 | Tucson, Arizona 288 | Virginia Beach, Virginia 289 | Macon, Georgia 290 | El Paso, Texas 291 | Louisville, Kentucky 292 | Lexington, Kentucky 293 | New York, New York 294 | Augusta, Georgia 295 | Charlotte, North Carolina 296 | Austin, Texas 297 | Kansas City, Missouri 298 | Memphis, Tennessee 299 | San Diego, California 300 | Chesapeake, Virginia 301 | Dallas, Texas 302 | Fort Worth, Texas 303 | Indianapolis, Indiana 304 | San Antonio, Texas 305 | Los Angeles, California 306 | Nashville, Tennessee 307 | Phoenix, Arizona 308 | Oklahoma City, Oklahoma 309 | Houston, Texas 310 | Jacksonville, Florida 311 | Anchorage, Alaska -------------------------------------------------------------------------------- /imagery.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pathlib 3 | import time 4 | from io import BytesIO 5 | 6 | from PIL import Image 7 | from mapbox import Static 8 | 9 | import solardb 10 | from process_city_shapes import num2deg 11 | 12 | 13 | class ImageTile(object): 14 | """Represents a single image tile.""" 15 | 16 | def __init__(self, image, coords, filename=None): 17 | self.image = image 18 | self.coords = coords 19 | self.filename = filename 20 | 21 | @property 22 | def column(self): 23 | return self.coords[0] 24 | 25 | @property 26 | def row(self): 27 | return self.coords[1] 28 | 29 | @property 30 | def basename(self): 31 | """Strip path and extension. Return base filename.""" 32 | return get_basename(self.filename) 33 | 34 | def generate_filename(self, zoom=21, directory=os.path.join(os.getcwd(), 'data', 'imagery'), 35 | format='jpg', path=True): 36 | """Construct and return a filename for this tile.""" 37 | filename = os.path.join(str(zoom), str(self.row), str(self.column) + 38 | '.{ext}'.format(ext=format.lower().replace('jpeg', 'jpg'))) 39 | if not path: 40 | return filename 41 | return os.path.join(directory, filename) 42 | 43 | def save(self, filename=None, file_format='jpeg', zoom=21): 44 | if not filename: 45 | filename = self.generate_filename(zoom=zoom) 46 | pathlib.Path(os.path.dirname(filename)).mkdir(parents=True, exist_ok=True) 47 | self.image.save(filename, file_format) 48 | self.filename = filename 49 | 50 | def load(self, filename=None, zoom=21): 51 | if not filename: 52 | filename = self.generate_filename(zoom=zoom) 53 | if self.image: 54 | return self.image 55 | if not pathlib.Path(filename).is_file(): 56 | return None 57 | self.filename = filename 58 | self.image = Image.open(filename) 59 | return self.image 60 | 61 | def delete(self, filename=None, zoom=21): # TODO zoom should probably be a tile property 62 | if not filename: 63 | filename = self.generate_filename(zoom=zoom) 64 | pathlib.Path(filename).unlink() 65 | self.filename = filename 66 | 67 | def __repr__(self): 68 | """Show tile coords, and if saved to disk, filename.""" 69 | if self.filename: 70 | return ''.format(self.coords, 71 | self.filename) 72 | return ''.format(self.coords) 73 | 74 | 75 | def get_basename(filename): 76 | """Strip path and extension. Return basename.""" 77 | return os.path.splitext(os.path.basename(filename))[0] 78 | 79 | 80 | # assumes a square image 81 | def slice_image(image, base_coords, upsample_count=0, slices_per_side=5): 82 | out = image 83 | base_column, base_row = base_coords 84 | for i in range(upsample_count): 85 | out = double_image_size(out) 86 | w, h = out.size 87 | w = w // slices_per_side 88 | h = h // slices_per_side 89 | tiles = [] 90 | for row_offset in range(slices_per_side): 91 | for column_offset in range(slices_per_side): 92 | box = (column_offset * w, row_offset * h, (column_offset + 1) * w, (row_offset + 1) * h) 93 | cropped_image = out.crop(box) 94 | coords = (column_offset + base_column, row_offset + base_row) 95 | tiles.append(ImageTile(cropped_image, coords)) 96 | return tiles 97 | 98 | 99 | def double_image_size(image, filter=Image.LANCZOS): 100 | return image.resize((image.size[0] * 2, image.size[0] * 2), filter) 101 | 102 | 103 | # amount of zooms out to do from final zoom level when querying for imagery 104 | ZOOM_FACTOR = 2 105 | # the final zoom level of the saved tiles 106 | FINAL_ZOOM = 21 107 | TILE_SIDE_LENGTH = 256 108 | MAX_IMAGE_SIDE_LENGTH = 1280 109 | # number of times to cut the source imagery to get it to correct tile size 110 | GRID_SIZE = (MAX_IMAGE_SIDE_LENGTH // TILE_SIDE_LENGTH) * 2 ** ZOOM_FACTOR 111 | 112 | # the side length of the stitched image 113 | FINISHED_TILE_SIDE_LENGTH = 320 114 | # the amount to stitch from each border tile 115 | STITCH_WIDTH = (FINISHED_TILE_SIDE_LENGTH - TILE_SIDE_LENGTH) // 2 116 | # the amount not to stitch from each border tile 117 | CROPPED_WIDTH = TILE_SIDE_LENGTH - STITCH_WIDTH 118 | CROP_BOXES = [ 119 | (CROPPED_WIDTH, CROPPED_WIDTH, TILE_SIDE_LENGTH, TILE_SIDE_LENGTH), 120 | (CROPPED_WIDTH, 0, TILE_SIDE_LENGTH, TILE_SIDE_LENGTH), 121 | (CROPPED_WIDTH, 0, TILE_SIDE_LENGTH, STITCH_WIDTH), 122 | (0, CROPPED_WIDTH, TILE_SIDE_LENGTH, TILE_SIDE_LENGTH), 123 | (0, 0, TILE_SIDE_LENGTH, TILE_SIDE_LENGTH), 124 | (0, 0, TILE_SIDE_LENGTH, STITCH_WIDTH), 125 | (0, CROPPED_WIDTH, STITCH_WIDTH, TILE_SIDE_LENGTH), 126 | (0, 0, STITCH_WIDTH, TILE_SIDE_LENGTH), 127 | (0, 0, STITCH_WIDTH, STITCH_WIDTH) 128 | ] 129 | PASTE_COORDINATES = [ 130 | (0, 0), 131 | (0, STITCH_WIDTH), 132 | (0, TILE_SIDE_LENGTH + STITCH_WIDTH), 133 | (STITCH_WIDTH, 0), 134 | (STITCH_WIDTH, STITCH_WIDTH), 135 | (STITCH_WIDTH, TILE_SIDE_LENGTH + STITCH_WIDTH), 136 | (TILE_SIDE_LENGTH + STITCH_WIDTH, 0), 137 | (TILE_SIDE_LENGTH + STITCH_WIDTH, STITCH_WIDTH), 138 | (TILE_SIDE_LENGTH + STITCH_WIDTH, TILE_SIDE_LENGTH + STITCH_WIDTH), 139 | ] 140 | 141 | MAX_RETRIES = 12 # max wait time with exponential backoff would be ~34 minutes 142 | 143 | service = Static() 144 | 145 | 146 | def gather_and_persist_imagery_at_coordinate(slippy_coordinates, final_zoom=FINAL_ZOOM, grid_size=GRID_SIZE, 147 | imagery="mapbox"): 148 | # the top left square of the query grid this point belongs to 149 | base_coords = tuple(map(lambda x: x - x % grid_size, slippy_coordinates)) 150 | if grid_size % 2 == 0: 151 | # if the grid size is even, the center point is between 4 tiles in center (or the top left of bottom right one) 152 | center_bottom_right_tile = tuple(map(lambda x: x + grid_size // 2, base_coords)) 153 | center_lon_lat = num2deg(center_bottom_right_tile, zoom=final_zoom, center=False) 154 | else: 155 | # if the grid is odd, the center point is in the center of the center square 156 | center_tile = tuple(map(lambda x: x + grid_size // 2, base_coords)) 157 | center_lon_lat = num2deg(center_tile, zoom=FINAL_ZOOM, center=True) 158 | if imagery == "mapbox": 159 | for i in range(MAX_RETRIES): 160 | response = service.image('mapbox.satellite', lon=center_lon_lat[0], lat=center_lon_lat[1], z=final_zoom - 2, 161 | width=MAX_IMAGE_SIDE_LENGTH, height=MAX_IMAGE_SIDE_LENGTH, image_format='jpg90', 162 | retina=(ZOOM_FACTOR > 0)) 163 | if response.ok: 164 | image = Image.open(BytesIO(response.content)) 165 | tiles = slice_image(image, base_coords, upsample_count=max(ZOOM_FACTOR - 1, 0), 166 | slices_per_side=grid_size) 167 | to_return = None 168 | for tile in tiles: 169 | if tile.coords == slippy_coordinates: 170 | to_return = tile.image 171 | tile.save(zoom=FINAL_ZOOM) 172 | solardb.mark_has_imagery(base_coords, grid_size, zoom=final_zoom) 173 | return to_return 174 | backoff_time = pow(2, i) 175 | print('Got this response from {service}:"{error}", exponentially backing off, {time} seconds.' 176 | .format(service=imagery, error=getattr(response, "content", None), time=backoff_time)) 177 | time.sleep(backoff_time) 178 | raise ConnectionError("Couldn't connect to {service} after {retries}" 179 | .format(service=imagery, retries=MAX_RETRIES)) 180 | else: 181 | AttributeError("Unsupported Imagery source: " + str(imagery)) 182 | 183 | 184 | # loads image from disk if possible, otherwise queries an imagery service 185 | def get_image_for_coordinate(slippy_coordinate): 186 | tile = ImageTile(None, slippy_coordinate) 187 | image = tile.load() 188 | if not image: 189 | image = gather_and_persist_imagery_at_coordinate(slippy_coordinate, final_zoom=FINAL_ZOOM) 190 | return image 191 | 192 | 193 | # gets a larger image at the specified slippy coordinate by stitching other border tiles together 194 | # TODO: optimize 195 | # TODO: there's also some symmetry here that can be exploited but this seems easier for now 196 | def stitch_image_at_coordinate(slippy_coordinate): 197 | images = [] 198 | # gather the images in each direction around the target image 199 | for column in range(slippy_coordinate[0] - 1, slippy_coordinate[0] + 2): 200 | for row in range(slippy_coordinate[1] - 1, slippy_coordinate[1] + 2): 201 | images.append(get_image_for_coordinate((column, row),)) 202 | 203 | cropped_images = [] 204 | for image, crop_box in zip(images, CROP_BOXES): 205 | cropped_images.append(image.crop(crop_box)) 206 | output_image = Image.new('RGB', (FINISHED_TILE_SIDE_LENGTH, FINISHED_TILE_SIDE_LENGTH)) 207 | for cropped_image, paste_coordinate in zip(cropped_images, PASTE_COORDINATES): 208 | cropped_images.append(output_image.paste(cropped_image, box=paste_coordinate)) 209 | return output_image 210 | 211 | 212 | def delete_images(slippy_coordinates): 213 | for coordinate_tuple in slippy_coordinates: 214 | ImageTile(None, coordinate_tuple).delete(zoom=coordinate_tuple[2]) 215 | -------------------------------------------------------------------------------- /solardb.py: -------------------------------------------------------------------------------- 1 | 2 | import time 3 | 4 | import math 5 | import overpy 6 | from sqlalchemy import Column, Integer, String, ForeignKey, Float, Boolean, PrimaryKeyConstraint, Index, desc 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.ext.declarative import declarative_base 9 | from sqlalchemy.orm import sessionmaker, relationship 10 | from sqlalchemy.sql import expression 11 | 12 | Base = declarative_base() 13 | # TODO improve session management 14 | 15 | 16 | class SearchPolygon(Base): 17 | __tablename__ = 'search_polygons' 18 | 19 | name = Column(String, primary_key=True) 20 | centroid_row = Column(Float, nullable=False) 21 | centroid_column = Column(Float, nullable=False) 22 | centroid_zoom = Column(Integer, nullable=False) 23 | inner_coords_calculated = Column(Boolean, nullable=False, server_default=expression.false()) 24 | 25 | 26 | class PositiveCluster(Base): 27 | __tablename__ = 'positive_clusters' 28 | 29 | id = Column(Integer, primary_key=True) 30 | 31 | 32 | class SlippyTile(Base): 33 | __tablename__ = 'slippy_tiles' 34 | 35 | row = Column(Integer, nullable=False) 36 | column = Column(Integer, nullable=False) 37 | zoom = Column(Integer, nullable=False) 38 | centroid_distance = Column(Float) 39 | polygon_name = Column(String, ForeignKey(SearchPolygon.name), nullable=True) 40 | polygon = relationship("SearchPolygon") 41 | cluster_id = Column(String, ForeignKey(PositiveCluster.id), nullable=True) 42 | cluster = relationship("PositiveCluster") 43 | has_image = Column(Boolean, nullable=False, server_default=expression.false()) 44 | inference_ran = Column(Boolean, nullable=False, server_default=expression.false()) 45 | inference_timestamp = Column(Integer, nullable=True) # UNIX EPOCH 46 | panel_softmax = Column(Float, nullable=True) 47 | panel_seen_by_human = Column(Boolean, nullable=True, server_default=expression.false()) 48 | panel_verified = Column(Boolean, nullable=True, server_default=expression.false()) 49 | 50 | __table_args__ = ( 51 | PrimaryKeyConstraint(row, column, zoom, sqlite_on_conflict='IGNORE'), 52 | Index('centroid_index', polygon_name, centroid_distance) 53 | ) 54 | 55 | 56 | class OSMSolarNode(Base): 57 | __tablename__ = 'osm_solar_nodes' 58 | 59 | longitude = Column(Float, nullable=False) 60 | latitude = Column(Float, nullable=False) 61 | 62 | __table_args__ = ( 63 | PrimaryKeyConstraint(longitude, latitude, sqlite_on_conflict='IGNORE'), 64 | ) 65 | 66 | 67 | engine = create_engine('sqlite:///data/solar.db') 68 | Base.metadata.create_all(engine) 69 | Session = sessionmaker(bind=engine) 70 | 71 | 72 | def persist_polygons(names_and_polygons, zoom=21): 73 | session = Session() 74 | for name, polygon in names_and_polygons: 75 | exists = session.query(SearchPolygon).filter(SearchPolygon.name == name).first() 76 | if not exists: 77 | session.add(SearchPolygon(name=name, centroid_column=polygon.centroid.x, centroid_row=polygon.centroid.y, 78 | centroid_zoom=zoom)) 79 | session.commit() 80 | session.close() 81 | 82 | 83 | def persist_coords(polygon_name, coords, zoom=21, batch_size=100000): 84 | start_time = time.time() 85 | session = Session() 86 | tiles_to_add = [] 87 | for coord in coords: 88 | if len(tiles_to_add) >= batch_size: 89 | session.add_all(tiles_to_add) 90 | session.commit() 91 | tiles_to_add = [] 92 | tiles_to_add.append(SlippyTile(polygon_name=polygon_name, column=coord[0], row=coord[1], zoom=zoom)) 93 | session.add_all(tiles_to_add) 94 | session.query(SearchPolygon).filter(SearchPolygon.name == polygon_name).first().inner_coords_calculated = True 95 | session.commit() 96 | session.close() 97 | print(str(time.time() - start_time) + " seconds to complete inner grid persistence for " + polygon_name) 98 | 99 | 100 | def get_polygon_names(): 101 | session = Session() 102 | polygons = session.query(SearchPolygon).all() 103 | session.close() 104 | return [polygon.name for polygon in polygons] 105 | 106 | 107 | def get_inner_coords_calculated_polygon_names(): 108 | session = Session() 109 | polygons = session.query(SearchPolygon).filter(SearchPolygon.inner_coords_calculated.is_(True)).all() 110 | session.close() 111 | return [polygon.name for polygon in polygons] 112 | 113 | 114 | def polygon_has_inner_grid(name): 115 | session = Session() 116 | inner_grid = session.query(SearchPolygon.inner_coords_calculated).filter(SearchPolygon.name == name).first()[0] 117 | session.close() 118 | return inner_grid 119 | 120 | 121 | def compute_centroid_distances(batch_size=10000): 122 | session = Session() 123 | while True: 124 | uncomputed_centroid_tiles = session.query(SlippyTile).filter(SlippyTile.centroid_distance.is_(None), 125 | SlippyTile.polygon_name.isnot(None) 126 | ).limit(batch_size).all() 127 | if not uncomputed_centroid_tiles: 128 | break 129 | for tile in uncomputed_centroid_tiles: 130 | tile.centroid_distance = math.sqrt( 131 | math.pow(tile.polygon.centroid_row - tile.row, 2) + math.pow(tile.polygon.centroid_column - tile.column, 132 | 2)) 133 | session.commit() 134 | session.close() 135 | 136 | 137 | # marks existing slippy tiles as having imagery in the db, and if the tiles don't exist it creates them (for cases where 138 | # the imagery gathered goes outside the planned polygon bounds, still need to track it, and maybe use it) 139 | def mark_has_imagery(base_coord, grid_size, zoom=21): 140 | session = Session() 141 | # get and update the tiles in this grid that exist 142 | tile_query = session.query(SlippyTile).filter(SlippyTile.zoom == zoom).filter(SlippyTile.column.between( 143 | base_coord[0], base_coord[0] + grid_size - 1)).filter(SlippyTile.row.between(base_coord[1], base_coord[1] + 144 | grid_size - 1)) 145 | tile_query.update({SlippyTile.has_image: True}, synchronize_session='fetch') 146 | tiles = tile_query.all() 147 | 148 | # create a meshgrid of points in this grid 149 | coords = {} 150 | for column in range(base_coord[0], base_coord[0] + 20): 151 | for row in range(base_coord[1], base_coord[1] + 20): 152 | coords[(column, row)] = True 153 | # remove the tiles that we already know exist 154 | for tile in tiles: 155 | coords.pop((tile.column, tile.row), None) 156 | tiles_to_add = [] 157 | # create new tile objects for the remaining points in the meshgrid and add them to the db 158 | for coord in coords.keys(): 159 | tiles_to_add.append(SlippyTile(column=coord[0], row=coord[1], zoom=zoom, has_image=True)) 160 | session.add_all(tiles_to_add) 161 | session.commit() 162 | session.close() 163 | 164 | 165 | # decimal places to round is so nodes with close lat/lon are only counted as one point, 166 | # degree precision versus length chart: https://en.wikipedia.org/wiki/Decimal_degrees#Precision 167 | def query_osm_solar(polygons, decimal_places_to_round=5): 168 | api = overpy.Overpass() 169 | solar_node_lon_lats = set() 170 | for polygon in polygons: 171 | # little bit of python magic to massage the polygon into a space separated list of coordinates 172 | polygon_coords_string = " ".join([" ".join(map(str, coord)) for coord in zip(*reversed(polygon.boundary.xy))]) 173 | # I've read that querying within a polygon is a lot slower than querying within a bounding box, so if this 174 | # ends up being too slow, feel free to just replace with the bounding box of the polygon 175 | query_string = \ 176 | """ 177 | [out:json][timeout:2500]; 178 | ( 179 | node["generator:source"="solar"](poly:"{poly}"); 180 | way["generator:source"="solar"](poly:"{poly}"); 181 | relation["generator:source"="solar"](poly:"{poly}"); 182 | ); 183 | out body; 184 | >; 185 | out skel qt; 186 | """.format(poly=polygon_coords_string) 187 | result = api.query(query_string) 188 | for node in result.nodes: 189 | solar_node_lon_lats.add( 190 | (round(node.lon, decimal_places_to_round), round(node.lat, decimal_places_to_round))) 191 | return solar_node_lon_lats 192 | 193 | 194 | def query_and_persist_osm_solar(polygons): 195 | session = Session() 196 | solar_node_lon_lats = query_osm_solar(polygons) 197 | solar_nodes = [] 198 | for lon, lat in solar_node_lon_lats: 199 | solar_nodes.append(OSMSolarNode(longitude=lon, latitude=lat)) 200 | session.add_all(solar_nodes) 201 | session.commit() 202 | session.close() 203 | 204 | 205 | def query_tile_batch(batch_size=1000000, polygon_name=None): 206 | session = Session() 207 | tile_query = session.query(SlippyTile).filter(SlippyTile.has_image.is_(True), SlippyTile.inference_ran.is_(True)) 208 | if polygon_name: 209 | tile_query = tile_query.filter(SlippyTile.polygon_name == polygon_name) 210 | tiles = tile_query.limit(batch_size).all() 211 | session.close() 212 | return tiles 213 | 214 | 215 | def query_tile_batch_for_inference(batch_size=400): 216 | session = Session() 217 | tiles = \ 218 | session.query(SlippyTile).filter(SlippyTile.centroid_distance.isnot(None), SlippyTile.inference_ran.is_(False))\ 219 | .order_by(SlippyTile.polygon_name, SlippyTile.centroid_distance).limit(batch_size).all() 220 | session.close() 221 | return tiles 222 | 223 | 224 | def update_tiles(tiles): 225 | session = Session() 226 | session.add_all(tiles) 227 | session.commit() 228 | session.close() 229 | 230 | 231 | def query_tiles_over_threshold(threshold=0.25, polygon_name=None, filter_clustered=False): 232 | session = Session() 233 | coordinate_query = session.query(SlippyTile).filter(SlippyTile.panel_softmax.isnot(None), 234 | SlippyTile.panel_softmax >= threshold).order_by( 235 | desc(SlippyTile.panel_softmax)) 236 | if polygon_name: 237 | coordinate_query = coordinate_query.filter(SlippyTile.polygon_name == polygon_name) 238 | if filter_clustered: 239 | coordinate_query = coordinate_query.filter(SlippyTile.cluster_id.is_(None)) 240 | coordinates = coordinate_query.all() 241 | session.close() 242 | return coordinates 243 | 244 | 245 | def get_new_positive_cluster_id(): 246 | session = Session() 247 | positive_cluster = PositiveCluster() 248 | session.add(positive_cluster) 249 | session.commit() 250 | positive_cluster_id = positive_cluster.id 251 | session.close() 252 | return positive_cluster_id 253 | 254 | 255 | def get_osm_pv_nodes(): 256 | session = Session() 257 | nodes = session.query(OSMSolarNode).all() 258 | session.close() 259 | return [(node.longitude, node.latitude) for node in nodes] 260 | 261 | 262 | def get_lat_lon_for_largest_clusters(limit=10, polygon_name=None): 263 | """ 264 | Queries the db for largest contiguous clusters 265 | :param limit: number of results to return 266 | :param polygon_name: optional name to filter for 267 | :return: list of lat_lon tuples near each cluster (exact center doesn't really matter for my use case) 268 | """ 269 | session = Session() 270 | cluster_query = session.query(SlippyTile.cluster_id).filter(SlippyTile.cluster_id.isnot(None)) 271 | if polygon_name: 272 | cluster_query = cluster_query.filter(SlippyTile.polygon_name == polygon_name) 273 | tuple_list = cluster_query.group_by(SlippyTile.cluster_id).order_by(desc(count(SlippyTile.cluster_id))).limit( 274 | limit).all() 275 | lat_lons = [] 276 | for cluster_id, in tuple_list: 277 | lat_lons.append(reversed(num2deg(session.query(SlippyTile.column, SlippyTile.row).filter( 278 | SlippyTile.cluster_id == cluster_id).limit(1).first()))) 279 | session.close() 280 | return lat_lons -------------------------------------------------------------------------------- /process_city_shapes.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import math 4 | import os 5 | import sys 6 | import time 7 | import solardb 8 | 9 | import geojson 10 | import geojsonio as geojsonio 11 | import geopandas 12 | import numpy as np 13 | from shapely.geometry import shape, mapping, GeometryCollection, Point 14 | 15 | from gather_city_shapes import get_city_state_filepaths, get_city_state_tuples 16 | 17 | 18 | def deg2num(arr, zoom=21): 19 | """ 20 | Convert input array of longitude and latitude into slippy tile coordinates. 21 | 22 | :param arr: input list or tuple that contains the longitude and latitude to convert, the input is in addressable 23 | form so that it can be called by np.apply_along_axis(...) 24 | :param zoom: zoom parameter necessary for calculating slippy tile coordinates, defaults to 21 because that's the 25 | zoom level DeepSolar operates at 26 | :return: slippy tile coordinate tuple containing column and row (sometimes referred to as x_tile and y_tile 27 | respectively) 28 | """ 29 | lon_deg = arr[0] 30 | lat_deg = arr[1] 31 | lat_rad = np.math.radians(lat_deg) 32 | n = 2.0 ** zoom 33 | column = int((lon_deg + 180.0) / 360.0 * n) 34 | row = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) 35 | return column, row 36 | 37 | 38 | def num2deg(arr, zoom=21, center=True): 39 | """ 40 | Convert input array of column and row into longitude latitude coordinates 41 | 42 | :param arr: input list or tuple that contains slippy tile column and row coordinates to convert. As above, the input 43 | is in addressable form so that np.apply_along_axis(...) can easily call it. 44 | :param zoom: zoom parameter necessary for calculating longitude latitude coordinates, defaults to 21 because that's 45 | the zoom level DeepSolar operates at 46 | :param center: boolean that determines whether the lon_lat should be at the middle of the tile or the top left, 47 | defaults to center 48 | :return: lon lat tuple 49 | """ 50 | column = arr[0] 51 | row = arr[1] 52 | if center: 53 | column += 0.5 54 | row += 0.5 55 | n = 2.0 ** zoom 56 | lon_deg = column / n * 360.0 - 180.0 57 | lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * row / n))) 58 | lat_deg = math.degrees(lat_rad) 59 | return lon_deg, lat_deg 60 | 61 | 62 | def get_polygons(csvpath, exclude=None): 63 | """ 64 | Loads polygons for cities listed in csvpath, polygons must have already been calculated and placed into 65 | data/geoJSON/..json 66 | 67 | :param csvpath: path to csv containing city, state names for polygons to load 68 | :param exclude: list of name strings to exclude from the load (name string is ", "), default None 69 | :return: yields the json of the polygon file 70 | """ 71 | if exclude is None: 72 | exclude = [] 73 | for city, state, filepath in get_city_state_filepaths(csvpath): 74 | name_string = ", ".join((city, state)) 75 | if name_string not in exclude: 76 | with open(filepath, 'r') as infile: 77 | yield json.load(infile) 78 | 79 | 80 | def combine_all_polygons(csvpath, exclude=None): 81 | """ 82 | Combines all polygons loaded from csvpath together into one GeometryCollection, after running some simplification on 83 | them to decrease computational complexity. 84 | 85 | :param csvpath: path to csv containing city, state names for polygons to load 86 | :param exclude: list of name strings to exclude from the load (name string is ", "), default None 87 | :return: GeometryCollection containing all simplified polygons loaded from files 88 | """ 89 | return GeometryCollection([simplify_polygon(polygon) for polygon in get_polygons( 90 | csvpath, exclude=exclude)]) 91 | 92 | 93 | def simplify_polygon(polygon, simplify_tolerance=0.001, buffer_distance=0.004): 94 | """ 95 | Copies the given polygon and runs simplification on it to reduce computational complexity. Iirc, the parameter 96 | defaults are taken from some service that simplifies polygons. 97 | 98 | :param polygon: Input polygon 99 | :param simplify_tolerance: parameter to pass to simplify, specifies how close the simplified coordinates have to be 100 | to the original 101 | :param buffer_distance: distance to "dilate" the polygon, the default parameter grows it somewhat 102 | :return: simplified shapely polygon 103 | """ 104 | return shape(polygon).convex_hull.simplify(simplify_tolerance).buffer(buffer_distance) 105 | 106 | 107 | def convert_to_slippy_tile_coords(polygons, zoom=21): 108 | """ 109 | Converts multiple polygons into slippy tile coordinates 110 | 111 | :param polygons: polygons to convert 112 | :param zoom: zoom level used in conversion, defaults to 21 113 | :return: converted polygons 114 | """ 115 | converted_polygons = [] 116 | for polygon in polygons: 117 | geojson_object = mapping(polygon) 118 | geojson_object['coordinates'] = np.apply_along_axis(deg2num, 2, np.array(geojson_object['coordinates']), 119 | zoom=zoom) 120 | converted_polygons.append(shape(geojson_object)) 121 | return converted_polygons 122 | 123 | 124 | def save_geojson(filename, feature): 125 | """ 126 | Saves the feature parameter in a proper geoJSON file at the given filename in the data directory 127 | 128 | :param filename: filename of saved file in ./data/ 129 | :param feature: geoJSON feature to save (usually polygon) 130 | """ 131 | with open(os.path.join('data', filename), 'w') as outfile: 132 | geojson.dump(geojson.Feature(geometry=feature, properties={}), outfile) 133 | 134 | 135 | def point_mapper(x, polygon=None): 136 | """ 137 | Simple function required to call apply_along_axis and get a boolean mask 138 | 139 | :param x: tuple/list point 140 | :param polygon: polygon to check if point is contained in 141 | :return: whether or not the polygon contains the point 142 | """ 143 | return not polygon.contains(Point((x[0], x[1]))) 144 | 145 | 146 | def get_coords_inside_polygon(polygon): 147 | """ 148 | Calculate all grid coordinate inside a given polygon. 149 | 150 | This method takes a while, possibly need to multiprocess (1 cpu is maxed out on my machine) or switch to matplotlib 151 | for possibly more efficient code: 152 | https://stackoverflow.com/questions/21339448/how-to-get-list-of-points-inside-a-polygon-in-python 153 | 154 | :param polygon: polygon to calculate coordinates inside of 155 | :return: ndarray containing coordinate pairs (shape (x,2)) 156 | """ 157 | # get a meshgrid the size of the polygon's bounding box 158 | x, y = np.meshgrid(np.arange(polygon.bounds[0], polygon.bounds[2]), np.arange(polygon.bounds[1], polygon.bounds[3])) 159 | 160 | # convert the meshgrid to an array of points 161 | x, y = x.flatten(), y.flatten() 162 | points = np.vstack((x, y)).T 163 | 164 | # calculate if the polygon contains every point 165 | mask = np.apply_along_axis(point_mapper, 1, points, polygon=polygon) 166 | 167 | # stack the mask so each boolean value gets propagated to both coords 168 | mask = np.stack((mask, mask), axis=1) 169 | 170 | # delete the points outside the polygon and return 171 | return np.ma.masked_array(points, mask=mask).compressed().reshape((-1, 2)) 172 | 173 | 174 | def get_coords_caller(name, polygon): 175 | """ 176 | Calls the get inner coordinate method and times the execution 177 | 178 | :param name: name of polygon 179 | :param polygon: polygon to calculate inner coordinates of 180 | :return: ndarray containing coordinate pairs (shape (x,2)) 181 | """ 182 | start_time = time.time() 183 | coordinates = get_coords_inside_polygon(polygon) 184 | print(str(time.time() - start_time) + " seconds to complete inner grid calculations for " + name) 185 | return coordinates 186 | 187 | 188 | def calculate_inner_coordinates_from_csvpath(csvpath, zoom=21): 189 | """ 190 | Calculates and persists inner coordinates of all polygons in csvpath, this is the public api 191 | 192 | :param csvpath: path containing the csv file for all polygons to calculate inner coordinates for 193 | :param zoom: zoom level at which to calculate inner coordinates, defaults to 21 194 | """ 195 | start = time.time() 196 | 197 | polygons = list(combine_all_polygons(csvpath, exclude=solardb.get_inner_coords_calculated_polygon_names())) 198 | city_state_tuples = list(get_city_state_tuples(csvpath)) 199 | polygon_names = [', '.join(city_state_tuple) for city_state_tuple in city_state_tuples] 200 | calculate_inner_coordinates(polygon_names, polygons, zoom) 201 | print("Total running time to calculate inner coordinates: " + str(time.time() - start) + " seconds.") 202 | 203 | 204 | def calculate_inner_coordinates(polygon_names, polygons, zoom=21): 205 | slippy_tile_coordinate_polygons = list(convert_to_slippy_tile_coords(polygons, zoom=zoom)) 206 | assert (len(polygon_names) == len(slippy_tile_coordinate_polygons)) # make sure no length mismatch 207 | zipped_names_and_polygons = list(zip(polygon_names, slippy_tile_coordinate_polygons)) 208 | solardb.persist_polygons(zipped_names_and_polygons, zoom=zoom) 209 | to_calculate_names_and_polygons = [] 210 | for name, polygon in zipped_names_and_polygons: 211 | if not solardb.polygon_has_inner_grid(name): 212 | to_calculate_names_and_polygons.append((name, polygon)) 213 | for name, polygon in to_calculate_names_and_polygons: 214 | coordinates = get_coords_caller(name, polygon) 215 | solardb.persist_coords(name, coordinates, zoom=zoom) 216 | 217 | 218 | if __name__ == '__main__': 219 | parser = argparse.ArgumentParser(description= 220 | 'Process shapes of city polygons that were created by gather_city_shapes.py') 221 | parser.add_argument('--input_csv', dest='csvpath', default=os.path.join('data', '100k_US_cities.csv'), 222 | help='specify the csv list of city and state names to gather geoJSON for') 223 | parser.add_argument('--combine_polygons', dest='combine_polygons', action='store_const', 224 | const=True, default=False, 225 | help='Combine all of the city polygons and save into a geojson') 226 | parser.add_argument('--calculate_area', dest='area', action='store_const', 227 | const=True, default=False, 228 | help='Calculates the area of all polygons in km2') 229 | parser.add_argument('--calculate_inner_grid', dest='inner', action='store_const', 230 | const=True, default=False, 231 | help='Calculates every slippy coordinate that\'s within a polygon, ' 232 | 'currently takes a very long time') 233 | parser.add_argument('--calculate_centroids', dest='centroids', action='store_const', 234 | const=True, default=False, 235 | help='Calculates missing centroids in the database') 236 | parser.add_argument('--query_osm_solar', dest='osm_solar', action='store_const', 237 | const=True, default=False, 238 | help='Queries and persists existing solar panel locations from osm from the combined polygons') 239 | parser.add_argument('--geojsonio', dest='geojsonio', action='store_const', 240 | const=True, default=False, 241 | help='Opens processing output in geojsonio if the operation makes sense') 242 | args = parser.parse_args() 243 | 244 | output = None 245 | if args.combine_polygons: 246 | geometry_collection_of_polygons = combine_all_polygons(args.csvpath) 247 | save_geojson('geom_collection.geojson', geometry_collection_of_polygons) 248 | output = geometry_collection_of_polygons 249 | if args.area: 250 | projected_polygons = convert_to_slippy_tile_coords(list(combine_all_polygons(args.csvpath)), zoom=21) 251 | print(str(math.ceil(sum([polygon.area for polygon in projected_polygons]))) 252 | + " total tiles at zoom level " + str(21) + " in this multipolygon area!") 253 | output = projected_polygons 254 | if args.inner: 255 | calculate_inner_coordinates_from_csvpath(csvpath=args.csvpath, zoom=21) 256 | if args.centroids: 257 | solardb.compute_centroid_distances() 258 | if args.osm_solar: 259 | solardb.query_and_persist_osm_solar(list(combine_all_polygons(args.csvpath))) 260 | if args.geojsonio and output is not None: 261 | geojsonio.display(geopandas.GeoSeries(output)) 262 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------