├── CONTRIBUTING.md ├── DEBUGGING.md ├── DEVELOPING.md ├── LICENSE ├── MAINTAINERS.md ├── README.md ├── data └── README.md ├── doc └── source │ └── images │ ├── add_file.png │ ├── analyze_results │ ├── analyze_results.png │ ├── architecture.png │ ├── bluemix_service_nodered.png │ ├── create_notebook_from_url.png │ ├── deploy_nodered_flow.png │ ├── html_node.png │ ├── import_nodered_flow.png │ ├── note_websocket_url.png │ ├── objectstorage_credentials.png │ ├── update_html_websocket_url.png │ └── update_websocket_url.png ├── node-red-flow └── orchestrate_dsx_workflow.json └── notebooks └── node_red_dsx_workflow.ipynb /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This is an open source project, and we appreciate your help! 4 | 5 | We use the GitHub issue tracker to discuss new features and non-trivial bugs. 6 | 7 | In addition to the issue tracker, [#journeys on 8 | Slack](https://dwopen.slack.com) is the best way to get into contact with the 9 | project's maintainers. 10 | 11 | To contribute code, documentation, or tests, please submit a pull request to 12 | the GitHub repository. Generally, we expect two maintainers to review your pull 13 | request before it is approved for merging. For more details, see the 14 | [MAINTAINERS](MAINTAINERS.md) page. 15 | -------------------------------------------------------------------------------- /DEBUGGING.md: -------------------------------------------------------------------------------- 1 | Troubleshooting 2 | =============== 3 | 4 | Jupyter Notebooks 5 | ----------------- 6 | 7 | * Make sure the pip install ran correctly. You might need to restart the 8 | kernel and run the cells from the top after the pip install runs the first 9 | time. 10 | * Many of the cells rely on variables that are set in earlier cells. Some of 11 | these are cleared in later cells. Start over at the top when troubleshooting. 12 | * Many of the cells rely on service credentials from IBM Cloud that are set in 13 | earlier cells. Make sure to add your service credentials correctly. 14 | * If there is an error in the `4.1 Prepare data section`, there could be a change in the column names or format of the data files downloaded from [kaggle](https://www.kaggle.com/the-guardian/olympic-games). Please change the column names and format of the files downloaded from [kaggle](https://www.kaggle.com/the-guardian/olympic-games) to match the format below. 15 | 16 | olympics.csv (renamed from summer.csv file downloaded from kaggle) 17 | 18 | |Year|City|Sport|Discipline|Athlete|Country|Gender|Event|Medal| 19 | |----|----|-----|-----------|------|-------|------|-----|-----| 20 | |1896|Athens|Aquatics|Swimming|HAJOS, Alfred|HUN|Men|100M Freestyle|Gold| 21 | |1896|Athens|Aquatics|Swimming|HERSCHMANN, Otto|AUT|Men|100M Freestyle|Silver| 22 | 23 | dictionary.csv 24 | 25 | |Country|Code|Population|GDP per Capita| 26 | |-------|----|----------|--------------| 27 | |Afghanistan|AFG|32526562|594.3230812| 28 | |Albania|ALB|2889167|3945.217582| 29 | 30 | 31 | * If the Start Websocket client step throws an error as shown below, please refer to the step `Update the websocket URL in the notebook` in Section 8 of the documentation. 32 | 33 | --- response header --- 34 | HTTP/1.1 500 Error 35 | X-Backside-Transport: FAIL FAIL 36 | Content-Type: text/xml 37 | Connection: close 38 | 39 | Node-RED 40 | -------- 41 | 42 | * Make sure that the websocket URL has been updated with the NODERED_BASE_URL in the HTML code. Refer to section `5. Update the websocket URL in HTML code` in the documentation for details. 43 | -------------------------------------------------------------------------------- /DEVELOPING.md: -------------------------------------------------------------------------------- 1 | Tips for Developers 2 | =================== 3 | 4 | The notebook is designed to be run top-down. Settings in early cells are used 5 | in later cells. Some variables are also cleared to free up memory. So, although 6 | you can often run single cell repeatedly while testing changes, you may want 7 | to start over from the top if anything seems to be missing. 8 | 9 | Setting credentials 10 | ------------------- 11 | Credentials need to be added to the notebook to access some IBM Cloud services. 12 | The credentials are set near the top of the notebook to make it 13 | more obvious that they need to be set and also to make it more obvious that 14 | you will be saving a notebook with credentials. You should not share your 15 | notebook with anyone that you would not share your credentials with 16 | unless you use the ``share`` feature with the ``Only text and output`` or 17 | ``All content excluding sensitive code cells`` option. 18 | 19 | The ```@hidden_cell``` magic is used to mark the credentials cells as 20 | "sensitive". If you do any rearranging of sensitive code, remember to identify 21 | sensitive cells with ``@hidden_cell``. 22 | 23 | Installing Python packages 24 | -------------------------- 25 | A notebook can use ```!pip install``` to install the Python packages 26 | from PyPI. You can follow this example if you decide to use additional Python 27 | packages in your notebook. Check the output to see that the install was 28 | successful. See the "Controlling output" section below for more information on 29 | how to suppress/show the output. You might want to use ``DEBUG = True`` until 30 | you've verified that the pip install was successful. 31 | 32 | > **Note**: After running a cell with pip install, you may need to restart 33 | the kernel and then run the cells again from the top. 34 | 35 | Importing libraries 36 | ------------------- 37 | Import and some setup of libraries is done near the top. This is another 38 | example of why cells need to run top-down. Keeping the imports near the top 39 | is a Python PEP8 style convention. Python does not require this convention, 40 | but Python developers are used to looking for imports at the top. 41 | 42 | Defining global variables and helper functions 43 | ---------------------------------------------- 44 | After the imports, a few global variables and helper functions are defined. 45 | These allow for code re-use. These cells need to run before other cells can 46 | use the functions and globals. These values do not change. You can change 47 | and run the later cells over and over without always restarting from the top. 48 | 49 | Controlling output 50 | ------------------ 51 | One of the great things about notebooks is that you can use them to document 52 | what you are doing, show your work, show the results, and document your 53 | conclusion -- all in one place. Sharing "your work" (the code) is a great 54 | feature, but to make the "only text and output" web page look nice and clean 55 | you can use the following tips. 56 | 57 | #### @hidden_cell magic 58 | 59 | The @hidden_cell magic is used to mark the credentials cells as "sensitive". 60 | If you do any rearranging of sensitive code, remember to identify sensitive 61 | cells with @hidden_cell. 62 | 63 | #### Ending with a semi-colon 64 | 65 | Statements in a notebook can end with a semi-colon. It looks like 66 | bad Python, but it is actually a trick to prevent these statements from 67 | showing their result in the output. 68 | 69 | #### if DEBUG 70 | 71 | A DEBUG boolean and 'if' statements can be used throughout the notebook 72 | wherever some print statements are handy during development and might be 73 | handy in the future, but are not something you want to share in the final 74 | output. 75 | 76 | #### %%capture captured_io 77 | 78 | "%%capture captured_io" magic can be used to capture the output when nothing 79 | else works. You can use that to hide the "!pip install" output and add a cell 80 | right after it that will print the captured output if DEBUG is True. 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | # Maintainers Guide 2 | 3 | This guide is intended for maintainers - anybody with commit access to one or 4 | more Code Pattern repositories. 5 | 6 | ## Methodology 7 | 8 | This repository does not have a traditional release management cycle, but 9 | should instead be maintained as as a useful, working, and polished reference at 10 | all times. While all work can therefore be focused on the master branch, the 11 | quality of this branch should never be compromised. 12 | 13 | The remainder of this document details how to merge pull requests to the 14 | repositories. 15 | 16 | ## Merge approval 17 | 18 | The project maintainers use LGTM (Looks Good To Me) in comments on the pull 19 | request to indicate acceptance prior to merging. A change requires LGTMs from 20 | two project maintainers. If the code is written by a maintainer, the change 21 | only requires one additional LGTM. 22 | 23 | ## Reviewing Pull Requests 24 | 25 | We recommend reviewing pull requests directly within GitHub. This allows a 26 | public commentary on changes, providing transparency for all users. When 27 | providing feedback be civil, courteous, and kind. Disagreement is fine, so long 28 | as the discourse is carried out politely. If we see a record of uncivil or 29 | abusive comments, we will revoke your commit privileges and invite you to leave 30 | the project. 31 | 32 | During your review, consider the following points: 33 | 34 | ### Does the change have positive impact? 35 | 36 | Some proposed changes may not represent a positive impact to the project. Ask 37 | whether or not the change will make understanding the code easier, or if it 38 | could simply be a personal preference on the part of the author (see 39 | [bikeshedding](https://en.wiktionary.org/wiki/bikeshedding)). 40 | 41 | Pull requests that do not have a clear positive impact should be closed without 42 | merging. 43 | 44 | ### Do the changes make sense? 45 | 46 | If you do not understand what the changes are or what they accomplish, ask the 47 | author for clarification. Ask the author to add comments and/or clarify test 48 | case names to make the intentions clear. 49 | 50 | At times, such clarification will reveal that the author may not be using the 51 | code correctly, or is unaware of features that accommodate their needs. If you 52 | feel this is the case, work up a code sample that would address the pull 53 | request for them, and feel free to close the pull request once they confirm. 54 | 55 | ### Does the change introduce a new feature? 56 | 57 | For any given pull request, ask yourself "is this a new feature?" If so, does 58 | the pull request (or associated issue) contain narrative indicating the need 59 | for the feature? If not, ask them to provide that information. 60 | 61 | Are new unit tests in place that test all new behaviors introduced? If not, do 62 | not merge the feature until they are! Is documentation in place for the new 63 | feature? (See the documentation guidelines). If not do not merge the feature 64 | until it is! Is the feature necessary for general use cases? Try and keep the 65 | scope of any given component narrow. If a proposed feature does not fit that 66 | scope, recommend to the user that they maintain the feature on their own, and 67 | close the request. You may also recommend that they see if the feature gains 68 | traction among other users, and suggest they re-submit when they can show such 69 | support. 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Orchestrate data science workflows using Node-RED 2 | 3 | ### Create a web interface using Node-RED to trigger an IBM Watson Studio analytics workflow 4 | 5 | > Data Science Experience is now Watson Studio. Although some images in this code pattern may show the service as Data Science Experience, the steps and processes will still work. 6 | 7 | IBM Watson Studio can be used to analyze data using Jupyter notebooks. There is no mechanism exposed by Watson Studio to trigger execution of the notebook cells from outside. If this capability is added, we can build a complete end to end analytics solution using IBM Watson Studio. 8 | 9 | The below two requirements are addressed by this journey to help build a complete analytics solution with IBM Watson Studio. 10 | * Trigger the execution of Python code in a Jupyter Notebook on IBM Watson Studio from a custom web user interface 11 | * Visualize the response from the Python code execution in a Jupyter Notebook on IBM Watson Studio on the custom web user interface 12 | 13 | We will use [Node-RED](https://nodered.org/) to invoke the analytics workflows in Jupyter notebooks on IBM Watson Studio and also to render a custom web user-interface with minimal programming. 14 | 15 | #### What is Node-RED? 16 | 17 | Node-RED is a tool for wiring together APIs and online services on IBM Cloud. The APIs and online services are configured as nodes that can be wired to orchestrate a workflow. It is also a web server where the UI solution can be deployed. It has nodes that support integration with many database services, watson services and analytics services. 18 | 19 | Node-RED reduces a lot of development effort. It is easy to improve the solution using other services with Node-RED. It opens a world of possibilities for developers. 20 | 21 | When the reader has completed this journey, they will understand how to: 22 | 23 | * Create and run a Jupyter notebook in Watson Studio. 24 | * Use Object Storage to access data files. 25 | * Use Python Pandas to derive insights on the data. 26 | * Develop a custom web user interface using Node-RED. 27 | * Triggering an analytics workflow on Watson Studio from the UI using Node-RED. 28 | 29 | The intended audience for this journey are developers who want to develop a complete analytics solution on Watson Studio with a custom web user interface. 30 | 31 | ![](doc/source/images/architecture.png) 32 | 33 | 1. The Object storage stores the data. 34 | 2. Data is utilized as csv files. 35 | 3. The Jupyter notebook processes the data and generates insights. 36 | 4. The Jupyter notebook is powered by Spark. 37 | 5. The Node-RED hosts a websocket server that is a medium of communication between the Jupyter notebook on IBM Watson Studio and Web UI. 38 | 6. The Node-RED hosts a web server that renders the Web UI. 39 | 40 | ## Included components 41 | 42 | * [Node-RED](https://cloud.ibm.com/catalog/starters/node-red-starter): Node-RED is a programming tool for wiring together APIs and online services. 43 | 44 | * [IBM Watson Studio](https://www.ibm.com/cloud/watson-studio): Analyze data using RStudio, Jupyter, and Python in a configured, collaborative environment that includes IBM value-adds, such as managed Spark. 45 | 46 | * [IBM Cloud Object Storage](https://cloud.ibm.com/catalog/services/cloud-object-storage): An IBM Cloud service that provides an unstructured cloud data store to build and deliver cost effective apps and services with high reliability and fast speed to market. 47 | 48 | * [Jupyter Notebooks](https://jupyter.org/): An open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. 49 | 50 | ## Featured technologies 51 | 52 | * [Data Science](https://medium.com/ibm-data-science-experience/): Systems and scientific methods to analyze structured and unstructured data in order to extract knowledge and insights. 53 | 54 | 55 | # Watch the Video 56 | 57 | [![](https://img.youtube.com/vi/hiYSYOgi1GM/0.jpg)](https://youtu.be/hiYSYOgi1GM) 58 | 59 | # Steps 60 | 61 | Follow these steps to setup and run this developer journey. The steps are 62 | described in detail below. 63 | 64 | 1. [Sign up for Watson Studio](#1-sign-up-for-watson-studio) 65 | 1. [Create IBM Cloud services](#2-create-ibm-cloud-services) 66 | 1. [Import the Node-RED flow](#3-import-the-node-red-flow) 67 | 1. [Note the websocket URL](#4-note-the-websocket-url) 68 | 1. [Update the websocket URL in HTML code](#5-update-the-websocket-url-in-html-code) 69 | 1. [Create the notebook](#6-create-the-notebook) 70 | 1. [Add the data](#7-add-the-data) 71 | 1. [Update the notebook with service credentials and websocket URL](#8-update-the-notebook-with-service-credentials-and-websocket-url) 72 | 1. [Run the notebook](#9-run-the-notebook) 73 | 1. [Analyze the results](#10-analyze-the-results) 74 | 75 | ## 1. Sign up for Watson Studio 76 | 77 | Sign up for IBM's [Watson Studio](https://dataplatform.cloud.ibm.com/). By signing up for Watson Studio, an Object Storage service will be created in your IBM Cloud account. 78 | 79 | ## 2. Create IBM Cloud services 80 | 81 | * Create the [Node-RED Starter application](https://cloud.ibm.com/catalog/starters/node-red-starter). 82 | * Choose an appropriate name for the Node-RED application - `App name:`. 83 | * Click on `Create`. 84 | 85 | * [**Node-RED Starter**](https://cloud.ibm.com/catalog/starters/node-red-starter) 86 | 87 | ![](doc/source/images/bluemix_service_nodered.png) 88 | 89 | * On the newly created Node-RED application page, Click on `Visit App URL` to launch the Node-RED editor once the application is in `Running` state. 90 | * On the `Welcome to your new Node-RED instance on IBM Cloud` screen, Click on `Next`. 91 | * On the `Secure your Node-RED editor` screen, enter a username and password to secure the Node-RED editor and click on `Next`. 92 | * On the `Browse available IBM Cloud nodes` screen, click on `Next`. 93 | * On the `Finish the install` screen, click on Finish. 94 | * Click on `Go to your Node-RED flow editor`. 95 | 96 | ## 3. Import the Node-RED flow 97 | 98 | * [Clone this repo](https://github.com/IBM/node-red-dsx-workflow). 99 | * Navigate to the [orchestrate_dsx_workflow.json](https://github.com/IBM/node-red-dsx-workflow/blob/master/node-red-flow/orchestrate_dsx_workflow.json). 100 | * Open the file with a text editor and copy the contents to Clipboard. 101 | * On the Node-RED flow editor, click the Menu and select `Import` -> `Clipboard` and paste the contents. 102 | 103 | ![](doc/source/images/import_nodered_flow.png) 104 |
105 |
106 | 107 | #### Deploy the Node-RED flow by clicking on the `Deploy` button 108 | 109 | ![](doc/source/images/deploy_nodered_flow.png) 110 | 111 | ## 4. Note the websocket URL 112 | 113 | ![](doc/source/images/note_websocket_url.png) 114 | 115 | The websocket URL is ws://``/ws/orchestrate where the `NODERED_BASE_URL` is the marked portion of the URL in the above image. 116 | ### Note: 117 | An example websocket URL for a Node-RED app with name `myApp` is `ws://myApp.mybluemix.net/ws/orchestrate`, where `myApp.mybluemix.net` is the `NODERED_BASE_URL`. 118 | 119 | The `NODERED_BASE_URL` may have additional region information i.e. `eu-gb` for the UK region. In this case `NODERED_BASE_URL` would be: `myApp.eu-gb.mybluemix.net`. 120 | 121 | ## 5. Update the websocket URL in HTML code 122 | 123 | Click on the node named `HTML`. 124 | ![](doc/source/images/html_node.png) 125 | 126 | Click on the HTML area and search for `ws:` to locate the line where the websocket URL is specified. 127 | Update the websocket URL with the base URL that was noted in the [Section 4](#4-note-the-websocket-url): 128 | 129 | var websocketURL = "ws://NODERED_BASE_URL/ws/orchestrate"; 130 | 131 | ![](doc/source/images/update_html_websocket_url.png) 132 | 133 | Click on `Done` and re-deploy the flow. 134 | 135 | ## 6. Create the notebook 136 | 137 | * In [Watson Studio](https://dataplatform.cloud.ibm.com/), click on `Create notebook` to create a notebook. 138 | * Create a project if necessary, provisioning an object storage service if required. 139 | * In the `Assets` tab, select the `Create notebook` option. 140 | * Select the `From URL` tab. 141 | * Enter a name for the notebook. 142 | * Optionally, enter a description for the notebook. 143 | * Enter this Notebook URL: https://github.com/IBM/node-red-dsx-workflow/blob/master/notebooks/node_red_dsx_workflow.ipynb 144 | * Select the free Anaconda runtime. 145 | * Click the `Create` button. 146 | 147 | ![](doc/source/images/create_notebook_from_url.png) 148 | 149 | ## 7. Add the data 150 | 151 | #### Add the data to the notebook 152 | 153 | * Please download the files - `summer.csv` and `dictionary.csv` from: 154 | https://www.kaggle.com/the-guardian/olympic-games. 155 | * Rename the file `summer.csv` to `olympics.csv` 156 | * From your project page in Watson Studio, click `Find and Add Data` (look for the `10/01` icon) 157 | and its `Files` tab. 158 | * Click `browse` and navigate to where you downloaded `olympics.csv` and `dictionary.csv` on your computer. 159 | * Add the files to Object storage. 160 | 161 | ![](doc/source/images/add_file.png) 162 | 163 | ## 8. Update the notebook with service credentials and websocket URL 164 | 165 | #### Add the Object Storage credentials to the notebook 166 | 167 | * Select the cell below `2.1 Add your service credentials for Object Storage` section in the notebook to update the credentials for Object Store. 168 | * Use `Find and Add Data` (look for the `10/01` icon) and its `Files` tab. You should see the file names uploaded earlier. Make sure your active cell is the empty one created earlier. 169 | * Select `Insert to code` below `olympics.csv`. 170 | * Click `Insert Crendentials` from the drop down menu. 171 | * If the credentials are written as `credential_2` change them to `credentials_1`. 172 | 173 | ![](doc/source/images/objectstorage_credentials.png) 174 | 175 | #### Update the websocket URL in the notebook 176 | 177 | * In the cell below `6. Expose integration point with a websocket client`, update the websocket url noted in [section 4](#4-note-the-websocket-url) in the `start_websocket_listener` function. 178 | 179 | ![](doc/source/images/update_websocket_url.png) 180 | 181 | ## 9. Run the notebook 182 | 183 | When a notebook is executed, what is actually happening is that each code cell in 184 | the notebook is executed, in order, from top to bottom. 185 | 186 | Each code cell is selectable and is preceded by a tag in the left margin. The tag 187 | format is `In [x]:`. Depending on the state of the notebook, the `x` can be: 188 | 189 | * A `blank`, this indicates that the cell has never been executed. 190 | * A `number`, this number represents the relative order this code step was executed. 191 | * A `*`, this indicates that the cell is currently executing. 192 | 193 | There are several ways to execute the code cells in your notebook: 194 | 195 | * One cell at a time. 196 | * Select the cell, and then press the `Play` button in the toolbar. 197 | * Batch mode, in sequential order. 198 | * From the `Cell` menu bar, there are several options available. For example, you 199 | can `Run All` cells in your notebook, or you can `Run All Below`, that will 200 | start executing from the first cell under the currently selected cell, and then 201 | continue executing all cells that follow. 202 | * At a scheduled time. 203 | * Press the `Schedule` button located in the top right section of your notebook 204 | panel. Here you can schedule your notebook to be executed once at some future 205 | time, or repeatedly at your specified interval. 206 | 207 | For this Notebook, you can simply `Run All` cells. 208 | The websocket client will be started when you run the cell under `7. Start websocket client`. This will start the communication between the UI and the Notebook. 209 | 210 | ## 10. Analyze the results 211 | 212 | The UI can be accessed at the URL: http://``/dsxinsights. 213 | The `` is the base URL noted in section [Note the websocket URL](#4-note-the-websocket-url). 214 | 215 | ![](doc/source/images/analyze_results.png) 216 | 217 | # Troubleshooting 218 | 219 | [See DEBUGGING.md.](DEBUGGING.md) 220 | 221 | # License 222 | 223 | This code pattern is licensed under the Apache Software License, Version 2. Separate third party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1 (DCO)](https://developercertificate.org/) and the [Apache Software License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt). 224 | 225 | [Apache Software License (ASL) FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN) 226 | -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | # Note 2 | 3 | Please download the files - summer.csv and dictionary.csv from : 4 | https://www.kaggle.com/the-guardian/olympic-games. 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /doc/source/images/add_file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/add_file.png -------------------------------------------------------------------------------- /doc/source/images/analyze_results: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /doc/source/images/analyze_results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/analyze_results.png -------------------------------------------------------------------------------- /doc/source/images/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/architecture.png -------------------------------------------------------------------------------- /doc/source/images/bluemix_service_nodered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/bluemix_service_nodered.png -------------------------------------------------------------------------------- /doc/source/images/create_notebook_from_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/create_notebook_from_url.png -------------------------------------------------------------------------------- /doc/source/images/deploy_nodered_flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/deploy_nodered_flow.png -------------------------------------------------------------------------------- /doc/source/images/html_node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/html_node.png -------------------------------------------------------------------------------- /doc/source/images/import_nodered_flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/import_nodered_flow.png -------------------------------------------------------------------------------- /doc/source/images/note_websocket_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/note_websocket_url.png -------------------------------------------------------------------------------- /doc/source/images/objectstorage_credentials.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/objectstorage_credentials.png -------------------------------------------------------------------------------- /doc/source/images/update_html_websocket_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/update_html_websocket_url.png -------------------------------------------------------------------------------- /doc/source/images/update_websocket_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/node-red-dsx-workflow/48a1e19812bedf50d626cce649365748dedf604c/doc/source/images/update_websocket_url.png -------------------------------------------------------------------------------- /node-red-flow/orchestrate_dsx_workflow.json: -------------------------------------------------------------------------------- 1 | [{"id":"ec7489e8.428408","type":"websocket in","z":"5ebc6228.47110c","name":"","server":"eb24a332.8705b","client":"","x":250,"y":220,"wires":[["a922a83a.b9d1e8","8919f694.292b4"]]},{"id":"8919f694.292b4","type":"function","z":"5ebc6228.47110c","name":"","func":"msg._session=\"\";\nreturn msg;","outputs":1,"noerr":0,"x":510,"y":220,"wires":[["62586da6.706c04"]]},{"id":"a922a83a.b9d1e8","type":"debug","z":"5ebc6228.47110c","name":"","active":true,"console":"false","complete":"false","x":430,"y":140,"wires":[]},{"id":"62586da6.706c04","type":"websocket out","z":"5ebc6228.47110c","name":"","server":"eb24a332.8705b","client":"","x":760,"y":220,"wires":[]},{"id":"598d8b7e.b07be4","type":"http in","z":"5ebc6228.47110c","name":"","url":"/dsxinsights","method":"get","swaggerDoc":"","x":244,"y":383,"wires":[["d977d8ed.a8415"]]},{"id":"d977d8ed.a8415","type":"template","z":"5ebc6228.47110c","name":"HTML","field":"payload","fieldType":"msg","format":"handlebars","syntax":"plain","template":"\n\n\n\n\tInsights from DSX\n\n\t\n\n\t\n\t\n\n\t\n\n\t\n\t\n\n\n\n\n\n\t
\n\t\t

Get Insights From IBM Data Science Experience(DSX)

\n\t
\n\t
\n\t
\n\t\t\n\n\t\t
\n\t\t\t
\n\t\t\t\t \n\t\t\t\t \n\t\t\t\t

\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n \t\t\t\t

100 Medals

\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n \t\t\t\t

100 Medals

\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t
\n\t\t
\n\n\t\t
\n\t\t\t
\n\t\t\t\t \n\t\t\t\t \n\t\t\t\t

\n\t\t\t\t
\n\t\t\t
\n\t\t
\n\n\t\t
\n\t\t\t
\n\t\t\t Editions and Venues

\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t \n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t
EditionVenue
\n\t\t\t
\n\n\t\t\t
\n\t\t\t Correlation of Countries' Total Medals Tally with Population & GDP per capita

\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t \n\t\t\t\t\t\t \n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t
EditionPopulationGDP Per Capita
\n\t\t\t
\n\t\t
\n\n\t\t
\n\t\t\tView complete dataset\n\t\t\t

\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t
\n\t
\n\t
\n\n\n","x":534,"y":383,"wires":[["bf5aa683.5ae8c8"]]},{"id":"bf5aa683.5ae8c8","type":"http response","z":"5ebc6228.47110c","name":"","x":794,"y":383,"wires":[]},{"id":"ecda6565.672df","type":"comment","z":"5ebc6228.47110c","name":"Flow that creates a Web socket server ","info":"This flow creates a web socket server","x":310,"y":78,"wires":[]},{"id":"ea8dec55.298e5","type":"comment","z":"5ebc6228.47110c","name":"Flow that renders a Web UI","info":"","x":286.5,"y":325,"wires":[]},{"id":"eb24a332.8705b","type":"websocket-listener","z":"","path":"/ws/orchestrate","wholemsg":"false"}] 2 | -------------------------------------------------------------------------------- /notebooks/node_red_dsx_workflow.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Derive insights on Olympics data using Python Pandas \n", 8 | "### Expose an integration point using websockets for orchestration with Node-RED." 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "## 1. Setup\n", 16 | "To prepare your environment, you need to install some packages.\n", 17 | "\n", 18 | "### 1.1 Install the necessary packages\n", 19 | "\n", 20 | "You need the latest versions of these packages:
\n", 21 | "- websocket-client: is a python client for the Websockets.
\n", 22 | "- python-swiftclient: is a python client for the Swift API.

\n", 23 | "\n", 24 | "** Install the websocket client: **" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "!pip install websocket-client" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "** Install IBM Cloud Object Storage Client: **" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": { 47 | "scrolled": true 48 | }, 49 | "outputs": [], 50 | "source": [ 51 | "!pip install ibm-cos-sdk" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "### 1.2 Import packages and libraries\n", 59 | "\n", 60 | "Import the packages and libraries that you'll use:" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "import pandas as pd\n", 70 | "import matplotlib.pyplot as plt\n", 71 | "import json, types\n", 72 | "import websocket\n", 73 | "import _thread\n", 74 | "import time\n", 75 | "import ibm_boto3\n", 76 | "from botocore.client import Config\n", 77 | "import codecs\n", 78 | "from io import StringIO" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "## 2. Configuration\n", 86 | "\n", 87 | "Add configurable items of the notebook below" 88 | ] 89 | }, 90 | { 91 | "cell_type": "markdown", 92 | "metadata": {}, 93 | "source": [ 94 | "### 2.1 Add your service credentials for Object Storage\n", 95 | "\n", 96 | "You must create Object Storage service on IBM Cloud.\n", 97 | "To access data in a file in Object Storage, you need the Object Storage authentication credentials.\n", 98 | "Insert the Object Storage authentication credentials as credentials_1 in the following cell after \n", 99 | "removing the current contents in the cell. " 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "# @hidden_cell\n", 109 | "# The following code contains the credentials for a file in your IBM Cloud Object Storage.\n", 110 | "# You might want to remove those credentials before you share your notebook.\n", 111 | "credentials_1 = {\n", 112 | " 'IBM_API_KEY_ID': '',\n", 113 | " 'IAM_SERVICE_ID': '',\n", 114 | " 'ENDPOINT': '',\n", 115 | " 'IBM_AUTH_ENDPOINT': '',\n", 116 | " 'BUCKET': '',\n", 117 | " 'FILE': ''\n", 118 | "}" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "### 2.3 Global Variables\n", 126 | "\n", 127 | "Add global variables." 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "olympics_data_filename = 'olympics.csv'\n", 137 | "dictionary_data_filename = 'dictionary.csv'" 138 | ] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "metadata": {}, 143 | "source": [ 144 | "# 3. Persistence and Storage" 145 | ] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": {}, 150 | "source": [ 151 | "### 3.1 Configure Object Storage Client" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "cos = ibm_boto3.client('s3',\n", 161 | " ibm_api_key_id=credentials_1['IBM_API_KEY_ID'],\n", 162 | " ibm_service_instance_id=credentials_1['IAM_SERVICE_ID'],\n", 163 | " ibm_auth_endpoint=credentials_1['IBM_AUTH_ENDPOINT'],\n", 164 | " config=Config(signature_version='oauth'),\n", 165 | " endpoint_url=credentials_1['ENDPOINT'])\n", 166 | "\n", 167 | "def get_file(filename):\n", 168 | " '''Retrieve file from Cloud Object Storage'''\n", 169 | " fileobject = cos.get_object(Bucket=credentials_1['BUCKET'], Key=filename)['Body']\n", 170 | " return fileobject\n", 171 | "\n", 172 | "def load_string(fileobject):\n", 173 | " '''Load the file contents into a Python string'''\n", 174 | " text = fileobject.read()\n", 175 | " return text\n", 176 | "\n", 177 | "def put_file(filename, filecontents):\n", 178 | " '''Write file to Cloud Object Storage'''\n", 179 | " resp = cos.put_object(Bucket=credentials_1['BUCKET'], Key=filename, Body=filecontents)\n", 180 | " return resp\n", 181 | "\n", 182 | "def __iter__(self): return 0" 183 | ] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "metadata": {}, 188 | "source": [ 189 | "# 4. Data " 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "### 4.1 Prepare data\n", 197 | "Combine the olympics and dictionary data into a single dataframe:\n", 198 | "- Read olympics data from Object Storage.
\n", 199 | "- Rename columns
\n", 200 | "- Populate the data in the dictionary to the Olympics data with a merge

" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "metadata": { 207 | "scrolled": false 208 | }, 209 | "outputs": [], 210 | "source": [ 211 | "body = get_file(olympics_data_filename)\n", 212 | "# add missing __iter__ method, so pandas accepts body as file-like object\n", 213 | "if not hasattr(body, \"__iter__\"): body.__iter__ = types.MethodType( __iter__, body )\n", 214 | "olympics = pd.read_csv(body)\n", 215 | "olympics = olympics.rename(columns = {'Country':'Code'})\n", 216 | "olympics = olympics.rename(columns = {'Year':'Edition'})\n", 217 | "body = get_file(dictionary_data_filename)\n", 218 | "# add missing __iter__ method, so pandas accepts body as file-like object\n", 219 | "if not hasattr(body, \"__iter__\"): body.__iter__ = types.MethodType( __iter__, body )\n", 220 | "dictionary = pd.read_csv(body)\n", 221 | "olympics = pd.merge(olympics, dictionary, on='Code')\n", 222 | "olympics.head()" 223 | ] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "metadata": {}, 228 | "source": [ 229 | "# 5. Insights on the data using Python Pandas\n", 230 | "- Create re-usable functions" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "def get_medals_gb_year_country():\n", 240 | " \"\"\" Group by edition and country and sum medals count.\n", 241 | " \"\"\"\n", 242 | " medals_groupedBy_yearCountry = olympics.groupby(['Edition','Code']).apply(lambda country: country['Code'].count())\n", 243 | " return medals_groupedBy_yearCountry\n", 244 | "\n", 245 | "def get_medals_gb_year_country_medal():\n", 246 | " \"\"\" Group by edition, country, medal type and sum medals count.\n", 247 | " \"\"\"\n", 248 | " medals_groupedBy_yearCountryMedal = olympics.groupby(['Edition', 'Code', 'Medal']).apply(lambda country: country['Medal'].count())\n", 249 | " return medals_groupedBy_yearCountryMedal\n", 250 | "\n", 251 | "def get_medals_last_10_years(countrycode):\n", 252 | " \"\"\" Get Gold, Silver and Bronze medals for a country for last 10 editions.\n", 253 | " \"\"\"\n", 254 | " last10pics = olympics['Edition'].unique()\n", 255 | " yrs = pd.Series(last10pics).nlargest(10)\n", 256 | " df = pd.DataFrame([], columns=['Year', 'Gold', 'Silver', 'Bronze'])\n", 257 | " medalsdf = get_medals_gb_year_country_medal()\n", 258 | " \n", 259 | " for yr in yrs:\n", 260 | " medaltally = medalsdf[yr][countrycode]\n", 261 | " gold = 0\n", 262 | " silver = 0\n", 263 | " bronze = 0\n", 264 | " if 'Gold' in medaltally:\n", 265 | " gold = medaltally['Gold']\n", 266 | " if 'Silver' in medaltally:\n", 267 | " silver = medaltally['Silver']\n", 268 | " if 'Bronze' in medaltally:\n", 269 | " bronze = medaltally['Bronze']\n", 270 | " df1 = pd.DataFrame([[yr,gold, silver, bronze]], columns=['Year', 'Gold', 'Silver', 'Bronze'])\n", 271 | " df = df.append(df1, ignore_index=True) \n", 272 | " df = df.sort_values(by=['Year'], ascending=True) \n", 273 | " df = df.reset_index()\n", 274 | " del df['index']\n", 275 | " return df\n", 276 | "\n", 277 | "def get_correlation_medalstally():\n", 278 | " \"\"\" Get correlation between the medals tally and population, GDP per capita.\n", 279 | " \"\"\"\n", 280 | " df = get_medals_gb_year_country()\n", 281 | " values = get_all_olympic_years().values\n", 282 | " size = values.size\n", 283 | " correlations = []\n", 284 | " for i in range(size):\n", 285 | " year = values[i][0]\n", 286 | " df1 = df[year].to_frame(name=\"Tally\")\n", 287 | " df1 = df1.reset_index()\n", 288 | " df2 = pd.merge(df1,dictionary, on='Code')\n", 289 | " corrpop = df2.corr().values[0][1]\n", 290 | " corrgdp = df2.corr().values[0][2]\n", 291 | " resp = {\"Year\": year, \"Population\":corrpop, \"GDP\":corrgdp}\n", 292 | " correlations.append(resp)\n", 293 | " return correlations \n", 294 | "\n", 295 | "def get_medals_category(countrycode, year):\n", 296 | " \"\"\" Get the medals count in different sports category for a country in an edition.\n", 297 | " \"\"\"\n", 298 | " df = olympics[olympics['Edition'] == year]\n", 299 | " df1 = df[df['Code'] == countrycode]\n", 300 | " df2 = df1.groupby(['Sport']).apply(lambda country: country['Medal'].count())\n", 301 | " return df2\n", 302 | "\n", 303 | "def get_medals_category_all(countrycode): \n", 304 | " \"\"\" Get the medals count in different sports category for a country for last ten editions.\n", 305 | " \"\"\"\n", 306 | " df1 = olympics[olympics['Code'] == countrycode]\n", 307 | " df2 = df1.groupby(['Sport']).apply(lambda country: country['Medal'].count())\n", 308 | " return df2\n", 309 | "\n", 310 | "def get_top_ten_gold_tally(year):\n", 311 | " \"\"\" Get the top ten gold medal winning countries in an edition.\n", 312 | " \"\"\"\n", 313 | " df = olympics[olympics['Edition'] == year]\n", 314 | " df1 = df[df['Medal'] == 'Gold']\n", 315 | " df2 = df1.groupby(['Code']).apply(lambda country: country['Medal'].count())\n", 316 | " return df2\n", 317 | "\n", 318 | "def get_top_ten_total_tally(year):\n", 319 | " \"\"\" Get the top ten total medal winning countries in an edition.\n", 320 | " \"\"\"\n", 321 | " df = olympics[olympics['Edition'] == year]\n", 322 | " df1 = df.groupby(['Code']).apply(lambda country: country['Medal'].count())\n", 323 | " return df1\n", 324 | "\n", 325 | "def get_year_venue():\n", 326 | " \"\"\" Get edition venue matrix.\n", 327 | " \"\"\"\n", 328 | " df = olympics[['Edition', 'City']]\n", 329 | " df = df.drop_duplicates()\n", 330 | " df = df.reset_index()\n", 331 | " df = df.set_index('Edition')\n", 332 | " del df['index']\n", 333 | " return df.sort_index()\n", 334 | "\n", 335 | "def get_all_olympic_years():\n", 336 | " \"\"\" Get list of all olympic editions.\n", 337 | " \"\"\"\n", 338 | " df = olympics['Edition']\n", 339 | " df = df.drop_duplicates()\n", 340 | " df = df.reset_index()\n", 341 | " del df['index']\n", 342 | " return df.sort_index()\n", 343 | "\n", 344 | "def get_all_countries():\n", 345 | " \"\"\" Get list of all countries.\n", 346 | " \"\"\"\n", 347 | " df = olympics[['Code','Country']]\n", 348 | " df = df.drop_duplicates()\n", 349 | " df = df.reset_index()\n", 350 | " del df['index']\n", 351 | " return df.sort(['Country'],ascending=[True])\n", 352 | "\n", 353 | "def get_country_edition_data(countrycode,edition):\n", 354 | " \"\"\" Get data for a country and edition.\n", 355 | " \"\"\"\n", 356 | " df = olympics[olympics[\"Code\"] == countrycode]\n", 357 | " df1 = df[df[\"Edition\"] == edition]\n", 358 | " return df1" 359 | ] 360 | }, 361 | { 362 | "cell_type": "markdown", 363 | "metadata": {}, 364 | "source": [ 365 | "# 6. Expose integration point with a websocket client " 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": null, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "def on_message(ws, message):\n", 375 | " print(message)\n", 376 | " msg = json.loads(message)\n", 377 | " cmd = msg['cmd']\n", 378 | " \n", 379 | " if cmd == 'MBY':\n", 380 | " country = msg['country']\n", 381 | " tally = get_medals_last_10_years(country) \n", 382 | " tallyarray=[]\n", 383 | " for i, row in tally.iterrows():\n", 384 | " medaltally = {\"Year\":int(row[\"Year\"]),\n", 385 | " \"Gold\":int(row[\"Gold\"]),\n", 386 | " \"Silver\":int(row[\"Silver\"]),\n", 387 | " \"Bronze\":int(row[\"Bronze\"])}\n", 388 | " tallyarray.append(medaltally)\n", 389 | " wsresponse = {}\n", 390 | " wsresponse[\"forcmd\"] = \"MBY\" \n", 391 | " wsresponse[\"response\"] = tallyarray\n", 392 | " ws.send(json.dumps(wsresponse))\n", 393 | " elif cmd == 'MBSC':\n", 394 | " country = msg['country']\n", 395 | " year = 2008\n", 396 | " response = get_medals_category(country, year)\n", 397 | " \n", 398 | " ct = response.count()\n", 399 | " if ct > 5:\n", 400 | " response = response.nlargest(5) \n", 401 | " \n", 402 | " medals = []\n", 403 | " categories = []\n", 404 | " for i, row in response.iteritems():\n", 405 | " categories.append(i)\n", 406 | " medals.append(row) \n", 407 | " \n", 408 | " wsresponse = {}\n", 409 | " wsresponse[\"forcmd\"] = \"MBSC\"\n", 410 | " wsresponse[\"response\"] = { \"categories\":categories, \"medals\":medals} \n", 411 | " ws.send(json.dumps(wsresponse))\n", 412 | " elif cmd == 'MBSA':\n", 413 | " country = msg['country']\n", 414 | " response = get_medals_category_all(country)\n", 415 | " \n", 416 | " ct = response.count()\n", 417 | " if ct > 5:\n", 418 | " response = response.nlargest(5) \n", 419 | " \n", 420 | " medals = []\n", 421 | " categories = []\n", 422 | " for i, row in response.iteritems():\n", 423 | " categories.append(i)\n", 424 | " medals.append(row) \n", 425 | " \n", 426 | " wsresponse = {}\n", 427 | " wsresponse[\"forcmd\"] = \"MBSA\"\n", 428 | " wsresponse[\"response\"] = { \"categories\":categories, \"medals\":medals} \n", 429 | " ws.send(json.dumps(wsresponse)) \n", 430 | " elif cmd == 'T10G':\n", 431 | " edition = msg[\"edition\"]\n", 432 | " response = get_top_ten_gold_tally(edition)\n", 433 | " ct = response.count()\n", 434 | " if ct > 10:\n", 435 | " response = response.nlargest(10)\n", 436 | " medals = []\n", 437 | " for i, row in response.iteritems():\n", 438 | " data = {\"country\":i,\"tally\":row}\n", 439 | " medals.append(data) \n", 440 | " wsresponse = {}\n", 441 | " wsresponse[\"forcmd\"] = \"T10G\"\n", 442 | " wsresponse[\"response\"] = medals \n", 443 | " print(wsresponse)\n", 444 | " ws.send(json.dumps(wsresponse)) \n", 445 | " elif cmd == 'T10M':\n", 446 | " year = msg[\"edition\"]\n", 447 | " response = get_top_ten_total_tally(year)\n", 448 | " ct = response.count()\n", 449 | " if ct > 10:\n", 450 | " response = response.nlargest(10)\n", 451 | " medals = []\n", 452 | " for i, row in response.iteritems():\n", 453 | " data = {\"country\":i,\"tally\":row}\n", 454 | " medals.append(data) \n", 455 | " wsresponse = {}\n", 456 | " wsresponse[\"forcmd\"] = \"T10M\"\n", 457 | " wsresponse[\"response\"] = medals \n", 458 | " print(wsresponse)\n", 459 | " ws.send(json.dumps(wsresponse)) \n", 460 | " elif cmd == 'CORR':\n", 461 | " corr = get_correlation_medalstally() \n", 462 | " wsresponse = {}\n", 463 | " wsresponse[\"forcmd\"] = \"CORR\"\n", 464 | " wsresponse[\"response\"] = corr\n", 465 | " ws.send(json.dumps(wsresponse)) \n", 466 | " elif cmd == 'YV': \n", 467 | " yearvenue = get_year_venue()\n", 468 | " yearvenuearray = []\n", 469 | " for i in range(yearvenue.size):\n", 470 | " value = {\"Year\":yearvenue.index[i],\"Venue\":yearvenue.values[i].tolist()[0]}\n", 471 | " yearvenuearray.append(value)\n", 472 | " responsejson = {}\n", 473 | " responsejson[\"forcmd\"]=\"YV\"\n", 474 | " responsejson[\"response\"]=yearvenuearray\n", 475 | " ws.send(json.dumps(responsejson)) \n", 476 | " elif cmd == 'DATA':\n", 477 | " country = msg['country']\n", 478 | " edition = msg['edition']\n", 479 | " olympicsslice = get_country_edition_data(country,edition)\n", 480 | " data = []\n", 481 | " numofcolumns = olympicsslice.columns.size\n", 482 | " cols = []\n", 483 | " values = []\n", 484 | " for column in olympicsslice.columns:\n", 485 | " cols.append(column)\n", 486 | " for value in olympicsslice.values:\n", 487 | " values.append(value.tolist()) \n", 488 | " data = {\"cols\":cols,\"vals\":values} \n", 489 | " responsejson = {}\n", 490 | " responsejson['forcmd']='DATA'\n", 491 | " responsejson['response']= data\n", 492 | " ws.send(json.dumps(responsejson)) \n", 493 | " elif cmd == 'EDITIONS':\n", 494 | " years = get_all_olympic_years()\n", 495 | " yearsarray = []\n", 496 | " for i,row in years.iteritems():\n", 497 | " for value in row:\n", 498 | " yearsarray.append(value)\n", 499 | " length = len(yearsarray)\n", 500 | " wsresponse = []\n", 501 | " for i in range(length):\n", 502 | " year = {\"text\":yearsarray[i],\"value\":yearsarray[i]}\n", 503 | " wsresponse.append(year)\n", 504 | " responsejson = {}\n", 505 | " responsejson['forcmd']='EDITIONS'\n", 506 | " responsejson['response']= wsresponse \n", 507 | " ws.send(json.dumps(responsejson)) \n", 508 | " elif cmd == 'COUNTRIES':\n", 509 | " countries = get_all_countries()\n", 510 | " countriesarray = []\n", 511 | " codearray = []\n", 512 | " for i,row in countries.iteritems():\n", 513 | " if i=='Code':\n", 514 | " for value in row:\n", 515 | " codearray.append(value)\n", 516 | " elif i=='Country': \n", 517 | " for value in row:\n", 518 | " countriesarray.append(value)\n", 519 | " length = len(codearray)\n", 520 | " wsresponse = []\n", 521 | " for i in range(length):\n", 522 | " country = {\"text\":countriesarray[i],\"value\":codearray[i]}\n", 523 | " wsresponse.append(country)\n", 524 | " responsejson = {}\n", 525 | " responsejson['forcmd']='COUNTRIES'\n", 526 | " responsejson['response']= wsresponse \n", 527 | " ws.send(json.dumps(responsejson)) \n", 528 | "\n", 529 | "def on_error(ws, error):\n", 530 | " print(error)\n", 531 | "\n", 532 | "def on_close(ws):\n", 533 | " ws.send(\"DSX Listen End\")\n", 534 | "\n", 535 | "def on_open(ws):\n", 536 | " def run(*args):\n", 537 | " for i in range(10000):\n", 538 | " hbeat = '{\"cmd\":\"Olympics DSX HeartBeat\"}'\n", 539 | " ws.send(hbeat)\n", 540 | " time.sleep(100)\n", 541 | " \n", 542 | " _thread.start_new_thread(run, ())\n", 543 | "\n", 544 | "\n", 545 | "def start_websocket_listener():\n", 546 | " websocket.enableTrace(True)\n", 547 | " ws = websocket.WebSocketApp(\"ws://NODERED_BASE_URL/ws/orchestrate\",\n", 548 | " on_message = on_message,\n", 549 | " on_error = on_error,\n", 550 | " on_close = on_close)\n", 551 | " ws.on_open = on_open\n", 552 | " ws.run_forever()" 553 | ] 554 | }, 555 | { 556 | "cell_type": "markdown", 557 | "metadata": {}, 558 | "source": [ 559 | "# 7. Start websocket client" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": null, 565 | "metadata": { 566 | "scrolled": false 567 | }, 568 | "outputs": [], 569 | "source": [ 570 | "start_websocket_listener()" 571 | ] 572 | } 573 | ], 574 | "metadata": { 575 | "kernelspec": { 576 | "display_name": "Python 3.5", 577 | "language": "python", 578 | "name": "python3" 579 | }, 580 | "language_info": { 581 | "codemirror_mode": { 582 | "name": "ipython", 583 | "version": 3 584 | }, 585 | "file_extension": ".py", 586 | "mimetype": "text/x-python", 587 | "name": "python", 588 | "nbconvert_exporter": "python", 589 | "pygments_lexer": "ipython3", 590 | "version": "3.5.4" 591 | } 592 | }, 593 | "nbformat": 4, 594 | "nbformat_minor": 1 595 | } 596 | --------------------------------------------------------------------------------