def home(request): """ Controller for the app home page. """ # Date Picker Options date_picker = DatePicker(name='date1', display_text='Date', autoclose=True, format='MM d, yyyy', start_date='2/15/2014', start_view='decade', today_button=True, initial='February 15, 2014') date_picker_error = DatePicker(name='data2', display_text='Date', initial='10/2/2013', disabled=True, error='Here is my error text.') context = { 'date_picker': date_picker, 'date_picker_error': date_picker_error, } return render(request, 'mapapp/home.html', context)\
def home(request): """ Controller for the app home page. """ start_date = DatePicker( name='start_date', display_text='Start Date', autoclose=True, format='MM d, yyyy', start_date='1/1/2003', end_date=time.strftime("%m/%d/%Y"), start_view='decade', today_button=True, initial='January 1, 2003' ) end_date = DatePicker( name='end_date', display_text='End Date', autoclose=True, format='MM d, yyyy', start_date='1/1/2003', end_date=time.strftime("%m/%d/%Y"), start_view='decade', today_button=True, initial='January 1, 2018' ) context = { 'start_date':start_date, 'end_date':end_date } return render(request, 'sma_africa/home.html', context)
def modis(request): """ Controller for the app home page. """ time_series_plot = LinePlot(height='500px', width='500px', engine='highcharts', title='Change in Snowpack', subtitle='Plot Subtitle', spline=True, x_axis_title='Time', x_axis_units='Month', y_axis_title='Depth', y_axis_units='Inches', series=[ { 'name': 'Snowpack Change', 'color': '#0066ff', 'marker': { 'enabled': False }, 'data': [[0, 5], [10, -70], [20, -86.5], [30, -66.5], [40, -32.1], [50, -12.5], [60, -47.7], [70, -85.7], [80, -106.5]] }, ]) add_region_button = Button(display_text='Add Region', name='add-region-button', icon='glyphicon glyphicon-plus', style='success') # Date Picker Options date_picker = DatePicker(name='date1', display_text='Date', autoclose=True, format='MM d, yyyy', start_date='2/15/2014', start_view='decade', today_button=True, initial='February 15, 2014') date_picker_error = DatePicker(name='data2', display_text='Date', initial='10/2/2013', disabled=True, error='Here is my error text.') context = { "time_series_plot": time_series_plot, "add_region_button": add_region_button, 'date_picker': date_picker, 'date_picker_error': date_picker_error, } return render(request, 'the_snowmen_snowpack_viewer/modis.html')
def home(request): """ Controller for the app home page. """ date_picker = DatePicker( name='date', display_text='Start Date', autoclose=True, format='mm/dd/yyyy', start_view='decade', start_date='01/01/2011', end_date='12/31/2011', ) start_date_picker = DatePicker( name='start_date_picker', display_text='Start Date Range', autoclose=True, format='mm/dd/yyyy', start_view='decade', start_date='01/01/2011', end_date='12/31/2011', ) end_date_picker = DatePicker( name='end_date_picker', display_text='End Date Range', autoclose=True, format='mm/dd/yyyy', start_view='decade', start_date='01/01/2011', end_date='12/31/2011', ) pick_date_range = Button( display_text='Choose this date range:', name='pick_date_range', style='success', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Save' } ) context = { 'pick_date_range': pick_date_range, 'date_picker': date_picker, 'start_date_picker': start_date_picker, 'end_date_picker': end_date_picker, } return render(request, 'flood_inu/home.html', context)
def export(request): """ Controller for the Export page. """ start_date_input = DatePicker( name='start_date', display_text='Start Date', autoclose=True, format='MM d, yyyy', start_date='8/24/2020', start_view='decade', today_button=True, attributes={'class': 'date-input'}, ) end_date_input = DatePicker( name='end_date', display_text='End Date', autoclose=True, format='MM d, yyyy', start_date='8/24/2020', start_view='decade', today_button=True, ) cancel_button = Button( display_text='Cancel', name='cancel-button', icon='glyphicon glyphicon-remove', style='danger', href=reverse('project_inventory:home') ) submit_button = Button( display_text='Submit', name='submit-button', style='success', icon='glyphicon glyphicon-plus', href=reverse('project_inventory:home') ) context = { 'start_date_input': start_date_input, 'end_date_input': end_date_input, 'cancel_button': cancel_button, 'submit_button':submit_button, 'can_add_projects': has_permission(request, 'add_projects') } return render(request, 'project_inventory/export.html', context)
def map(request): """ Controller for map page. """ #configure the date picker date_picker = DatePicker( display_text='Date', name='endDate', autoclose=True, format='yyyy-mm-dd', start_date='2013-01-01', today_button=True, initial=datetime.datetime.today().strftime("%Y-%m-%d")) days_picker = { 'display_text': 'Number of days:', 'name': 'inputDays', 'placeholder': '100' } # Pre-populate lat-picker and lon_picker from model lat_picker = {'display_text': 'Latitude:', 'name': 'inputLat'} lon_picker = {'display_text': 'Longitude:', 'name': 'inputLon'} # Pass variables to the template via the context dictionary context = { 'date_picker': date_picker, 'days_picker': days_picker, 'lon_picker': lon_picker, 'lat_picker': lat_picker } return render(request, 'snow_inspector/openlayers_map.html', context)
def gizmos(request): """ Controller for the app home page. """ date_picker = DatePicker(name='date', display_text='Date', autoclose=True, format='MM d, yyyy', start_date='2/15/2014', start_view='decade', today_button=True, initial='February 15, 2017') text_input = TextInput(display_text='Text', name='inputAmount', placeholder='e.g.: 10.00', prepend='$') slider1 = RangeSlider(display_text='Slider 1', name='slider1', min=0, max=100, initial=50, step=1) context = { 'date_picker': date_picker, 'text_input': text_input, 'slider1': slider1, } return render(request, 'map_app_lippold/gizmos.html', context)
def create_plot_ctrls(model, controller): """ Function that creates and return the "start_date", "end_hour", and "plot_button" elements """ differentiator = 1 if controller == 'plot' else 2 start_date = DatePicker(display_text=False, name='startDate%s' % differentiator, autoclose=True, format='mm/dd/yyyy', start_date=get_model_fences()[model]['start_date'], end_date=get_model_fences()[model]['end_date'], start_view=0, classes='startDate', attributes='onchange=oc_sten_dt("startDate%s");' % differentiator) end_date = DatePicker(display_text=False, name='endDate%s' % differentiator, autoclose=True, format='mm/dd/yyyy', start_date=get_model_fences()[model]['start_date'], end_date=get_model_fences()[model]['end_date'], start_view=0, classes='endDate', attributes='onchange=oc_sten_dt("endDate%s");' % differentiator) plot_button = Button(display_text='Plot', name=controller, style='', icon='', href='', submit=False, disabled=False, attributes='onclick=createPlot(this.name);', classes='btn-plot') return [start_date, end_date, plot_button]
def add_dam(request): """ Controller for the Add Dam page. """ # Define form gizmos name_input = TextInput(display_text='Name', name='name') owner_input = SelectInput(display_text='Owner', name='owner', multiple=False, options=[('Reclamation', 'Reclamation'), ('Army Corp', 'Army Corp'), ('Other', 'Other')], initial=['Reclamation']) river_input = TextInput(display_text='River', name='river', placeholder='e.g.: Mississippi River') date_built = DatePicker(name='date-built', display_text='Date Built', autoclose=True, format='MM d, yyyy', start_view='decade', today_button=True, initial='February 15, 2017') add_button = Button(display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-dam-form'}, submit=True) cancel_button = Button(display_text='Cancel', name='cancel-button', href=reverse('dam_inventory:home')) context = { 'name_input': name_input, 'owner_input': owner_input, 'river_input': river_input, 'date_built_input': date_built, 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'dam_inventory/add_dam.html', context)
def mapview(request): """ map view page for my app """ toggle_switch_DEM = ToggleSwitch(display_text='Utah DEM', name='DEM_toggle', on_label='Yes', off_label='No', on_style='success', off_style='danger', initial=True, size='large') toggle_switch_road = ToggleSwitch(display_text='Roads', name='road_toggle', on_label='Yes', off_label='No', on_style='success', off_style='danger', initial=True, size='large') date_picker = DatePicker(name='date1', display_text='Prediction Date', autoclose=True, format='MM d, yyyy', start_date='3/6/2018', start_view='month', today_button=True, initial='March 6, 2018') distance_slider = RangeSlider(display_text='Distance of Interest (km)', name='distance_slider', min=0, max=50, initial=25, step=5) context = { 'toggle_switch_DEM': toggle_switch_DEM, 'toggle_switch_road': toggle_switch_road, 'date_picker': date_picker, 'distance_slider': distance_slider } return render(request, 'jacobmapapp/mapview.html', context)
def mapview(request): """ Controller for the app map page. """ time_slider = RangeSlider(display_text='Time of Day', name='time_slider', min=0, max=24, initial=12, step=1 ) adjust_slider = RangeSlider(display_text='Air Quality Adjustment', name='slider2', min=-5, max=5, initial=0, step=0.5, ) search_input = TextInput(display_text='Location Search', name = 'search_input', icon_append = 'glyphicon glyphicon-search', ) date_picker = DatePicker(name='date_picker', display_text='Date', autoclose=True, format='MM d, yyyy', start_date='03/05/18', start_view='decade', today_button=True, initial='March 5, 2018' ) context = { 'time_slider': time_slider, 'adjust_slider': adjust_slider, 'search_input': search_input, 'date_picker': date_picker, } return render(request, 'mapapp_gibbons/mapview.html', context)
def create_map_date_ctrls(model): """ Function that creates and return the "select_date", "select_hour", and "Display map" elements """ select_date = DatePicker( display_text=False, name='plot_date', autoclose=True, format='mm/dd/yyyy', start_date=get_model_fences()[model]['start_date'], end_date=get_model_fences()[model]['end_date'], start_view=0, attributes='onchange=oc_map_dt();', classes='') select_hour = SelectInput(display_text='', name='plot_hour', multiple=False, original=True, options=[('00:00', '00'), ('01:00', '01'), ('02:00', '02'), ('03:00', '03'), ('04:00', '04'), ('05:00', '05'), ('06:00', '06'), ('07:00', '07'), ('08:00', '08'), ('09:00', '09'), ('10:00', '10'), ('11:00', '11'), ('12:00', '12'), ('13:00', '13'), ('14:00', '14'), ('15:00', '15'), ('16:00', '16'), ('17:00', '17'), ('18:00', '18'), ('19:00', '19'), ('20:00', '20'), ('21:00', '21'), ('22:00', '22'), ('23:00', '23')], initial=['00:00'], attributes='onchange=oc_map_dt();', classes='') return [select_date, select_hour]
def add_dam(request): """ Controller for the Add Dam page. """ # Default Values name = '' owner = 'Reclamation' river = '' date_built = '' location = '' # Errors name_error = '' owner_error = '' river_error = '' date_error = '' location_error = '' # Handle form submission if request.POST and 'add-button' in request.POST: # Get values has_errors = False name = request.POST.get('name', None) owner = request.POST.get('owner', None) river = request.POST.get('river', None) date_built = request.POST.get('date-built', None) location = request.POST.get('geometry', None) # Validate if not name: has_errors = True name_error = 'Name is required.' if not owner: has_errors = True owner_error = 'Owner is required.' if not river: has_errors = True river_error = 'River is required.' if not date_built: has_errors = True date_error = 'Date Built is required.' if not location: has_errors = True location_error = 'Location is required.' if not has_errors: # Get value of max_dams custom setting max_dams = app.get_custom_setting('max_dams') # Query database for count of dams Session = app.get_persistent_store_database('primary_db', as_sessionmaker=True) session = Session() num_dams = session.query(Dam).count() user_id = request.user.id # Only add the dam if custom setting doesn't exist or we have not exceed max_dams if not max_dams or num_dams < max_dams: add_new_dam(location=location, name=name, owner=owner, river=river, date_built=date_built, user_id=user_id) else: messages.warning( request, 'Unable to add dam "{0}", because the inventory is full.'. format(name)) new_num_dams = session.query(Dam).count() if new_num_dams > num_dams: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("notifications", { "type": "dam_notifications", "message": "New Dam" }) return redirect(reverse('dam_inventory:home')) messages.error(request, "Please fix errors.") # Define form gizmos name_input = TextInput(display_text='Name', name='name', initial=name, error=name_error) owner_input = SelectInput(display_text='Owner', name='owner', multiple=False, options=[('Reclamation', 'Reclamation'), ('Army Corp', 'Army Corp'), ('Other', 'Other')], initial=owner, error=owner_error) river_input = TextInput(display_text='River', name='river', placeholder='e.g.: Mississippi River', initial=river, error=river_error) date_built = DatePicker(name='date-built', display_text='Date Built', autoclose=True, format='MM d, yyyy', start_view='decade', today_button=True, initial=date_built, error=date_error) initial_view = MVView(projection='EPSG:4326', center=[-98.6, 39.8], zoom=3.5) drawing_options = MVDraw(controls=['Modify', 'Delete', 'Move', 'Point'], initial='Point', output_format='GeoJSON', point_color='#FF0000') location_input = MapView(height='300px', width='100%', basemap='OpenStreetMap', draw=drawing_options, view=initial_view) add_button = Button(display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-dam-form'}, submit=True) cancel_button = Button(display_text='Cancel', name='cancel-button', href=reverse('dam_inventory:home')) context = { 'name_input': name_input, 'owner_input': owner_input, 'river_input': river_input, 'date_built_input': date_built, 'location_input': location_input, 'location_error': location_error, 'add_button': add_button, 'cancel_button': cancel_button, 'can_add_dams': has_permission(request, 'add_dams') } return render(request, 'dam_inventory/add_dam.html', context)
def New_Data(request, app_workspace): """ Controller for New Data page. """ # Default Values sampleid = '' river = '' datecol = '' timecol = '' note = '' pH = '' temper = '' cond = '' ca = '' mg = '' na = '' k = '' hco = '' cl = '' so = '' sio = '' loaction = '' # Errors sampleid_error = '' datecol_error = '' location_error = '' # Handle form submission if request.POST and 'add-button' in request.POST: # Get values has_errors = False sampleid = request.POST.get('sampleid', None) river = request.POST.get('river', None) datecol = request.POST.get('datecol', None) timecol = request.POST.get('timecol', None) note = request.POST.get('note', None) pH = request.POST.get('pH', None) temper = request.POST.get('temper', None) cond = request.POST.get('cond', None) ca = request.POST.get('ca', None) mg = request.POST.get('mg', None) na = request.POST.get('na', None) k = request.POST.get('k', None) hco = request.POST.get('hco', None) cl = request.POST.get('cl', None) so = request.POST.get('so', None) sio = request.POST.get('sio', None) location = request.POST.get('geometry', None) #validate if not sampleid: has_errors = True sampleid_error = 'Sample ID is required' if not datecol: has_errors = True datecol_error = 'Date Collected is Required' if not location: has_errors = True location_error = 'Location is required' if not has_errors: #Do Stuff here add_new_data(db_directory=app_workspace.path, location=location, sampleid=sampleid, river=river, datecol=datecol, timecol=timecol, note=note, pH=pH, temper=temper, cond=cond, ca=ca, mg=mg, na=na, k=k, hco=hco, cl=cl, so=so, sio=sio) return redirect(reverse('waimea_flux:home')) messages.error(request, "Please fix errors.") # Define form gizmos sampleid_input = TextInput(display_text='Sample ID', name='sampleid', initial=sampleid, error=sampleid_error) river_input = TextInput(display_text='River', name='river', placeholder='e.g.: Waimea River') datecol_input = DatePicker(name='datecol', display_text='Date Collected', autoclose=True, format='MM d, yyyy', start_view='decade', today_button=True, initial=datecol, error=datecol_error) timecol_input = TextInput(display_text='Time of Sample Collection', name='timecol') note_input = TextInput(display_text='Any Notes?', name='note') pH_input = TextInput(display_text='pH', name='pH') temper_input = TextInput(display_text='Temperature (C)', name='temper') cond_input = TextInput(display_text='Conductivity (microsiemens/cm)', name='cond') ca_input = TextInput(display_text='Ca2+ (mg/L)', name='ca') mg_input = TextInput(display_text='Mg2+ (mg/L)', name='mg') na_input = TextInput(display_text='Na+ (mg/L)', name='na') k_input = TextInput(display_text='K+ (mg/L)', name='k') hco_input = TextInput(display_text='HCO3- (mg/L)', name='hco') cl_input = TextInput(display_text='Cl- (mg/L)', name='cl') so_input = TextInput(display_text='SO42- (mg/L)', name='so') sio_input = TextInput(display_text='SiO2 (mg/L)', name='sio') initial_view = MVView(projection='EPSG:4326', center=[-159.5, 22.07], zoom=10) drawing_options = MVDraw(controls=['Modify', 'Delete', 'Move', 'Point'], initial='Point', output_format='GeoJSON', point_color='#FF0000') location_input = MapView(height='300px', width='100%', basemap='OpenStreetMap', draw=drawing_options, view=initial_view) add_button = Button(display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-sample-form'}, submit=True) cancel_button = Button(display_text='Cancel', name='cancel-button', href=reverse('waimea_flux:home')) context = { 'sampleid_input': sampleid_input, 'river_input': river_input, 'datecol_input': datecol_input, 'timecol_input': timecol_input, 'note_input': note_input, 'pH_input': pH_input, 'temper_input': temper_input, 'cond_input': cond_input, 'ca_input': ca_input, 'mg_input': mg_input, 'na_input': na_input, 'k_input': k_input, 'hco_input': hco_input, 'cl_input': cl_input, 'so_input': so_input, 'sio_input': sio_input, 'location_input': location_input, 'location_error': location_error, 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'waimea_flux/New_Data.html', context)
def home(request): """ Controller for the app home page. """ default_platform = 'modis' default_sensors = EE_PRODUCTS[default_platform] first_sensor_key = next(iter(default_sensors.keys())) default_products = default_sensors[first_sensor_key] first_product_key = next(iter(default_products.keys())) first_product = default_products[first_product_key] # Build initial platform control platform_select = SelectInput(name='platform', display_text='Satellite Platform', options=(('MODIS', 'modis'), ('Sentinel', 'sentinel'), ('Landsat', 'landsat'))) # Build initial sensor control sensor_options = [] for sensor in default_sensors: sensor_options.append((sensor.upper(), sensor)) sensor_select = SelectInput(name='sensor', display_text='Sensor', options=sensor_options) # Build initial product control product_options = [] for product, info in default_products.items(): product_options.append((info['display'], product)) product_select = SelectInput(name='product', display_text='Product', options=product_options) # Hardcode initial end date to today (since all of our datasets extend to present) today = dt.datetime.today() initial_end_date = today.strftime('%Y-%m-%d') # Initial start date will a set number of days before the end date # NOTE: This assumes the start date of the dataset is at least 30+ days prior to today initial_end_date_dt = dt.datetime.strptime(initial_end_date, '%Y-%m-%d') initial_start_date_dt = initial_end_date_dt - dt.timedelta(days=30) initial_start_date = initial_start_date_dt.strftime('%Y-%m-%d') # Build date controls first_product_start_date = first_product.get('start_date', None) first_product_end_date = first_product.get('end_date', None) or initial_end_date start_date = DatePicker(name='start_date', display_text='Start Date', format='yyyy-mm-dd', start_view='decade', today_button=True, today_highlight=True, start_date=first_product_start_date, end_date=first_product_end_date, initial=initial_start_date, autoclose=True) end_date = DatePicker(name='end_date', display_text='End Date', format='yyyy-mm-dd', start_view='decade', today_button=True, today_highlight=True, start_date=first_product_start_date, end_date=first_product_end_date, initial=initial_end_date, autoclose=True) # Build reducer method control reducer_select = SelectInput(name='reducer', display_text='Reduction Method', options=( ('Median', 'median'), ('Mosaic', 'mosaic'), ('Mode', 'mode'), ('Mean', 'mean'), ('Minimum', 'min'), ('Maximum', 'max'), ('Sum', 'sum'), ('Count', 'count'), ('Product', 'product'), )) # Build Buttons load_button = Button(name='load_map', display_text='Load', style='default', attributes={'id': 'load_map'}) clear_button = Button(name='clear_map', display_text='Clear', style='default', attributes={'id': 'clear_map'}) plot_button = Button(name='load_plot', display_text='Plot AOI', style='default', attributes={'id': 'load_plot'}) map_view = MapView(height='100%', width='100%', controls=[ 'ZoomSlider', 'Rotate', 'FullScreen', { 'ZoomToExtent': { 'projection': 'EPSG:4326', 'extent': [29.25, -4.75, 46.25, 5.2] } } ], basemap=[ 'CartoDB', { 'CartoDB': { 'style': 'dark' } }, 'OpenStreetMap', 'Stamen', 'ESRI' ], view=MVView(projection='EPSG:4326', center=[37.880859, 0.219726], zoom=7, maxZoom=18, minZoom=2), draw=MVDraw(controls=[ 'Pan', 'Modify', 'Delete', 'Move', 'Point', 'Polygon', 'Box' ], initial='Pan', output_format='GeoJSON')) context = { 'platform_select': platform_select, 'sensor_select': sensor_select, 'product_select': product_select, 'start_date': start_date, 'end_date': end_date, 'reducer_select': reducer_select, 'load_button': load_button, 'clear_button': clear_button, 'plot_button': plot_button, 'ee_products': EE_PRODUCTS, 'map_view': map_view } return render(request, 'earth_engine/home.html', context)
def add_dam(request, app_workspace): """ Controller for the Add Dam page. """ # Default values name = '' owner = 'Reclamation' river = '' date_built = '' location = '' # Errors name_error = '' owner_error = '' river_error = '' date_error = '' location_error = '' # Handle form submission if request.POST and 'add-button' in request.POST: # Get values has_errors = False name = request.POST.get('name', None) owner = request.POST.get('owner', None) river = request.POST.get('river', None) date_built = request.POST.get('date-built', None) location = request.POST.get('geometry', None) # Validate if not name: has_errors = True name_error = 'Name is required.' if not owner: has_errors = True owner_error = 'Owner is required.' if not river: has_errors = True river_error = 'River is required.' if not date_built: has_errors = True date_error = 'Date Built is required.' if not location: has_errors = True location_error = 'Location is required.' if not has_errors: add_new_dam(db_directory=app_workspace.path, name=name, owner=owner, river=river, date_built=date_built, location=location) return redirect(reverse('dam_inventory:home')) messages.error(request, "Please fix errors.") # Define form gizmos name_input = TextInput(display_text='Name', name='name', initial=name, error=name_error) owner_input = SelectInput(display_text='Owner', name='owner', multiple=False, options=[('Reclamation', 'Reclamation'), ('Army Corp', 'Army Corp'), ('Other', 'Other')], initial=owner, error=owner_error) river_input = TextInput(display_text='River', name='river', placeholder='e.g.: Mississippi River', initial=river, error=river_error) date_built = DatePicker(display_text='Date Built', name='date-built', autoclose=True, format='MM d, yyyy', start_view='decade', today_button=True, initial=date_built, error=date_error) initial_view = MVView(projection='EPSG:4326', center=[-98.6, 39.8], zoom=3.5) drawing_options = MVDraw(controls=['Modify', 'Delete', 'Move', 'Point'], initial='Point', output_format='GeoJSON', point_color='#FF0000') location_input = MapView(height='300px', width='100%', basemap='OpenStreetMap', draw=drawing_options, view=initial_view) add_button = Button(display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-dam-form'}, submit=True) cancel_button = Button(display_text='Cancel', name='cancel-button', href=reverse('dam_inventory:home')) context = { 'name_input': name_input, 'owner_input': owner_input, 'river_input': river_input, 'date_built_input': date_built, 'location_input': location_input, 'location_error': location_error, 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'dam_inventory/add_dam.html', context)
def home(request): """ Controller for the app home page. """ sensor_selection = SelectInput( # display_text='Select precipitation product:', name='sensor_selection', multiple=False, options=[('Landsat 8', 'lc8'), ('Sentinel-2', 's2')], initial=['Landsat 8'], select2_options={'placeholder': 'Select a sensor', 'allowClear': False} ) product_selection = SelectInput( # display_text='Select precipitation product:', name='product_selection', multiple=False, options=[('Rrs', 'rrs'), ('Secchi Depth', 'sd'), ('Trophic State Index', 'tsi'), ('Chlorophyll-a', 'chla')], initial=['Rrs'], select2_options={'placeholder': 'Select a product', 'allowClear': False} ) download_button = Button( display_text='Download Region', name='download-button', icon='glyphicon glyphicon-cloud-download', style='primary', ) timeseries_button = Button( display_text='Get Time Series', name='timeseries-button', icon='glyphicon glyphicon-signal', style='success', ) time_start = DatePicker( name='time_start', # display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, initial='2015-08-01' ) time_end = DatePicker( name='time_end', # display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, initial='2015-09-01' ) # result = myProcess(time_start['initial'],time_end['initial']).getChlMap() # # mapid,token = str(result['mapid']),str(result['token']) # print(mapid,token) # chla_layer = tile_url_template.format(**map_id) context = { # 'chla_mapid': mapid, # 'chla_token': token, 'sensor_selection':sensor_selection, 'product_selection': product_selection, 'download_button': download_button, 'timeseries_button': timeseries_button, 'time_start': time_start, 'time_end': time_end, } return render(request, 'wq_viewer/home.html', context)
def add_data(request,event_id=1,site_number = 'no',start_date = 'no',end_date='no',concentration_parameter = 'no',fc = '0.996', PKThreshold = 'no' ,ReRa = '0.1', MINDUR = '0', BSLOPE = '0.0001',ESLOPE = '0.4',SC = '4',dyslp = '0.001',segment_button_disable=True, download_button_disable=True,select_input = 'CUAHSI',network = 'NWISUV',visualize_button_disable = True): """ Controller for the Add Data page. """ #link to use on base page template html #href="/apps/heda/data/add/1/01362500/2019-06-04/2019-06-26/63680/0.996/0.03/0.1/0/0.0001/0.001/4/0.001/1/1/USGS/NWISUV/True/" #default blank values if site_number == 'no': site_number = '' if concentration_parameter == 'no': concentration_parameter = '' if start_date == 'no': start_date = '' if end_date == 'no': end_date = '' if PKThreshold == 'no': PKThreshold = '' # Default Values #site_number = '01646500' #site_number = '01362500' #start_date = '' #end_date ='' if segment_button_disable =='False': segment_button_disable = False else: segment_button_disable = True if visualize_button_disable == 'False': visualize_button_disable = False else: visualize_button_disable = True if download_button_disable == 'False': download_button_disable = False else: download_button_disable=True if event_id == 1 or event_id == '1': segment_button_disable= True download_button_disable=True # Errors site_number_error = '' start_date_error = '' end_date_error = '' PKThreshold_error ='' fc_error = '' hydrograph_file_error = '' concentration_number_error = '' hydrograph_file = None hydrograph_plot = create_hydrograph(event_id) # Case where the form has been submitted if request.POST and 'upload-button' in request.POST: # Get Values has_errors = False # Get File if request.FILES and 'hydrograph-file' in request.FILES: # Get a list of the files hydrograph_file = request.FILES.getlist('hydrograph-file') if not hydrograph_file: has_errors = True hydrograph_file_error = 'Hydrograph File is Required.' if not has_errors: # Process file here success = upload_trajectory(hydrograph_file[0]) #print('trajectory function returned with event id as : '+str(success)) # Provide feedback to user if success: messages.info(request, 'Successfully uploaded trajectory.') download_button_disable = False segment_button_disable = False visualize_button_disable = False event_id = str(success) else: messages.info(request, 'Unable to upload trajectory. Please try again or check file format.') if site_number =='': site_number ='no' if PKThreshold == '': PKThreshold ='no' if start_date == '': start_date = 'no' if end_date == '': end_date = 'no' if concentration_parameter =='': concentration_parameter = 'no' return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable),"select_input":select_input,"network":network,"visualize_button_disable" : str(visualize_button_disable)})) #return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable),"select_input":select_input})) #return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable)})) messages.error(request, "Please fix errors.") if request.POST and 'segment-button' in request.POST: # Get values has_errors = False fc = request.POST.get('fc',None) PKThreshold = request.POST.get('PKThreshold',None) ReRa = request.POST.get('ReRa',None) BSLOPE = request.POST.get('BSLOPE',None) ESLOPE = request.POST.get('ESLOPE',None) SC = request.POST.get('SC',None) MINDUR = request.POST.get('MINDUR',None) dyslp = request.POST.get('dyslp',None) # Validate if not PKThreshold: has_errors = True PKThreshold_error = 'PKThreshold 1 is required.' if not fc: has_errors = True fc_error = 'FC required.' if not has_errors: status = segmentation(event_id,float(fc),float(PKThreshold),float(ReRa),float(BSLOPE),float(ESLOPE),float(SC),float(MINDUR),float(dyslp)) if not status: messages.error(request, "Segmentation failed. Please retrieve data again and try or change parameters.") hydrograph_plot = create_hydrograph(event_id) else: segment_button_disable = False download_button_disable = False visualize_button_disable = False if site_number =='': site_number ='no' if PKThreshold == '': PKThreshold ='no' if start_date == '': start_date = 'no' if end_date == '': end_date = 'no' if concentration_parameter =='': concentration_parameter = 'no' return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable),"select_input":select_input,"network":network,"visualize_button_disable" : str(visualize_button_disable)})) #return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable)})) #hydrograph_plot = create_hydrograph(event_id) else: messages.error(request, "Please fix errors.") if request.POST and 'retrieve-button' in request.POST: # Get values has_errors = False site_number = request.POST.get('site-number', None) start_date = request.POST.get('start-date', None) end_date = request.POST.get('end-date', None) concentration_parameter = request.POST.get('concentration-parameter',None) select_input = request.POST.get('select-input',None) network = request.POST.get('network',None) # Validate if not site_number: has_errors = True site_number_error = 'Site Number is required.' if not start_date: has_errors = True start_date_error = 'Start date is required.' if not end_date: has_errors = True end_date_error = 'End date is required.' if not concentration_parameter: has_errors = True concentration_parameter = 'Concentration parameter is required' if not has_errors: #segmentation parameters event_id = add_new_data(sites=site_number, start=start_date,end = end_date, concentration = concentration_parameter,source = select_input, network =network ) #hydrograph_plot =create_hydrograph(event_id) if not event_id: messages.error(request, "Unable to retrieve data please check parameters or try again after a few minutes.") segment_button_disable = True #print('event not added') else: #print('Event '+str(event_id) +' added') segment_button_disable = False download_button_disable = False visualize_button_disable = True if site_number =='': site_number ='no' if PKThreshold == '': PKThreshold ='no' if start_date == '': start_date = 'no' if end_date == '': end_date = 'no' if concentration_parameter =='': concentration_parameter = 'no' return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable),"select_input":select_input,"network":network,"visualize_button_disable" : str(visualize_button_disable)})) else: messages.error(request, "Please fix errors.") if request.POST and 'download-button' in request.POST: # Get Values has_errors = False select_input = request.POST.get('select-input',None) if not has_errors: # Process file here success = download_file(event_id) #print('download file returned : '+str(success)) # Provide feedback to user if success: filename = success fname = 'HEDA_download' content = FileWrapper(open(filename)) response = HttpResponse(content, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % fname return response else: messages.info(request, 'Unable to download data file.') if site_number =='': site_number ='no' if PKThreshold == '': PKThreshold ='no' if start_date == '': start_date = 'no' if end_date == '': end_date = 'no' if concentration_parameter =='': concentration_parameter = 'no' return redirect(reverse('heda:add_data', kwargs={"event_id": event_id,"site_number":site_number,"start_date":start_date,"end_date":end_date,"concentration_parameter":concentration_parameter,"fc":fc, "PKThreshold": PKThreshold , "ReRa": ReRa, "MINDUR":MINDUR,"BSLOPE":BSLOPE,"ESLOPE":ESLOPE,"SC":SC,"dyslp":dyslp,"segment_button_disable":str(segment_button_disable),"download_button_disable":str(download_button_disable),"select_input":select_input,"network":network,"visualize_button_disable" : str(visualize_button_disable)})) messages.error(request, "Unknown problem.") # Define form gizmos select_input = SelectInput(display_text='Source', name='select-input', multiple=False, original=True, options=[('USGS', 'USGS'), ('CUAHSI', 'CUAHSI')], initial=['USGS'], attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Choose USGS NWIS or CUAHSI-HIS'}) network_input = TextInput( display_text='Network (*only-CUAHSI)', name='network', initial=network, placeholder='e.g.: NWISUV', error=site_number_error, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Enter the CUAHSI data source provider/network ID'}, ) site_number_input = TextInput( display_text='Site Number', name='site-number', initial=site_number, placeholder='e.g.: 01362500', error=site_number_error, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'USGS or CUAHSI HIS Site Number'}, ) # Define form gizmos concentration_parameter_input = TextInput( display_text='Concentration code', name='concentration-parameter', placeholder='e.g.: 63680', initial=concentration_parameter, error=concentration_number_error, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Enter the USGS or CUAHSI paramater id for concentration value of interest'} ) start_date_input = DatePicker( name='start-date', display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, error=start_date_error, initial = start_date, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Choose starting date'} ) end_date_input = DatePicker( name='end-date', display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, error=end_date_error, initial = end_date, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Choose ending data. Recommended not to be more than a year from starting date.'} ) dyslp_input = TextInput( display_text='dyslp', name='dyslp', initial=dyslp, placeholder='e.g.: 0.001', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Dynamic slope threshold. Used to cut the flat head and end of the runoff event. Default is 0.001.'} ) MINDUR_input = TextInput( display_text='Minimum Duration', name='MINDUR', initial=MINDUR, placeholder='e.g.: 0', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Enter the minimum duration that a single event can be. Default is zero to not have a set minimum.'} ) SC_input = TextInput( display_text='Smoothing Coefficient', name='SC', initial=SC, placeholder='e.g.: 4', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Smoothing coefficient determine how many filtering passes will apply on stormflow. More passes result smoother hydrograph. Default is 4'} ) ESLOPE_input = TextInput( display_text='ESlope', name='ESLOPE', initial=ESLOPE, placeholder='e.g.: 0.0001', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Ending slope threshold. Used to cut flat head and end of the runoff event. Default is 0.0001.'} ) BSLOPE_input = TextInput( display_text='BSlope', name='BSLOPE', initial=BSLOPE, placeholder='e.g.: 0.001', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Beginning slope threshold. Used to cut flat head and end of the runoff event. Default is 0.001.'} ) ReRa_input = TextInput( display_text='Return Ratio Threshold', name='ReRa', initial=ReRa, placeholder='e.g.: 0.1', disabled=segment_button_disable, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Return ratio threshold for tolerance of ending stormflow being different from event start. Default is 0.10 (10%). Higher values (0.2-0.3) results in less multi-peaked events. Lower values (e.g. 0.05) results in more longer, multi-peaked events'} ) PKThreshold_input = TextInput( display_text='Peak Threshold', name='PKThreshold', initial=PKThreshold, placeholder='e.g.: 10', disabled=segment_button_disable, error = PKThreshold_error, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Peak threshold for detecting and event. Minimum rise above baseflow for an event to be detected. Entered in units of streamflow being analyzed (e.g. cfs for USGS)'} ) fc_input = TextInput( display_text='Filter Coefficient', name='fc', initial=fc, placeholder='e.g.: 0.996', disabled=segment_button_disable, error = fc_error, attributes={'data-toggle':'tooltip', 'data-placement':'top', 'title':'Baseflow extraction filter coefficient. Detault is 0.995. Lower coefficient values (e.g., 0.990) results in baseflow tracking streamflow more closely. Higher values (e.g., 0.999) results in more muted baseflow.'} ) def loading(): messages.success(request, 'loading.') return 0 retrieve_button = Button( display_text='Retrieve', name='retrieve-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-data-form','onclick':"loading()"}, submit=True ) segment_button = Button( display_text='Segment', name='segment-button', icon='glyphicon glyphicon-scissors', style='success', attributes={'form': 'segment-data-form'}, #href=reverse('heda:add_data', kwargs={"event_id": event_id}), #disabled=segment_button_disable, submit=True ) cancel_button = Button( display_text='Cancel', name='cancel-button', href=reverse('heda:home') ) visualize_button = Button( display_text='Visualize Events', name='visualize-button', icon='glyphicon glyphicon-picture', href=reverse('heda:visualize_events', kwargs={"event_id": event_id,"sub_event": 0}), style='success', disabled=visualize_button_disable, #submit=True ) download_button = Button( display_text='Download', name='download-button', disabled = download_button_disable, submit=True, icon='glyphicon glyphicon-download', style='success', attributes={'form': 'segment-data-form'}, ) upload_button = Button( display_text='Upload', name='upload-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'upload-data-form'}, submit=True ) context = { 'retrieve_button': retrieve_button, 'cancel_button': cancel_button, 'visualize_button':visualize_button, 'site_number_input': site_number_input, 'start_date_input':start_date_input, 'end_date_input':end_date_input, 'hydrograph_plot':hydrograph_plot, 'segment_button':segment_button, 'fc_input': fc_input, 'PKThreshold_input': PKThreshold_input, 'ReRa_input':ReRa_input, 'BSLOPE_input':BSLOPE_input, 'ESLOPE_input':ESLOPE_input, 'SC_input':SC_input, 'MINDUR_input':MINDUR_input, 'dyslp_input':dyslp_input, 'download_button':download_button, 'upload_button': upload_button, 'hydrograph_file_error': hydrograph_file_error, 'concentration_parameter_input':concentration_parameter_input, 'select_input': select_input, 'network_input': network_input, } return render(request, 'heda/add_data.html', context)
def mapviewer(request): """ Controller for the app home page. """ # today = datetime.datetime.now() # thisdate = today-datetime.timedelta(2) # isodate = thisdate.strftime('%Y-%m-%d') initial_date = '2015-08-11' if request.method == 'GET': info = request.GET start_date = info.get('sDate') if not start_date: start_date = initial_date sensor = info.get('sensor_txt') if not sensor: sensor = 'viirs' else: print('no request') precip_layer1 = geeutils.getPrecipMap(initial_date, accumulation=1) historical_layer = geeutils.getHistoricalMap(REGION, '2010', '2015', '01', '01', climatology=False, algorithm='JRC') flood_layer = geeutils.getfloodMap('sentinel1', start_date) date_selection = DatePicker( name='date_selection', # display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, initial=initial_date) update_button = Button(display_text='Update Historic Layer', name='update-button', icon='glyphicon glyphicon-refresh', style='primary', classes="btn_custom") method_historical_selection = SelectInput( name='method_historical_selection', multiple=False, options=[('Continuous', 'continuous'), ('Seasonal', 'discrete')], initial=['Continuous'], select2_options={ 'placeholder': 'Select a mothod', 'allowClear': False }) start_month_selection_historical = DatePicker( name='start_month_selection_historical', format='mm', autoclose=True, #startDate= new Date('1984'), #endDate: new Date('2015'), clear_button=True, start_view='months', min_view_mode='months', initial='01') end_month_selection_historical = DatePicker( name='end_month_selection_historical', format='mm', autoclose=True, #startDate= new Date('1984'), #endDate: new Date('2015'), clear_button=True, start_view='months', min_view_mode='months', initial='02') start_year_selection_historical = DatePicker( name='start_year_selection_historical', format='yyyy', autoclose=True, #start_date= '1/1/2015', #end_date = '1/1/2016', clear_button=True, start_view='years', min_view_mode='years', initial='2010') end_year_selection_historical = DatePicker( name='end_year_selection_historical', format='yyyy', autoclose=True, #start_date= new Date('2010'), #endDate: new Date('2015'), clear_button=True, start_view='years', min_view_mode='years', initial='2015') product_selection = SelectInput( # display_text='Select precipitation product:', name='product_selection', multiple=False, options=[('1 Day Accumulation', '1|0'), ('3 Day Accumulation', '3|0'), ('7 Day Accumulation', '7|0')], initial=['1 Day Accumulation'], select2_options={ 'placeholder': 'Select a product', 'allowClear': False }) cmap_selection = SelectInput( # display_text='Select precipitation product:', name='cmap_selection', multiple=False, options=[('nipy_spectral', 'nipy_spectral'), ('gist_ncar', 'gist_ncar'), ('cubehelix', 'cubehelix')], initial=['nipy_spectral'], select2_options={ 'placeholder': 'Select a product', 'allowClear': False }) browse_selection = SelectInput( # display_text='Select precipitation product:', name='browse_selection', multiple=False, options=[('VIIRS NRT TRUE COLOR', '1|VIIRS_SNPP_CorrectedReflectance_TrueColor'), ('VIIRS NRT NATURAL COLOR', '2|VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1'), ('MODIS AQUA TRUE COLOR', '3|MODIS_Aqua_CorrectedReflectance_TrueColor'), ('MODIS AQUA NATURAL COLOR', '4|MODIS_Aqua_CorrectedReflectance_Bands721'), ('MODIS TERRA TRUE COLOR', '5|MODIS_Terra_CorrectedReflectance_TrueColor'), ('MODIS TERRA NATURAL COLOR', '5|MODIS_Terra_CorrectedReflectance_Bands721')], initial=['VIIRS NRT NATURAL COLOR'], select2_options={ 'placeholder': 'Select browse imagery:', 'allowClear': False }) sensor_selection = SelectInput( # display_text='Select precipitation product:', name='sensor_selection', multiple=False, options=[('Sentinel 1', 'sentinel1'), ('VIIRS Downscaled', 'viirs'), ('ATMS (Comming soon)', 'atms')], initial=['Sentinel 1'], select2_options={ 'placeholder': 'Select sensor:', 'allowClear': False }) context = { 'date_selection': date_selection, 'precip_layer': precip_layer1, 'historical_layer': historical_layer, 'flood_layer': flood_layer, 'admin_layer': ADMIN_LAYER, 'product_selection': product_selection, 'cmap_selection': cmap_selection, 'browse_selection': browse_selection, 'sensor_selection': sensor_selection, 'start_month_selection_historical': start_month_selection_historical, 'start_year_selection_historical': start_year_selection_historical, 'end_month_selection_historical': end_month_selection_historical, 'end_year_selection_historical': end_year_selection_historical, 'method_historical_selection': method_historical_selection, 'update_button': update_button } return render(request, 'hydraviewer/map.html', context)
def ahps(request): """ Controller for the AHPS.html page :param request: URL request for the page, including GET information :return: Returns a rendering of the page with AHPS data available displayed """ # REFACTOR TO "This + 2" t_now = datetime.now() now_str = "{0}-{1}-{2}".format(t_now.year, check_digit(t_now.month), check_digit(t_now.day)) t_delta = timedelta(days=7) t_before = t_now - t_delta before_str = "{0}-{1}-{2}".format(t_before.year, check_digit(t_before.month), check_digit(t_before.day)) # Get values for gauge_id and waterbody gauge_id = request.GET['gaugeno'] waterbody = request.GET['waterbody'] latitude = request.GET['lat'] longitude = request.GET['long'] forecast_date = before_str forecast_date_end = now_str forecast_range_initialize = 'Analysis and Assimilation' comid_time = "06" do_forecast = request.GET.get("forecast_range", None) forecast_range = 'analysis_assim' got_comid = False comid = None failed = False # Get AHPS data using a dedicated function data = get_ahps_data( gauge_id) # data will be in a string, but is an xml document # Get Closest COMID to gauge # comid_filler = str(json.loads(urllib2.urlopen('https://ofmpub.epa.gov/waters10/PointIndexing.Service?pGeometry=POINT(' + longitude + '+' + latitude + ')').read())['output']['ary_flowlines'][0]['comid']) comid_filler = get_comid(latitude, longitude) # Convert AHPS stage and flow data to a usable string format (NOT INCLUDING METADATA) # print data python_data = convert_ahps_to_python(data) flow_data = [] flow = float() stage_data = [] stage = float() for item in python_data: flow_data.append([item[1], item[4]]) flow += item[4] stage_data.append([item[1], item[2]]) stage += item[2] # Check if AHPS flow data exists gotdata_flow = False if flow > 0: gotdata_flow = True time_series_list_api = [] # REFACTOR TO LINE 'This + 50' # URL for getting forecast data and in a list if do_forecast is not None: comid = request.GET['comid'] comid_filler = comid forecast_range = request.GET['forecast_range'] forecast_date = request.GET['forecast_date'] if comid is not None and len(comid) > 0: print 'in loop' got_comid = True if forecast_range == "short_range": print 'In Short' comid_time = request.GET['comid_time'] forecast_range_initialize = 'Short' elif forecast_range == "analysis_assim": print 'In analsis and Assim' forecast_date_end = request.GET['forecast_date_end'] forecast_range_initialize = 'Analysis and Assimilation' else: print "In Medium" forecast_range_initialize = 'Medium' print comid_time url = 'https://apps.hydroshare.org/apps/nwm-forecasts/api/GetWaterML/?config={0}&geom=channel_rt&variable=streamflow&COMID={1}&lon=&lat=&startDate={2}&endDate={3}&time={4}&lag='.format( forecast_range, comid, forecast_date, forecast_date_end, comid_time) try: url_api = urllib2.urlopen(url) data_api = url_api.read() # print data_api x = data_api.split('dateTimeUTC=') x.pop(0) for elm in x: info = elm.split(' ') time1 = info[0].replace('T', ' ') time2 = time1.replace('"', '') time3 = time2[:-3] time4 = time3.split(' ') time5 = time4[0].split('-') timedate = time5 year = int(timedate[0]) month = int(timedate[1]) day = int(timedate[2]) timetime = time4[1] time_split = timetime.split(':') time_minute = time_split[1].replace(':', '') hour = time_split[0] minute = time_minute[1] hour_int = int(hour) minute_int = int(minute) value = info[7].split('<') value1 = value[0].replace('>', '') value2 = float(value1) time_series_list_api.append( [datetime(year, month, day, hour_int, minute_int), value2]) except HTTPError: failed = True # Plot AHPS flow data timeseries_plot = TimeSeries(height='500px', width='500px', engine='highcharts', title='Streamflow Plot', y_axis_title='Flow', y_axis_units='cfs', series=[{ 'name': 'Streamflow', 'data': flow_data }, { 'name': 'Forecasted Streamflow', 'data': time_series_list_api }], colors=[ '#7cb5ec', '#b880e9', '#ecc07c', '#7cec84', '#ec7c7c', '#cf7cec', '#df2525', '#90ed7d' ]) # Check if AHPS stagedata exists gotdata_stage = False if stage > 0: gotdata_stage = True # Plot AHPS stage data timeseries_plot_stage = TimeSeries(height='500px', width='500px', engine='highcharts', title='Stage Plot', y_axis_title='Stage', y_axis_units='ft', series=[{ 'name': 'Stage', 'data': stage_data }]) comid_time += ':00' generate_graphs_button = Button(display_text='Generate New Graphs', name='generate_graphs', attributes={""}, submit=True) comid_input = TextInput(display_text='COMID', name='comid', initial=comid_filler, classes='form-control') forecast_date_picker = DatePicker(name='forecast_date', display_text='Forecast Date Start', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=forecast_date) forecast_date_end_picker = DatePicker(name='forecast_date_end', display_text='Forecast Date End', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=forecast_date_end) forecast_range_select = SelectInput(display_text='Forecast Size', name='forecast_range', multiple=False, options=[('Analysis and Assimilation', 'analysis_assim'), ('Short', 'short_range'), ('Medium', 'medium_range')], initial=forecast_range_initialize, original=True) forecast_time_select = SelectInput(display_text='Start Time', name='comid_time', multiple=False, options=[ ('00:00', "00"), ('01:00', "01"), ('02:00', "02"), ('03:00', "03"), ('04:00', "04"), ('05:00', "05"), ('06:00', "06"), ('07:00', "07"), ('08:00', "08"), ('09:00', "09"), ('10:00', "10"), ('11:00', "11"), ('12:00', "12"), ('13:00', "13"), ('14:00', "14"), ('15:00', "15"), ('16:00', "16"), ('17:00', "17"), ('18:00', "18"), ('19:00', "19"), ('20:00', "20"), ('21:00', "21"), ('22:00', "22"), ('23:00', "23") ], initial=comid_time, original=True) context = { "gaugeno": gauge_id, "waterbody": waterbody, "timeseries_plot": timeseries_plot, "gotdata_flow": gotdata_flow, "timeseries_plot_stage": timeseries_plot_stage, "gotdata_stage": gotdata_stage, "lat": latitude, "long": longitude, "generate_graphs_button": generate_graphs_button, "comid_input": comid_input, "forecast_date_picker": forecast_date_picker, "forecast_date_end_picker": forecast_date_end_picker, "forecast_range_select": forecast_range_select, "forecast_time_select": forecast_time_select, "comid": comid, "gotComid": got_comid, "forecast_failed": failed } return render(request, 'gaugeviewwml/ahps.html', context)
name='timeseries-button', icon='glyphicon glyphicon-signal', style='success', ), "map_button": Button( display_text='Get WQ Map', name='map-button', icon='glyphicon glyphicon-signal', style='info', ), "start_time": DatePicker(name='time_start', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, initial='2015-08-01', attributes={'class': 'hide'}, classes='buttontheme'), "end_time": DatePicker(name='time_end', autoclose=True, format='yyyy-mm-dd', start_view='decade', today_button=True, initial='2015-09-01', attributes={'class': 'hide'}, classes='buttontheme'), "download_button": Button( display_text='Download Region',
def home(request): """ Controller for the app home page. """ # Start the GLDAS code # Generate the dropdown options for GLDAS. See utilities.py for # gen_gldas_dropdown function gldas_dropdown = gen_gldas_dropdown() select_gldas_variable = SelectInput(display_text='Select Variable', name="select_gldas_var", multiple=False, options=gldas_dropdown) # Dropdown for selecting the GLDAS Variable # Get the GLDAS date range. See utilities.py for get_gldas_range function gldas_dates = get_gldas_range() start_date = DatePicker(name='start_date', display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=gldas_dates["start"], start_date=gldas_dates["start"], end_date=gldas_dates["end"]) # Datepicker object for selecting the GLDAS start date end_date = DatePicker(name='end_date', display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=gldas_dates["end"], start_date=gldas_dates["start"], end_date=gldas_dates["end"]) # Datepicker object for selecting the GLDAS end date # End of GLDAS code segment # Start Climate Serv code data_type_options = [["CHIRPS Precipitation", "0|CHIRPS Precipitation(mm/day)"], ["IMERG 1 Day", "26|IMERG 1 Day(1 mm/day)"], ["Seasonal Forecast", "6|Seasonal Forecast"] ] # Climate Serv Data Type Options operation_type_options = [["Max", "0|max"], ["Min", "1|min"], ["Average", "5|avg"] ] # Climate Serv Operation Type options # Climate Serv interval type options interval_type_options = [["Daily", "0"]] select_data_type = SelectInput(display_text='Select a data type', name='cs_data_type', multiple=False, options=data_type_options) # Dropdown object for the select data type select_operation_type = SelectInput(display_text='Select a operation type', name='cs_operation_type', multiple=False, options=operation_type_options) # Dropdown for select operation type select_interval_type = SelectInput(display_text='Select a date interval', name='cs_interval_type', multiple=False, options=interval_type_options) # Dropdown for select interval type select_forecast_variable = SelectInput(display_text='Select a variable', name='cs_forecast_variable', multiple=False, options=[("Precipitation", "Precipitation"), ("Temperature", "Temperature")]) # A dropdown object for selecting the forecast variable # Get the seasonal forecast range. See utilities.py. seasonal_forecast_range = get_sf_range() today = datetime.today().strftime("%m/%d/%Y") forecast_start = DatePicker(name='forecast_start', display_text='Start Date', autoclose=True, format='mm/dd/yyyy', start_view='month', today_button=True, initial="01/10/2016") # Datepicker object for Climate Serv forecast start date forecast_end = DatePicker(name='forecast_end', display_text='End Date', autoclose=True, format='mm/dd/yyyy', start_view='month', today_button=True, initial="01/20/2016") # Datepicker object for Climate Serv forecast end date seasonal_forecast_start = DatePicker(name='seasonal_forecast_start', display_text='Start Date', autoclose=True, format='mm/dd/yyyy', start_view='month', today_button=True, initial=today, start_date=seasonal_forecast_range[ "start"], end_date=seasonal_forecast_range["end"]) # Datepicker object for Climate Serv seasonal forecast start date seasonal_forecast_end = DatePicker(name='seasonal_forecast_end', display_text='End Date', autoclose=True, format='mm/dd/yyyy', start_view='month', today_button=True, initial=today, start_date=seasonal_forecast_range[ "start"], end_date=seasonal_forecast_range["end"]) # Datepicker object for Climate Serv seasonal forecast end date # End Climate Serv code block # Django context variables that will be used in home.html context = { "select_gldas_variable": select_gldas_variable, "start_date": start_date, "end_date": end_date, "select_data_type": select_data_type, "select_operation_type": select_operation_type, "select_interval_type": select_interval_type, "forecast_start": forecast_start, "forecast_end": forecast_end, "select_forecast_variable": select_forecast_variable, "seasonal_forecast_start": seasonal_forecast_start, "seasonal_forecast_end": seasonal_forecast_end} return render(request, 'hydroexplorer/home.html', context)
def details(request): # Defining the variables for site name, site code, network and hydroserver # url. site_name = request.GET.get('sitename') site_code = request.GET.get('sitecode') network = request.GET.get('network') hs_url = request.GET.get('hsurl') hidenav = request.GET.get('hidenav') error_message = None select_soap_variable = [] select_variable = [] graphs_object = {} soap_obj = {} # soap_obj json dictionary is used so that part of the important metadata can be stored as a session object soap_obj["url"] = hs_url client = Client(hs_url) # Connecting to the HydroServer via suds client.set_options(port='WaterOneFlow') site_desc = network + ":" + site_code soap_obj["site"] = site_desc soap_obj["network"] = network site_info = client.service.GetSiteInfo(site_desc) # Get site info # Encoding is necessary for making sure that this thing works for sites # with weird characters site_info = site_info.encode('utf-8') # Converting xml2dict to make it easier to parse info_dict = xmltodict.parse(site_info) # Converting the dict to a json object info_json_object = json.dumps(info_dict) info_json = json.loads(info_json_object) site_variables = [] site_object_info = info_json['sitesResponse']['site']['seriesCatalog'] # This exception was necessary as there were some sites with no data try: site_object = info_json['sitesResponse']['site']['seriesCatalog']['series'] except KeyError: error_message = "Site Details do not exist" context = {"site_name": site_name, "site_code": site_code, "service": "SOAP", "error_message": error_message} return render(request, 'hydroexplorer/error.html', context) graph_variables = [] # List for storing all avaiable variables var_json = [] # List for storing the variable metadata such as the date range for the data for that variable # Check if there are multiple variables in the selected site if type(site_object) is list: count = 0 for i in site_object: var_obj = {} # var_obj json dictionary is used so that the variable selected by the user can be retrieved as a session object count = count + 1 variable_name = i['variable']['variableName'] variable_id = i['variable']['variableCode']['@variableID'] variable_text = i['variable']['variableCode']['#text'] var_obj["variableName"] = variable_name var_obj["variableID"] = variable_id # value_type = i['variable']['valueType'] value_count = i['valueCount'] # data_type = i['variable']['dataType'] # unit_name = i['variable']['unit']['unitName'] # unit_type = i['variable']['unit']['unitType'] # unit_abbr = i['variable']['unit']['unitAbbreviation'] # unit_code = i['variable']['unit']['unitCode'] # time_support = i['variable']['timeScale']['timeSupport'] # time_support_name = i['variable']['timeScale']['unit']['unitName'] # time_support_type = i['variable']['timeScale']['unit']['unitAbbreviation'] begin_time = i["variableTimeInterval"]["beginDateTimeUTC"] begin_time = begin_time.split("T") begin_time = str(begin_time[0]) end_time = i["variableTimeInterval"]["endDateTimeUTC"] end_time = end_time.split("T") end_time = str(end_time[0]) var_obj["startDate"] = begin_time var_obj["endDate"] = end_time # print begin_time,end_time method_id = i["method"]["@methodID"] # method_desc = i["method"]["methodDescription"] # source_id = i["source"]["@sourceID"] # source_org = i["source"]["organization"] # source_desc = i["source"]["sourceDescription"] # qc_code = i["qualityControlLevel"]["qualityControlLevelCode"] # qc_id = i["qualityControlLevel"]["@qualityControlLevelID"] # qc_definition = i["qualityControlLevel"]["definition"] # print variable_name,variable_id, source_id,method_id, qc_code # Generating the string that the user sees variable_string = str( count) + '. Variable Name:' + variable_name + ',' + 'Count: ' + value_count + ',Variable ID:' + variable_id + ', Start Date:' + begin_time + ', End Date:' + end_time # value_string = variable_id,variable_text,source_id,method_id,qc_code, variable_name value_list = [variable_text, method_id] value_string = str(value_list) # Creating a list of lists. The graph variables list will be # used for generating a select variable dropdown. graph_variables.append([variable_string, value_string]) # Adding all the important variable metadata to a json object, # so that it can be retrieved later through request.session var_json.append(var_obj) else: # If there is a single variable do the following. The struture is # slightly different if there is only one variable in the site. # Thus this method is implemented var_obj = {} variable_name = site_object['variable']['variableName'] variable_id = site_object['variable'][ 'variableCode']['@variableID'] variable_text = site_object['variable']['variableCode']['#text'] value_count = site_object['valueCount'] # value_type = site_object['variable']['valueType'] # data_type = site_object['variable']['dataType'] # unit_name = site_object['variable']['unit']['unitName'] # unit_type = site_object['variable']['unit']['unitType'] # unit_abbr = site_object['variable']['unit']['unitAbbreviation'] # unit_code = site_object['variable']['unit']['unitCode'] # time_support = site_object['variable']['timeScale']['timeSupport'] # time_support_name = site_object['variable']['timeScale']['unit']['unitName'] # time_support_type = site_object['variable']['timeScale']['unit']['unitAbbreviation'] begin_time = site_object[ "variableTimeInterval"]["beginDateTimeUTC"] begin_time = begin_time.split("T") begin_time = str(begin_time[0]) end_time = site_object["variableTimeInterval"]["endDateTimeUTC"] end_time = end_time.split("T") end_time = str(end_time[0]) method_id = site_object["method"]["@methodID"] # method_desc = site_object["method"]["methodDescription"] # source_id = site_object["source"]["@sourceID"] # source_org = site_object["source"]["organization"] # source_desc = site_object["source"]["sourceDescription"] # qc_code = site_object["qualityControlLevel"]["qualityControlLevelCode"] # qc_id = site_object["qualityControlLevel"]["@qualityControlLevelID"] # qc_definition = site_object["qualityControlLevel"]["definition"] variable_string = '1. Variable Name:' + variable_name + ',' + 'Count: ' + value_count + \ ',Variable ID:' + variable_id + ', Start Date:' + \ begin_time + ', End Date:' + end_time # print variable_name, variable_id, source_id, method_id, qc_code value_list = [variable_text, method_id] value_string = str(value_list) var_obj["variableName"] = variable_name var_obj["variableID"] = variable_id var_obj["startDate"] = begin_time var_obj["endDate"] = end_time # Adding the variable metadata to a json object so that it can # retrieved using request.session var_json.append(var_obj) # Appending the solo variable to the empty list. This will be used # to generate the dropdown. graph_variables.append([variable_string, value_string]) # print site_values # values = client.service.GetSiteInfo(site_desc) # print values select_soap_variable = SelectInput(display_text='Select Variable', name="select_var", multiple=False, options=graph_variables) # Dropdown object for selecting a soap variable t_now = datetime.now() now_str = "{0}-{1}-{2}".format(t_now.year, check_digit(t_now.month), check_digit(t_now.day)) start_date = DatePicker(name='start_date', display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=now_str) # Datepicker object for selecting the start date. This simply initializes the datepicker. The actual validation is done directly through JavaScript. end_date = DatePicker(name='end_date', display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=now_str) # Datepicker object for selecting the end date. Same as above. select_variable = [] graphs_object = {} json.JSONEncoder.default = lambda self, obj: (obj.isoformat() if isinstance( obj, datetime) else None) # Encoding everything so that it can be retrieved as session object soap_obj["var_list"] = var_json # Saving the var_json as a session obj request.session['soap_obj'] = soap_obj context = {"site_name": site_name, "site_code": site_code, "network": network, "hs_url": hs_url, "hidenav": hidenav, "select_soap_variable": select_soap_variable, "select_variable": select_variable, "start_date": start_date, "end_date": end_date, "graphs_object": graphs_object, "soap_obj": soap_obj, "error_message": error_message} return render(request, 'hydroexplorer/details.html', context)
def home(request): """ Controller for the app home page. """ gage_names = [] select_gage_options_tuple = [] # This is new temp_dir = RecessionAnalyzer.get_app_workspace().path #res_ids = request.GET.getlist('WofUri') res_ids = [] res_ids.append('cuahsi-wdc-2017-04-03-30616779') res_ids.append('cuahsi-wdc-2017-04-03-30650403') res_ids.append('cuahsi-wdc-2017-04-03-30705857') for res_id in res_ids: url_zip = 'http://qa-webclient-solr.azurewebsites.net/CUAHSI/HydroClient/WaterOneFlowArchive/' + res_id + '/zip' r = requests.get(url_zip, verify=False) z = zipfile.ZipFile(io.BytesIO(r.content)) file_list = z.namelist() for file in file_list: file_data = z.read(file) file_path = temp_dir + '/id/' + res_id + '.xml' with open(file_path, 'wb') as f: f.write(file_data) gage_name = getSite(res_id) gage_names.append(gage_name) select_gage_options_tuple.append((gage_name, gage_name)) # New stuff ends here concave_initial = False nonlinear_fitting_initial = False rec_sense_initial = 1 min_length_initial = 4 antecedent_moisture_initial = 1 lag_start_initial = 0 #select_gage_options_initial = ['11476500'] select_gage_options_initial = gage_names #select_gage_options_tuple = [('11476500', '11476500'), ('11477000', '11477000')] #select_gage_options_tuple = [(getSite(res_id), getSite(res_id))] abJson = '' seriesDict = {} scatter_plot_view = [] line_plot_view = [] context = {} gage_json = '' ab_stats = buildStatTable({'stats': []}) submitted = False sites = pd.read_csv( '/usr/lib/tethys/src/tethys_apps/tethysapp/recession_analyzer/public/huc_18.tsv', sep='\t', header=30, index_col=False, skiprows=[31]) sites = sites[sites.site_tp_cd == 'ST'] names = sites.station_nm values = [str(x) for x in list(sites.site_no)] text = [num + ' ' + name[0:20] for (num, name) in zip(values, names)] gages_options_options = zip(text, values) gages_options_options_dict = dict(zip(values, text)) # "Analyze recessions" button has been pressed # this stores new set of analysis parameters # and performs recession analysis, stores data in dictionaries # creates a new dropdown box with user gages if request.POST and 'analyze' in request.POST: # PRESERVE THE PREVIOUS STATE # gages_initial = request.POST.getlist("gages_input") start_initial = request.POST['start_input'] stop_initial = request.POST['stop_input'] if 'concave_input' in request.POST: concave_initial = True else: concave_initial = False if 'nonlinear_fitting_input' in request.POST: nonlinear_fitting_initial = True else: nonlinear_fitting_initial = False rec_sense_initial = request.POST['rec_sense_input'] min_length_initial = request.POST['min_length_input'] lag_start_initial = request.POST['lag_start_input'] antecedent_moisture_initial = request.POST['antecedent_moisture_input'] ######################################## app_workspace = RecessionAnalyzer.get_user_workspace(request.user) new_file_path = os.path.join(app_workspace.path, 'current_plot.txt') pickle.dump(request.POST, open(new_file_path[:-4] + '.p', 'w')) post = pickle.load(open(new_file_path[:-4] + '.p', 'r')) submitted = True gage_json = json.dumps(gage_names) start = post['start_input'] stop = post['stop_input'] rec_sense = post['rec_sense_input'] min_length = post['min_length_input'] nonlin_fit = post.get('nonlinear_fitting_input', False) min_length = float(min_length) selectivity = float(rec_sense) * 500 sitesDict, startStopDict = recessionExtract(gage_names, res_ids, start, stop, ante=10, alph=0.90, window=3, selectivity=selectivity, minLen=min_length, option=1, nonlin_fit=nonlin_fit) abJson, abDict = createAbJson(sitesDict, gage_names) a = [] a0 = [] b = [] q = [] g = [] flow = np.array([]) time = np.array([], dtype='<U10') gage_flow = [] for gage in gage_names: a = a + abDict[gage]['a'] a0 = a0 + abDict[gage]['a0'] b = b + abDict[gage]['b'] q = q + abDict[gage]['q'] g = g + [str(gage)] * len(abDict[gage]['a']) flow2 = sitesDict[gage][gage].values flow = np.concatenate((flow, flow2), axis=0) time2 = sitesDict[gage].index.strftime('%Y-%m-%d') time = np.concatenate((time, time2), axis=0) gage_flow = gage_flow + [str(gage)] * len(sitesDict[gage][gage]) dfinfo = np.array([g, a, a0, b, q]) flow_info = np.array([gage_flow, time, flow]) df = pd.DataFrame(data=np.transpose(dfinfo), columns=['Gage', 'a', 'a0', 'b', 'q']) flow_df = pd.DataFrame(data=np.transpose(flow_info), columns=['Gage', 'Time', 'Flow rate']) new_file_path = "/usr/local/lib/tethys/src/tethys_apps/tethysapp/recession_analyzer/templates/recession_analyzer/flowdata.html" flow_df.to_html(new_file_path) newline = '{% extends "recession_analyzer/base.html" %}\n{% load tethys_gizmos %}\n{% block app_content %}' line_prepender(new_file_path, newline) newline = '{% endblock %}' line_appender(new_file_path, newline) new_file_path = "/usr/local/lib/tethys/src/tethys_apps/tethysapp/recession_analyzer/templates/recession_analyzer/dataframe.html" df.to_html(new_file_path) newline = '{% extends "recession_analyzer/base.html" %}\n{% load tethys_gizmos %}\n{% block app_content %}' line_prepender(new_file_path, newline) newline = '{% endblock %}' line_appender(new_file_path, newline) # FIXME: Throw error here if len(gage_names) == 0 for gage in gage_names: ts = sitesDict[gage] startStop = startStopDict[gage] startVec = startStop[0] endVec = startStop[1] flow = ts[gage] tsinds = ts.index series = [] series.append({ 'name': ' ', 'color': '#0066ff', 'data': zip(flow[tsinds[0]:startVec[0]].index, flow[tsinds[0]:startVec[0]]) }) series.append({ 'name': ' ', 'color': '#ff6600', 'data': zip(flow[startVec[0]:endVec[0]].index, flow[startVec[0]:endVec[0]]) }) for i in np.arange(0, len(startVec) - 1): series.append({ 'name': ' ', 'color': '#0066ff', 'data': zip(flow[endVec[i]:startVec[i + 1]].index, flow[endVec[i]:startVec[i + 1]]) }) series.append({ 'name': ' ', 'color': '#ff6600', 'data': zip(flow[startVec[i + 1]:endVec[i + 1]].index, flow[startVec[i + 1]:endVec[i + 1]]) }) series.append({ 'name': ' ', 'color': '#0066ff', 'data': zip(flow[endVec[-1]:tsinds[-1]].index, flow[endVec[-1]:tsinds[-1]]) }) seriesDict[gage] = series line_plot_view.append( buildFlowTimeSeriesPlot(series=seriesDict[gage], name=gage)) avals = ts['A0n'][ts['A0n'] > 0].values bvals = ts['Bn'][ts['Bn'] > 0].values tuplelist = zip(avals, bvals) scatter_plot_view.append( buildRecParamPlot(tuplelist=tuplelist, name=gage)) stats_dict = createStatsInfo(abJson) ab_stats = buildStatTable(stats_dict) gages_options = SelectInput( display_text='Select gage(s)', name='gages_input', multiple=True, options=gages_options_options, initial=[gages_options_options_dict[init] for init in gages_initial]) start_options = DatePicker(name='start_input', display_text='Start date', autoclose=True, format='yyyy-m-d', start_date='01/01/1910', initial=start_initial) stop_options = DatePicker(name='stop_input', display_text='Stop date', autoclose=True, format='yyyy-m-d', start_date='01/01/1910', initial=stop_initial) concave_options = ToggleSwitch(name='concave_input', size='small', initial=concave_initial, display_text='Concave recessions') nonlinear_fitting_options = ToggleSwitch(name='nonlinear_fitting_input', display_text='Nonlinear fitting', size='small', initial=nonlinear_fitting_initial) min_length_options = RangeSlider( name='min_length_input', min=4, max=10, initial=min_length_initial, step=1, attributes={"onchange": "showValue(this.value,'min_length_initial');"}) rec_sense_options = RangeSlider( name='rec_sense_input', min=0, max=1, initial=rec_sense_initial, step=0.01, attributes={"onchange": "showValue(this.value,'rec_sense_initial');"}) antecedent_moisture_options = RangeSlider( name='antecedent_moisture_input', min=0, max=1, initial=antecedent_moisture_initial, step=0.01, attributes={ "onchange": "showValue(this.value,'antecedent_moisture_initial');" }) lag_start_options = RangeSlider( name='lag_start_input', min=0, max=3, initial=lag_start_initial, step=1, attributes={"onchange": "showValue(this.value,'lag_start_initial');"}) select_gage_options = SelectInput( display_text='Select gage', name='gage_input', multiple=False, initial=select_gage_options_initial, options=select_gage_options_tuple, attributes={"onchange": "updatePlots(this.value);"}) context.update({ 'rec_sense_initial': rec_sense_initial, 'antecedent_moisture_initial': antecedent_moisture_initial, 'lag_start_initial': lag_start_initial, 'gage_json': gage_json, 'min_length_initial': min_length_initial, 'concave_options': concave_options, 'nonlinear_fitting_options': nonlinear_fitting_options, 'min_length_options': min_length_options, 'submitted': submitted, 'antecedent_moisture_options': antecedent_moisture_options, 'lag_start_options': lag_start_options, 'rec_sense_options': rec_sense_options, 'line_plot_view': line_plot_view, 'ab_stats': ab_stats, 'scatter_plot_view': scatter_plot_view, 'select_gage_options': select_gage_options, 'abJson': abJson, 'seriesDict': seriesDict, 'gages_options': gages_options, 'start_options': start_options, 'stop_options': stop_options }) return render(request, 'recession_analyzer/home.html', context)
def home(request): # Date Picker Options date_picker = DatePicker(name='date1', display_text='Date', autoclose=True, format='MM d, yyyy', start_date='2/15/2014', start_view='decade', today_button=True, initial='February 15, 2014') """ Controller for the app home page. """ save_button = Button(display_text='', name='save-button', icon='glyphicon glyphicon-floppy-disk', style='success', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Save' }) edit_button = Button(display_text='', name='edit-button', icon='glyphicon glyphicon-edit', style='warning', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Edit' }) remove_button = Button(display_text='', name='remove-button', icon='glyphicon glyphicon-remove', style='danger', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Remove' }) previous_button = Button(display_text='Previous', name='previous-button', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Previous' }) next_button = Button(display_text='Next', name='next-button', attributes={ 'data-toggle': 'tooltip', 'data-placement': 'top', 'title': 'Next' }) context = { 'save_button': save_button, 'edit_button': edit_button, 'remove_button': remove_button, 'previous_button': previous_button, 'next_button': next_button, 'date_picker': date_picker, } return render(request, 'izzatmapapp/home.html', context)
def home(request): """ Controller for the app home page. """ # Define initial view for Map View view_options = MVView(projection='EPSG:4326', center=[-100, 40], zoom=3.5, maxZoom=18, minZoom=2) # Configure the map map_options = MapView(height='350px', width='100%', view=view_options, legend=False) # Pre-populate lat-picker and lon_picker from model select_basemap = SelectInput( display_text='Basemap', name='select_basemap', multiple=False, options=[('Bing', 'bing_layer'), ('OpenStreet', 'openstreet_layer')], original=['Bing'], attributes="id=select_basemap onchange=run_select_basemap()") select_site = SelectInput( display_text='Sites', name='select_site', multiple=False, options=[('Select a site', 'Select a site'), ('LR_Mendon_AA', 'LR_Mendon_AA'), ('LR_MainStreet_BA', 'LR_MainStreet_BA'), ('LR_WaterLab_AA', 'LR_WaterLab_AA'), ('LR_TG_BA', 'LR_TG_BA'), ('LR_FB_BA', 'LR_FB_BA'), ('PR_BI_AA', 'PR_BI_AA'), ('PR_CH_AA', 'PR_CH_AA'), ('PR_LM_AA', 'PR_LM_AA'), ('PR_ST_AA', 'PR_ST_AA'), ('RB_ARBR_AA', 'RB_ARBR_AA'), ('RB_CG_BA', 'RB_CG_BA'), ('RB_FD_AA', 'RB_FD_AA'), ('RB_RBG_BA', 'RB_RBG_BA'), ('RB_KF_BA', 'RB_KF_BA')], attributes="id=select_site onchange=run_select_site()") begin_date = DatePicker(name='begin_date', display_text='Begin Date', autoclose=True, format='yyyy-mm-dd', start_date='2010-01-01', start_view='decade', today_button=True, initial='2015-03-01') end_date = DatePicker(name='end_date', display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_date='2010-01-01', start_view='decade', today_button=True, initial='2015-03-04') btnSearch = Button(display_text="Search", name="btnSearch", attributes="id=btnSearch onclick=run_search_results();", submit=False) xValue = TextInput(display_text='Input Ca Concentration (ppm):', name="xValue", initial="", disabled=False) btnPhreeqc = Button( display_text="Run PHREEQC", name="btnPhreeqc", attributes="id=btnPhreeqc onclick=run_phreeqc_analyze();", submit=False) # Pass variables to the template via the context dictionary context = { 'map_options': map_options, 'select_basemap': select_basemap, 'select_site': select_site, 'btnSearch': btnSearch, 'begin_date': begin_date, 'end_date': end_date, 'xValue': xValue, 'btnPhreeqc': btnPhreeqc, } return render(request, 'sherin_phreeqc/home.html', context)
def details(request): site_name = request.GET['sitename'] site_code = request.GET['sitecode'] network = request.GET['network'] hs_url = request.GET['hsurl'] hidenav = request.GET['hidenav'] service = request.GET['service'] rest = None soap = None error_message = None if service == 'SOAP': soap_obj = {} soap = service soap_obj["url"] = hs_url client = Client(hs_url) client.set_options(port='WaterOneFlow') site_desc = network + ":" + site_code soap_obj["site"] = site_desc soap_obj["network"] = network site_info = client.service.GetSiteInfo(site_desc) site_info = site_info.encode('utf-8') # site_values = client.service.GetValuesForASiteObject(site_desc,"","","") # print site_values info_dict = xmltodict.parse(site_info) info_json_object = json.dumps(info_dict) info_json = json.loads(info_json_object) # print site_values # print info_json site_variables = [] site_object_info = info_json['sitesResponse']['site']['seriesCatalog'] # print info_json try: site_object = info_json['sitesResponse']['site']['seriesCatalog'][ 'series'] except KeyError: error_message = "Site Details do not exist" context = { "site_name": site_name, "site_code": site_code, "service": service, "error_message": error_message } return render(request, 'hydrocatalog/error.html', context) graph_variables = [] var_json = [] if type(site_object) is list: count = 0 for i in site_object: var_obj = {} count = count + 1 variable_name = i['variable']['variableName'] variable_id = i['variable']['variableCode']['@variableID'] variable_text = i['variable']['variableCode']['#text'] var_obj["variableName"] = variable_name var_obj["variableID"] = variable_id # value_type = i['variable']['valueType'] value_count = i['valueCount'] # data_type = i['variable']['dataType'] # unit_name = i['variable']['unit']['unitName'] # unit_type = i['variable']['unit']['unitType'] # unit_abbr = i['variable']['unit']['unitAbbreviation'] # unit_code = i['variable']['unit']['unitCode'] # time_support = i['variable']['timeScale']['timeSupport'] # time_support_name = i['variable']['timeScale']['unit']['unitName'] # time_support_type = i['variable']['timeScale']['unit']['unitAbbreviation'] begin_time = i["variableTimeInterval"]["beginDateTimeUTC"] begin_time = begin_time.split("T") begin_time = str(begin_time[0]) end_time = i["variableTimeInterval"]["endDateTimeUTC"] end_time = end_time.split("T") end_time = str(end_time[0]) var_obj["startDate"] = begin_time var_obj["endDate"] = end_time # print begin_time,end_time method_id = i["method"]["@methodID"] # method_desc = i["method"]["methodDescription"] # source_id = i["source"]["@sourceID"] # source_org = i["source"]["organization"] # source_desc = i["source"]["sourceDescription"] # qc_code = i["qualityControlLevel"]["qualityControlLevelCode"] # qc_id = i["qualityControlLevel"]["@qualityControlLevelID"] # qc_definition = i["qualityControlLevel"]["definition"] # print variable_name,variable_id, source_id,method_id, qc_code variable_string = str( count ) + '. Variable Name:' + variable_name + ',' + 'Count: ' + value_count + ',Variable ID:' + variable_id + ', Start Date:' + begin_time + ', End Date:' + end_time # value_string = variable_id,variable_text,source_id,method_id,qc_code, variable_name value_list = [variable_text, method_id] value_string = str(value_list) graph_variables.append([variable_string, value_string]) var_json.append(var_obj) # print variable_name, variable_id, value_type, data_type, unit_name,unit_type, unit_abbr,unit_abbr,unit_code, time_support, time_support_name, time_support_type else: var_obj = {} variable_name = site_object['variable']['variableName'] variable_id = site_object['variable']['variableCode'][ '@variableID'] variable_text = site_object['variable']['variableCode']['#text'] value_count = site_object['valueCount'] # value_type = site_object['variable']['valueType'] # data_type = site_object['variable']['dataType'] # unit_name = site_object['variable']['unit']['unitName'] # unit_type = site_object['variable']['unit']['unitType'] # unit_abbr = site_object['variable']['unit']['unitAbbreviation'] # unit_code = site_object['variable']['unit']['unitCode'] # time_support = site_object['variable']['timeScale']['timeSupport'] # time_support_name = site_object['variable']['timeScale']['unit']['unitName'] # time_support_type = site_object['variable']['timeScale']['unit']['unitAbbreviation'] begin_time = site_object["variableTimeInterval"][ "beginDateTimeUTC"] begin_time = begin_time.split("T") begin_time = str(begin_time[0]) end_time = site_object["variableTimeInterval"]["endDateTimeUTC"] end_time = end_time.split("T") end_time = str(end_time[0]) method_id = site_object["method"]["@methodID"] # method_desc = site_object["method"]["methodDescription"] # source_id = site_object["source"]["@sourceID"] # source_org = site_object["source"]["organization"] # source_desc = site_object["source"]["sourceDescription"] # qc_code = site_object["qualityControlLevel"]["qualityControlLevelCode"] # qc_id = site_object["qualityControlLevel"]["@qualityControlLevelID"] # qc_definition = site_object["qualityControlLevel"]["definition"] variable_string = '1. Variable Name:' + variable_name + ',' + 'Count: ' + value_count + ',Variable ID:' + variable_id + ', Start Date:' + begin_time + ', End Date:' + end_time # print variable_name, variable_id, source_id, method_id, qc_code value_list = [variable_text, method_id] value_string = str(value_list) var_obj["variableName"] = variable_name var_obj["variableID"] = variable_id var_obj["startDate"] = begin_time var_obj["endDate"] = end_time var_json.append(var_obj) graph_variables.append([variable_string, value_string]) select_soap_variable = SelectInput(display_text='Select Variable', name="select_var", multiple=False, options=graph_variables) t_now = datetime.now() now_str = "{0}-{1}-{2}".format(t_now.year, check_digit(t_now.month), check_digit(t_now.day)) start_date = DatePicker(name='start_date', display_text='Start Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=now_str) end_date = DatePicker(name='end_date', display_text='End Date', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=now_str) select_variable = [] graphs_object = {} json.JSONEncoder.default = lambda self, obj: (obj.isoformat( ) if isinstance(obj, datetime) else None) soap_obj["var_list"] = var_json request.session['soap_obj'] = soap_obj context = { "site_name": site_name, "site_code": site_code, "network": network, "hs_url": hs_url, "service": service, "rest": rest, "soap": soap, "hidenav": hidenav, "select_soap_variable": select_soap_variable, "select_variable": select_variable, "start_date": start_date, "end_date": end_date, "graphs_object": graphs_object, "soap_obj": soap_obj, "error_message": error_message } return render(request, 'hydrocatalog/details.html', context)
def usgs(request): """ Controller for the app usgs page. :param request: Is the URL request of the page :return: renders the page with context available """ # DETERMINE WHAT DATA IS NEEDED (GaugeViewer 308)... gauge_id = request.GET['gaugeid'] waterbody = request.GET['waterbody'] start = request.GET['start'] end = request.GET['end'] lat = request.GET['lat'] long = request.GET['long'] do_forecast = request.GET.get("forecast_range", None) comid = None forecast_range = 'analysis_assim' forecast_range_initialize = 'Analysis and Assimilation' forecast_date = start forecast_date_end = end comid_time = "06" got_comid = False failed = False # Get Closest COMID to gauge # comid_filler = str(json.loads(urllib2.urlopen('https://ofmpub.epa.gov/waters10/PointIndexing.Service?pGeometry=POINT(' + long + '+' + lat + ')').read())['output']['ary_flowlines'][0]['comid']) comid_filler = get_comid(lat, long) if do_forecast is not None: forecast_range = request.GET['forecast_range'] comid = request.GET['comid'] comid_filler = comid forecast_date = request.GET['forecast_date'] # comid_time = request.GET['comid_time'] inst_data = get_usgs_iv_data(gauge_id, start, end) metadata, inst_data = convert_usgs_iv_to_python(inst_data) inst_time_series_list = create_time_series_usgs(inst_data) # Check if USGS instantaneous data exists for time frame gotinstdata = False if len(inst_time_series_list) > 0: gotinstdata = True # REFACTOR TO LINE "This + 40" # URL for getting forecast data and in a list time_series_list_api = [] if comid is not None and len(comid) > 0: # print 'in loop' got_comid = True if forecast_range == "short_range": # print 'In Short' comid_time = request.GET['comid_time'] forecast_range_initialize = 'Short' elif forecast_range == "analysis_assim": # print 'In analsis and Assim' forecast_date_end = request.GET['forecast_date_end'] forecast_range_initialize = 'Analysis and Assimilation' else: # print "In Medium" forecast_range_initialize = 'Medium' # print comid_time url = 'https://apps.hydroshare.org/apps/nwm-forecasts/api/GetWaterML/?config={0}&geom=channel_rt&variable=streamflow&COMID={1}&lon=&lat=&startDate={2}&endDate={3}&time={4}&lag='.format( forecast_range, comid, forecast_date, forecast_date_end, comid_time) try: url_api = urllib2.urlopen(url) data_api = url_api.read() x = data_api.split('dateTimeUTC=') x.pop(0) for elm in x: info = elm.split(' ') time1 = info[0].replace('T', ' ') time2 = time1.replace('"', '') time3 = time2[:-3] time4 = time3.split(' ') time5 = time4[0].split('-') timedate = time5 year = int(timedate[0]) month = int(timedate[1]) day = int(timedate[2]) timetime = time4[1] time_split = timetime.split(':') time_minute = time_split[1].replace(':', '') hour = time_split[0] minute = time_minute[1] hour_int = int(hour) minute_int = int(minute) value = info[7].split('<') value1 = value[0].replace('>', '') value2 = float(value1) time_series_list_api.append( [datetime(year, month, day, hour_int, minute_int), value2]) except HTTPError: failed = True # Plot USGS data usgs_inst_plot = TimeSeries(height='500px', width='500px', engine='highcharts', title='Instantaneous Values Streamflow Plot', y_axis_title='Flow', y_axis_units='cfs', series=[{ 'name': 'Streamflow', 'data': inst_time_series_list, }, { 'name': 'Forecasted Streamflow', 'data': time_series_list_api }], colors=[ '#7cb5ec', '#b880e9', '#ecc07c', '#7cec84', '#ec7c7c', '#cf7cec', '#df2525', '#90ed7d' ]) dv_data = get_usgs_dv_data(gauge_id, start, end) metadata, dv_data = convert_usgs_dv_to_python(dv_data) dv_time_series_list = create_time_series_usgs(dv_data, 'dv') # Check if USGS daily data exists for time frame gotdvdata = False if len(dv_time_series_list) > 0: gotdvdata = True # Plot USGS data usgs_dv_plot = TimeSeries(height='500px', width='500px', engine='highcharts', title='Daily Average Streamflow Values Plot', y_axis_title='Flow', y_axis_units='cfs', series=[{ 'name': 'Streamflow', 'data': dv_time_series_list, }]) comid_time += ':00' # Gizmos usgs_start_date_picker = DatePicker(name='start', display_text='Start Date', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=start) usgs_end_date_picker = DatePicker(name='end', display_text='End Date', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=end) generate_graphs_button = Button(display_text='Update Graph', submit=True) comid_input = TextInput(display_text='COMID', name='comid', initial=comid_filler, classes='form-control') forecast_date_picker = DatePicker(name='forecast_date', display_text='Forecast Date Start', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=forecast_date) forecast_date_end_picker = DatePicker(name='forecast_date_end', display_text='Forecast Date End', end_date='0d', autoclose=True, format='yyyy-mm-dd', start_view='month', today_button=True, initial=end) forecast_range_select = SelectInput(display_text='Forecast Size', name='forecast_range', multiple=False, options=[('Analysis and Assimilation', 'analysis_assim'), ('Short', 'short_range'), ('Medium', 'medium_range')], initial=forecast_range_initialize, original=True) forecast_time_select = SelectInput(display_text='Start Time', name='comid_time', multiple=False, options=[ ('00:00', "00"), ('01:00', "01"), ('02:00', "02"), ('03:00', "03"), ('04:00', "04"), ('05:00', "05"), ('06:00', "06"), ('07:00', "07"), ('08:00', "08"), ('09:00', "09"), ('10:00', "10"), ('11:00', "11"), ('12:00', "12"), ('13:00', "13"), ('14:00', "14"), ('15:00', "15"), ('16:00', "16"), ('17:00', "17"), ('18:00', "18"), ('19:00', "19"), ('20:00', "20"), ('21:00', "21"), ('22:00', "22"), ('23:00', "23") ], initial=comid_time, original=True) context = { "gaugeid": gauge_id, "waterbody": waterbody, "generate_graphs_button": generate_graphs_button, "usgs_inst_plot": usgs_inst_plot, "got_inst_data": gotinstdata, "usgs_dv_plot": usgs_dv_plot, "got_dv_data": gotdvdata, "usgs_start_date_picker": usgs_start_date_picker, "usgs_end_date_picker": usgs_end_date_picker, "start": start, "end": end, "lat": lat, "long": long, "comid_input": comid_input, "forecast_date_picker": forecast_date_picker, "forecast_date_end_picker": forecast_date_end_picker, "forecast_range_select": forecast_range_select, "forecast_time_select": forecast_time_select, "forecast_range": forecast_range, "comid": comid, "gotComid": got_comid, "forecast_failed": failed } return render(request, 'gaugeviewwml/usgs.html', context)
def home(request, user_workspace): """ Controller for the app home page. """ # Get bounding box from user boundary if it exists boundary_props = get_boundary_fc_props_for_user(request.user) map_view = MapView( height='100%', width='100%', controls=[{ 'Zoom': { 'projection': 'EPSG:4326', 'extent': boundary_props.get('bbox', [-180, -90, 180, 90]) # Default to World } }], basemap=[ 'OpenStreetMap', 'Stamen', { 'ESRI': { 'layer': 'World_Imagery' } }, { 'ESRI': { 'layer': 'World_Street_Map' } }, ], view=MVView( projection='EPSG:4326', center=boundary_props.get('centroid', [0, 0]), # Default to World zoom=boundary_props.get('zoom', 3), # Default to World maxZoom=18, minZoom=2), draw=MVDraw(controls=[ 'Pan', 'Modify', 'Delete', 'Move', 'Point', 'Polygon', 'Box' ], initial='Pan', output_format='GeoJSON')) default_platform = 'modis' default_sensors = EE_PRODUCTS[default_platform] first_sensor_key = next(iter(default_sensors.keys())) default_products = default_sensors[first_sensor_key] first_product_key = next(iter(default_products.keys())) first_product = default_products[first_product_key] # Build initial platform control platform_select = SelectInput( name='platform', display_text='Satellite Platform or model', options=( ('MODIS', 'modis'), ('Sentinel', 'sentinel'), ('Landsat', 'landsat'), ('GLDAS', 'gldas'), ('WAPOR', 'wapor'), ('GPWV411', 'gpwv411'), ('GRACE', 'grace'), ('CHIRPS', 'chirps'), ('TERRACLIMATE', 'terraclimate'), # ('OpenLandMap', 'openlandmap'),terraclimate # ('GHSL', 'ghsl') )) # Build initial sensor control sensor_options = [] for sensor in default_sensors: sensor_options.append((sensor.upper(), sensor)) sensor_select = SelectInput( name='sensor', display_text='Sensor', options=sensor_options, ) # Build initial product control product_options = [] for product, info in default_products.items(): product_options.append((info['display'], product)) product_select = SelectInput(name='product', display_text='Product', options=product_options) # Hardcode initial end date to today (since all of our datasets extend to present) today = dt.datetime.today() initial_end_date = today.strftime('%Y-%m-%d') # Initial start date will a set number of days before the end date # NOTE: This assumes the start date of the dataset is at least 30+ days prior to today initial_end_date_dt = dt.datetime.strptime(initial_end_date, '%Y-%m-%d') initial_start_date_dt = initial_end_date_dt - dt.timedelta(days=30) initial_start_date = initial_start_date_dt.strftime('%Y-%m-%d') # Build date controls first_product_start_date = first_product.get('start_date', None) first_product_end_date = first_product.get('end_date', None) or initial_end_date start_date = DatePicker(name='start_date', display_text='Start Date', format='yyyy-mm-dd', start_view='decade', today_button=True, today_highlight=True, start_date=first_product_start_date, end_date=first_product_end_date, initial=initial_start_date, autoclose=True) end_date = DatePicker(name='end_date', display_text='End Date', format='yyyy-mm-dd', start_view='decade', today_button=True, today_highlight=True, start_date=first_product_start_date, end_date=first_product_end_date, initial=initial_end_date, autoclose=True) # Build reducer method control reducer_select = SelectInput(name='reducer', display_text='Reduction Method', options=( ('Median', 'median'), ('Mosaic', 'mosaic'), ('Mode', 'mode'), ('Mean', 'mean'), ('Minimum', 'min'), ('Maximum', 'max'), ('Sum', 'sum'), ('Count', 'count'), ('Product', 'product'), )) # Build Buttons load_button = Button(name='load_map', display_text='Load', style='default', attributes={'id': 'load_map'}) clear_button = Button(name='clear_map', display_text='Clear', style='default', attributes={'id': 'clear_map'}) plot_button = Button(name='load_plot', display_text='Plot Time Series', style='default', attributes={'id': 'load_plot'}) # Boundary Upload Form set_boundary_button = Button( name='set_boundary', display_text='Set Boundary', style='default', attributes={ 'id': 'set_boundary', 'data-toggle': 'modal', 'data-target': '#set-boundary-modal' # ID of the Set Boundary Modal }) # Handle Set Boundary Form # Handle Set Boundary Form set_boundary_error = '' if request.POST and request.FILES: set_boundary_error = handle_shapefile_upload(request, user_workspace) if not set_boundary_error: # Redirect back to this page to clear form return HttpResponseRedirect(request.path) context = { 'platform_select': platform_select, 'sensor_select': sensor_select, 'product_select': product_select, 'start_date': start_date, 'end_date': end_date, 'reducer_select': reducer_select, 'ee_products': EE_PRODUCTS, 'load_button': load_button, 'clear_button': clear_button, 'plot_button': plot_button, 'set_boundary_button': set_boundary_button, 'set_boundary_error': set_boundary_error, 'map_view': map_view } return render(request, 'earth_engine2/home.html', context)
def new_bloom(request, app_workspace): """ Controller for the background page. """ #Default Values location = '' type = 'Lake' severity = '' date = '' mapdraw = '' #Errors location_error = '' type_error = '' severity_error = '' date_error = '' mapdraw_error = '' #Handle form submission if request.POST and 'add-button' in request.POST: #Get values has_errors = False location = request.POST.get('location', None) type = request.POST.get('type', None) severity = request.POST.get('severity', None) date = request.POST.get('date', None) mapdraw = request.POST.get('geometry', None) #validate if not location: has_errors = True location_error = 'Location is required.' if not type: has_errors = True type_error = 'Type is required.' if not severity: has_errors = True severity_error = 'Severity is required.' if not date: has_errors = True date_error = 'Date is required.' if not mapdraw: has_errors = True mapdraw_error = 'Must draw location on map.' if not has_errors: add_new_bloom(db_directory=app_workspace.path, mapdraw=mapdraw, location=location, type=type, severity=severity, date=date) return redirect(reverse('utah_algal_blooms:home')) messages.error(request, "Please fix errors.") # Define form gizmos location_input = TextInput(display_text='Location', name='location', placeholder='e.g.: Utah Lake', initial=location, error=location_error) type_input = SelectInput(display_text='Water Body Type', name='type', multiple=False, options=[('Lake', 'Lake'), ('Reservoir', 'Reservoir'), ('Other', 'Other')], initial=type, error=type_error) severity_input = SelectInput(display_text='Severity', name='severity', multiple=False, options=[('Low', 'Low'), ('Moderate', 'Moderate'), ('High', 'High'), ('Extreme', 'Extreme')], initial=severity, error=severity_error) date = DatePicker(name='date', display_text='Date of Appearance', autoclose=True, format='MM d, yyyy', start_view='decade', today_button=True, initial=date, error=date_error) initial_view = MVView(projection='EPSG:4326', center=[-110, 39.8], zoom=5) drawing_options = MVDraw(controls=['Modify', 'Delete', 'Move', 'Point'], initial='Point', output_format='GeoJSON', point_color='#FF0000') mapdraw_input = MapView(height='300px', width='100%', basemap='OpenStreetMap', draw=drawing_options, view=initial_view) add_button = Button(display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes={'form': 'add-bloom-form'}, submit=True) cancel_button = Button(display_text='Cancel', name='cancel-button', href=reverse('utah_algal_blooms:home')) context = { 'location_input': location_input, 'type_input': type_input, 'severity_input': severity_input, 'date_input': date, 'mapdraw_input': mapdraw_input, 'mapdraw_error': mapdraw_error, 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'utah_algal_blooms/new_bloom.html', context)