In [21]:
#This notebook can post-process a QUALTX output file
#and plot water quality profiles along all the modeled reaches
#ET 20160514
#Enter the location of the QUALTX output file
#This program can parse both urls and local paths
QUALTXoutfile = r'https://raw.githubusercontent.com/Harefoot/TurboQUALTX/master/RHOTRUNC.OUT'

In [22]:
# ET Space holder for when later I want to implement widgets to turn this python into a dashboard
from ipywidgets import interact
from bokeh.io import push_notebook
#http://bokeh.pydata.org/en/0.10.0/docs/user_guide/notebook.html#integrating-ipython-interactors

In [23]:
#Import python packages
import pandas as pd
pd.options.mode.chained_assignment = None  # default='warn'
import os

import sys
#sys.path.insert(0,r'M:\Library\Python\Packages')
import ET_Utils.QUALTX_Utils
import numpy as np
import bokeh
from bokeh.plotting import figure, show
from bokeh.models import HoverTool, BoxSelectTool
from bokeh.io import output_notebook
output_notebook()


Loading BokehJS ...

In [24]:
#Parse the QUALTX output file 
Scenario = QUALTXoutfile
DOstd = 4#[5,4.8]
#WQC_of_interest = ['DO_MG/L','BOD_MG/L','NH3_MG/L','NO3+2_MG/L','PHOS_MG/L']
WQC_of_interest = ['DO_MG/L','BOD_MG/L','NH3_MG/L']#,'NO3+2_MG/L','PHOS_MG/L']
StreamNames, Rdf, Hdf, AllWQdf = ET_Utils.QUALTX_Utils.Process_QUALTX(QUALTXoutfile,
                                                                      Scenario,DOstd = DOstd,
                                                                      WQC_of_interest = WQC_of_interest,
                                                                      loc = 1,plot_pdf = 0)


RHODAIR GULLY
UNND TRIB 2
UNND TRIB 3

In [25]:
from bokeh.io import output_file, show
from bokeh.models import GeoJSONDataSource
from bokeh.plotting import figure
import json 
#from bokeh.sampledata.sample _geojson import geojson

geojsonfile = r'C:\Users\Ernest\Ernest_Sandbox\TurboQUALTX\TurboQUALTX\GIS\TCEQ Wastewater Outfalls 20160514.geojson'
#geojson=json.load(geojsonfile)
#geo_source = GeoJSONDataSource(geojson= geojson)
#GeoJSONDataSource(geojson=json.load(datafilename)))
#p = figure()
#p.circle(x='x', y='y', alpha=0.9, source=geo_source)
#output_file("geojson.html")
#show(p)
#from bokeh.io import output_file, show
#from bokeh.io import output_file, show
#from bokeh.models import GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, PanTool, WheelZoomTool, BoxSelectTool

#map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)

#plot = GMapPlot(x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Austin 1")

#source = ColumnDataSource(data=dict(lat=[30.29, 30.20, 30.29],lon=[-97.70, -97.74, -97.78],))

#circle = Circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, line_color=None)
#plot.add_glyph(source, circle)

#plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
#output_file("gmap_plot.html")
#show(plot)

In [26]:
#Plot a map
import folium
import numpy as np
from folium.element import IFrame
#bbox = [-87.40, 24.25, -74.70, 36.70]
bbox = [-106.6460, 25.8371, -93.5083, 36.5007]
location = np.array(bbox).reshape(2, 2).mean(axis=0).tolist()[::-1]
tiles = ('http://services.arcgisonline.com/arcgis/rest/'
         'services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}')

mapa = folium.Map(location=location, zoom_start=6,
                  tiles=tiles, attr='ESRI')

geo_path = r'C:\Users\Ernest\Ernest_Sandbox\TurboQUALTX\TurboQUALTX\GIS\TCEQ Wastewater Outfalls 20160514.geojson'
#mapa.geo_json(geo_path=geo_path)
points = folium.features.GeoJson(geo_path)
print points
print dir(points)
print points.data
print dir(points.data)
mapa.add_children(points)
marker = folium.Marker(location=[-106.6460, 25.8371])
#marker.add_to(mapa)
#mapa.geo_json(geo_path=geo_path)
#mapa.simple_marker(points)
mapa.add_children(marker)
#See https://github.com/NelsonMinar/vector-river-map

#mapa.lat_lng_popover()
#mapa.LatLngPopup()
#mapa.add_children(folium.ClickForMarker())
#mapa.add_children(folium.LatLngPopup())

mapa


<folium.features.GeoJson object at 0x000000000EEFC780>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', '_env', '_get_self_bounds', '_id', '_name', '_parent', '_template', 'add_child', 'add_children', 'add_to', 'control', 'data', 'embed', 'get_bounds', 'get_name', 'get_root', 'layer_name', 'overlay', 'render', 'save', 'style_data', 'style_function', 'to_dict', 'to_json']
C:\Users\Ernest\Ernest_Sandbox\TurboQUALTX\TurboQUALTX\GIS\TCEQ Wastewater Outfalls 20160514.geojson
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Out[26]:

In [27]:
#Set plotting parameters
plot_width=900
plot_height=600

y_label = 'Concentration (mg/L)'
x_label = 'Distance (km)'

#Set line width
lws = np.zeros(len(WQC_of_interest))+2

#Set line colors
plot_colors = ['blue','black','green','cyan','orange']

#Set line symbols
plot_symbols = ['-','-','-','-','-']

#Set marker sizes
markersizes = np.zeros(len(WQC_of_interest))+1

#Set label sizes
x_labelsize = 15
y_labelsize = 15

In [28]:
# Loop through each stream and plot the WQ profile plot
TOOLS="hover,box_zoom,wheel_zoom,pan,reset"

for StreamName in StreamNames:
    WQdf = AllWQdf[AllWQdf['Stream']==StreamName].copy()
    SRdf = Rdf[Rdf['StreamName']==StreamName].reset_index()
    x_range = [max(WQdf['ENDING_DIST'])*1.025,min(WQdf['ENDING_DIST'])]

    #Determine range of y-axis
    maxy = []
    for tempWQC in WQC_of_interest:
        maxy.append(max(WQdf[tempWQC]))    
    y_range = [0,round(max(maxy))]#*1.5)]

    p = figure(title=StreamName, tools=TOOLS,x_range = x_range,y_range=y_range,plot_width=plot_width, plot_height=plot_height)  
    if StreamName == StreamNames[0]:
        hover = p.select(dict(type=HoverTool))
        hover.tooltips = [
            # format text in tooltip
            ("Conc ", "$y mg/L"),
        ]    
    p.xaxis.axis_label = x_label
    p.yaxis.axis_label = y_label

   
    for k in range(0,len(WQC_of_interest)):        
        # add a line renderer
        p.line(np.asarray(WQdf['ENDING_DIST']),np.asarray(WQdf[WQC_of_interest[k]]), 
               legend=WQC_of_interest[k], line_width= lws[k],
               color = plot_colors[k],name = WQC_of_interest[k])

         #Overplot reach start and end points of each reach
        if len(SRdf) > 0:
            Points1 = list(SRdf['BEGIN NAME'])
            Rkms1 = list(SRdf['BEGIN REACH KM'])
            if len(SRdf) > 1:
                Points2 = [SRdf['END NAME'][SRdf.index[-1]]]
                Rkms2 = [SRdf['END REACH KM'][SRdf.index[-1]]]
            else:
                Points2 = list(SRdf['END NAME'])
                Rkms2 = list(SRdf['END REACH KM'])
                
            Points = Points1 + Points2
        
            #Rkms = Rkms1.append(Rkms2)
            Rkms = Rkms1+Rkms2
        #p1.text([65,65,65],[65,65,65], text=[ str(i) for i in x], alpha=0.5, text_font_size="5pt", text_baseline="middle", 
        #text_align="center")
            for i in range(0,len(Points)):
                #print Points[i]
                p.line([Rkms[i],Rkms[i]],[-999,999],'..',line_dash = 'dotted',color = 'grey')
                p.text([Rkms[i]],[np.mean(y_range)],text = [Points[i]],text_align = 'center',
                       angle = 3.14159265/2,text_font_size = '9pt',text_color = 'grey')
    
        if DOstd != np.nan:
            DOstds = [DOstd,DOstd-0.2]
            vas = ['bottom','top']
            for i in range(len(DOstds)):
                p.line([-999,999],[DOstds[i],DOstds[i]],'..',line_dash = 'dotted',color = 'red')
                p.text([np.mean(x_range)],[DOstds[i]],["DO std = "+"{:4.1f}".format(DOstds[i])+" mg/L"],
                       text_baseline = vas[i],text_font_size = '9pt',text_color = 'red')
                pass
        p.xgrid.grid_line_color = None
        p.ygrid.grid_line_color = None
    show(p)



In [29]:
from fastkml.kml import KML

def read_kml(fname='ss.kml'):
    kml = KML()
    kml.from_string(open(fname).read())
    points = dict()
    for feature in kml.features():
        for placemark in feature.features():
            if placemark.styleUrl.startswith('#hf'):
                points.update({placemark.name:
                               (placemark.geometry.y, placemark.geometry.x, )})
    return points

In [30]:
fname = r'C:\Users\Ernest\Ernest_Sandbox\TurboQUALTX\TurboQUALTX\GIS\ss.kml'
#fname = r'C:\Users\Ernest\Ernest_Sandbox\TurboQUALTX\TurboQUALTX\GIS\TCEQ Wastewater Outfalls2.kml'
locations = read_kml(fname)

In [31]:
import folium




width, height = 650, 500
#radars = folium.Map(location=[40, -122], zoom_start=5,
#                    tiles='OpenStreetMap', width=width, height=height)
radars = folium.Map(location=location, zoom_start=6,
                  tiles=tiles, attr='ESRI')
for name, location in locations.items():
    radars.simple_marker(location=location, popup=name)
radars

#inline_map(radars)


C:\Anaconda\lib\site-packages\ipykernel\__main__.py:20: FutureWarning: simple_marker is deprecated. Use add_children(Marker) instead
Out[31]:

In [ ]: