Full text
Pag. 2
Abstract In the actual climate change emergency situation several transformations and redefinitions in the systems are required. The thesis focuses in the end user of the electricity sector, specifically in the demand side management strategies. The development of a data pipeline from scratch for a Home Energy Management System is presented, with detailed explanations of the data fluxes, treatment, storage, visualization, analysis and conversion. Also the code that runs the system is provided and explained for better understanding. It is programmed in python, an open source language with powerful data libraries. The resulting program defines a standalone data collection entity that collects, treats, stores and forecasts diverse data provided by assets located in a household grid. Those assets are electrical loads, a photovoltaic array, an electric vehicle and are completed with external data sources like Spanish electricity market retail price, weather stations and specific PV libraries. All the stored data turns to be a useful resource for further analysis such forecasting and visualization purposes, real demand and production curves are plotted and compared with calculated predictions of generation and consumption. This information is refined and stored thanks to a database manager module developed that eases also the process of data extraction. The pipeline is ready to correctly feed the optimization engine of a HEMS. In addition to it the document provides useful information in REST APIs communications with known platforms such Nissan Kamereon, Fronius devices, OpenWeatherMap source and ESIOS database. There are also object oriented programming tips, explanations and examples in Python. It accounts with photovoltaic modelization using PVlib and its powerful tools and finally data storage and analysis with pandas library and pickle files. Pag. 3
Pag. 4
Table of contents Abstract 3 Table of contents 5 List of figures 8 List of tables 9 1. Preface 11 1.1 Origin of the project 11 1.2 Previous requirements 11 2. Introduction 12 2.1 Objectives of the project 14 2.2 Scope of the project 15 2.3 State of the art 15 2.4 First steps: Calculation of the potential savings 15 3. Project development 19 3.1 The database structure and the “A” flux 20 The data pipeline 20 The REST APIs 22 The “A” flux 23 3.1.1 External raw data collection and treatment 25 Weather data 25 Nissan data 28 Grid data 29 Spanish Electricity Market Price Data (ESIOS) 33 3.1.2 Data storing 35 Store_data function 36 Fill_BBDD function 38 check_BBDD_exists 39 import_BBDD 40 check_keys_dict_BBDD 40 Save_to_pickle 40 _print_ 40 3.1.3 Database fill protocol 40 3.2 “B” flux, the clean data presentation 45 3.2.1 Temporal conditioning of stored data 46 Import_BBDD 48 Extract 48 Extract_weekday 48 Pag. 5
3.2.2 Models of the system and inputs for the HEMS 49 Irradiance 49 Forecasted irradiance 52 Production forecast 53 Consumption forecast 57 Corrected weather PV model 58 3.3 The process data representation 59 3.3.1 Plotter 59 Consumption and production 60 Forecasts 64 Other plots 66 3.3.2 Scoring 70 Production forecast scoring 70 Corrected weather production model 71 Weather parameters scoring 72 Consumption forecast scoring 74 Summarized scorings 75 4. Budget 77 4.1 Costs 77 4.2 Price of the project itself 78 4.3 The final price 78 5. Environmental impact assessment 79 6. Planification 80 Conclusions and further research 81 Acknowledgements 83 Appendix 84 A Learnings 84 Git methodology 84 Python coding 85 Use of OOP 85 Modules creation 87 Multiprocessing compilation for IP searching 88 B The code 89 __main__.py 89 Data_caller.py 90 Weather.py 93 SearchIP.py 96 Fr_inverter.py 98 PVPC_prices.py 101 Pag. 6
Nissanapi.py 103 Irradiance.py 104 PV_model_singlediode.py 107 Forecaster.py 110 BBDD.py 111 Analytics.py 115 Bibliography 119 Pag. 7
List of figures Figure 2.1: Solar generation vs consumption curves source Figure 2.2: Demand side management (DSM) strategies Figure 2.3: Consumption profile base consumption and car consumption differentiated Figure 2.4: Zoom in the consumption profile with daily car charges Figure 2.5: Price curves and load curves Figure 2.6: Potential savings and total costs Figure 3.1: HEMS scheme Figure 3.2: Data pipeline scheme Figure 3.3: Sliced REST API Figure 3.4: “A” flux representation Figure 3.5: JSON current weather response example Figure 3.6: Data in dict format Figure 3.7: Weather example usage Figure 3.8: Data obtained from the electric vehicle Figure 3.9: Nissan example usage Figure 3.10: API detail Figure 3.11: Example of the naive_inverter_program.exe Figure 3.12: JSON response from the “GetPowerFlowRealtimeData” API. Some data is elided Figure 3.13: JSON response from the “GetInverterRealtimeData” API. Some data is elided Figure 3.14: Resulting dict that will be stored in the database Figure 3.15: Example of calling the functions Figure 3.16: JSON response from Esios REST API Figure 3.17: Resulting dict that will be stored in the database Figure 3.18: Examples to call the functions Figure 3.19: The storing function and how it is called Figure 3.20: store_data function logical procedure Figure 3.21: file containing all the grid information Figure 3.22: The logical process of the fill_BBDD function Figure 3.23: Procedure coded inside data_caller.py Figure 3.24: data caller attributes Figure 3.25: __main__.py code, example usage of data_caller.py Figure 3.26: Detail of the command line while collecting data with the data_caller.py Figure 3.27: “B” flux, data paths Figure 3.28: Resampling demonstrations Figure 3.29: “B” flux procedure Figure 3.30: import_BBDD example usage Figure 3.31: extract example usage Figure 3.32: extract_weekday example usage Figure 3.33: The developed models and its interrelation Figure 3.34: Irradiation components per month mean day by PVGis Figure 3.35: Clear sky Global Horizontal Irradiance (GHI) and Plane of Array irradiance (POA) Pag. 8
Figure 3.36: example of obtaining the POA irradiance for today and tomorrow Figure 3.37: POA irradiation vs effective calculated irradiation Figure 3.38: process to compute the effective irradiance Figure 3.39: Electrical circuit of the single cell model. Source= Sandia National Laboratories Figure 3.40: Data flow and orders direction of the PV model Figure 3.41: photovoltaic curves. Source: Read the docs “pvlib” Figure 3.42: usage of apply method with the massive_rounder function Figure 3.43: Group by method Figure 3.44: Example of a data representation code Figure 3.45: Consumption of a monday Figure 3.46: Consumption of a sunday Figure 3.47: Consumption of a sunday code Figure 3.48: Consumption vs production for a sunny day Figure 3.49: Consumption vs production for a cloudy day Figure 3.50: Consumption vs production for a cloudy day code Figure 3.51: Consumption and generation for 5 days with missing values. Figure 3.52: Forecasted consumption vs real consumption Figure 3.53: Production forecast vs corrected forecast and real production Figure 3.54: Car plug and charging status and the state of charge Figure 3.55: The net power balance of the system Figure 3.56: Grid voltage and frequency parameters Figure 3.57: Real vs modeled array DC voltage Figure 3.58: Temperatures Figure 3.59: Wind speed and cloudiness index from the current weather database Figure 3.60: Code for scoring Figure 3.61: Code for production forecast scoring Figure 3.62: Production scoring graph for 18 days Figure 3.63: Production corrected weather scoring graph for 16 days Figure 3.64: Cloudiness index for the last 16 days current vs forecasted Figure 3.65: Temperatures for the last 16 days current vs forecasted Figure 3.66: Wind speeds for the last 16 days current vs forecasted Figure 3.67: Load scoring code Figure 3.68: Consumption for the last 16 days the real vs the forecasted Figure 6.1: First part of the planification of the project Figure 6.2: Second part of the project planification List of tables Table 3.1: The parameters and inputs for the PV model compilation Table 3.2 : Forecast scoring Table 3.3: Energy bias Table 4.1: Project costs Table 4.2: Final invoice Table 5.1: Environmental impact calculations Pag. 9
The load curve can be observed below in figure 2.3 and highlighted in orange when the car is charging. Figure 2.3: Consumption profile base consumption and car consumption differentiated As can be observed the effect of the car is clear in the consumption, the hourly charging profile of the car is necessary to have an idea of the amount of energy it consumes daily. Figure 2.4: Zoom in the consumption profile with daily car charges The mean consumption of the car is 14,3 kWh per day. With this information an optimization model is developed in an spreadsheet, then the optimal scheduling of the car is found for each tariff. Later on the estimated savings are calculated comparing different options between them. The options are divided in two categories of three options each. The categories are car scheduling and contracted tariff. There exist 3 options for car scheduling, the actual one, the optimal (calculated for each tariff) and the worst one (calculated for each tariff). There exist also 3 tariffs that are 2.0, 2.0DHA and 2.0DHS. The first tariff doesn’t makes special difference in the price among the day, the second has two prices for night and day and the third has “3” levels of prices but not very pronounced. In figure 2.5 there is a representation of the variation of tariffs 2.0DHA and DHS and 3 consumption profiles for the DHS tariff. Pag. 16
Figure 2.5: Price curves and load curves Note that for the optimal case the car recharges are when the lowest prices appear. After calculating all the possibilities a table is done to see the potential annual savings: Figure 2.6: Potential savings and total costs The table shows all the possibilities but summarizing this results the potential savings can of almost 400 € per year with the DHS tariff and the optimal scheduling. The reality is that by default the car recharge hardly ever will be on the worst scenario so has to be compared with a baseline. In this case the user is conscious that the prices are lower at night with its Pag. 17
tariff (DHA) so its potential savings are only of 27 € per year. If the user would have a more common tariff like 2.0A its potential savings would be of 340 €. With the important benefits of the DSM in the renewables integration and the additional possibility of reducing costs the implementation of HEMS would be a part of the energy transition. The project starts conceptualizing the parts of the HEMS and focuses in one part of it. Pag. 18
3. Project development The HEMS for the studied case is conceptualized and has some differentiated areas, these areas well interconnected between them would end in a functional device. The following figure shows the scheme of the HEMS. Figure 3.1: HEMS scheme In figure 3.1 it is seen that a “Main” module controls the different areas of the HEMS, it actively executes the code of them when it has to. The five areas are: - Data extractors and treatment - Models - Optimization - Actuators controller - Analytics An additional element is the database it is executed for the different modules that make up the five areas, it is not directly compiled by the “Main” module. When each area has to work it demands to the database the required data to perform its tasks and return several outputs of different nature. These outputs can be more data which is stored in the database, plots and other visualization types which are displayed in a screen and electrical signals that control the different actuators of the system. The dotted lines in the figure represent the data fluxes, the legend of colours represents: - Red represent the “A” flux, the process to store data from scratch. - Yellow represent a part of the “A” flux which is not implemented yet. Pag. 19
- Blue represent the “B” flux, when the data is queried to the database to perform analysis and visualization. - Green represent the “B” fluxes that are still not implemented. This device has to work autonomously and the visualization is the tool to present to the end user the achieved milestones of it and the current status. Its purpose is to manage efficiently the energy in order to provide the desired comfort and at the same time save energy, save money, help to grid adjustment and a long etcetera. 3.1 The database structure and the “A” flux The data pipeline The data pipeline is the basis that will enable the consecution of the objectives described in 2.1. A data pipeline is: “A software that eliminates many manual steps from the process and enables a smooth, automated flow of data [...]. It automates the processes involved in extracting, transforming, combining, validating, and loading data for further analysis and visualization.” Source: Alooma [10] Hence in this project it is seen as the structure of it, the shape it will take is the one observed in figure 3.2. Figure 3.2: Data pipeline scheme . Source [11] Its main parts are: Data ingestion First of all, in a data pipeline there is a step called Data ingestion which is in charge to run the so called extractors that will collect the data, the extractors can be called also as Node JS scripts. In our case the information comes from different online data sources and existing local sensors. Pag. 20
Data storage When the data it directly collected from the main source it has the name of raw data. That is because, usually for the final objective, the data extracted will not match exactly our needs. Hence, this data has to be is transformed, usually from a format to another and also from one type to another. Finally, it can also be enriched with more relevant data for our project that is not implicitly given by the same data source, but can be obtained from the rest of the data. Those three steps happened in what is called a data lake which is a repository where all the cleaned and structured information is stored and organized in a plane way, but not our raw data. In the document we refer to this repository as local database or simply database. The repository is locally saved in a pickle file [12], which allows a fast and compressed data management as can be seen in [13]. Compared with other file formats also offers a safe format storage by eliminating the errors when uploading the data, this problem usually happens with data time formats. Data warehouse The date the warehouse is a hierarchical way to store the data it usually moves data in batches every scheduled time. It is used when the data is not necessary to be streamed. In the actual case the data is moving enough often to make prescindible the data warehouse. At a high level DSM in an aggregation of several HEMS in a community would be necessary for high level requirements and decision taking. Visualization The data in the data lake is ready to be extracted or queried, a query table is a piece of a table stored in the database, just the piece needed for the analysis to perform or the expected visualization. Visualizing is important, maybe in automated systems such a HEMS is not imprescindible for the decision making but is crucial for reporting results and determining the improvement points. Also is a good support to report results and offer a better user friendly platform to the final user. Forecasting A very interesting analysis with the stored data is to perform forecasts. They are done with more or less complex model of a system or a part of the system and have to be provided with well treated data. This data treatment is usually temporal since the time is the most used independent variable in engineering models but not the only one. Mixing data from different sources and therefore stored in different tables requires temporal synchronization before starting the analysis. The results of this forecasting may be susceptible of being stored for future analysis such calculation of scoring values for later comparisons. In this project all of them are stored. Optimization (out of the scope) As stated in figure 3.1 for an automated exploitation of the energy home system a HEMS is necessary. This element has an important part which is called the optimization, in it a mathematical optimization is compiled with its restraints and objective function, which can differ a lot between different purposes. This optimization module has to be fed with some forecasts and models of the elements composing the system. With all this information a day Pag. 21
can be simulated and with it some decisions can be taken to achieve the maximization or minimization of the objective function. This module is out of the scope of the project and presents its own challenges, the challenge of this project is to be able to provide the information to it. The REST APIs An API is an Application Programming Interface, a code to access to functions of a determined external software. They are published by the software builders to let access third parties with only detailing how to do it and the functionality it brings, without explaining procedures. They are used by developers and allow to include functionalities without having to develop them from scratch and with the certainty of using a code that is tested and with proven effectiveness. In the web the theory is the same, obtaining functionalities and information of softwares that are not in the local system. The type of APIs that we are interested in are the REST (REpresentational State Transfer) APIs based on HTTP [14]. Those APIs have specific purposes such the ones listed below: - GET, obtain information - POST, give information or send order - PUT, modify - PATCH, modify partially - DELETE, delete The calls to these APIs will be performed in python, which has an specific module to perform these requests. The library is called “requests” and to do a “GET” request it is necessary to have the HTTP url and code the following lines: import requests endpoint='http://'+inv_IP+'/' get_archives='solar_api/v1/GetPowerFlowRealtimeData.fcgi' response = requests.get(url = endpoint+get_archives) Data = response.json() Note that the requests class has a method called “get” where the different inputs has to be inserted. In this case the url is composed by two strings called “endpoint” and “get_archives”, those names are just extracted from the documentation of the API, are not really important, could be “a” and “b”. Each one use its methodology when created and the construction can differ a bit, an example of an sliced get request is shown below. Pag. 22
Figure 3.3: Sliced REST API All the APIs has documentation, it is important to read it carefully in order to understand how they are constructed and to perform requests on them. Some demand extra parameters such authentication to access the data, it’s the case of the electric vehicle platform. This process is hard to follow and instead of developing it from scratch a fork of another code is done and then adapted to the project [15]. Finally the response is an object that has a method to convert the information into JSON object which is easily readable and the desired information can be extracted. The “A” flux The “A” flux is the name given to the path the data take until they are correctly stored in tables. With the objective of doing it as robust as possible some format protocol is determined. Thanks to it the database structure can be reused for other projects or easily enlarge the current project by adding external data providers such sensors or external databases. In figure 3.4 the protocol is graphically explained and some hints of format can be seen. The continuous arrows represent which block is calling which and the discontinuous arrows the path the data is taking. The terse description in the middle of the arrows reveal the data format changes. Pag. 23
Figure 3.4: “A” flux representation Pag. 24
In the following chapters, each protocol is explained in detail, according to its main objective and the data involved in the process. 3.1.1 External raw data collection and treatment The main data collection is divided in the four modules , according to Figure 3.4. All this data is obtained from several REST APIs. The base URL of them is shown below: 'https://alliance-platform-caradapter-prod.apps.eu.kamereon.io/car-adapt er/' 'https://prod.eu.auth.kamereon.org/kauth/' 'http://192.168.1.143/solar_api/v1/GetPowerFlowRealtimeData.fcgi' 'http://192.168.1.143/solar_api/v1/GetInverterRealtimeData.cgi?' 'http://api.openweathermap.org/data/2.5/forecast?' 'http://api.openweathermap.org/data/2.5/weather?' 'https://api.esios.ree.es/application/json/api.esios.ree.es/' The codification structure is similar in every script but with little changes due to programming learnings. The object oriented programming is the methodology used to develop it. Each script contains a class with the necessary functions to collect the data and process it (3.1.1 External raw data collection and treatment) and to call the modules to store the data (3.1.2 Data storing). The OOP is a programming paradigm which is not the fastest in terms of computational speed but allows a useful and visual logical organization of the code. The code is structured in classes that are object builders, so the program generates objects that are representations of the real world. Each object has each own methods that are the functions it can perform, and attributes that define the specific object. For example a class called printer creates an object of type printer with its own attributes that can be for example name “printer of the second floor” and colours “black/white”. This printer object has a method called “print” and when it is invoked it prints. More information on how to code with the OOP approach in the A learnings appendix. Now exclusively concerning on this chapter the following sections present the APIs used and the data obtained and the aspect of its transformation. Weather data In the script weather.py a class called “weather” is defined, in it one function is in charge of calling the following APIs (code available in the appendix B): 'http://api.openweathermap.org/data/2.5/forecast?lat={LAT}&lon={LON}&app id={TOKEN KEY}&lang=ca' Pag. 25
"IDC" : { "Unit" : "A", "Value" : 6.75 }, "PAC" : { "Unit" : "W", "Value" : 2612 }, "TOTAL_ENERGY" : { "Unit" : "Wh", "Value" : 2048214.1200000001 }, "UAC" : { "Unit" : "V", "Value" : 239.80000000000001 }, "UDC" : { "Unit" : "V", "Value" : 392 }, "YEAR_ENERGY" : { "Unit" : "Wh", "Value" : 2048214.3799999999 } } }, "Head" : { "RequestArguments" : { ... }, "Status" : { ... }, "Timestamp" : "2020-06-01T17:38:03+02:00" } } Figure 3.13: JSON response from the “GetInverterRealtimeData” API. Some data is elided Two functions are implemented to transform the data, they are called “power_flows” (only returns the power flows data and don’t store it into the database, and the “grid_data” function which actually calls the previous function, combines the data and returns the following dict: [{'dt': datetime.datetime(2020, 6, 1, 17, 32, 10), 'P_PV [kW]': 2.916, 'P_grid [kW]': -2.41784, Pag. 32
'P_load [kW]': -0.4981599999999999, 'P_Akku [kW]': None, 'Frequency [Hz]': 49.95, 'AC current [A]': 11.86, 'AC voltage [V]': 245.8, 'DC current [A]': 7.5, 'DC voltage [V]': 394.2}] Figure 3.14: Resulting dict that will be stored in the database Examples to call the data are: #First we create the object which is the inverter places in Puig and I'll call it fr_puig (Fronius Puig) fr_puig=fr_inverter() #the method returns the values in a dict P=fr_puig.power_flows() grid_status=fr_puig.grid_data() Figure 3.15: Example of calling the functions Spanish Electricity Market Price Data (ESIOS) Correctly speaking the data is extracted from Esios [21] but the module coded to extract the data is called PVPC_prices.py, it contains a class “PVPC_prices” with a “request” function that connects with the REE database. The request returns data in JSON format with a large list of prices at every hour, for an specific day, like in figure 3.16. {'PrecioFinal': [{'Dia': '31/05/2020', 'Hora': '00-01', 'GEN': '92,89', 'NOC': '44,59', 'VHC': '47,61', 'COF': '0,000083870338000000', 'BOEGEN': '51,57', 'BOENOC': '4,95', 'BOEVHC': '6,09', 'PMHGEN': '36,64', 'PMHNOC': '35,16', 'PMHVHC': '36,83', 'SAHGEN': '4,67', 'SAHNOC': '4,48', 'SAHVHC': '4,69'}, {'Dia': '31/05/2020', 'Hora': '01-02', Pag. 33
'GEN': '92,47', 'NOC': '44,10', ... Figure 3.16: JSON response from Esios REST API The interesting prices are the ones called ‘GEN’, ‘NOC’, ‘VHC’ which correspond to 2.0A, 2.0DHA and 2.0DHS respectively or what is the same “constant” price, night hour discrimination price, EV tariff price. The units are in €/MWh. Then an interactive function called “day_prices” takes advantage of this information, by interactive it is meant the functions and classes that allow input arguments, in this case the class is also interactive, it can be seen in figure 3.18. The data returned and in this case stored is a list of one dict like the rest functions, the correct format to store it: [{'dt': datetime.datetime(2020, 6, 1, 0, 0), 0: 0.05286, 1: 0.04599, 2: 0.04636, 3: 0.04629, 4: 0.0463, 5: 0.04597, 6: 0.04604, 7: 0.05018, 8: 0.0456, 9: 0.04612, 10: 0.04547, 11: 0.045020000000000004, 12: 0.04564, 13: 0.10928, 14: 0.10881, 15: 0.10876000000000001, 16: 0.10807, 17: 0.10839, 18: 0.10873000000000001, 19: 0.10955, 20: 0.11097, 21: 0.11277, 22: 0.11373000000000001, 23: 0.050140000000000004}] Figure 3.17: Resulting dict that will be stored in the database Note that the values has been transformed, the commas turned into dots and the units are in €/kWh. Pag. 34
Examples of calling this function are: PVPC_2A = PVPC_prices('GEN') PVPC_2DHA = PVPC_prices('NOC') PVPC_2DHS = PVPC_prices('VHC') #OR PVPC_2DHS = PVPC_prices() #to know the price at a specific hour and day in € use: print(PVPC_2DHS.hour_price()) #returns the actual price #preu=PVPC_2DHS.hour_price(8,0) #returns the price at 8 o'clock of today #to know the prices of a complete day use: preus_dia=PVPC_2DHS.day_prices() #returns the prices of today preus_dia=PVPC_2DHS.day_prices(-1,2)#returns prices from yesterday (-1) to today (2) Figure 3.18: Examples to call the functions The interactivity in the class is by choosing the tariff (‘GEN’, ‘NOC’, ‘VHC’), and in the functions by setting the “hour” and the “day_from_today” and the “ndays”, which allow a good versatility to obtain the electricity prices. 3.1.2 Data storing The storage process is quite complex because the data is transformed from a dictionary to a dataframe, this process can lead to data loss or format errors. For solving this the module called BBDD.py has several functionalities that help with it and allow to safely store data from other modules with a few simple lines. When a module that generates or extracts data is done a simple call to BBDD module is enough to store the information, following always the objective of versatility. In figure 3.19 the function implemented in the modules can be observed. That function is easy since only needs the name of the file where to store the data and the dict object containing the information. # lines inside the data treatment function . . . self.store_data(data,'current_weather_BBDD') return data # store data function def store_data(self,data,name): this_BBDD=BBDD(name) this_BBDD.store_data(data) Figure 3.19: The storing function and how it is called Pag. 35
The two lines inside the treatment function define the output choice, return will allow to store the information in a local variable, and the self.store_data function will store the information in the local file with the rest of measures taken before. Remember the data format is a list of dicts. The data storing process is all the stuff that takes place behind the lines “this_BBDD.store_data(data)” . This protocol initial objective was to store easily and in a robust way the data given by the “Node JS scripts”, and later on thanks to the “reality shock” effect it was little by little upgraded by the trustable method of try and failure. Again the code will be available in the B appendix. The module has two attributes 'nom_BBDD', 'BBDD’ which are like global variables and are specific for each BBDD object, in this way it is not necessary to indicate constantly to the object to which file the data has to be stored. In addition the module has 7 relevant functions for flux “A” process. This functions will be explained below following the figures 3.19 and 3.21 as a guide. This functions are: - self.store_data(self, object) - self.fill_BBDD(self) - self.check_BBDD_exists(self) - self.import_BBDD(self) - self.check_keys_dict_BBDD(self, object) - self.save_to_pickle(self) - self._print_(self) The first 2 require a detailed explanation, the next 5 are easy to understand and programatically are not complex, but will be explained too because they are optimized for easy programatical use. Store_data function This is the mother function, all dicts or dataframes containing new information that we want to add to the database has to be given to this function. Calling this function, see figure 3.19, only requires 2 inputs, the name of the specific BBDD object “self” and the information container “object”. As how the classes work (further information in A appendix) the first input is given by “self.” statement usually called “this_BBDD” which contains as an attribute the real name of the database file where the container has to pour its data, for example “current_weather_BBDD” following the example in figure 3.19. Figure 3.20 shows a schematic explanation of what happens inside the “store_data” function. Pag. 36
Figure 3.20: store_data function logical procedure First the module BBDD.py has to be imported and its class by typing: from BBDD import BBDD Now a BBDD object has to be defined and giving it a name of the file where the data frame will be stored, this is the first attribute. grid_BBDD=BBDD('grid_BBDD') And call the store_function with the new data container: grid_BBDD.store_data(new_data_container) If it is not existing yet, the script will create a new file in the directory called grid_BBDD.p where the “p” stands for pandas pickle. Figure 3.21: file containing all the grid information From now on, each time we want to interactuate with the file ‘grid_BBDD.p’ we will use grid_BBDD.“function”, because the list of functions created in this module are made with the purpose to interactuate correctly with the database and to save changes when necessary automatically avoiding mistakes. Pag. 37
Inside the function, the code first determines whether the container is a data frame or a list of dicts, because the procedure to append the new information differs. Later on it checks if the database file already exists or it not. In the case it doesn’t exist, it creates the new dataframe and saves it as a file with the function save_to_pickle. Note that if the container is a list of dicts it is necessary to create an empty dataframe and later call the fill_BBDD function to progressively add the new information. When the database already exists, the procedure is to import the dataframe in the database, to append or fill the new information to the existent dataframe, eliminate duplicates and reset indexes in the case the container is a data frame and save it to pickle. Note that if the container is a list of dicts the duplicates depuration takes places inside the fill_BBDD function. The process is optimal when the container is a data frame since the append method is very robust. At this point the data is correctly added to the database and saved but some missing parts will be explained in the next chapters. Fill_BBDD function The fill_BBDD function does all the dirty work, which corresponds to patiently fill row by row and columns by column the database table with the new information in a loop process. It is important to say that for big amounts of data the loops are completely inefficient and will originate long time programs. At the moment this implementations is out of the scope. Also the object oriented programming is very useful to carry out progressive upgrades maintaining the functionality of the complete program. In figure 3.22 the logical process of the fill_BBDD function is explained. This function makes the database very robust to dynamic raw data. Some of the data providers such the weather give JSON objects with different parameters according to the weather, if it is raining a new parameter called “3h rain” will appear and disappear when its forecasted to be sunny. So the first step is to check the dict has new parameters respect to the database table, this is done with the check_keys_dict_BBDD function. If there are new parameters that are not already in the dataframe, new empty columns has to be added to the table, later and empty row is added and filled with a loop per each value. The objective of this empty rows and columns is to fulfill the requirements of a pandas dataframe where a slot cannot be empty or ignored, instead a “Nan” value or an empty list “[]” has to be there. It makes the dataframe fulfillment really robust until the extreme to accept data from the car to be stored in the weather database table without any problem. Pag. 38
Figure 3.22: The logical process of the fill_BBDD function Once the fill in process is done, two more steps are remaining which are the elimination of duplicates, and the index resetting. These are very important because storing data 5 times for the same moment is not efficient, this is a temporal filter of course, if the duplicates of car charging status were eliminated the table would only have two rows. It is also interesting for the forecasts, that are 5 days forward but are updated daily if some changes occur dropping the old forecasts. After dropping the extra entrances some index gaps take place or maybe duplicated number rows, the index is the number of the row, this can lead to confusing bugs when treating the data so a reset of the indexing is done with a pandas method called “reset_index”. Note that the function doesn’t return the data frame to the store_data function, at least not explicitly, it saves the changes to the attribute “self.BBDD” that is like a global variable so all the functions can work with it without the need of passing it like a ball. check_BBDD_exists This function tries to import the BBDD with the import_BBDD function, if it fails returns a “0” if if success returns a “1”. Pag. 39
import_BBDD The import function is made of one simple line: return pd.read_pickle(self.nom_BBDD) So why those simple processes are made as a function? The answer is to adapt the function to the specific purpose of the asset, which is import a database, not read a pickle file, the naming is important for clearing the code. Also to not have to remember the name of the data file each time we want to import it, extract some rows, etc… So the name of the file will be given once. check_keys_dict_BBDD This function has an important paper by checking the puzzle piece of the new data container fits with the database table. If they fit the returned value is a “True” statement, if they don’t fit the returned value is a list with the missing columns in the dataframe, so the fill_BBDD function will know what columns to add in order to import correctly and without errors the new information. Save_to_pickle Again as import_BBDD the function has only a line of code: self.BBDD.to_pickle(self.nom_BBDD) Note that now we are using the two global variables which are “self.BBDD” and “self.nom_BBDD” allowing to save correctly the dataframe into the pickle file without having to send the object and the file name as inputs, just typing “grid_BBDD.save_to_pickle()”. _print_ This additional function would be the equivalent to “print(dataframe)” but for a database that is not still in the variable explorator of the python, so it imports the file data and prints the data, which is the last actualized data. 3.1.3 Database fill protocol Once all the code to store, treat and enrich data is developed it has to be used to drain the database. Each extractor has different specifications as shown in figure 3.4, for this it is not necessary to communicate with the APIs each 10 seconds but would be interesting to do so with the inverter. With the information provided by each supplier the following tempos are proposed: - Forecast weather once a day. Since the data is actualized every day has no sense to do it more often. Pag. 40
- Electric vehicle data once each 15 minutes. The provided data is binary information such the car is connected or not, maybe in a future when the charge control is implemented would be interesting to track it more often. - Grid data each 10 seconds. The frequency has to be high to collect instantaneous peaks of consumption. - Electricity prices daily. The electricity market is closed each day at 12 o’clock so the prices for the next day are available daily. - Current weather every 10 minutes. The current weather parameters are actualized every 10 minutes. This module works fine for the data resulting of the model area as seen in figure 3.1. This information is calculated and stored daily because the forecast data allows us to calculate at least the predictions 5 days forward. Once they are calculated they are stored in the database so any other module requiring them can get them when necessary. The optimization area would usually calculate the actuation vectors for a complete day. -Forecasted PV production, daily. -Corrected weather PV model, daily. -Consumption forecast, daily. All the code centralized in the _main_.py script has to be really concise and this gives sense to the high level of modularization applied. So a module for periodically calling the data is developed and called data_caller.py, it works properly when implemented inside a loop. Figure 3.23 explains how it works and below there is detailed explanation. Pag. 41
- self.extract_weekday(self,weekday) Import_BBDD This function imports the complete table, this functionality is useful when developing because it allows to search inside the table where the things are. However is not efficient when the columns/rows searched are localized since it occupies space in the memory importing a big table. An example of calling this function is: from BBDD import BBDD loads_forecast_BBDD=BBDD('loads_forecast') fore_l_df=loads_forecast_BBDD.import_BBDD() Figure 3.30: import_BBDD example usage Extract This function imports just a piece of the table, making the compilation faster. Specifically it extracts the rows that are in the temporal space defined in the inputs. The inputs are “days_from_today” and “ndays” which constitute a structure widely used in the modules of this program for its simplicity and because it fits easily with the temporal needs of the system. An example of utilization: from BBDD import BBDD PV_forecast_BBDD=BBDD('PV_forecast_BBDD') PV_forecast_BBDD.extract(0,1) Figure 3.31: extract example usage This example will only extract the PV parameters of today. Extract_weekday This method has an input called “weekday” if you set a “0” the resulting output will be a dataframe with data of all the mondays stored in the table queried. For example: from BBDD import BBDD PV_forecast_BBDD=BBDD('PV_forecast_BBDD') PV_forecast_BBDD.extract(0) #mondays Figure 3.32: extract_weekday example usage Pag. 48
3.2.2 Models of the system and inputs for the HEMS There are four models in the system, some of them give their outputs as inputs of other models. Figure 3.33: The developed models and its interrelation Irradiance There are several ways to obtain the theoretical irradiance that a specific surface will receive which can be grouped in: - Analytical method - External resources method The analytical method uses the trigonometry and other physics equations to determine this irradiance, lots of information about this can be found in [22]. The empirical method should be the other option, but since some of the equations and factors used in the analytical method we could say that the analytical method is more or less a mix. The external resources method comes by connecting with external platforms such PVGis [23] and its non-interactive service, empirical mostly. Or using a specific library which does this calculations, analytical mostly. For previous experience doing it by yourself leads to not satisfactory results so the analytical method is automatically discarded. The two other methods are studied. Pag. 49
The strategy is to obtain the clear sky irradiance for an specific surface located at a specific point in the earth (coordinates) and with specific tilt and aspect. Later this irradiance should pass to the forecasted irradiance model where some weather parameters will affect its shape. PVGis returned a curve of irradiance accomplishing the previous requirements but for a mean day for each month as shown below. This requires a data treatment to fulfill the dataframe for all the days of the year with an interpolation. So the PVGis is discarded. Figure 3.34: Irradiation components per month mean day by PVGis In python exists a library called pvlib [24] which was originally from Matlab and it provides several classes to simulate a pv system, the irradiance is imported and used. This module allows to ask the clear sky irradiance using the “days_from_today”, “ndays” and “freq” structure, since it is very helpful it is the method chosen. Figure 3.35: Clear sky Global Horizontal Irradiance (GHI) and Plane of Array irradiance (POA) Pag. 50
The POA irradiance is the one used to make the predictions. The module uses a method of a location class called get_clearsky. An example of usage is shown below. Note in figure 3.35 that the POA irradiance is deviated compared to GHI but not very much that is because the array has a very low tilt, more or less of 7 degrees and west oriented [25]. from pvlib import location, irradiance from datetime import datetime, timedelta import pandas as pd # parameters definition lat=41.1235... lon=1.1235... tilt=7 surface_azimuth=150 days_from_today=0 ndays=2 freq=15 initial_date=(datetime.now()+timedelta(days=days_from_today)).strftime(' %m-%d-%Y') # Create the location object and the time range site_location=location.Location(lat, lon, tz='Europe/Madrid') times = pd.date_range(initial_date, freq=str(freq)+'min', periods=60/freq*24*ndays,tz=site_location.tz) # use the api from pvlib to obtain the clearsky of the specific lcoation clearsky = site_location.get_clearsky(times) # pass from the GHI to POA by using get_total_irradiance solar_position = site_location.get_solarposition(times=times) POA_irradiance = irradiance.get_total_irradiance( surface_tilt=tilt, surface_azimuth=surface_azimuth, dni=clearsky['dni'], ghi=clearsky['ghi'], dhi=clearsky['dhi'], solar_zenith=solar_position['apparent_zenith'], solar_azimuth=solar_position['azimuth']) Figure 3.36: example of obtaining the POA irradiance for today and tomorrow Note that the code in figure 3.36 is not object oriented programming, a module called “irradiance.py” is developed to easily use this feature, in the same module the forecasted irradiance is implemented. This model is not completed at all because inputs such albedo effect are not given, so the diffuse component of the irradiation is not taken into account, but as a first stage model is enough. Pag. 51
Forecasted irradiance Once obtained the data frame of POA irradiance it has to be treated with the forecasted weather in the location, to do so the weather forecasted data is extracted from the database. At that point we have 2 dataframes with data that has to interactuate. To ease this process the irradiation data frame is obtained with the following characteristics: - 15 minutes timestamp - 5 days forward from today The weather dataframe extracted is: - 3 hour timestamp - 5 days forward today So the weather data frame is resampled as explained in 3.2.1 to 15 minutes timestep. Now similar size dataframes are obtained, probably the number of rows is different because the weather database and the forecasted model are not called in the “data_caller.py” at the same time but it is not a problem. A left join is performed. Joining tables is a widely used method in data analysis and consists on merging two tables by one common column, in this case the datetime, adding to the first table the columns of the second table. The suffix “left” means that if a datetime is non existent in the first table but existent in the second table this row will be ignored, the other way around the row values will be filled with “Nan” values. The expected irradiance over the array is a simple calculation: ffective OA cloudinesse irradiance =Pirradiance *% The resulting effective irradiance is shown below in figure 3.37. Figure 3.37: POA irradiation vs effective calculated irradiation Pag. 52
The output of this module is a dataframe of the weather parameters and two additional columns, POA and effective irradiance. In future versions this modelization will be compared with forecast modules already existent in pvlib library. By the moment it is a good trade off between complexity and results. A continuation this process in code format is shown: # extract the weather parameters from the database forecast_weather_BBDD=BBDD(BBDDs) weather_df=forecast_weather_BBDD.extract(days_from_today,ndays) weather_df=weather_df.reset_index(drop=True) # save into a variable the outputs of the irradiance model irradiance=self.get_net_irradiance(days_from_today,freq,ndays) POA_irradiance=irradiance['POA'] #convert 'dt' column into datetime type (if it is not already), set it as index of the dataframe, add timezone to the datetime type (imprescindible for the join) weather_df['dt'] = pd.to_datetime(weather_df['dt']) weather_df.index = weather_df['dt'] weather_df=weather_df.tz_localize(self.tz) del weather_df['dt'] # convert all the columns of the dataframe into numeric, imprescindible for resampling method to work for col in weather_df: weather_df[col] = pd.to_numeric(weather_df[col], errors='coerce') # resample from 3h to 15 minutes with the pad() method weather_df=weather_df.resample(str(freq)+'T').pad() # perform the join and the effective irradiance calculation df =weather_df.join(POA_irradiance, lsuffix='_caller', rsuffix='_other') df['eff_irrad']=(1-df['clouds all']/100)*df['POA'] Figure 3.38: process to compute the effective irradiance Production forecast The single diode model is an analytical model that simplifies the pv cell operation to a single diode. Pag. 53
Figure 3.39: Electrical circuit of the single cell model. Source= Sandia National Laboratories [26] To obtain the parameters of the cell and its production some equations shown in [26] are evaluated in a loop. That is because the independent variable is not the time, but the voltage of the cell, so for the same moment with the same weather conditions the cell could generate a lot or nothing depending on how it is controlled. Then a new element enters the scene, the mppt tracker (maximum power point tracker) which is an electronic device that continuously searches for the voltage (independent variable) that generates the maximum energy [27]. In figure 3.41 you can see how it looks like. The inputs of the model are several, they are listed below: Group Name Value Description Destination PV array num_panels 12 The number of panels in the array Multiply the output power of the model and/or the DC voltage of the series connected array Panel model Panel name LONGi_Green_ Energy_Techno logy_Co___Ltd __LR6_72PE_3 60M The panel commercial model CECMod database in pvlib to extract module parameters alpha_sc Temperature coefficient of short-circuit 0.003686 Pag. 54
current a_ref modified ideality factor 1.89500699999 99999 I_L_ref reference light current (A) 9.703366 I_o_ref Reference diode reverse saturation current (A) 1.016265e-10 R_sh_ref Shunt resistance ( ) 943.829773 R_s series resistance ( ) 0.327599 Weather parameters eff_irrad [800,900,1000,9 00,...] Array usually with values between 0 and 1000 W/m2 To calculate the cell working temperature and the desoto calculation main temp [25,26,27,26,...] Array of temperatures in ºC To calculate the cell working temperature wind speed [1,5,4,2,...] Array of wind speeds in m/s Cell temperature parameters a -3.56 Parameters in [28] b -0.075 deltaT 0 irrad_ref 1000 Reference irradiance Physical parameters EgRef 1.121 Reference energy gap Desoto calculation [29] dEgdT -0.0002677 Temperature coefficient of Energy gap Table 3.1: The parameters and inputs for the PV model compilation How it is structured in the code: Pag. 55
Figure 3.40: Data flow and orders direction of the PV model Figure 3.40 shows how the information is trespassed and modified when modelling the pv system, first it is necessary to define the object “PV” with the number of panels, the name of the module and the type of modelizations (corrected=0 or 1). Latter call the function “sim_PV_power” that will call other functions asking for data, this chain effect ends on the forecasted irradiance model that will send its output, see “forecasted irradiance”. The function conditions will calculate the cell temperature by using a method in a pvlib object “temperature” called “sapm_cell” [28]. The Desoto function returns 5 parameters to evaluate the PV curves which is done in the “PV_curves_info” function that returns the curves data. These curves looks like below: Pag. 56
Figure 3.41: photovoltaic curves. Source: Read the docs “pvlib” [24] All the data is stored in the database. Consumption forecast The consumption predictions when you only have the information of the general consumption, without distinguishing the loads, has to be done empirically and relying in the habits of the users and maybe on the weather. As a first approximation a mean day forecast is calculated, this modelization basically calculates the minute mean consumption per each weekday and uses it as a prediction. Since different methodologies can take place a library called forecaster.py is created. This library has an class named consumption and in it there is a main method “mean_day” that performs this calculation. In the future if other approximations are developed more methods could be added to this class. As figure 3.29 shows the first step is to extract from the database all the entries stored referring to mondays for example. The next step would be resampling, but in this case a previous step is necessary. Resampling is similar to a “group by” but for datetimes, if we need to calculate the mean value of the minute 206 of all the mondays we have to tell to pandas that this registration belongs to minute 206 of an specific day, so the apply method has to be used to the dataframe. The apply method is a feature in pandas that allows to apply a calculation to a series of a dataframe more efficiently than performing a loop. The function is named “massive_rounder” its name refers to the possibility of rounding a 2 or a 3 to a 0 or a 6 to a 5 depending on the inputs, it works for datetimes. Let’s see the function: Pag. 57
Figure 3.51: Consumption and generation for 5 days with missing values. Forecasts It is nice to see how are the predictions behaving versus the real data. In the system two forecasts are calculated and a corrected forecast is also implemented, lets see how they perform. Pag. 64
Figure 3.52: Forecasted consumption vs real consumption The consumption forecast looks well in a plot, some days seems more accurate and some other leser, the evaluation of this forecasts is calculated in the scoring section. The consumption in general is a representation of some habits in the house life that make it generally predictable. For the production the estimation is less precise for three reasons. The weather forecast is not enough precise, the values are in timestamps of 3 hours and calculated five days ago. It is observed that the forecasts are not changing if they are requested the next day, hence this is a big source of imprecision. The second reason is the model of forecasted irradiance is a first estimation, a trade-off between accuracy and time. The third reason is the photovoltaic model which is not matching the real production even for a sunny day, there is a clear bias. Pag. 65
Figure 3.53: Production forecast vs corrected forecast and real production As can be observed the forecasts are not precise and the corrected are better, the current weather is actualized every 10 minutes so offer more granularity. The bias i observed clearly in the curvature between the corrected and the real production. Other plots Other interesting plots from the rest of the database are: Pag. 66
Figure 3.54: Car plug and charging status and the state of charge Figure 3.55: The net power balance of the system Pag. 67
Figure 3.56: Grid voltage and frequency parameters Figure 3.57: Real vs modeled array DC voltage Pag. 68
Figure 3.58: Temperatures Figure 3.59: Wind speed and cloudiness index from the current weather database Pag. 69
3.3.2 Scoring After seeing all the plotted data it is expected to evaluate it by means of accuracy in the predictions. To evaluate forecasts a system of scoring is used and implemented in the analytics.py module. This scoring evaluates two curves the real and the forecasted and returns four indicators and one array: - MAPE stands for mean absolute percentage error [31] - RMSE stands for root-mean-square error [32] - Bias [33] - MAE stands for mean absolute error [34] - Forecast error [35] A continuation some forecasts will be evaluated using the scoring class which is specially made for that, this class has a principal function called “some_scores” which is used as follows: pv_scores=sc.some_scores(BBDDs=['grid_BBDD','PV_forecast_BBDD'],Columns= ['P_PV [kW]','p_mp'],frequencies=5, signs=[1,1],days_from_today=-5,ndays=5) Figure 3.60: Code for scoring It is simpler than the plotter but returns also the plot, it is customizable it allows to indicate the y_lables, title,... It has a drawback that accepts just two curves, and the order is important, the first columns refers to the first database. A powerful feature compared to “plotter” is that it allows to plot two columns of different databases with the same name. Production forecast scoring The first one to be analyzed is the forecasted production, this forecast is the one that relies on more steps, each one with its own deviations. Hence it is expected to have the worst scorings. The analysis will be performed within all the days with registration. The code is: sc=scoring() pv_scores=sc.some_scores(BBDDs=['grid_BBDD','PV_forecast_BBDD'],Columns= ['P_PV [kW]','p_mp'],frequencies=15, signs=[1,1],days_from_today=-18,ndays=18,title='Production forecast scoring graph',save='Production forecast scoring graph') Figure 3.61: Code for production forecast scoring A plot is shown for the 18 days, this is useful if some datas has to be omitted. In this case the first two days present a bug therefore will be erased for the scoring calculation. The inputs “days_from_today” and “ndays” will be set to 16. Pag. 70
Figure 3.62: Production scoring graph for 18 days The scores are shown in “Summarized scorings”. Corrected weather production model To calculate the scores of the corrected production is very useful to identify the inaccuracies of production forecasts. These inaccuracies comes from the weather forecasts see in “weather parameters scoring” and from the PV model. The code is: Pag. 71
Figure 3.63: Production corrected weather scoring graph for 16 days Weather parameters scoring The weather parameters that influentiate in the modelization are the wind speed, the temperature and the cloudiness index. The code is: cloud_scores=sc.some_scores(BBDDs=['current_weather_BBDD','forecast_weat her_BBDD'],Columns=['clouds all','clouds all'],frequencies=15, signs=[1,1],days_from_today=-16,ndays=16,y_label='Cloudiness index',title='Weather forecast cloudiness scoring',save='Cloudiness scoring') temperature_scores=sc.some_scores(BBDDs=['current_weather_BBDD','forecas t_weather_BBDD'],Columns=['main temp','main temp'],frequencies=15, signs=[1,1],days_from_today=-16,ndays=16,y_label='Temperature K',title='Weather forecast temperature scoring',save='Temperature scoring') wind_speed_scores=sc.some_scores(BBDDs=['current_weather_BBDD','forecast _weather_BBDD'],Columns=['wind speed','wind speed'],frequencies=15, signs=[1,1],days_from_today=-16,ndays=16,y_label='Wind speed m/s',title='Weather forecast wind speed scoring',save='Wind speed scoring') Pag. 72
The resulting plots are: Figure 3.64: Cloudiness index for the last 16 days current vs forecasted Figure 3.65: Temperatures for the last 16 days current vs forecasted Pag. 73
6. Planification The project development is divided in 3 stages, deliverables, research and evaluation. The bigger tasks are shown in gray, and the achieved milestones can also be observed. (Figures 6.1 and 6.2). Figure 6.1: First part of the planification of the project Figure 6.2: Second part of the project planification Pag. 80
Conclusions and further research The optimal control of the loads in a household can lead to interesting economic savings, the quantification of the magnitude of them is an important part for almost all the developing projects. In addition to the economic savings the benefits a correct DSM can provide to the grid and the renewables are important enough to find the HEMS interesting. The project started by quantifying the potentiality of this platform by calculating the range of potential savings for different situations and concluded the reaffirming the importance of it. The results are rewarding and they fulfill the listed requirements, the developed pipeline is ready to be implemented in a real HEMS. The code is functional and autonomous, it has been running for 18 consecutive days storing data every 10 seconds, draining the database up to 97.000 rows for the biggest table which is the “grid_BBDD”. It was connected actively with errors and without to multiple platforms and it drained a database with interesting data for energetical analysis such temperatures, wind speeds, consumption power, generation power, grid frequency and voltage, etc. Some analysis using the stored data were performed such production and consumption forecasts, doing them in a robust way wouldn’t have been possible without the database managing tool developed “BBDD.py”. This module provided flexibility and versatility to the data pipeline by using protocols that allow to extract and insert data safely. This protocols are the ones used in SQL “Structured Query Language” which is an standardized language for relational databases and is intrinsic in the used pandas library. The database managing tool combined with matplotlib library returned useful and visual representations of the data, those two functionalities along with the numpy matrix library were gathered in an “analytics.py” module. It facilitated the plotting and the quantifiable analysis of the forecasts all in one line the “one line pretty plot “. All those steps are the result of a conscious programming methodology which helps the modelization of the system. In the same line, the last objective concerning on scalability of the project is supported by the programming approach, the OOP. It is a very useful paradigm that introduces a powerful logical order in the code allowing at the same time an easy third party participation by adding new elements. They can be added in form of classes in already existing modules or by creating new ones. Examples of future new integrations would be interesting loads such water heaters, climatization elements, programmable appliances such the dishwasher and a long etcetera. To complete the HEMS further works are necessary, and they are distributed in three research paths. The functional works, they are the ones that will consummate the platform, specifically are the addition of an optimization engine, and actuation hardware. They are in charge to address the decision taking challenge and to make it possible in real loads and other devices. Then, another research path deals with generalization works. They take this name because of the objectives they fetch. These works would emphasize on making the platform usable in more environments like distribution grids, with more elements that can be batteries, climatization control, displaceable loads, wind power, etc. Pag. 81
Last but not least, interactive works is the latter research path considered as a future work. It would take the platform to another level in terms of interaction, this higher level visualization would allow more users to understand, choose preferences, set parameters, etc. It Would also make stress in the results awareness with interactive dashboards and similar. The completion of the further tasks will end with a device able to actuate actively in the demand side management and clearing the way for The transition in the electric system. Pag. 82
Acknowledgements To the directors which their unconditional support in the big abrupt turns the project had and the absolute faith on me. Also for the help in the writing and the constant tracking trough video conferences. Thanks to my family and friends for the comprehension of that much time spend in front of a computer. Also for understanding the heavy load of combining it with a full time job in the same room and screen. Thanks Ingrid, Dani, Tere, Quim, David, Ricard, Edu, Pol, Marc, Albert, Aleix, Edra, Sergi and much more. Pag. 83
Appendix A Learnings This section of the appendix focuses on giving more information about the learned subjects in python programming and in general. This knowledge was little or inexistent at the beginning of the project and really has a huge importance during all the development of it. These skills are schematized below. - To code based on Git methodology, research and change of habits was required since this methodology was never used before either known. -Use of APIs, its use opens the possibilities of developing functional programs to incredible levels. There is some knowledge about the use of this tools but further theory research is necessary due to different complexities and types of APIs. In this project several application programming interfaces will be used, to communicate with the car, with the inverter, with the transmission system operator and with the weather station. -Python coding the Object Oriented Programming and other capabilities. In the following sections the remarkable knowledge is reported for future understanding. Git methodology Git is an open-source version control system, started by Linus Torvalds, the Linux creator. The definition of this concept is better when explained in its context, when a developer write a code makes constant changes to solve problems, add new features or simply continue completing the algorithm. These changes represent at the end new versions of the code, version control systems save these versions in a repository to ease the collaboration with other developers or give the possibility to return back, to a working version, when a bug appears and cannot be detected easily. GitHub and GitLab are the web pages consulted for the accomplishment of this project, their structure for the projects is as follows. Each project is saved in a repository “repo” in it the files that compose it are saved and with them their versions. As a user you can fork a “repo” which means to create a new project based off of someone else’s project, in this way it is possible to work over an already done code to accommodate it to your personal needs. On the other way exists the pull request, when you fork a “repo” and make on it fancy changes and then want this effort to be recognized by the original developers or even included in the official project you can do a pull request. At this point the owners will be able to take a look on the codes and compare and decide whether or not include it [39]. Pag. 84
When you want to have some code in your laptop and work on it, fork it and then use git clone with the http… provided by GitHub for example in the specific folder where you will work. Some other interesting functions for git are: -git clone https... -git status -git add filename -git commit -m “description” -git push origin master -git diff filename -git log -git checkout 1aaqbf… -git checkout master Python coding All the code is developed in python, the communications, the modelizations the data treatment,... And each of them requires knowledge of specific ítems. For the communications the use of libraries such requests and the definition of classes make the code difficult to understand so it is necessary a basic knowledge to reverse engineer someone else’s code and implement it in the project. This basic knowledge comes from [40]. The use of classes allow to synthesize the code and make it more robust, that’s why developers use this structure and at the end Python is an Object Oriented Language where almost everything is an object and classes are object constructors. The code developed will be structured this way with the aim to take advantage of its strong points. All the interesting and unusual learnings in programming are mentioned below: - Use of OOP - Modules creation - Multiprocessing compilation for IP searching Use of OOP Python is an object oriented language, the libraries developed for it are structured in classes. In order to conceive this paradigm an example is used. The code recreates an object, lets see for example a speaker, at the home there are two different speakers. The first step is to create a class called speaker: class speaker: Pag. 85
pass These speakers have several attributes that make them unique, that are the name, the colour and the power. Inside the class there should go the methods and there is one special method called “__init__” in it the general attributes can be defined since when we invoke the class this method will be automatically compiled: class speaker: def __init__(self, colour, power): self.colour=colour self.power=power Check that a new element appeared, the “self” statement, the use self to refer to the object itself, since the class is an object builder each object we create of type speaker will have its name, the self is the name, its identificator. When creating the class the code is useful for creating n objects and the name is not known yet. Note that is quite logical to say “self.colour” is equal to say the colour of the Dolby speakers is green. Now these speakers do some things like consuming energy, so a method called consumption is created: class speaker: def __init__(self, colour, power): self.colour=colour self.power=power def consumption(self, time): #time in hours energy=self.power*time #kWh print(energy) Now our speakers consume, it is time to see it in action, if we write and execute: dolby=speaker('green',0.05) JBL=speaker('pink', 0.04) The result is: Two speaker object are created, now to estimate how much they are going to consume during three hours we have to invoke the method consumption: Pag. 86
dolby.consumption(3) JBL.consumption(3) Note that only the argument “time” is given, the argument self is “dolby” and “JBL” and are already given before the dot. The results are: runfile('C:/Users/adria/Sin título0.py', wdir='C:/Users) 0.15000000000000002 0.12 This is object oriented programing, usually some methods will be repeated in different classes, this is one of the main drawbacks of this approach because some functions are repeated, but it offers a clear organization and allows coworking. Modules creation Some classes can refer to similar purposes and can be grouped into a module. Following the previous example a dishwasher is a load as the speakers are, they could be grouped in a module called loads, the same for the LEDs and the laptop. A module is an script when is invoked by another script, in this project almost all the scripts invoke the “BBDD.py” module, and the script “data_caller.py” invokes these scripts, finally the module “__main__.py” invokes the “data_caller.py” module. Just an example of how segmented it can be. Python is full of modules and libraries for covering several purposes and most of them are written over other libraries. In the module “loads.py” we write the classes of the different loads like this: class speaker: def __init__(self, colour, power): self.colour=colour self.power=power def consumption(self, time): #time in hours energy=self.power*time #kWh print(energy) class dishwasher: def __init__(self, colour, power): self.colour=colour self.power=power Pag. 87
def consumption(self, time): #time in hours energy=self.power*time #kWh print(energy) class laptop: def __init__(self, colour, power): self.colour=colour self.power=power def consumption(self, time): #time in hours energy=self.power*time #kWh print(energy) class LED: def __init__(self, colour, power): self.colour=colour self.power=power def consumption(self, time): #time in hours energy=self.power*time #kWh print(energy) And safe it as loads.py, now we can invoke it from another script by simply coding: from loads import speaker, LED dolby=speaker('green',0.05) PHILLIPS=LED('white', 0.004) dolby.consumption(3) PHILLIPS.consumption(5) Note the versatility of the modules, where huge amounts of code can be executed in a few lines making readable teh code that is being programmed. The classes can be enhanced in the loads.py module and will automatically actualized for the rest of the scripts using this libraries. Multiprocessing compilation for IP searching Searching a dynamic IP in an internal grid can be very difficult, some solutions are provided in internet but not exactly matching the needs of the code. In this case the dynamic IP of the inverted is required for communicating with it and extract the valuable information. Pag. 88
The developed method for doing so consists in basically call the API with different IPs and the one returning an answer will be the good one. Receiving the answer of the inverter can take 1 or 2 seconds so calling 400 different IPs and expecting to collect data each 10 seconds is not feasible. To solve this problem the multiprocessing compilation was implemented, calling 400 times the API with 400 different IPs at the same time would only take 2 seconds, it could work. A module called searchIP.py is developed, and the modules “multiprocessing.dummy” and “functools” are imported. They will allow in the first stage to compile the same line 400 times without waiting it to finish and later to determine which IP returned a response. When executing this code the given result is: runfile('C:/Users/adria/searchIP.py', wdir='C:/Users/adria') 192.168.1.143 --- 3.037867784500122 seconds --- 400 requests performed in 3 seconds and the correct IP of the inverter. This code is very powerful because it allows to fetch the IP of the inverter connected in the grid, hence is usable when the inverter changes its IP or for other inverters in other houses. This code was converted into an executable for using it with other computers and in other houses and it worked. An example of the result of the program is: B The code The following sections contain the integral code of the system module by module. The nissanapi.py code is obviated since it is extracted from github and is too long, only the added parts are posted. __main__.py # -*- coding: utf-8 -*- """ Created on Sat Apr 25 21:53:11 2020 @author: adria.bove """ from data_caller import datacall #, datagive from datetime import datetime from inputimeout import inputimeout, TimeoutOccurred Pag. 89
SearchIP.py # -*- coding: utf-8 -*- """ Created on Fri May 1 10:34:59 2020 @author: adria.bove """ """ We want to run a function asychronously and run a callback function with multiple parameters when it returns! In this example, we are pretending we're analyzing the names and ages of some people. We want to print out: jack 0 jill 1 james 2 """ import time from multiprocessing.dummy import Pool import requests import ipaddress from functools import partial class searchIPfronius(): def __init__(self): pass def async_function(self,ip_inicial): """ Function we want to run asynchronously and in parallel, usually one with heavy input/output, though using a dummy function here. """ url='http://'+str(ip_inicial)+'/solar_api/v1/GetInverterRealtimeData.cgi?Scope=Device&De viceId=1&DataCollection=CommonInverterData' response=requests.get(url,timeout=2) #time.sleep(1) response=response.json() return response['Body']['Data']['DAY_ENERGY']['Unit'] def callback_function(self,status, ip_inicial): """ Function we want to run with the result of the async function. The async function returns one parameter, but Pag. 96
this function takes two parameters. We have to figure out how to pass the age parameter from the async function to this function.. """ if status=='Wh': #print(status, ip_inicial) self.ip_inversor=str(ip_inicial) def buscador(self): nIP_search=400 pool = Pool(processes=nIP_search) #status=[] ip_inicial=ipaddress.ip_address('192.168.1.0') for ip in range(nIP_search): """ Partial is a technique for creating a function that just calls another function but with one or more of the parameters "frozen". In this way, we can capture the 'ip_inicial' paramter in each iteration of the loop and pass it along with the return value of the async function. """ ip_inicial=ip_inicial+1 new_callback_function = partial(self.callback_function, ip_inicial=ip_inicial) pool.apply_async( self.async_function, args=[ip_inicial], callback=new_callback_function, error_callback=new_callback_function ) pool.close() pool.join() if '__main__'==__name__: start_time = time.time() sIP=searchIPfronius() sIP.buscador() print(sIP.ip_inversor) print("--- %s seconds ---" % (time.time() - start_time)) Pag. 97
Fr_inverter.py # -*- coding: utf-8 -*- """ Created on Sun Apr 26 10:34:05 2020 @author: adria.bove """ #http://192.168.1.143/solar_api/v1/GetPowerFlowRealtimeData.fcgi #http://192.168.1.143/solar_api/v1/GetInverterRealtimeData.cgi?Scope=Device&DeviceId=1&D ataCollection=CommonInverterData import requests from searchIP import searchIPfronius from BBDD import BBDD from datetime import datetime class fr_inverter(): def __init__(self): sIP=searchIPfronius() sIP.buscador() self.inv_IP=sIP.ip_inversor def check_ip(self): pass def search_ip(self): pass def request(self, archive): if archive == 'FlowRT': try: endpoint='http://'+self.inv_IP+'/' get_archives='solar_api/v1/GetPowerFlowRealtimeData.fcgi' response = requests.get(url = endpoint+get_archives) return response except: print('NO ENS HEM CONNECTAT') elif archive == 'InverterRT': try: endpoint='http://'+self.inv_IP+'/solar_api/' version='v1/' get_archives='GetInverterRealtimeData.cgi?' scope='Scope=Device&' scopeid='DeviceId=1&' Pag. 98
datacollection='DataCollection=CommonInverterData' response = requests.get(url = endpoint+version+'/'+get_archives+scope+scopeid+datacollection) return response except: print('NO ENS HEM CONNECTAT') def formating(self, objecte, process: str='W2kW'): if process=='W2kW': if objecte != None: objecte=objecte/1000 return objecte def power_flows(self): response=self.request('FlowRT') response=response.json() P_PV=self.formating(response['Body']['Data']['Site']['P_PV']) P_grid=self.formating(response['Body']['Data']['Site']['P_Grid']) P_load=self.formating(response['Body']['Data']['Site']['P_Load']) P_Akku=self.formating(response['Body']['Data']['Site']['P_Akku']) dt=datetime.strptime(response['Head']['Timestamp'][0:19], '%Y-%m-%dT%H:%M:%S') data=[dict(zip(['dt','P_PV [kW]','P_grid [kW]','P_load [kW]','P_Akku [kW]'],[dt,P_PV, P_grid, P_load,P_Akku]))] return data def P_grid(self): response=self.request('FlowRT') response=response.json() P_grid=self.formating(response['Body']['Data']['Site']['P_Grid']) return P_grid def P_PV(self): response=self.request('FlowRT') response=response.json() P_PV=self.formating(response['Body']['Data']['Site']['P_PV']) return P_PV def P_load(self): response=self.request('FlowRT') response=response.json() P_load=self.formating(response['Body']['Data']['Site']['P_Load']) return P_load def grid_data(self): PF_data=self.power_flows() response=self.request('InverterRT') response=response.json() try: F_AC=response['Body']['Data']['FAC']['Value'] except: F_AC=None Pag. 99
try: I_AC=response['Body']['Data']['IAC']['Value'] except: I_AC=None try: U_AC=response['Body']['Data']['UAC']['Value'] except: U_AC=None try: I_DC=response['Body']['Data']['IDC']['Value'] except: I_DC=None try: U_DC=response['Body']['Data']['UDC']['Value'] except: U_DC=None data=[{'Frequency [Hz]':F_AC, 'AC current [A]':I_AC, 'AC voltage [V]':U_AC, 'DC current [A]':I_DC, 'DC voltage [V]':U_DC}] PF_data[0].update(data[0]) self.store_data(PF_data,'grid_BBDD') return PF_data def store_data(self,data,name): this_BBDD=BBDD(name) this_BBDD.store_data(data) if __name__ == '__main__': #First we create the object which is the inverter places in Puig and I'll call it fr_puig (Fronius Puig) fr_puig=fr_inverter() recalcular='y' while recalcular=='y': #to get the data of the power flows exist several methods to use power_flows() give them in a tuple and kW #exist also methods for the single values this difference is important because calling all together ensures they are in the same instant P=fr_puig.power_flows() consum=fr_puig.P_load() p_PV=fr_puig.P_PV() intercanvi_xarxa=fr_puig.P_grid() print("Ara estàs consumint "+str(consum)+" kW") print("Les teves plaques generen "+str(p_PV)+" kW") if intercanvi_xarxa<0: print("Per tant a la xarxa hi van "+str(-intercanvi_xarxa)+" kW") Pag. 100
else: print("Per tant estas agafant de la xarxa "+str(intercanvi_xarxa)+" kW") #to get the status of the grids of the household the inverter and its sensosrs provides the frequency and voltages #the method returns the values in a dict grid_status=fr_puig.grid_data() recalcular=input("Escriu 'y' i prem enter per recalcular: ") print() print() #to extract the value use: #print(grid_status['Frequency']['Value']) #print(grid_status['AC current']['Value']) #print(grid_status['AC voltage']['Value']) #print(grid_status['DC current']['Value']) #print(grid_status['DC voltage']['Value']) PVPC_prices.py # -*- coding: utf-8 -*- """ Created on Sat Apr 25 20:54:26 2020 @author: adria.bove """ #https://api.esios.ree.es/application/json/api.esios.ree.es/Token token=\ import credentials import datetime as dt import requests import matplotlib.pyplot as plt from BBDD import BBDD class PVPC_prices: def __init__(self,tariff: str='VHC'): #2.0A 2.0DHA 2.0DHS 'GEN' 'NOC' 'VHC' self.tariff=tariff self.tokenREE=credentials.tokenREE def request(self): endpoint='https://api.esios.ree.es/' headers = {'Accept': 'application/json', 'Host': 'api.esios.ree.es', 'Authorization': 'Token token=\' self.tokenREE' } params = {'date': self.date} get_archives='/archives/66/download_json?locale=es' self.response = requests.get(url = endpoint+get_archives, params = params, headers = headers) Pag. 101
return self.response.json() def formating(self,objecte,size): if size=='1': objecte=float(objecte.replace(',', '.'))*0.001 return objecte def hour_price(self, hora: int=int(dt.datetime.now().strftime('%H')), day_from_today: int=0): self.date=str(dt.date.today()+dt.timedelta(days=day_from_today)) try: response=self.request() hourprice=response['PrecioFinal'][hora][self.tariff] return self.formating(hourprice,'1') except: return 0.09 def day_prices(self,day_from_today: int=0, ndays: int=1): dayprices=[[self.hour_price(hora,day_from_today+day) for hora in range(24)] for day in range(ndays)] dtdays=[dt.datetime.combine(dt.date.today()+dt.timedelta(days=day_from_today)+dt.timedel ta(days=day), dt.datetime.min.time()) for day in range(ndays)] data=[] for i in range(ndays): data=data+[dict(zip(['dt']+list(range(24)),[dtdays[i]]+dayprices[i]))] self.store_data(data,'REE_BBDD') return data def store_data(self,data,name): this_BBDD=BBDD(name) this_BBDD.store_data(data) def plot_prices(self,object): llista=[] try : len(object[0]) for i in range(len(object)): piece=[] for a in range(len(object[i])): piece=piece + [object[i][a]] llista=llista+piece except: llista=object plt.plot(llista) if __name__ == '__main__': Pag. 102
# to use this module first import the module # from PVPC_prices import PVPC_prices #next declare the objects which usually are the three tariffs: PVPC_2A = PVPC_prices('GEN') PVPC_2DHA = PVPC_prices('NOC') PVPC_2DHS = PVPC_prices('VHC') #OR PVPC_2DHS = PVPC_prices() #next ask for the prices in the desired format #to know the price at a specific hour and day in € use: print(PVPC_2DHS.hour_price()) #preu=PVPC_2DHS.hour_price(8,0) #to know the prices of a complete day use: preus_dia=PVPC_2DHS.day_prices() #to get the prices for a range of days use: first argument the initial day, if yesterday use -1, today 0 and tomorrow 1. Can reat from -9 to 1. #the second argument the number of days you want #preus_dies=PVPC_2DHS.day_prices(-1,2) #to plot the results #PVPC_2DHS.plot_prices(preus_dies) #PVPC_2DHS.plot_prices(preus_dia) Nissanapi.py class car_data_recollect(): def __init__(self): import pprint import sys import credentials region = 'EU' username = credentials.username password = credentials.password nci = NCISession(region) nci.login(username, password) self.user_id = nci.get_user_id() self.vehicles = nci.fetch_vehicles() def data(self): for vehicle in self.vehicles: vehicle.fetch_cockpit() Pag. 103
#date= dt.datetime.now() #hora=int(date.strftime('%H')) vehicle.refresh_battery_status() vehicle.fetch_battery_status() vehicle.refresh_location() vehicle.fetch_location() if 'PluggedStatus.NOT_PLUGGED'==str(vehicle.plugged_in): plug_status=0 else: plug_status=1 if 'ChargingStatus.NOT_CHARGING'==str(vehicle.charging): charging_status=0 else: charging_status=1 row=[dt.datetime.now(),vehicle.battery_status_last_updated + dt.timedelta(hours=2),vehicle.battery_level,charging_status,plug_status,vehicle.location _last_updated + dt.timedelta(hours=2),vehicle.total_mileage,vehicle.charge_time_required_to_full,str(veh icle.charging_speed),vehicle.instantaneous_power,vehicle.battery_temperature,vehicle.bat tery_capacity] names=['dt','dt battery update','battery level','charging status','plug status','dt location update','mileage','time to full','charging speed','instant power','battery temperature','battery capacity'] data=[(dict(zip(names,row)))] self.store_data(data,'car_BBDD') return data def store_data(self,data,name): this_BBDD=BBDD(name) this_BBDD.store_data(data) Irradiance.py """ GHI to POA Transposition ========================= Example of generating clearsky GHI and POA irradiance. """ # # This example shows how to use the Pag. 104
# :py:meth:`pvlib.location.Location.get_clearsky` method to generate clearsky # GHI data as well as how to use the # :py:meth:`pvlib.irradiance.get_total_irradiance` function to transpose # GHI data to Plane of Array (POA) irradiance. from pvlib import location, irradiance import pandas as pd from matplotlib import pyplot as plt from credentials import tilt,azimuth,latitud,longitud from datetime import datetime, timedelta from BBDD import BBDD class irradiation: def __init__(self): # For this example, we will be using Golden, Colorado self.tz = 'Europe/Madrid' lat, lon = latitud, longitud self.tilt=tilt self.surface_azimuth=azimuth # Create location object to store lat, lon, timezone self.site = location.Location(lat, lon, tz=self.tz) # Calculate clear-sky GHI and transpose to plane of array # Define a function so that we can re-use the sequence of operations with # different locations def get_net_irradiance(self, days_from_today: int=0, freq: int=15 , ndays: int=1): initial_date=(datetime.now()+timedelta(days=days_from_today)).strftime('%m-%d-%Y') site_location=self.site # Creates one day's worth of 10 min intervals times = pd.date_range(initial_date, freq=str(freq)+'min', periods=60/freq*24*ndays, tz=site_location.tz) # Generate clearsky data using the Ineichen model, which is the default # The get_clearsky method returns a dataframe with values for GHI, DNI, # and DHI clearsky = site_location.get_clearsky(times) # Get solar azimuth and zenith to pass to the transposition function solar_position = site_location.get_solarposition(times=times) # Use the get_total_irradiance function to transpose the GHI to POA POA_irradiance = irradiance.get_total_irradiance( surface_tilt=self.tilt, surface_azimuth=self.surface_azimuth, dni=clearsky['dni'], ghi=clearsky['ghi'], dhi=clearsky['dhi'], solar_zenith=solar_position['apparent_zenith'], solar_azimuth=solar_position['azimuth']) # Return DataFrame with only GHI and POA. POA is the irradiance for the specified tilt and azimuth return pd.DataFrame({'GHI': clearsky['ghi'], Pag. 105
pickle_file = open('todo.pickle', 'wb') pickle.dump(todo, pickle_file) del todo pickle_file = open('todo.pickle','rb') todos = pickle.load(pickle_file) todo=todos+{str(i) :['asdf','qerwt']} print(todo) """ import pandas as pd from datetime import datetime, timedelta class BBDD: def __init__(self,nom_BBDD): """ Parameters ---------- nom_BBDD : TYPE DESCRIPTION. Returns ------- None. """ self.nom_BBDD=nom_BBDD+'.p' def store_data(self,objecte): if str(type(objecte))=="<class 'pandas.core.frame.DataFrame'>": if self.check_BBDD_exists()==0: self.BBDD =objecte self.save_to_pickle() else: self.BBDD=self.import_BBDD() self.BBDD=self.BBDD.append(objecte) self.BBDD = self.BBDD.drop_duplicates(subset='dt', keep='last') self.BBDD = self.BBDD.sort_values(by=['dt']) self.BBDD = self.BBDD.reset_index(drop=True) self.save_to_pickle() else: if self.check_BBDD_exists()==0: columns=list(objecte[0].keys()) empty_lists_list=[[] for i in range(len(objecte[0]))] Pag. 112
initiate_bbdd=dict(zip(columns, empty_lists_list)) self.BBDD = pd.DataFrame(initiate_bbdd) self.fill_BBDD(objecte) self.save_to_pickle() else: self.BBDD=self.import_BBDD() self.fill_BBDD(objecte) self.save_to_pickle() def fill_BBDD(self, objecte): a=len(self.BBDD.index) check=self.check_keys_dict_BBDD(objecte) if check!=True: for i in range(len(check)): empty_lists_list=[[] for h in range(a)] self.BBDD[check[i]]=empty_lists_list for i in range(len(objecte)): empty_lists_list=[[] for h in range(len(self.BBDD.keys()))] self.BBDD.loc[a+i] = empty_lists_list b=[b for b in objecte[i]] for n in b: self.BBDD[n][a+i]=objecte[i][n] self.BBDD = self.BBDD.drop_duplicates(subset='dt', keep='last') self.BBDD = self.BBDD.sort_values(by=['dt']) self.BBDD = self.BBDD.reset_index(drop=True) def check_BBDD_exists(self): try: pd.read_pickle(self.nom_BBDD) return 1 except: return 0 def import_BBDD(self): return pd.read_pickle(self.nom_BBDD) def check_keys_dict_BBDD(self,objecte): new_columns=[] for i in range(len(objecte)): list1=list(objecte[i].keys()) list2=list(self.BBDD.keys()) new_columns=new_columns+list(set(list1) - set(list2)) new_columns = list(dict.fromkeys(new_columns)) Pag. 113
if new_columns==[]: return True else: return new_columns def save_to_pickle(self): self.BBDD.to_pickle(self.nom_BBDD) def _print_(self): self.BBDD=self.import_BBDD() print (self.BBDD) def extract(self,days_from_today:int=0, ndays:int=1): df=self.import_BBDD() today=datetime.strptime(datetime.today().__str__()[0:10], '%Y-%m-%d') df.dt = df.dt.apply(lambda d: d.replace(tzinfo=None)) new_df=df[(df.dt >= today+timedelta(days=days_from_today)) & (df.dt < (today+timedelta(days=days_from_today+ndays)))] return new_df #new_df = df[df.dt >= init_time | df.dt <=init_time+duration] #return new_df def extract_pers(self,column_name,coincident_value): df=self.import_BBDD() new_df=df[(df[column_name] == coincident_value)] return new_df def extract_weekday(self,weekday): df=self.import_BBDD() df.index=df.dt df.index.names = ['Date'] new_df=df[(df.index.weekday == weekday)] return new_df def last_entry_time(self): df=self.import_BBDD() last_time=max(df['dt']) return last_time if __name__=='__main__': """ my_df = pd.DataFrame() names = ['Bob', 'Sam', 'Jo', 'Bill'] Pag. 114
favourite_sports = [['Tennis', 'Motorsports'], ['Football', 'Rugby', 'Hockey'], ['Table tennis', 'Swimming', 'Athletics'], ['Eating cheese']] my_df['name'] = names my_df['favourite_sport'] = favourite_sports print(my_df) # Save DataFrame to pickle object my_df.to_pickle('test_df.p') del my_df """ # Load DataFrame with pickle object weather_BBDD=BBDD('grid_BBDD') weather_BBDD._print_() #weather_BBDD.store_data(forecast) Analytics.py # -*- coding: utf-8 -*- """ Created on Fri May 29 14:07:58 2020 @author: adria.bove """ from datetime import datetime, timedelta from BBDD import BBDD from PVPC_prices import PVPC_prices from weather import weather import nissanapi from fr_inverter import fr_inverter from PV_model_singlediode import PV from credentials import num_panels from forecaster import consumption class datacall: def __init__(self): self.num_panels=num_panels Pag. 115
self.calls=['forecast_weather_BBDD','car_BBDD','grid_BBDD','REE_BBDD','PV_forecast_BBDD' ,'current_weather_BBDD','loads_forecast','PV_corr_forecast_BBDD'] self.freq=[timedelta(days=1),timedelta(minutes=15),timedelta(seconds=10),timedelta(days= 1),timedelta(days=1),timedelta(minutes=10),timedelta(days=1),timedelta(days=1)] self.offset=[timedelta(days=-5),timedelta(days=0),timedelta(days=0),timedelta(days=0),ti medelta(days=-5),timedelta(days=0),timedelta(days=-5),timedelta(days=0)] def caller(self): self.now=datetime.now() ide=-1 for i in self.calls: ide=ide+1 BBDD_=BBDD(i) if BBDD_.check_BBDD_exists()==1: last_entry_time=BBDD_.last_entry_time() flag=0 else: flag=1 if ((self.now-last_entry_time.replace(tzinfo=None)-self.offset[ide])>self.freq[ide]) | flag==1: self.weather(ide) self.nissan(ide) self.inverter(ide) self.REE(ide) self.PV_forecast(ide) self.current_weather(ide) self.consumption_forecast(ide) self.PV_corr_forecast(ide) def weather(self,ide): if ide==0: try: wth_call=weather() wth_call.fore_w_req() print('weather actualitzat') except: print('weather error connexió') def nissan(self,ide): if ide==1: try: nissan=nissanapi.car_data_recollect() nissan.data() print('car actualitzat') Pag. 116
except: print('nissan error connexió') def inverter(self,ide): if ide==2: try: fr_puig=fr_inverter() fr_puig.grid_data() print('inverter actualitzat') except: print('inverter error connexió') def REE(self,ide): if ide==3: try: PVPC_2DHS = PVPC_prices('VHC') #OR PVPC_2DHS = PVPC_prices() PVPC_2DHS.day_prices() print('REE actualitzat') except: print('REE error connexió') def PV_forecast(self,ide): if ide==4: try: puig_pv=PV(num_panels=self.num_panels) puig_pv.sim_PV_power(timestamp=15) print('PV actualitzat') except: print('PV error connexió') def current_weather(self,ide): if ide==5: try: wth_call=weather() wth_call.current_w_req() print('weather actualitzat') except: print('weather error connexió') def consumption_forecast(self,ide): if ide==6: try: load_call=consumption('grid_BBDD') load_call.forecaster(timestamp=15) print('consumption forecast actualitzat') except: print('consumption forecast error connexió') def PV_corr_forecast(self,ide): if ide==7: try: puig_pv=PV(num_panels=self.num_panels, corrected=1) puig_pv.sim_PV_power(timestamp=15) Pag. 117
print('PV corrected actualitzat') except: print('PV corrected error connexió') if __name__=='__main__': self=datacall() self.caller() Pag. 118
Bibliography [1] «Power system flexibility for the energy transition.pdf». Accedido: jun. 22, 2020. [En línea]. Disponible en: https://www.irena.org/-/media/Files/IRENA/Agency/Publication/2018/Nov/IRENA_Power _system_flexibility_1_2018.pdf. [2] «Energy transition», Wikipedia . jun. 20, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Energy_transition&oldid=963573730. [3] «Energy Transitions Indicators – Analysis», IEA . https://www.iea.org/articles/energy-transitions-indicators (accedido jun. 22, 2020). [4] «Home energy consumption versus solar PV generation», Solar Choice . https://www.solarchoice.net.au/blog/home-energy-consumption-versus-solar-pv-generati on (accedido jun. 22, 2020). [5] «Figure 1. Example of demand side management / energy flexibility.», ResearchGate . https://www.researchgate.net/figure/Example-of-demand-side-management-energy-flexi bility_fig1_337376867 (accedido jun. 22, 2020). [6] «A Comprehensive Guide to Home Energy Management Systems», European Sustainable Technology blog , sep. 23, 2017. https://sustainable-now.eu/guide-to-home-energy-management-systems/ (accedido jun. 22, 2020). [7] «What is a home energy management system?» https://carbontrack.com.au/blog/what-is-a-home-energy-management-system/ (accedido jun. 22, 2020). [8] «Home Energy Management System | E.ON Home | E.ON». https://www.eonenergy.com/energy-management.html (accedido jun. 22, 2020). [9] S. B. Martínez, «Intelligent Flexibility Management for Prosumers: Development of algorithms for the Energy Management of Electric Vehicles, Loads, Generators and Batteries», p. 136. [10]G. Alley, «What is a Data Pipeline? | Alooma». https://www.alooma.com/blog/what-is-a-data-pipeline (accedido jun. 22, 2020). [11]R. de Araújo, «Building a data pipeline from scratch on AWS», Medium , sep. 06, 2019. https://towardsdatascience.com/building-a-data-pipeline-from-scratch-on-aws-35f139420 ebc (accedido jun. 22, 2020). [12]«Python Pickle Tutorial - DataCamp». https://www.datacamp.com/community/tutorials/pickle-python-tutorial?utm_source=adwo rds_ppc&utm_campaignid=898687156&utm_adgroupid=48947256715&utm_device=c&u tm_keyword=&utm_matchtype=b&utm_network=g&utm_adpostion=&utm_creative=3326 02034343&utm_targetid=dsa-429603003980&utm_loc_interest_ms=&utm_loc_physical_ ms=20270&gclid=EAIaIQobChMI2Pf88unt6QIVDbTVCh1DGAArEAAYASAAEgIxo_D_B wE (accedido jun. 22, 2020). [13]«What is the fastest way to upload a big csv file in notebook to work with python pandas?», Stack Overflow . https://stackoverflow.com/questions/37010212/what-is-the-fastest-way-to-upload-a-big-c sv-file-in-notebook-to-work-with-python (accedido jun. 22, 2020). [14]«API REST | Definición, Requisitos y Ejemplos». https://www.tecnologias-informacion.com/api-rest.html (accedido jun. 22, 2020). [15]R. Mitchell, mitchellrj/kamereon-python . 2020. Pag. 119
[16]«Weather API - OpenWeatherMap». https://openweathermap.org/api (accedido jun. 22, 2020). [17]«Relational model», Wikipedia . may 31, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Relational_model&oldid=959885233. [18]«Fronius Smart Meter 63A-1». https://www.fronius.com/es-es/spain/energia-solar/productos/todos-los-productos/monito rizaci%C3%B3n-de-instalaciones/hardware/fronius-smart-meter/fronius-smart-meter-63a -1 (accedido jun. 22, 2020). [19]«Fronius Primo 4.0-1». http://www.fronius.com/es-es/spain/energia-solar/productos/todos-los-productos/inversor /fronius-primo/fronius-primo-4-0-1 (accedido jun. 22, 2020). [20]«Fronius Solar API V1». [En línea]. Disponible en: https://www.fronius.com/~/downloads/Solar%20Energy/Operating%20Instructions/42%2 C0410%2C2012.pdf. [21]«Bienvenido | ESIOS electricidad · datos · transparencia». https://www.esios.ree.es/es (accedido jun. 22, 2020). [22]«Solar Radiation on a Tilted Surface | PVEducation». https://www.pveducation.org/pvcdrom/properties-of-sunlight/solar-radiation-on-a-tilted-su rface (accedido jun. 22, 2020). [23]B. CATTANEO, «Photovoltaic Geographical Information System (PVGIS)», EU Science Hub - European Commission , jun. 15, 2018. https://ec.europa.eu/jrc/en/pvgis (accedido jun. 22, 2020). [24]W. F. Holmgren, C. W. Hansen, y M. A. Mikofski, «pvlib python: a python package for modeling solar energy systems», J. Open Source Softw. , vol. 3, n.o 29, p. 884, sep. 2018, doi: 10.21105/joss.00884. [25]«GHI to POA Transposition — pvlib-python 0.7.2+0.gb35905a.dirty documentation». https://pvlib-python.readthedocs.io/en/stable/auto_examples/plot_ghi_transposition.html #sphx-glr-auto-examples-plot-ghi-transposition-py (accedido jun. 22, 2020). [26]«PV Performance Modeling Collaborative | Single Diode Equivalent Circuit Models». https://pvpmc.sandia.gov/modeling-steps/2-dc-module-iv/diode-equivalent-circuit-models / (accedido jun. 22, 2020). [27]M. A. G. de Brito, L. Galotto, L. P. Sampaio, G. de A. e Melo, y C. A. Canesin, «Evaluation of the Main MPPT Techniques for Photovoltaic Applications», IEEE Trans. Ind. Electron. , vol. 60, n.o 3, pp. 1156-1167, mar. 2013, doi: 10.1109/TIE.2012.2198036. [28]J. A. Kratochvil, W. E. Boyson, y D. L. King, «Photovoltaic array performance model.», SAND2004-3535, 919131, ago. 2004. doi: 10.2172/919131. [29]W. De Soto, S. A. Klein, y W. A. Beckman, «Improvement and validation of a model for photovoltaic array performance», Sol. Energy , vol. 80, n.o 1, pp. 78-88, ene. 2006, doi: 10.1016/j.solener.2005.06.010. [30]«COVID-19 pandemic», Wikipedia . jun. 22, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=COVID-19_pandemic&oldid=963872817. [31]«Mean absolute percentage error», Wikipedia . jun. 02, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Mean_absolute_percentage_error&oldid=9604 05128. [32]«Root-mean-square deviation», Wikipedia . feb. 17, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Root-mean-square_deviation&oldid=94125635 3. Pag. 120
[33]«Bias (statistics)», Wikipedia . may 26, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Bias_(statistics)&oldid=959047819. [34]«Mean absolute error», Wikipedia . jun. 09, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Mean_absolute_error&oldid=961700965. [35]«Forecast error», Wikipedia . mar. 31, 2020, Accedido: jun. 22, 2020. [En línea]. Disponible en: https://en.wikipedia.org/w/index.php?title=Forecast_error&oldid=948405844. [36]«Interpret all statistics and graphs for trend analysis - Minitab Express». https://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/ time-series/how-to/trend-analysis/interpret-the-results/all-statistics-and-graphs/ (accedido jun. 22, 2020). [37]«200211_Nota-metodologica-mix_cat.pdf». Accedido: jun. 22, 2020. [En línea]. Disponible en: https://canviclimatic.gencat.cat/web/.content/04_ACTUA/Com_calcular_emissions_GEH/ factors_emissio_associats_energia/200211_Nota-metodologica-mix_cat.pdf. [38]«Emisiones de CO₂ del consumo eléctrico en tiempo real». http://electricitymap.tmrow.co (accedido jun. 22, 2020). [39]K. Brown, «What Is GitHub, and What Is It Used For?», How-To Geek . https://www.howtogeek.com/180167/htg-explains-what-is-github-and-what-do-geeks-use -it-for/ (accedido jun. 22, 2020). [40]Python OOP Tutorial 1: Classes and Instances . . Pag. 121