Skip to content

Commit

Permalink
Merge pull request #42 from mtpain/issue34
Browse files Browse the repository at this point in the history
Issue34
  • Loading branch information
mt-digital committed Apr 22, 2016
2 parents f81f067 + 332be05 commit 09f4dee
Show file tree
Hide file tree
Showing 10 changed files with 211 additions and 10 deletions.
8 changes: 5 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ ENV APP_USERNAME abc@xyz.com
ENV APP_PORT 5000
ENV APP_PASSWORD prms

CMD gunicorn --worker-class eventlet -w 4 manage:app -b 0.0.0.0:${APP_PORT} \
--error-logfile='err.log' --access-logfile='log.log' --log-level DEBUG -e \
APP_USERNAME=${APP_USERNAME} -e APP_PASSWORD=${APP_PASSWORD}
#CMD gunicorn --worker-class eventlet -w 4 manage:app -b 0.0.0.0:${APP_PORT} \
# --error-logfile='err.log' --access-logfile='log.log' --log-level DEBUG -e \
# APP_USERNAME=${APP_USERNAME} -e APP_PASSWORD=${APP_PASSWORD}

CMD python manage.py runserver -h 0.0.0.0 -p ${APP_PORT} --threaded

#CMD ./serve-swag.sh
29 changes: 29 additions & 0 deletions app/api/util.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import json
import netCDF4
import shutil


from numpy import where

from ..models import VegetationMapByHRU, ProjectionInformation

from client.model_client.client import ModelApiClient
from client.swagger_client.apis.default_api import DefaultApi

LEHMAN_CREEK_CELLSIZE = 100 # in meters; should be in netCDF, but it's not


Expand Down Expand Up @@ -79,3 +84,27 @@ def get_veg_map_by_hru(prms_params_file):
vegmap.elevation = prms_params.variables['hru_elev'][:].flatten().tolist()

return vegmap

def model_run_name(auth_host=None, model_host=None,
app_username=None, app_password=None):
"""
the function is used to collect model run names
"""

cl = ModelApiClient(auth_host=auth_host, model_host=model_host)
cl.authenticate_jwt(username=app_username, password=app_password)

api = DefaultApi(api_client=cl)

# record all the model runs
model_run = api.search_modelruns().objects

temp_list = [0] * len(model_run)

for loop_count in range(len(temp_list)):
temp_item = model_run[loop_count]
# for current version, we only display finished model run
if temp_item['progress_state'] =='FINISHED':
temp_list[loop_count] = {'id':temp_item['id']}

return json.dumps(temp_list)
11 changes: 10 additions & 1 deletion app/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from . import api
from ..models import Scenario, Hydrograph, Inputs, Outputs
from util import get_veg_map_by_hru
from util import get_veg_map_by_hru, model_run_name


@api.route('/api/scenarios/<scenario_id>', methods=['GET', 'DELETE'])
Expand Down Expand Up @@ -67,6 +67,15 @@ def scenario_by_id(scenario_id):
), 400, mimetype='application/json'
)

@api.route('/api/scenarios/finished_modelruns')
def display_modelruns():
temp_list = model_run_name(
auth_host=app.config['AUTH_HOST'],
model_host=app.config['MODEL_HOST'],
app_username=app.config['APP_USERNAME'],
app_password=app.config['APP_PASSWORD']
)
return temp_list

@api.route('/api/scenarios', methods=['GET', 'POST'])
def scenarios():
Expand Down
5 changes: 5 additions & 0 deletions app/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@
from . import main



@main.route('/')
def index():
"""Help page"""

return render_template('index.html')

@main.route('/modelruns_table')
def show_all_modelruns():
return render_template('modelruns_table.html')

@main.route('/hydrograph_vis/<scenario_id>')
def hydrograph_visualization(scenario_id = ''):
"""
Expand Down
9 changes: 9 additions & 0 deletions app/static/js/model_run_table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
$(document).ready(function(){
$.get('/api/scenarios/finished_modelruns', function(data){
var temp = jQuery.parseJSON(data);
for(var i=0; i<temp.length; i++)
{
$('#scenario-list').append("<p>"+temp[i]['id'].toString()+"</p>");
}
});
});
67 changes: 66 additions & 1 deletion app/static/js/vis/draw_polygon_on_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ $(document).ready(function(){
// current veg code
var vegCurrent;

// elevation information for all HRU cells
var elevationInfo;

var canvasWidth;
var canvasHeight;
var canvasHandle;
Expand Down Expand Up @@ -68,6 +71,15 @@ $(document).ready(function(){

vegOrigin = obtainJsoninto1D(inputJson);

elevationInfo = inputJson['elevation'].slice();
var minElevation = elevationInfo.min();
var maxElevation = elevationInfo.max();
// append input area and instruction
// this part should be dynamically generated
$("#elevationInputID").append("<p>The elevation scale is from "+minElevation.toString()+" to "+maxElevation.toString()+"</p>");
$("#elevationInputID").append("<input type='number' min='"+minElevation.toString()+"' max='"+maxElevation.toString()+"' step='0.1' id='elevationSelectorID'>");
$("#elevationInputID").append("<input type='button' class='btn btn-sm btn-sm-map' id='confirmElevationButton' value='Update Map by Elevation' />");

// should not use var vegCurrent = vegOrigin
// coz when we change vegCurrent and then vegOrigin will change too
vegCurrent = vegOrigin.slice();
Expand Down Expand Up @@ -148,6 +160,15 @@ $(document).ready(function(){
chosenHRU=[];
});

$('#confirmElevationButton').click(function(){
changeVegByElevation(vegCurrent, elevationInfo, dataX, dataY);

resetCanvas(vegCurrent);

// update map overlay
updateMapOverlay();
});


$("#resetCanvasButton").click(function(){
resetCanvas(vegOrigin);
Expand Down Expand Up @@ -253,21 +274,37 @@ $(document).ready(function(){
// this function grab data json input and create a 1D array of hru values
function obtainJsoninto1D(inputJson)
{
var totalHRUNum = 0;

var outputArr = new Array(dataX*dataY);
// for this case veg_code is the loop count (from 0), vegCode is str
// therefore veg_code = i.toString()
var tempSize;
$.each(['bare_ground', 'grasses', 'shrubs', 'trees', 'conifers'],
function(i, cov_type) {
tempSize = inputJson[cov_type].length;

totalHRUNum = totalHRUNum + tempSize;

for(var m=0; m<tempSize; m++ )
{
outputArr[inputJson[cov_type][m]] = i;
}
}
);

return outputArr;
// test if the inputJson is valid
if(totalHRUNum == dataX*dataY)
{
return outputArr;
}
else
{
console.log('Data from the get request is not right.');
console.log('HRU number is not consistent.');
return [];
}

}

// this is from http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
Expand Down Expand Up @@ -407,5 +444,33 @@ $(document).ready(function(){

}

Array.prototype.max = function() {
return Math.max.apply(null, this);
};

Array.prototype.min = function() {
return Math.min.apply(null, this);
};

function changeVegByElevation(inputHRU, inputElevationInfo, inputArrX, inputArrY)
{
var hruNum = 0;
var elevationThreshold = $('#elevationSelectorID').val();
// get the current chosen color number
var colorOptNum = parseInt($('#vegetation-type-selector label.active input').val());

for(var m=0 ; m<inputArrY ; m++)
{
for(var i=0 ; i<inputArrX ; i++)
{
hruNum = i + m*dataX;
if(inputElevationInfo[hruNum] >= elevationThreshold)
{
inputHRU[hruNum] = colorOptNum;
}
}
}
}


});
3 changes: 2 additions & 1 deletion app/static/js/vis/overlay_google_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ function overlayCanvasonGoogleMap(xllcorner,xurcorner,yllcorner,yurcorner)
{
onrendered: function(canvas) {
imgURL = canvas.toDataURL();
google.maps.event.addDomListener(window, 'load', initialize);
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
}
});
}
Expand Down
16 changes: 13 additions & 3 deletions app/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
<script type="text/javascript" src='/static/bower_components/html2canvas/build/html2canvas.min.js' type='text/javascript'></script>
<!-- THIS JS IS an AWESOME COLOR LIB -->
<script type="text/javascript" src="/static/bower_components/chroma-js/chroma.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBINKUFZugKXNT1ieZy315WFViufQUZvv4"
async defer></script>
<script type="text/javascript" src="/static/js/vis/overlay_google_map.js"></script>
<!-- THIS JS IS USED FOR 2D map polygon -->
<script type="text/javascript" src="/static/js/vis/draw_polygon_on_map.js"></script>
Expand Down Expand Up @@ -139,6 +140,14 @@ <h4>1. Select Vegetation Type</h4>
{% include 'includes/veg-type-selector.html' %}
</div>

<!-- TODO need to improve design -->
<div class="row">
<h4>2.a Change the vegetation using elevation information</h4>
<p>Press the "UPDATE MAP BY ELEVATION" button and all the hru cell above the input elevation veg type will be
changed into the type chosen in Step 1</p>
<div id='elevationInputID'>
</div>
</div>

<div class="row">
<h4>2. Select HRU on map for the selected vegetation type then save to persist the change</h4>
Expand Down Expand Up @@ -194,7 +203,8 @@ <h4>
</div>


<h4>4. Enter a scenario name</h4>
<h4>4. Enter a scenario</h4>

<div class="row"
id="new-scenario-menu" align="center">
<div style="width:70%" align="left">
Expand Down Expand Up @@ -240,7 +250,7 @@ <h3 class="section-header">List of Completed Scenarios</h3>

<script type="text/babel">
ReactDOM.render(
<ScenarioListBox pollInterval={1000} />,
<ScenarioListBox pollInterval={5000} />,
document.getElementById('scenario-list')
);
</script>
Expand Down
68 changes: 68 additions & 0 deletions app/templates/modelruns_table.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<!-- Home page for our human adaptor -->
{% extends "base.html" %}
{% set active_page = "index" %}
{% block scripts %}
{{ super() }}
<script type="text/babel" src="/static/js/scenarios.js"></script>
<script type="text/javascript" src="/static/js/model_run_table.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
{% endblock %}

{% block head_ext %}
{{ super() }}
<style>
.delete-scenario {
vertical-align: middle;
text-align: center;
border-width: 1px;
}
.delete-scenario:hover {
cursor: pointer;
}
.delete-scenario span {
line-height: 20px;
}
#new-scenario-menu-content {
position: relative;
}
#scenario-list {
display: table;
}
.section-header {
text-decoration: underline;
}
.btn-custom {
border-color: #dfd7ca;
border-width: 2px;
border-style: solid;
}
.btn-custom.active {
background-color: #f8f5f0;
}
.btn-custom:hover {
background-color: #f8f5f0;
color: #3e3f3a;
}
.btn {
margin: 3.5px;
}

td.download-link>a:hover {
cursor: pointer;
}
</style>
{% endblock %}

{% block content %}
<div class="container">

<div class="row">
<h3 class="section-header">List of Completed Scenarios</h3>
<div id="scenario-list"></div>
</div>


</div>


{% endblock %}
5 changes: 4 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ def init_app(app):

APP_USERNAME = os.getenv('APP_USERNAME', '')
APP_PASSWORD = os.getenv('APP_PASSWORD', '')
# MONGODB_HOST = os.getenv('MONGODB_HOST', 'mongo')
# MONGODB_DB = os.getenv('MONGODB_DB', 'scenarios')
# MONGODB_PORT = os.getenv('MONGODB_PORT', 27017)


class DevelopmentConfig(Config):

DEBUG = True

MONGODB_SETTINGS = {'db': 'scenarios'}
MONGODB_SETTINGS = {'db': 'scenarios'} # ,'host':'mongo'}

BASE_PARAMETER_NC = 'app/static/data/LC.param.nc'

Expand Down

0 comments on commit 09f4dee

Please sign in to comment.