Skip to content

Commit

Permalink
Merge pull request SoftwareDefinedBuildings#63 from rajasriramoju/34-…
Browse files Browse the repository at this point in the history
…new-login-with-graphs

34 new login with graphs
  • Loading branch information
rajasriramoju authored Jun 6, 2019
2 parents 4523e88 + 2dd8cc3 commit 6d835c4
Show file tree
Hide file tree
Showing 5 changed files with 363 additions and 120 deletions.
161 changes: 141 additions & 20 deletions dashboards/solarplus-ui/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def cieeData():
ciee = pd.read_csv("./sample_data/ciee.csv")
ciee.columns = ['TimeStamp', 'ciee', 's0', 's1', 's2', 's3']

#limiting to 20 entries like prev demo
#limiting to 20 entries
ciee = ciee[:20]

return ciee.to_json(orient='records')
Expand All @@ -259,6 +259,12 @@ def cieeData():
@main.route('/cieeData/<startDate>/<endDate>')
@crossdomain(origin="*")
def extractData(startDate, endDate):
"""
Not used in the project anymore
Extracts data using start date and end date
"""
cieeDF = pd.read_csv("./sample_data/ciee.csv")
cieeDF.columns = ['TimeStamp', 'ciee', 's0', 's1', 's2', 's3']

Expand All @@ -281,16 +287,34 @@ def extractData(startDate, endDate):

#fetching data in the specific timeframe
dataInRange = cieeDF[startDateIndex:(endDateIndex+1)]
#print(dataInRange)

return dataInRange.to_json(orient = 'records')


# This function takes in a file name, start and end date with the two features that
# the user wants plotted on the graph
@main.route('/<filename>/<startDate>/<endDate>/<feature1>/<feature2>')
@crossdomain(origin="*")
def extractData_plotTwoQueries(filename, startDate, endDate, feature1, feature2):

"""
Not used in the project anymore
extractData_plotTwoQueries(filename, startDate, endDate, feature1, feature2)
Parameters
----------
filename: str,
startDate: str (formatted as yyyy-mm-dd),
endDate: str (formatted as yyyy-mm-dd),
feature1: str,
feature2: str
This function takes in a file name, start and end date with the two features that
the user wants plotted on the graph
Returns
-------
JSON object
pandas dataframe that is converted to JSON object to hold the data of dates and 2 features' values
"""

filePathString = "./solarplus_sample_data/" + filename+".csv"
print(filePathString)
Expand Down Expand Up @@ -329,7 +353,28 @@ def extractData_plotTwoQueries(filename, startDate, endDate, feature1, feature2)
@main.route('/analysis/MLModel/<day1>/<day2>/<day3>/<day4>/<day5>/<day6>/<day7>')
@crossdomain(origin="*")
def MLPredictionModel(day1, day2, day3, day4, day5, day6, day7):
print(day1, day2, day3, day4, day5, day6, day7)

"""
MLPredictionModel(day1, day2, day3, day4, day5, day6, day7)
Parameters
----------
day1 : str
day2 : str
day3 : str
day4 : str
day5 : str
day6 : str
day7 : str
The function predicts the solar power generated given the temperatures of different days
Returns
-------
JSON object
pandas dataframe that is converted to JSON object to hold the data of dates and predicted values
"""

filename = './solarplus-ui/trained_model.sav'
loaded_model = pickle.load(open(filename, 'rb'))

Expand All @@ -341,46 +386,122 @@ def MLPredictionModel(day1, day2, day3, day4, day5, day6, day7):

X_pred=[float(day1), float(day2), float(day3), float(day4), float(day5), float(day6), float(day7)]
dataset = pd.DataFrame({'X_pred': X_pred, 'Column1':Y_pred})
#dataset = pd.DataFrame.from_records(Y_pred)

#print(Y_pred[0])
print(dataset)
#Y_pred0 = {'temperature': Y_pred[0]}

#return make_response(dumps(Y_pred))

return dataset.to_json(orient = 'records')

# This function extracts data for any feature's data from Control.csv data
# of the solarplus sample data -> will be used for total power consumption
# values for dashboard

@main.route('/dashboard/access/<feature1>')
@crossdomain(origin="*")
def extractData_oneFeature_Control2(feature1):

"""
extractData_oneFeature_Control2(feature1)
Parameters
----------
feature1 : str
This function extracts data for any feature's data from Control.csv data
of the solarplus sample data -> will be used for total power consumption
values for dashboard
Returns
-------
JSON object
pandas dataframe that is converted to JSON object to hold the data of dates and feature1 values
"""
filePathString = "./solarplus-ui/solarplus_sample_data/Control2.csv"
readDF = pd.read_csv(filePathString)

df = readDF.loc[:,['Time',feature1]]
return df.to_json(orient = 'records')

# This function extracts data for any 2 features' data from Control.csv data
# of the solarplus sample data -> will be used for HVAC1 and HVAC2
# values for dashboard

@main.route('/dashboard/access/<feature1>/<feature2>')
@crossdomain(origin="*")
def extractData_twoFeatures_Control2(feature1, feature2):
"""
Parameters
----------
feature1 : str
feature2 : str
This function extracts data for any 2 features' data from Control.csv data
of the solarplus sample data -> will be used for HVAC1 and HVAC2
values for dashboard
Returns
-------
JSON object
pandas dataframe that is converted to JSON object to hold the data of dates and feature1 and feature2 values
"""
filePathString = "./solarplus-ui/solarplus_sample_data/Control2.csv"
readDF = pd.read_csv(filePathString)

df = readDF.loc[:,['Time',feature1,feature2]]
return df.to_json(orient = 'records')

# This function extracts data for solar production values from
@main.route('/dashboard/PVPowerGenData')
@crossdomain(origin="*")
def extractData_PVPowerGenData():
filePathString = "./Historic_microgrid_data/PVPowerGenData.csv"
"""
extractData_PVPowerGenData()
This function extracts data for solar production values from
"""
filePathString = "./solarplus-ui/Historic_microgrid_data/PVPowerGenData.csv"
readDF = pd.read_csv(filePathString)

df = readDF.loc[:,['Date_PT','PVPower_kW']]
return df.to_json(orient = 'records')


@main.route('/dashboard/access/<feature1>/average')
@crossdomain(origin="*")
def extractData_oneFeature_Control3(feature1):
"""
extractData_oneFeature_Control3(feature1)
Parameters
----------
feature1 : str
This function extracts data for any feature's data from Control.csv data
of the solarplus sample data -> will be used for average power consumption
values
Returns
-------
JSON object
pandas dataframe that is converted to JSON object to hold the data of dates and average values
"""
filePathString = "./solarplus-ui/solarplus_sample_data/Control2.csv"
readDF = pd.read_csv(filePathString)

df = readDF.loc[:,['Time',feature1]]

# loop here to go through the dataframe and calculate the average
nextEntryIndex = df.index[0]
df_model = pd.DataFrame() #creating an epty dataframe that feeds to model
df_model = pd.DataFrame(columns=['Time', feature1])

#having a while loop that runs till the power dataframe is empty since that is shorter
while not df.empty:
# getting the date of the entry we want to deal with
currDateEntry = df.iloc[nextEntryIndex].Time
currDate = (currDateEntry.split(' '))[0]
print(currDateEntry)

#obtaining average power production of a day
currDateEntries_power = df[df['Time'].str.contains(currDate)].Building
currDateEntriesPowerAverage = sum(currDateEntries_power)/len(currDateEntries_power)
df_model.loc[len(df_model)] = [currDate, currDateEntriesPowerAverage]

df = df[~df.Time.str.contains(currDate)]
# finding the next date to perform the same operations on, as long as the dataframe is not alraedy empty
if not df.empty:
nextEntryIndex_power = df.index[0]

return df_model.to_json(orient = 'records')
44 changes: 33 additions & 11 deletions dashboards/solarplus-ui/static/assets/js/analysis-mlgraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,36 @@ $(document).ready(function () {
return (value);
}

/*
* Graphs the temperature, days, and solar power
*
* @author: Raja Vyshnavi Sriramoju
* @param {Array of numbers} predictedSolarVals
* @param {Array of numbers} tempVals - the max temperatures for the following week
* @param {Array of Strings} daysArray - the days of the week starting from the next day
*/
function renderChart(predictedSolarVals, tempVals, daysArray) {
var highChart = new Highcharts.chart('predictionChart', {
chart: {
//type: 'line',
zoomType: "xy"
},
title: {
text: 'Predicted Solar production values'
},
tooltip: {
valueSuffix: '\xB0C'
valueSuffix: '\xB0C' //the suffix when you hover over the graph for temperature
},
xAxis: {
categories: daysArray,
crosshair: true
},
yAxis: [
{
//creating the 2 y-axis elements in the array
labels: {
format: '{value}°C'
},
opposite: true,
opposite: true, //creating axis on the oppposite sides
title: {
text: 'Forecast Temperature'
},
Expand Down Expand Up @@ -68,31 +76,45 @@ $(document).ready(function () {
});
}

/*
* Request url and returns recieved data
*
* @author: Raja Vyshnavi Sriramoju
* @param {string} url for the flask server
* @return {JSON} The prediction values from flask.
*/
function Get(yourUrl) {
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET", yourUrl, false);
Httpreq.send(null);
return Httpreq.responseText;
}

/*
* Retrieves max temperature data from 'Weather' tab and predicts the predicted solar power generated in the next week
* Calls renderChart() to plot the values
* @author: Raja Vyshnavi Sriramoju
*/
function graphData_MLModel() {

// TODO: have to extract daily values instead of static ones for now
var forecast_TempVals = sessionStorage.getItem("temperatureVals");
forecast_TempVals = JSON.parse(forecast_TempVals);
console.log("Printing vals from weather tab");
console.log(forecast_TempVals);
//console.log("Printing vals from weather tab");
//console.log(forecast_TempVals);

if (forecast_TempVals == null){
document.getElementById("predictionChart").innerHTML = "Weather Values have not been obtained for prediction of solar power production. Please visit Weather tab first.";
}

//var tempVals = [14,19,18,17,18,20,22];
const uri_chart1 =
`http://127.0.0.1:5000/analysis/MLModel/${forecast_TempVals[0]}/${forecast_TempVals[1]}/${forecast_TempVals[2]}/${forecast_TempVals[3]}/${forecast_TempVals[4]}/${forecast_TempVals[5]}/${forecast_TempVals[6]}`;
var res_chart1 = JSON.parse(Get(uri_chart1));
console.log(res_chart1);

var d = new Date();
var today = d.getDay();
var days = [];

//This creates the array of days for the x-axis values
for(let j = 0; j < 7; j++)
{
switch(today){
Expand Down Expand Up @@ -120,18 +142,18 @@ $(document).ready(function () {
var predictedSolarVals = [];
var labels = [];

//res_chart1.length
for (let i = 0; i < 7; i++) {

let singleElement = res_chart1[i];

for (let prop in singleElement) {
if (prop == 'Column1')
predictedSolarVals.push(singleElement[prop]);
predictedSolarVals.push(singleElement[prop]); //will be y-values
}
}
renderChart(predictedSolarVals, forecast_TempVals, days);
renderChart(predictedSolarVals, forecast_TempVals, days); //x-values

}
//making the function call so that call is made as soon as html page loads
graphData_MLModel();
});
Loading

0 comments on commit 6d835c4

Please sign in to comment.