<jupyter_start><jupyter_text>Use Case 3.2: What agriculture water use data to use for a demand site?load it into WEAPThis notebook demonstrates basic WaMDaM use cases analysis using scientific Python libraries such as [pandas](https://pandas.pydata.org/) and [plotly](https://plot.ly/).  It reads WaMDaM SQLite data, runs SQL script, and them uses Python plotly to visualize the resultsThis use case identifies five time series and seasonal flow data for the site below Stewart Dam, IdahoFor more info: http://docs.wamdam.org/UseCases/use_case_3/use-case-3.2 Steps to reproduce this use case results and plots 1.[Import python libraries](Import)         2.[Connect to the WaMDaM populated SQLite file](Connect)      3.[Query WaMDaM dababase for seasonal agriculture demand](QueryDemandSeasonal)       4.[Plot the seasonal demand sites](PlotSeasonal_a)   5.[Pick a flow source and update the db to "Verified"](PickaSource)  6.[Connect to the WEAP API](ConnectWEAP)      7.[Prepare the time series to be ready for WEAP](PrepareWEAP)      8.[Load the time series  data into WEAP](Load)  9.[Query seasonal and time series for comparisons](QuerySeasonalTime)  10.[Plot annual demand for Cache County](QuerySeasonalTime)  9.[Close the SQLite and WEAP API connections](Close)    1. Import python libraries  Install any missing ones you dont have. How? see at this link herehttps://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/<jupyter_code># 1. Import python libraries 
### set the notebook mode to embed the figures within the cell

import plotly
plotly.__version__
import plotly.offline as offline
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
offline.init_notebook_mode(connected=True)
from plotly.offline import init_notebook_mode, iplot
from plotly.graph_objs import *

init_notebook_mode(connected=True)         # initiate notebook for offline plot

import os
import csv
from collections import OrderedDict
import sqlite3
import pandas as pd
import numpy as np
from IPython.display import display, Image, SVG, Math, YouTubeVideo
import urllib

print 'imported'<jupyter_output><empty_output><jupyter_text>2. Connect to the WaMDaM populated SQLite file<jupyter_code># Then we can run queries against it within this notebook :)  

# the SQLite file is published here 
#https://github.com/WamdamProject/WaMDaM_UseCases/blob/master/UseCases_files/3SQLite_database/BearRiverDatasets_June_2018.sqlite

conn = sqlite3.connect('BearRiverDatasets_June_2018_Final.sqlite')

print 'connected'<jupyter_output>connected<jupyter_text>3. Query WaMDaM dababase for seasonal + time series agriculture demand<jupyter_code>## Query WaMDaM dababase for seasonal agriculture demand

# Use Case 3.1Identify_aggregate_TimeSeriesValues.csv
# plot aggregated to monthly and converted to acre-feet time series data of multiple sources


# 2.2Identify_aggregate_TimeSeriesValues.csv
Query_UseCase3_2_URL="""
https://raw.githubusercontent.com/WamdamProject/WaMDaM_UseCases/master/UseCases_files/4Queries_SQL/UseCase3/UseCase3.2/2_IdentifyDemandSites_Seasonal_Values.sql

"""
# Read the query text inside the URL
Query_UseCase3_2_text = urllib.urlopen(Query_UseCase3_2_URL).read()

# print Query_UseCase3_2_text

# return query result in a pandas data frame
result_df_UseCase3_2= pd.read_sql_query(Query_UseCase3_2_text, conn)

# uncomment the below line to see the list of attributes
# display (result_df_required)


# Save the datafrom as a csv file into the Jupyter notebook working space
result_df_UseCase3_2.to_csv('UseCases_Results_csv\UseCase3_2aaaaaaaaaaaa.csv', index = False)

df_Seasonal=result_df_UseCase3_2

# display (df_Seasonal)


column_name = "InstanceName"
subsets = df_Seasonal.groupby(column_name)<jupyter_output><empty_output><jupyter_text>4. Plot the seasonal demand sites Reproduce this plot [Figure 13-A] in the WaMDaM paper<jupyter_code># Use Case 2.3Identify_SeasonalValues

# plot Seasonal data for multiple scenarios

# <NAME>
# November 16, 2017


## read the input data from GitHub csv file which is a direct query output
# 3.3Identify_SeasonalValues.csv 




#get the many curves by looking under "ScenarioName" column header. 
#Then plot Season name vs season value
column_name = "InstanceName"
subsets = df_Seasonal.groupby(column_name)

data = []


#for each subset (curve), set up its legend and line info manually so they can be edited
subsets_settings = {
    'West Cache Irr': {
        'dash': 'solid',
         'mode':'lines+markers',
        'symbol': 'circle',
        'width':'4',
        'legend_index': 0,
        'legend_name': 'West Cache Irr',
         'color':'rgb(0, 63, 255)'
        },

    'Logan Irr': { # this oone is the name of subset as it appears in the csv file
        'dash': 'solid',     # this is properity of the line (curve)
        'width':'4',
        'mode':'lines+markers',
        'symbol': 'diamond',
        'legend_index': 1,   # to order the legend
        'legend_name': 'Logan Irr',  # this is the manual curve name 
         'color':'rgb(25, 101, 255)'

        },
    'North Cache Irr': {
        'dash': 'solid',
        'mode':'lines+markers',
         'symbol': 'triangle-down',
         'width':'4',
        'legend_index': 2,
        'legend_name': 'North Cache Irr',
         'color':'rgb(50, 136, 255)'
        },
    'Highline Canal': {
        'dash': 'solid',
        'mode':'lines+markers',
        'symbol': 'square',
        'width':'4',
        'legend_index': 3,
        'legend_name': 'Highline Canal',
         'color':'rgb(76, 165, 255)'
        },
    
    'Hyrum Canal': {
        'dash': 'solid',
        'mode':'lines+markers',
         'width':'4',
         'symbol': 'star',
        'legend_index': 4,
        'legend_name': 'Hyrum Canal',
         'color':'rgb(101, 191, 255)'
        },    
    'Paradise Canal': {
        'dash': 'solid',
        'mode':'lines+markers',
         'symbol': 'circle',
         'width':'4',
        'legend_index': 5,
        'legend_name': 'Paradise Canal',
         'color':'rgb(127, 212, 255)'
        },

        }

# This dict is used to map legend_name to original subset name
subsets_names = {y['legend_name']: x for x,y in subsets_settings.iteritems()}


for subset in subsets.groups.keys():
    print subset
    dt = subsets.get_group(name=subset)
    s = go.Scatter(
                    x=df_Seasonal.SeasonName,
                    y=dt['SeasonNumericValue'],
                    name = subsets_settings[subset]['legend_name'],
                    line = dict(
                        color =subsets_settings[subset]['color'],
                        width =subsets_settings[subset]['width'],
                        dash=subsets_settings[subset]['dash']
                    ),
                    marker=dict(
                            size=10,
                            symbol =subsets_settings[subset]['symbol']
                                 ),            
                    opacity = 0.8
    )
                   
    data.append(s)
    
    
# Legend is ordered based on data, so we are sorting the data based 
# on desired legend order indicarted by the index value entered above
data.sort(key=lambda x: subsets_settings[subsets_names[x['name']]]['legend_index'])

    

layout = dict(
    #title = "Use Case 3.3",
    yaxis = dict(
        title = "Cumulative flow <br> (acre-feet/month)",
        tickformat= ',',
        showline=True,
        dtick='2000',
        ticks='outside',
        ticklen=5,
         range = ['0', '10000']


                ),
    
    xaxis = dict(
        #title = "Month",
        showline=True,
        ticks='outside',

        ticklen=30
                    ),
    legend=dict(
        x=0.1,y=0.6,
          bordercolor='#00000',
            borderwidth=2
        
               ),
    width=1200,
    height=800,
    #paper_bgcolor='rgb(233,233,233)',
    #plot_bgcolor='rgb(233,233,233)',
    margin=go.Margin(l=250,b=100),
    font=dict(size=30)
             )
# create a figure object
fig = dict(data=data, layout=layout)
#py.iplot(fig, filename = "2.3Identify_SeasonalValues") 


## it can be run from the local machine on Pycharm like this like below
## It would also work here offline but in a seperate window  
offline.iplot(fig,filename = 'jupyter/3Identify_SeasonalValues' )<jupyter_output>North Cache Irr
West Cache Irr
Highline Canal
Hyrum Canal
Logan Irr
Paradise Canal<jupyter_text>5. Pick a flow source and update the db to "Verified"This "Update" SQL query allows users to update the Mappings table to indicate a "verified" DataValue. A verified record set to True indicates that the user has verified, curated, checked, or selected this data value as ready to be used for models. A verified recored can then be used from an automated script to serve data to models. Its particularly useful when the same set of controlled object type, attribute, and instances names return multiple data values from different sources with potentially smiliar or different values due to many factors.<jupyter_code># scenario_name_data = subsets.get_group(name='Base case')
# print scenario_name_data
# Get a cursor object

SQL_update = """
UPDATE Mappings 

SET Verified= 'True'
WHERE  MappingID in

(SELECT Mappings.MappingID FROM Mappings

-- Join the Mappings to get their Attributes
LEFT JOIN "Attributes"
ON Attributes.AttributeID= Mappings.AttributeID

-- Join the Attributes to get their ObjectTypes
LEFT JOIN  "ObjectTypes"
ON "ObjectTypes"."ObjectTypeID"="Attributes"."ObjectTypeID"

-- Join the Mappings to get their Instances   
LEFT JOIN "Instances" 
ON "Instances"."InstanceID"="Mappings"."InstanceID"

-- Join the Mappings to get their ScenarioMappings   
LEFT JOIN "ScenarioMappings"
ON "ScenarioMappings"."MappingID"="Mappings"."MappingID"

-- Join the ScenarioMappings to get their Scenarios   
LEFT JOIN "Scenarios"
ON "Scenarios"."ScenarioID"="ScenarioMappings"."ScenarioID"

-- Join the Scenarios to get their MasterNetworks   
LEFT JOIN "MasterNetworks" 
ON "MasterNetworks"."MasterNetworkID"="Scenarios"."MasterNetworkID"

where 
ObjectTypes.ObjectType='Demand site'  

AND "Instances"."InstanceName"='Bear River Canal Company'  

AND AttributeName_Abstract='Monthly Demand'

AND ScenarioName='USU WEAP Model 2017'

AND MasterNetworkName='Bear River Network')
"""

cur = conn.cursor()

res = cur.execute(SQL_update)

print 'done'<jupyter_output><empty_output><jupyter_text>6. Connect to the WEAP APIFirst make sure to have a copy of the Water Evaluation And Planning" system (WEAP) installed on your local machine (Windows). You will need to have an active licence to use the APIFor more info, see here http://www.weap21.org/index.asp?action=40 WEAP API info http://www.weap21.org/WebHelp/API.htm Install dependency and register WEAP A. Install pywin32 extensions which provide access to many of the Windows APIs from Python.**Choose on option**1. Install using an executable basedon your python version. I used Python 2.7https://github.com/mhammond/pywin32/releases2. Install from source code (for advanced users) https://github.com/mhammond/pywin32 B. Register WEAP with Windows Use Windows "Command Prompt" as Administrator, go to WEAP install directory (e.g. `cd C:\Program Files (x86)\WEAP`) and simply run the following command: `WEAP /regserver`<jupyter_code># this library is needed to connect to the WEAP API
import win32com.client

# this command will open the WEAP software (if closed) and get the last active model
# you could change the active area to another one inside WEAP or by passing it to the command here
#WEAP.ActiveArea = "BearRiverFeb2017_V10.9"

WEAP=win32com.client.Dispatch("WEAP.WEAPApplication")

if not WEAP.Registered:
    print "Because WEAP is not registered, you cannot use the API"

# get the active WEAP Area (model) to serve data into it 
ActiveArea=WEAP.ActiveArea.Name 
print  'ActiveArea= '+ActiveArea

# get the active WEAP scenario to serve data into it 

ActiveScenario= WEAP.ActiveScenario.Name
print 'ActiveScenario= '+ActiveScenario

WEAP_Area_dir=WEAP.AreasDirectory
print WEAP_Area_dir<jupyter_output><empty_output><jupyter_text>7. Prepare the time series to be ready for WEAP<jupyter_code># 7. Prepare the time series to be ready for WEAP

import pandas as pd
import os

# Use Case 2.3Identify_SeasonalValues

# plot Seasonal data for multiple scenarios

# <NAME>
# November 16, 2017


## read the input data from GitHub csv file which is a direct query output
# 3.3Identify_SeasonalValues.csv


# get the many curves by looking under "ScenarioName" column header.
# Then plot Season name vs season value
column_name = "InstanceName"
subsets = df_Seasonal.groupby(column_name)

data = []

for subset in subsets.groups.keys():
    print subset
    dt = subsets.get_group(name=subset)
    # s = go.Scatter(
    #     x=df_Seasonal.SeasonName,
    #     y=dt['SeasonNumericValue'],
    #     name=subset,
    #     marker=dict(size=10),
    #     opacity=0.8
    # )
    # data.append(s)

# Legend is ordered based on data, so we are sorting the data based
# on desired legend order indicarted by the index value entered above
# data.sort(key=lambda x: subsets_settings[subsets_names[x['name']]]['legend_index'])



## it can be run from the local machine on Pycharm like this like below
## It would also work here offline but in a seperate window

output_dir = "Seasonal_csv_files/"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

#############################################################
# Convert the Acre-feet per month to cfs as required by WEAP

# print df_Seasonal
    #     if len(df_Seasonal['AttributeName_Abstract']) < 2: continue
    # SeasonName,SeasonNumericValue
Seasonal_valueAll={}
SeasonalParam = ''
# print df_Seasonal['SeasonName']
for i in range(len(df_Seasonal['InstanceName'])):
    instance_name = df_Seasonal['InstanceName'][i]
    attributeName = df_Seasonal['AttributeName_Abstract'][i]
    m_data = df_Seasonal['SeasonName'][i]
    n_data = df_Seasonal['SeasonNumericValue'][i]
    if not (instance_name, attributeName) in Seasonal_valueAll.keys():
        SeasonalParam = ''
        SeasonalParam += '{},{}'.format(m_data, n_data)
        Seasonal_value = "MonthlyValues( " + SeasonalParam + ")"
        Seasonal_valueAll[instance_name, attributeName] = Seasonal_value
    else:

        SeasonalParam = ',{},{})'.format(m_data, n_data)
        Seasonal_valueAll[instance_name, attributeName] = Seasonal_valueAll[instance_name, attributeName][0:-1] + SeasonalParam



# result ~10 rows in the Seasonal_valueAll where each row has the string like 'MonthlyValues( Oct,221.176,Nov,60.63749,Dec,20.68512, etc)
# print Seasonal_valueAll

# Output strucut:
# InstanceName1, Seasonal_value1
# InstanceName2, Seasonal_value2
# etc
#
# Bear River Canal Company:'MonthlyValues( Oct,221.176,Nov,60.63749,Dec,20.68512,Jan,16.92178,Feb,10.42869,Mar,3.948858,Apr,33.71105,May,456.4773,Jun,608.9324,Jul,675.3607,Aug,633.501,Sep,470.9079)
# Highline Canal:'MonthlyValues( Oct,221.176,Nov,60.63749,Dec,20.68512,Jan,16.92178,Feb,10.42869,Mar,3.948858,Apr,33.71105,May,456.4773,Jun,608.9324,Jul,675.3607,Aug,633.501,Sep,470.9079,)
# 'MonthlyValues( Oct,221.176,Nov,60.63749,Dec,20.68512,Jan,16.92178,Feb,10.42869,Mar,3.948858,Apr,33.71105,May,456.4773,Jun,608.9324,Jul,675.3607,Aug,633.501,Sep,470.9079,)
# 'MonthlyValues( Oct,221.176,Nov,60.63749,Dec,20.68512,Jan,16.92178,Feb,10.42869,Mar,3.948858,Apr,33.71105,May,456.4773,Jun,608.9324,Jul,675.3607,Aug,633.501,Sep,470.9079,)<jupyter_output>North Cache Irr
West Cache Irr
Highline Canal
Hyrum Canal
Logan Irr
Paradise Canal<jupyter_text>8. Load the seasonal data into WEAP<jupyter_code># 8. Load the seasonal data into WEAP

# Get the Instance Name and Attribute names and pass them to 
# the function below to load their values into WEAP

# Make sure to select the scenario of interest in the WEAP software  
WEAP.Scenarios("Current Accounts").Activate

#WEAP.Scenarios("Current Accounts").Name
    
# timeSeriesValue is the PATH for the cvs file for time series

for key in Seasonal_valueAll.keys():
    InstanceName =  key[0]
    AttributeName =  key[1]
    # get the Instance Name
    Seasonal_value = Seasonal_valueAll[key]
    
#     AttributeName=Seasonal_valueAll[AttributeName]
    
#     InstanceName=Seasonal_value.keys()
    # Use the Instance Name and Attribute Name to populate the Season value string to WEAP
    for Branch in WEAP.Branches:
        if Branch.Name == InstanceName:
            print InstanceName
            GetInstanceFullBranch = Branch.FullName
            WEAP.Branch(GetInstanceFullBranch).Variable(AttributeName).Expression = Seasonal_value<jupyter_output><empty_output><jupyter_text>9. Query seasonal and time series for comparisons<jupyter_code># 9. Query seasonal and time series for comparisons

# Use Case 3.1Identify_aggregate_TimeSeriesValues.csv
# plot aggregated to monthly and converted to acre-feet time series data of multiple sources


# 2.2Identify_aggregate_TimeSeriesValues.csv
Query_UseCase3_2_URL="""
https://raw.githubusercontent.com/WamdamProject/WaMDaM_UseCases/master/UseCases_files/4Queries_SQL/UseCase3/UseCase3.2/3_IdentifyDemandSites_TimeSeriesValues.sql

"""

# Read the query text inside the URL
Query_UseCase3_2_text = urllib.urlopen(Query_UseCase3_2_URL).read()


# return query result in a pandas data frame
result_df_UseCase3_2= pd.read_sql_query(Query_UseCase3_2_text, conn)

# uncomment the below line to see the list of attributes
# display (result_df_required)


# Save the datafrom as a csv file into the Jupyter notebook working space
result_df_UseCase3_2.to_csv('UseCase3_2.csv', index = False)


######################
# read the input data from GitHub csv file which is a direct query output for these queries:

df=result_df_UseCase3_2

# display (df)



# Use Case 3.1Iccdentify_aggregate_TimeSeriesValues.csv
# plot aggregated to monthly and converted to acre-feet time series data of multiple sources


# 2.2Identify_aggregate_TimeSeriesValues.csv
Query_UseCase3_2c_URL="""
https://raw.githubusercontent.com/WamdamProject/WaMDaM_UseCases/master/UseCases_files/4Queries_SQL/UseCase3/UseCase3.2/2_IdentifyDemandSites_Seasonal_Numeric_totals.sql
"""

# Read the query text inside the URL
Query_UseCase3_2c_text = urllib.urlopen(Query_UseCase3_2c_URL).read()


# return query result in a pandas data frame
result_df_UseCase3_2c= pd.read_sql_query(Query_UseCase3_2c_text, conn)

# uncomment the below line to see the list of attributes
# display (result_df_required)


# Save the datafrom as a csv file into the Jupyter notebook working space
result_df_UseCase3_2c.to_csv('UseCase3_2cc.csv', index = False)


######################
# read the input data from GitHub csv file which is a direct query output for these queries:

dfc=result_df_UseCase3_2c

display (dfc)


# DataFrame.get_value(index, col, takeable=False)[source]

USU_WEAP_Model_2017_Numeric=dfc.get_value(1,'TotalNumeric')
print USU_WEAP_Model_2017_Numeric

USU_WEAP_Model_2017_Seasonal=dfc.get_value(2,'TotalAnnualUseCacheCanals')
print USU_WEAP_Model_2017_Seasonal

USU_WEAP_Model_2017=USU_WEAP_Model_2017_Seasonal+ USU_WEAP_Model_2017_Numeric<jupyter_output><empty_output><jupyter_text>10. Plot annual demand for Cache County Reproduce this plot [Figure 14] in the WaMDaM paper<jupyter_code># UseCase2.2_dentifyDemandSites_TimeSeriesValues.py

# plot time series data aggregated in space and time from multiple sources


#6.3dentifyDemandSites_TimeSeriesValues.csv

## read the input data from GitHub csv file which is a direct query output
#To get the data block (WaterYear,CumulativeAnnual) for each curve, you need to look up two columns:
#ScenarioName and then AttributeName. So the combination of these two columns will have their separate set of data.

subsets = df.groupby('AttributeName')

data = []


# for each subset (curve), set up its legend and line info manually so they can be edited
subsets_settings = {
    
    'Diversions /surface water': {
        'dash': 'solid',
        'legend_index': 0,
        'legend_name': '<br> 1 site (time series): WaDE <br> "Diversions"',
        'width':'3',
                'color':'rgb(41, 10, 216)'

        },    
    
        '8 sites (Seasonal+ avge annual): WEAP Model 2017': {
        'dash': 'solid',
        'legend_index': 1,
        'legend_name': '<br> 8 sites (seasonal+ avg annual): <br> WEAP Model 2017 "Monthly Demand" ',
        'width':'3',
        'color':'rgb(38, 77, 255)'        
        },  
    
        
    'Water Use /surface and ground': {
        'dash': 'dash',
        'legend_index': 2,
        'legend_name': '<br> 1 site (time series): WaDE  <br> "Water Use"',
        'width':'3',
        'color':'rgb(63, 160, 255)'
        },
    
    'dReq': { # this one is the name of subset as it appears in the csv file
        'dash': 'solid',     # this is properity of the line (curve)
        'legend_index': 3,   # to order the legend
        'legend_name': '<br> 7 sites (time series): WASH Model <br> "dReq"',  # this is the manual curve name 
         'width':'3',
        'color':'rgb(114, 217, 255)'
        },
    'Monthly Demand_TS': {
        'dash': 'solid',
        'legend_index': 4,
        'legend_name': '<br> 1 site (time series): WEAP Model 2010 <br> "Monthly Demand"',
        'width':'3',
        'color':'rgb(170, 247, 255)'
        },

            }
    

# This dict is used to map legend_name to original subset name
subsets_names = {y['legend_name']: x for x,y in subsets_settings.iteritems()}



for subset in subsets.groups.keys():
    scenario_name_data = subsets.get_group(name=subset)
    subsets_of_scenario = scenario_name_data.groupby("AttributeName")
    for group in subsets_of_scenario.groups.keys():
        print group
      
        s = go.Scatter(
                x = subsets_of_scenario.get_group(name=group).WaterYear[-10:],
                y = subsets_of_scenario.get_group(name=group).CumulativeAnnual[-10:],
                name = subsets_settings[subset]['legend_name'],
                line = dict(
                        color =subsets_settings[subset]['color'],
                        width =subsets_settings[subset]['width'], 
                        dash=subsets_settings[subset]['dash']
                        ),
                mode = 'lines',
                opacity = 1)

        
        
        
        data.append(s)

        
               
        
        
# horizontal line
horizontal_line = go.Scatter(
    x=[2003, 2016],
    y=[USU_WEAP_Model_2017,USU_WEAP_Model_2017],
    mode='lines',
    name = '<br> 8 sites (seasonal+ avg annual): <br> WEAP Model 2017 "Monthly Demand" ',
    hoverinfo='8 sites: WEAP Model 2017',
    showlegend=True,
    line=dict(
        shape='hv',
        color = 'rgb(38, 77, 255)',
        width='3'
    )
)
data.append(horizontal_line)


# Legend is ordered based on data, so we are sorting the data based 
# on desired legend order indicarted by the index value entered above
data.sort(key=lambda x: subsets_settings[subsets_names[x['name']]]['legend_index'])        
   
layout = dict(
    #title = "Use Case 6",
    yaxis = dict(
        title = "Total volume per water year <br> (acre-feet)",       
        tickformat= ',',
        showline=True,
        range = ['0', '300000'],

                ),
    xaxis = dict(
        range = ['2004', '2016'],
        ticks='outside',
        tickwidth=0.5,
        ticklen=25,
        showline=True
                ),
    legend=dict(x=0.86,y=0.445,
                bordercolor='#00000',
                borderwidth=2  
               ),
     width=1650,
    height=1000,
    margin=go.Margin(
        l=250,
        b=100       ),
    #paper_bgcolor='rgb(233,233,233)',
    #plot_bgcolor='rgb(233,233,233)',
    font=dict(size=32)

)


# see the label Lines with Annotations
# https://plot.ly/python/line-charts/      
# annotations = []

# label = ['8 sites', '1 site', '1 site', '7 sites','1 site']

# for legend_index in subsets_settings:
#     annotations.append(dict(xref='paper', x=2004, y=subsets_settings[legend_index],
#                                   xanchor='right', yanchor='middle',
#                                   text=label)
#                       )

# layout['annotations'] = annotations
                

# create a figure object          
fig = dict(data=data, layout=layout)

offline.iplot(fig,filename = 'Use Case 3.2-b')#,image='png' )       


#py.iplot(fig, filename = "UseCase2.2_dentifyDemandSites_TimeSeriesValues") 

## it can be run from the local machine on Pycharm like this like below
## It would also work here offline but in a seperate window  
# plotly.offline.plot(fig, filename = "UseCase2.2_dentifyDemandSites_TimeSeriesValues")       

# offline.iplot(fig,filename = 'UseCase2.2_dentifyDemandSites_TimeSeriesValues',
#              image='png')
# it might take 30-60 seconds to load the html interactive image<jupyter_output>dReq
Water Use /surface and ground
Diversions /surface water
Monthly Demand_TS<jupyter_text>11. Close the SQLite and WEAP API connections<jupyter_code># conn.close()

print 'connection disconnected'

# Uncomment 
# WEAP.SaveArea

# Or 
NewWEAPCopyName=ActiveArea+"Test"
print NewWEAPCopyName

# Call API function to save WEAP
# WEAP.SaveAreaAS(NewWEAPCopyName)

# this command will clode WEAP
# WEAP.Quit
WEAP='nil'<jupyter_output>connection disconnected
{'fraction_non_alphanumeric': 0.104544560299036, 'fraction_numerical': 0.0355695455439701, 'mean_word_length': 3.520811099252935, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 56, 'https://': 10, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '177202', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 8791, 'n_tokens_neox': 7915, 'n_words': 2266, 'path': 'Final_notebooks/5_Use_Case_3.2_Seasonal_Demand.ipynb', 'repo_name': 'amabdallah/Notebooks', 'size': '25429'}