BENCHMARKING the STAR Controller using Matlab

Size: px
Start display at page:

Download "BENCHMARKING the STAR Controller using Matlab"

Transcription

1 CODEN:LUTEDX/(TEIE-5244)/1-126/(2006) Industrial Electrical Engineering and Automation BENCHMARKING the STAR Controller using Matlab Josep Carrasco Martínez Dept. of Industrial Electrical Engineering and Automation Lund University

2 BENCHMARKING the STAR Controller using Matlab A MSC THESIS PRESENTED AT THE DEPARTMENT OF Industrial Electrical Engineering and Automation (IEA) of LTH at LUND UNIVERSITY Author: Josep Carrasco Martínez For the Degree of: Master of Science Supervisor: Dr Christian Rosen Examiner: Dr Ulf Jeppsson Date: September 2006

3 ii

4 iii

5 iv

6 ABSTRACT Abstract Along the years there have been large advances in Wastewater Treatment Plants (WWTP since now), from the basic treatment until applying the last technologies in automatic control systems, concentration measurements and mathematical modelling of wastewater treatments. About the last technologies it has to be stood out the fast advanced of computer systems, that let not only implement the most complex models of WWTP to check the evolution of the system in a short time, but also the possibility of integrating more complex controls, and it has to be stood the advanced of electronic systems too, that let apply the last sensor technologies, increasing the reliability and the device life in the abrasive ambient as it is the waste water. The difficulty in WWTP is the biological processes that take part within the vessels. Principally the growth of biological microorganisms that are the responsible of removing the organic matter dissolved in the wastewater. The main organic matter that is removed from wastewater is the carbon, the nitrogen and the phosphorus, although the phosphorus can be removed sometimes by chemistry processes, which are faster than biological processes. The problem in biological processes is its slow dynamic and the external perturbations, which can affect considerably the growth of biological microorganisms. Currently, the companies involved in WWTP offer automation tools and packages that let to apply automation techniques in WWTP easily. One of the most important devices offered is the controller, which will try to lead the progress of the wastewater by the right values and to ensure the process is getting the goals. It means that the controller is going to control the biological processes that take part in wastewater treatment applying the different control strategies programmed. Here there are three concepts all together; the controller, the biological process and the control strategy. First, the control strategy is tested using a model of the WWTP. After, it is implemented in the controller to apply it to the real WWTP to control the biological process. The problem appears when the control strategy is applied to the real process. It is impossible to predict all that is going to happen in WWTP, because there are unpredictable external disturbances (rain, storms, temperature, dry weather, snow, ice, etc) that can affect the biological processes. The biological processes are sensible to the external changes of the weather. It means that a control strategy tested in a simulation within ideal conditions can not be the suitable. The problem rises when the control strategy is not the suitable. The biological processes dynamic is really slow, a time constant of days, even weeks some times. Hence, it is possible to know when a control strategy is wrong after days or weeks, and then, is too late to try to control the process and one more week is needed to test another control strategy. All this time checking the control strategy means to spend a lot of resources. There is one possible solution that would save a lot time and would let to test more control strategies using less resources. The solution consists in building a complete model of the WWTP that is going to be controlled (it would be necessary a particular model for each WWTP), and to simulate it in real time at the same time as the evolution of the real WWTP. It would let the controller to have two kinds of data, the data v

7 measured in the WWTP and the data from the simulation of the model. With these data the controller or the operator can compare and test the control strategies, so that if the data measured in the WWTP are far from the data calculated in the simulation, it is possible to guess that there is something wrong with the control strategy. Of course, this solution forces to implement a perfect model of the WWTP because the controller is comparing the data of the simulation of the model and the data of the WWTP, considering that the data calculated with the model are always right. vi

8 PREFACE Preface Before has been introduced one of the current problems in WWTP, a problem responsible of spending a lot of resources and time when testing control strategies to improve the efficiency in WWTP. The realization of the present thesis is one of the results of a task group work of the krüger (in Copenhagen, Denmark, from Veolia Water Systems group, in collaboration with the department of Industrial Electrical Engineering and Automation (IEA, at Lund University, Sweden). There has been created a research group with workers of the company and researchers of the IEA department, which purposes are to improve modelling WWTP and the control strategies minimizing the necessary resources. Acknowledgements: At last, the finalization of this thesis was possible not only to the work realized by the author, but also to the IEA department and the krüger company. There were involved more people, directly and indirectly related with the thesis. I would like to express my special gratitude to all the people that have helped me in one or another way finishing the thesis. Thank you to Christian Rosen (research associated of the IEA department), he has followed and supervised the progress of the thesis, despite of all the work that he had. He is part of the research group in collaboration with the company Veolia Water Systems. It was inestimable his help to introduce me in the topic of waste water treatment; it was absolutely new for me at the beginning of the thesis. Thank you to Ulf Jeppsson, the responsible of the IEA department, who has supervised the thesis too, specially the part of modelling batch process. His work about modelling settling and clarification and the model programmed in Matlab by Krist V. Gernaey (CAPEC, Dept. of Chemical Engineering, DTU, Denmark) and him, are the key model implemented in this thesis. Thank you to Eric Login from Veolia Water System (krüger, in Copenhagen, Denmark). The communication of the main application was developed and discussed in collaboration with him. Thank you to Sergey Litvinov too. I never met him personally, but his help was essential to resolve the creation of XML files with Matlab. Finally, my gratitude to Dalius Misiunas, Fredrick Roos, Carlos Álbarez, Daniel Aguado, Jon Bolmstedt, Gunnar Lindstedt and all the department of Industrial Electrical Engineering and Automation (IEA, LTH, Lund, Sweden), and specially to Lunds Universitet and the Polytechnic University of Valencia (Universidad Politécnica de Valencia UPV-, Valencia, Spain) who gave me the possibility of taking part in this foreign experience and realise the final degree thesis abroad. vii

9 viii

10 CONTENTS Contents ABSTRACT v PREFACE vii PART I: Introduction 1 Chapter 1: Introduction Motivation Objectives Contribution Outline of the thesis 7 Chapter 2: Wastewater Treatment Processes Process description Automation in wastewater treatment plants Modelling of wastewater treatment processes 17 Modelling mass transfer 17 Modelling biological nutrient removal (ASM1) 18 Modelling hydraulics 21 Modelling settling and clarification 22 Modelling batch processes 25 PART II: Modelling the wastewater treatment plant with Matlab 27 Chapter 3: Application Design Introduction Main flow-sheet Structure of the program Initialization Main loop Application Implemented Application Interface Program Code 40 ix

11 CONTENTS Chapter 4: Data Exchange Introduction What SOAP is XML communication files Data-flux in the communication Data-exchange with the database Write the data in results.xml Read the data from database.xml Synchronization Read the data from synchro.xml 56 Chapter 5: Modelling Batch Processes with Matlab Introduction Model developed Model diagram Model equations Implementation of the model S-function programmed Comments 79 PART III: Appendixes (included papers) 81 APPENDIX I: Appendixes to CHAPTER 2 83 I.1 Appendixes for MODELLING WASTEWATER TREATMENT PROCESSES 84 I.1.1 Tabular form for simple biological kinetics 84 I.1.2 Tabular form for simple biological kinetics and carbon removal kinetics 84 I.1.3 Tabular form for simple biological kinetics, carbon removal kinetics and nitrogen removal kinetics 85 I.1.4 Tabular form for phosphorus removal kinetics 86 APPENDIX II: Appendixes to CHAPTER 3 87 II.1 STAR emulator to check the synchronization code 88 II.1.1 writexml_synchro code 89 II.2 Control functions 89 II.2.1 controlloop code 90 II.2.2 control_check code 90 II.3 Processing data with Matlab 92 II.3.1 read_data function 92 II.3.2 wirte_data function 93 x

12 CONTENTS II.4 GUIDE application 93 II.4.1 What s GUIDE 93 II.4.2 Application GUIDE code 93 APPENDIX III: Appendixes to CHAPTER 4 95 III.1 Web Services 96 III.2 SOAP protocol 97 III.3 org.apache.xerces.dom.documetimpl class 98 APPENDIX IV: Appendixes to CHAPTER IV.1 S-function settlerb_batchm.c code 102 PART IV: Bibliography 111 xi

13 xii CONTENTS

14 PART I TITLE: Introduction 1

15 2

16 CHAPTER 1 Introduction This chapter is a brief sight of the thesis; motivations, contributions, structure and objectives. After reading this chapter the reader knows the contents of each point in this thesis, so it s important to know how to read it and where is each topic studied. 3

17 CHAPTER 1: Introduction 1.1 MOTIVATION The treatment of the waste water is a complex process, process compound of several biological processes sensitive to the external disturbances, as can be the storm, the rain, the snow, the ice; all the climatological changes can affect the wastewater treatment process. The sensitive biological processes and the disturbances of the weather make difficult the control of the wastewater treatment process. Through the new technologies the most avant-garde companies have tried to solve the problem of the complex control needed and the existing disturbances within the process. With the new sensors it is easier to measure the state of the process and try to design suitable control strategies. The possibilities of the new computers let this and more, but there is still one restriction: the dynamic of the biological processes. With the new advances of the techniques sometimes it is forgot that the new techniques cant change the process, they are only developed to control it, to get a stable and controllable process. The dynamic of some biological process are so slow, it means that the results of an action control will be observed a long time after applying it. This difficult the control of the process more than it seems at the beginning, because when the controller tries to solve the mistakes of the strategies or the effect of the disturbances it is too late, and the process need double time to became stable again. The task group formed by Veolia Water System (krüger, in Copenhagen, Denmark) and the department of Industrial Electrical Engineering and Automation (LTH, Lund, Sweden) was formed to improve the wastewater treatment processes using sophisticate techniques to model the whole process including the sensors model, the controller model and the plant model. Within the group rose the idea of simulating the wastewater process plant in real time. What does this idea mean? How can the real time simulation of the WWTP improve the behaviour or the control of the plant? The answer to these questions is the motivation of this thesis. If it is possible to implement a perfect model of the WWTP and the controller that is being applied in the real WWTP, and to start the simulation of the process from the values of the data measured in the real plant, it would be possible to have the progress of the WWTP at the same time as the progress of the model implemented, and it would be easy to compare the values of the state variables of the simulation and the state variables of the real process. Comparing these values would be suitable to find disturbances in the process or important features of the plant that are not included in the model used usually to check the control strategies in simulation time. By the other side, the values of the simulation in real time would let to see the progress of some state variables that the real measurements can not let due to the characteristics of the sensor: the noise, the error, the precision, etc. 4

18 Josep Carrasco Martínez 1.2 OBJECTIVES In the point before has been discussed the motivation of the present thesis, but there is not enough with motivations to developed a thesis. The motivation is the beginning, the main idea to solve a problem, to improve a process, to do anything. The motivation says that it would be a good idea to simulate the model of the WWTP at the same time that the plant is working, with the same conditions, the same value of the state variables, the same control strategy, and after, to compare the results of the simulation and the measurements of the process. But now the motivation has to be translated to objectives, which will represent a concrete aims. If we start to analyze the motivation, the purpose is to simulate a model while the WWTP is working. So the first objective will be the implementation of an application to simulate the model of the WWTP. The controller has to compare the results of the simulation and the measurements of the WWTP. It points that it is need a communication between the application developed and the controller of the WWTP. The application is simulating the model of the WWTP at the same time that the real plant is working, and the controller is transferring data from the real process to ensure the model of the simulation and the real plant have the same conditions. So not is only needed a communication between the application and the controller, the synchronization is needed too. At last, the most important is the model. The model of the WWTP has to be developed. There are a lot of possibilities to implement a model of the WWTP, and only to model one part of the plant can be a master thesis. Here in this thesis in implemented the model of the batch process (see chapter 2 to know what a batch process is) in one vessel. From the model exposed is possible to implement the full model of the secondary treatment in WWTP, but it will not be the aim of this thesis. Summarising, the objectives of the present thesis are: Implementation of an automatic application to simulate a model of the WWTP in real time. To program the communication and the synchronization with the controller. To model batch process in one simple vessel and implement it. 5

19 CHAPTER 1: Introduction 1.3 CONTRIBUTIONS There have been named the objectives of the thesis to get improve the control in wastewater treatment plants. To get these objectives is join to the techniques and applications that are going to be used for getting them. The whole code programmed in this thesis and the user interface of the application has been programmed within Matlab package toolbox. Matlab is a powerful application that let the researchers to implement, simulate, check, program, control near all the things. There are a big number of packages to complement Matlab and let the user to execute different things or processes sharing the same workspace, thing that allows interconnect implemented applications in Matlab and simulations that are running at the same time, without translating the data from one application to another. The thesis has each chapter divided in two virtual parts; the first one explain the abstract discussion of the topic that is going to be developed. After the abstract discussion, the second part is the implementation of the topic discussed in a real and operative code. Starting from the paragraphs before, the contributions can be understood as: The design of an automatic application that simulate the model of the real WWTP in real time. The implementation of the automatic application in Matlab. The communication of the application with the controller through the Ethernet network. The basis and the implementation in Matlab. The synchronization of the controller and the implemented application, the design of several possibilities and the posterior implementation of it. The design of the batch process model, with the evolution of the equations along all the phases, and the translation of the equations into code to implement the model. The contributions have been presented as independent works, but they can be read as a main big contribution, the contribution of implementing an application to get the combination between the abstract part of the control and the real part of the control in the process working together. The abstract part would be the implementation of the model of the process that is going to be controlled, all the part of the code programmed dedicated to model and simulate the WWTP plants. And the real part would represent all the structures and devises that form the WWTP, the controller, the sensors, the actuators. The implementation of this application is not the substitute for the first simulation and testing of the control strategies before applying it, it is like an automatic test of the control strategy in real time, a test to verify the control of the WWTP while it is working. 6

20 Josep Carrasco Martínez 1.4 OUTLINE OF THE THESIS The distribution of the thesis try to get the better way to understand the topic developed in. It tries to introduced and explain all the concepts used along the thesis, and to give the necessary bibliography to look for extra information if it is necessary for the reader, not only to better understanding the thesis, but also to increase the given information in the present work. The thesis is divided in four parts: 1. Introduction. 2. Modelling the Wastewater Treatment Plant in Matlab. 3. Appendixes. 4. Bibliography. Each part is divided in chapters that expose the topics developed along the thesis. The first and the second part form the work of the thesis, and the third and fourth part are complementary to read more about the topics developed in the first and second part. The first part is an introduction about wastewater treatment processes, what they are, how to model, the parts of a WWTP plant, the previous knowledge to better understand the thesis. This part is divided in two chapters: chapter 1 and chapter 2. The chapter 1 is the current chapter. The chapter 2 is an introduction about wastewater treatment plants, the description of the process, automation in WWTP and the basis of modelling WWTP. The second part is that we can call the work developed. There are three chapters: chapter 3, chapter 4 and chapter 5. The chapter 3 contains the design and implementation of the main application and the user interface. In chapter 4 is discussed and programmed the communication with the controller and the database and the synchronization with the controller. In chapter 5 is designed and programmed the batch process model in Matlab. The third part contains the appendixes to the chapters of the first and second part, and the last part is the bibliography used to develope the thesis. 7

21 8 CHAPTER 1: Introduction

22 CHAPTER 2 Wastewater Treatment Processes Previous to the full report of the project presented in this thesis it is essential a brief explanation about wastewater treatment processes, what is that, basic modelling and automation within it. In the pages below it is made a description about wastewater treatment processes, giving more details of the second treatment in the plant. After it, a brief introduction about automation in wastewater treatment and finally the basic modelling in wastewater treatment plants is presented. In this chapter is presented only a basic idea about description, automation and modelling wastewater treatment, for further knowledge it is the possibility of checking the chapter 7 ( Appendix of CHAPTER 2 ) and the bibliography. 9

23 CHAPTER 2: Wastewater Treatment Processes 2.1 PROCESS DESCRIPTION There are four disciplines involved in wastewater treatment processes, and we need all of them to make work the wastewater plant. In the figure below there is a schema of these disciplines: Chemistry Hydraulics Biology Water distribution and wastewater collection Hydrology Water processing Water quality and pollution Wastewater processing Advanced wastewater treatment and water reclamation Water reuse figure 1: disciplines involved in wastewater treatment The process starts when wastewater is collected in a sewer system and transported to a plant for treatment prior to disposal (hydraulic discipline). Once the wastewater arrives to the treatment plant it has to pass through three main treatments: PRIMARY TREATMENT SECONDARY TREATMENT TERTIARY TREATMENT figure 2: main treatments in wastewater treatment plants The primary treatment is the simplest one, and the most of times it consists in a group of screens and primary settler to remove the largest rejects (plastic bags, food and another solid products) and to skims off floating greases and oils. After this first treatment it is the secondary treatment, where it takes part the biological reactions, chemical precipitation, nutrient mass transfer, biomass growth and settling and clarification; it is called Biological Nutrient Removal (BNR). The last treatment, tertiary treatment, is a group of filters and membrane techniques and, this part of the plant can change considerably, it depends of the final use of the e-fluent water (human consume, industry use, river recirculation, etc); this treatment attempts to limit the micro-organisms and other pathogens in the treated water. 10

24 Josep Carrasco Martínez All the work of this thesis has been developed about modelling of secondary treatment, and below it is showed the scheme of this treatment: Secondary treatment Primary treatment Biological reactors Secondary settler Clear water Tertiary tretament Sludge Return activated sludge figure 3: Layout for the secondary treatment in a continuous wastewater treatment plant We can find in the secondary treatment the following mechanisms: HYDRAULICS: Wastewater flows through the treatment plant by the force of gravity if it is possible, and pumping the wastewater to lift it from the sewer to the plant inlet. The mechanisms which take part are the vessels, which are usually concrete tanks of various shapes and sizes with controlled levels, and pumps which are almost used to recycle mixed liquor and sludge and the small sludge wastage streams. NUTRIENT REACTIONS: The biological reactions involved are: removal of organic carbon, removal of nitrogen (nitrification and denitrification) and removal of phosphorus. The reactions are showed below: Insoluble Carbon HIDROLISIS ORGANIC CARBON REMOVAL Dissolved Oxygen figure 4: Nutrient Reactions BIOMASS NITRIFICATION AUTOTROPHS Soluble Carbon HETEROTROP Dissolved Oxygen Amonium Soluble Carbon Nitrites / Nitrates Nitrogen Gas Carbon dioxide BIOMASS NITROGEN REMOVAL HETEROTROP DENITRIFICATION BIOMASS Soluble Phosphats Soluble Carbon FERMENTATION VFA PAO Biomass Polyphosphat nodules Bio-P PHA Soluble Phosphates Dissolved Oxygen PHA BIOMASS Bio-P: Organisms which have the removed PHA nodules inside PAO: Phosphorus Accumulationg Organisms PHA: PolyHidroxy Alkanoates VFA: Volatile Fatty Acids ANAEROBIC PROCESS (PO 4 release) AEROBIC PROCESS (PO 4 uptake) PHOSPHORUS REMOVAL 11

25 CHAPTER 2: Wastewater Treatment Processes Carbon removal and nitrogen removal are the most common process modelled and used in wastewater treatment. The first one is easily understood, but the complexity of nitrogen removal makes it was necessary a brief explanation of it. Predenitrification AS process Many modern treatment plants utilising AS have biological nitrogen removal. Biological nitrogen removal relies on nitrifying and denitrifying bacteria for removal of nitrogen in two steps (as it is showed in figure 4): nitrification and denitrification. Two different types of bacteria cultures are used to achieve nitrification and denitrification: autotrophic bacteria uses inorganic carbon as carbon source. heterotrophic bacteria uses organic carbon as carbon source. In the nitrification step, ammonium is oxidised to nitrite and then nitrate (nitrification) by autotrophs. In the second step, nitrate is reduced to nitrogen gas (denitrification) by heterotrophs. A difficulty with this procedure is that the two steps require different ambient conditions to function effectively. The nitrification step needs dissolved oxygen, whereas the denitrification step requires an oxygen free environment. A solution to this is to divide the reaction volume into separate compartments in which the conditions are different. A relatively common configuration for nitrogen removal is the predenitrification process. The first reactor is anoxic, that is no dissolved oxygen is present, and is followed by an aerated volume. This may appear somewhat backwards as the nitrification is done after the denitrification. However, the denitrification process requires readily biodegradable organic substrate and this is normally present in the influent wastewater. If the denitrificaiton has to take place after the nitrification (i.e. a post-denitrification configuration), most of the organic substrate will have been consumed and external carbon will have to be added. Thus, to provide the anoxic reactor with nitrate, a recirculation stream is introduced from the last reactor to the first reactor (sometimes the sludge recirculation is sufficient and no internal recirculation is needed). Internal nitrate recirculation figure 5: Basic principle of the predenitrification configuration ANOXIC AEROBIC Sludge recirculation 12

26 Josep Carrasco Martínez CHEMICAL PRECIPITATION: Sometimes it is possible to remove the phosphorus using chemical precipitation instead of nutrient reactions; it is faster and more economically favourable. This mechanism is made by the addition of aluminium or iron compounds such as alum, pickle liquor, ferric hydroxide or ferric chloride. NUTRIENT MASS TRANSFER: this mechanism occurs in biological reactions and the purpose is to get oxygen from gaseous air into water, and it is promoted in stirred vessels. BIOMASS GROWTH: It means the maintenance of the right proportions of different species of organisms within the sludge in an active state. The aim is to avoid the growth of harmful organisms. SETTLING AND CLARIFICATION: Finally it takes part the separation of insoluble particles form water. It is used the gravity force, thus the insoluble particles which are denser than the water go down the settler and they form the sludge (see figure 3). 2.2 AUTOMATION IN WASTEWATER TREATMENT PLANTS Online measuring and data collection systems The number of measurable entities increases as research on and development of instrumentation and sensors progress. A difficulty in online measuring is the aggressive environment in which the sensors must function and that many of the interesting entities must be derived from reaction analysis in batch or continuous experiments. Interesting development in the sensor area involves new types of sensors such as sensor arrays or soft sensors, where variables are deduced from a number of measurements, biosensors that utilise (immobilised) cultures of bacteria, and microbial sensors for measuring inhibitors and substrates. In the last few years, a wide variety of biosensors have been developed. Within this large field, microbial sensors stand out because of their multi-receptor behaviour. In fact, these results in rather poor selectivity, but a great variety of substances can be detected simultaneously with one sensor. It is for this reason that microbial sensors are preferred for measuring environmentally relevant summary parameters (such as Biochemical Oxygen Demand) or for detecting inhibiting and toxic effects. Compared to enzyme sensors, their higher stability and lower production costs are additional arguments for using microbial sensors for environmental analyses. With rapid, direct, and exact detection of these parameters with microbial sensors, it will be possible to make the momentary situation in a water or wastewater stream visible. This results in new possibilities for the control of sewage plants. The data collecting systems differ from plant to plant and from supplier to supplier but common sampling rates (in Sweden) are 10 and 12 per hour, i.e. every sixth and fifth minute, respectively. The sample values are often an average over the sampling period, during which some sensors continuously deliver values and others perhaps only once a 13

27 CHAPTER 2: Wastewater Treatment Processes minute. All sensors are afflicted with time lags, but normally these are short in comparison to the dominant time constants of the process. The most often measurements in wastewater treatment are aerobic growth of heterotrophs, anoxic growth of heterotrophs, aerobic growth of autotrophs, decay of heterotrophs, decay of autotrophs, ammonification of soluble organic nitrogen, hydrolysis of entrapped organics and hydrolysis of entrapped organic nitrogen in biological processes, and settler velocity, suspend solids concentration, feed volumetric flow rate, effluent volumetric flow rate and underflow volumetric flow rate in settler processes. Control handles There are limitations to what can be controlled in a wastewater treatment plant. This is due to a lack of powerful control handles in comparison to the relatively severe disturbances that varying influent wastewater characteristics impose on the system. A majority of the manipulated variables are macro variables (DO and some of the chemical additions excepted) whereas some of the major mechanisms that drive the processes are on the micro level. Moreover, these mechanisms are often coupled. Thus, most control handles must be considered rather blunt and often a combination of control handles is required to reach a certain control objective. Environmental control increasingly requires the use of analytical methods, which should be uncomplicated and thus able to operate at low cost and with minimal maintenance. Miniaturized components should make the devices suitable for mobile investigations. They should also be capable of carrying out rapid measurements. Biosensors fulfil these requirements due to their simple principle of operation. In biological process, soluble inert organic matter (S I ), readily biodegradable substrate (S S ), particulate inert organic (X I ), slowly biodegradable substrate (X S ), active heterotrophic biomass (X B,H ), active autotrophic biomass (X B,A ), particulate products arising from biomass decay (X P ), oxygen (S O ), nitrate and nitrite nitrogen (S NO ), NH4+NH3 nitrogen (S NH ), soluble biodegradable organic nitrogen (S ND ), particulate biodegradable organic nitrogen (X ND ) and alkalinity-molar units (S ALK ), and in activated sludge, suspend solids concentration and sludge concentration are examples of the state variables we can control in a wastewater treatment plant. STAR controller (Superior Tuning And Reporting) is an example of commercial controller for wastewater treatment plants distributed by Krüger (VEOLIA group); the one used to developed the thesis. Its main performances are: Supervisory control system for WWTP Control modules for different unit processes Rule-based control Data screening and reconciliation system Web-based interface 14

28 Josep Carrasco Martínez Below it is showed the network interface of the STAR controller. Through this software interface it is possible to check the values measured by the controller from every place if there is an Ethernet connection. Process dynamics figure 6: Ethernet interface of the STAR controller A wastewater treatment process consists of many sub-processes with dynamics of different time scales. Some variations are slow, for instance sludge dynamics and temperature, with time scales of days, week and even months. The daily variation in influent flow rate and substance concentrations is perhaps the most dominant variation. However, there are even faster dynamics present, such as dissolved oxygen (DO) dynamics and hydraulic shocks. The different time scales make it difficult to analyse the cause-effect relationships, especially when recirculation and other feedback loops are present. Therefore, it is important to establish the dynamic behaviour of the involved processes and adapt the analysis methods in accordance to the dynamics. 15

29 CHAPTER 2: Wastewater Treatment Processes It is important to project out the different dynamics within the sub-processes in Biological Nutrient Removal. It is possible to divide the process dynamic in six subprocesses as well as it was showed before in process description. Thus these are different dynamics: HYDRAULIC DYNAMIC: Commonly the exponential lag characterizes the hydraulic dynamic, and the size of the lag depends on the weir geometry. In spite of this, it is usual to find different time constants. In instance intensive variable, concentration or temperature, dynamics for flow through vessels are characterised by the mean residence time (vessel volume divided by flow rate). This parameter is commonly known as the hydraulic residence time or HRT. The spread of the residence time depends on the flow patterns within the vessel which will fall somewhere between plug flow, no spread giving a dead time response, and perfectly mixed a first-order lag with time constant equal to the residence time. The time constant is typically of the order of minutes to hours. Flow down pipes causes a transport delay for intensive variables such as nutrient concentrations. The dead time is equal to pipe length divided by liquid velocity. These are unlikely to be significant with the possible exception of return activated sludge which could experience dead times of a few minutes, and poorly designed analyser sampling systems which have been known to have dead times of hours. Recycle flows slow down the dynamics of intensive variables. For a well-mixed vessel, the time constant of the dynamic response is (R+1) times the mean residence time of the vessel, where R is the recycle ratio (recycle flow rate divided by inlet flow rate). NUTRIENT REACTIONS: Nutrient removal by the biomass in a well-mixed reactor effectively speeds up the dynamics for that nutrient concentration compared to the residence time of the tank. If the effluent concentration is one tenth the influent concentration, the time constant is one tenth the reactor residence time. It follows that time constants for nutrient concentrations will be within an order of magnitude of the reactor residence times, and generally smaller, depending on nutrient removal ratios and recycle ratios. Thus time constants of the order of 1 to 10 hours could be expected. Recirculation of nitrate in a pre-denitrification system is a fast process, since the flow rate is so high. Consequently the nitrate concentration can be changed within minutes. CHEMICAL PRECIPITATION: The most important aspect of chemical precipitation is to achieve rapid and complete mixing. Once the chemicals are mixed with the wastewater, the dynamics are very fast, responding in a matter of seconds. MASS TRANSFER: The transfer of oxygen from a gaseous form to a dissolved form takes place within a time scale of minutes. A change in air flow rates therefore does not immediately affect the dissolved oxygen concentration in the aerator. The respiration rate may change within minutes due to changes in substrate loading or toxic inputs. This will result in DO changes that take place in the time scale determined by the DO dynamics. 16

30 Josep Carrasco Martínez BIOMASS GROWTH: If biomass growth and sludge wastage are in balance, the sludge dynamics time constant is equal to the solids residence time (SRT). The SRT is the solids hold-up divided by the solids wastage, where the suspended solids in the effluent should be neglected with great care. This is typically of the order of several days for the activated-sludge process. Significant changes in the proportions of different species within the biomass could take longer, maybe several weeks for slow growing species. CLARIFICATION: The flow patterns in a clarifier will approximate plug flow upwards for clarified effluent and plug flow downwards for return activated sludge. This would typically involve a dead time of 1-4 hours in each stream. Summarising, it is possible to distinguish three kind of dynamics in wastewater processes attending to the speed; fast dynamic (flow dynamic and dissolved oxygen dynamic), medium dynamic (concentration dynamic and nutrient removal) and slow dynamic (biomass growth). 2.3 MODELLING OF WASTEWATER TREATMENT PROCESSES First, it is necessary to leave clear some questions about the nomenclature in going to be used in this point, in order to understand the equations shown below: S, used for concentrations of components dissolved in wastewater X, used for concentrations of solid components in wastewater V, used to refer to the tank volume (it is assumed is constant) qin or q out, referred to the input and output flow rate After this brief introduction, how modelling wastewater treatment plants is exposed and, as it was shown before, can be divided in different groups: Modelling mass transfer Mass transfer is defined as the movement of a component from one phase to another. The main mass transfer in wastewater treatment is the transfer of oxygen from the air into the water to be used by the biomass. The mass transfer is represented as: r a = K a( S, SO ) (2.1) L O sat, where: r a is rate of oxygen transfer K L is the mass transfer coefficient a is the air water surface area, and S O,sat S O is the concentration difference 17

31 CHAPTER 2: Wastewater Treatment Processes In that way, if we consider a well mixed tank with constant volume, chemical oxygen demand (COD) and water, without taking care about the transfer of oxygen, the component mass balance is the one below: d( VS dt O ) q S = in O, in q out S O (2.2), but now the new oxygen mass balance in the tank is: d( VS dt Modelling biological nutrient removal O ) = q S q S K a( S S ) V (2.3) in O, in out O L O, sat In biological nutrient removal there are involved different processes; carbon removal, nitrogen removal and phosphorus removal. And it is pertinent to add the modelling of a single nutrient, because it has to be modelled not only the nutrient removal but also the biomass present in wastewater. By the other side it is assumed a well-mixed tank for modelling biological nutrient removal. MODELLING A SINGLE NUTRIENT: In the simplest example there are involved three components; water, nutrient and biomass. The microorganisms absorb the nutrient from the wastewater using it to grow and to produce more biomass. We assume constant volume tank and constant density so: Mass balance: q out = qin (2.4) d( VX B ) Biomass balance: = qin X B, in qout X B, out + rbv dt (2.5) d( VS N ) Nutrient mass balance: = qin S N, in qout S N, out rnv dt (2.6), where: r B is reaction rate for biomass growth r N is nutrient reaction rate X B is biomass concentration S N is nutrient concentration MODELLING CARBON REMOVAL: Now let to go further, and to consider four components; water, soluble carbon, oxygen and heterotrophic biomass. It is the simplest example of biological treatment of wastewater. There are the balances shown below: d( VX H ) Heterotrophic biomass balance: = qin X H, in qout X H, out + rhv dt (2.7) d( VS S ) Carbon mass balance: = qin S S, in qout S S, out rsv dt (2.8) d( VSO ) Oxygen mass balance: = qin SO, in qout SO K La( SO, sat SO ) V (2.3) dt O 18

32 Josep Carrasco Martínez, where: r H is reaction rate for biomass growth r S is nutrient reaction rate X H is biomass concentration S S is soluble carbon nutrient concentration MODELLING NITROGEN REMOVAL: The main description of this process was made before, and it was exposed there are two steps for nitrogen removal: 1. Aerobic growth of autotrophs 2. Anoxic growth of heterotrophs Now there are two biological processes; carbon removal and nitrogen removal. The balances of the different concentrations to model the nitrogen removal are: d( VX A ) Autotrophic biomass balance: = qin X A, in qout X A, out + rav (2.9) dt d( VS NH ) Ammonia nutrient mass balance: = qin S NH, in qout S NH, out rnhv (2.10) dt Nitrate mass balance: d(vs ) NO = q in S NO,in q out S NO r NO V (2.11) dt, where: r A is reaction rate for autotrophic biomass growth r NH is reaction rate of ammonia nutrient r NO is reaction rate of nitrate X A is biomass concentration S NH is soluble ammonia nutrient concentration S NO is nitrate concentration MODELLING PHOSPHORUS REMOVAL: In the figure 4 it is shown the process of phosphorus removal. It is evident the phosphorus removal is a complex process for modelling, but there are for basic mechanisms to describe it: 1. Fermentation of fermentable COD, S F, to volatile fatty acids (VFA), S A, which can be utilised by the PAO microorganisms to store carbon as polyhydroxyl-alkanoates (PHA), X PHA. 2. Phosphorus release from poly-phosphate (PP), X PP, into solution at the same time as the VFA is converted to PHA. 3. Phosphorus uptake from solution to PP utilising the PHA and dissolved oxygen, S O. 4. Growth of the PAO biomass, X PAO, also utilising the PHA and dissolved oxygen. And this model of the phosphorus removal process introduces five more mass balances and states: S A, S PO4, X PHA, X PP, X PAO. 19

33 CHAPTER 2: Wastewater Treatment Processes The additional mass balance is integrated with the nitrogen removal model, but it is replaced the single component balance (S S ) by two component balances (S A and S F ) and using the kinetic expressions shown in the tabular forms in appendix I (appendixes to CHAPTER 2). ACTIVATED SLUDGE MODEL Nº1 (ASM1): The Activated Sludge Model No.1 (ASM1) was developed by a task group work in collaboration with the International Water Association (IWA, formerly IAWQ and IAWPRC) in 1983 and published in The state variables included in the ASM1 are listed in the table below: The state variables of the ASM1 model Symbol Variable S I S S X I X S X B,H X B,A X P S O S NO S NH S ND X ND S ALK Inert organic matter Readily biodegradable substrate Particulate inert organic matter Slowly biodegradable substrate Active heterotrophic biomass Active autotrophic biomass Particulate product from biomass decay Dissolved oxygen Nitrate and nitrite nitrogen Ammonia nitrogen Biodegradable organic nitrogen Particulate biodegradable organic nitrogen Alkalinity Table 1: state variables of the ASM1 model. And to model the total suspended solids (TSS), which is a normally measured, in wastewater treatment plants, it is used the following conversion: TSS = 0,75(X I + X P + X S ) + 0,9(X B,H + X B,A ) (2,12) There are eight different dynamic processes in the ASM1 model for describing the dynamics: 1. Aerobic growth of heterotrophs 2. Anoxic growth of heterotrophs 3. Aerobic growths of autotrophs 4. Decay of heterotrophs 5. Decay of autotrophs 6. Ammonification of soluble organic nitrogen 7. Hydrolysis of entrapped organics 8. Hydrolysis of entrapped organic nitrogen Phosphorus removal is not modelled in ASM1 model, the one used in this thesis for programming batch process with Matlab as it will be shown later. 20

34 Josep Carrasco Martínez Modelling hydraulics To begin, it is assumed there are no waves on the surface, so the total flow rate over all the weirs with an arbitrary shape is: q out = N h 0 b( z) v ( z) dz (2.13) z, where: v z (z), is the velocity of the flow rate b(z), is the shape of the weir z, is the translocation from the surface of the weir until where we are measuring the velocity In the flow-sheet below it is shown all of them: figure 7: weir geometry The liquid velocity is calculated from Bernoulli equation: p 1 = p + zρg ρ (2.14) 2 2 stat 0 v z, where ρ is the density and g is the gravity acceleration. It is assumed the pressures are equals, so p stat = p 0 and the velocity of the flow rate is: v z ( z) = 2gz (2.15) If the equation 2.15 is inserted into equation 2.13 the total flow rate becomes: q out = N h 2 g b( z) zdz (2.16) 0 21

35 CHAPTER 2: Wastewater Treatment Processes Modelling settling and clarification For modelling settling and clarification is used the one-dimensional layer model. It only describes the settling process along the vertical axis, leaving cross-sectional area and depth as design parameters. The main assumptions in this model were made by Stenstrom in 1975: The continuous thickener does not exhibit vertical dispersion. The concentration of suspended solids is completely uniform within any horizontal plane within the settler. The bottom of the solids-liquid separator represents a physical boundary to separation and the solids flux due to gravitational settling is zero at the bottom. There is no significant biological reaction affecting the solid mass concentration within the separator. The mass flux into a differential volume cannot exceed the mass flux, the volume is capable of passing, nor can it exceed the mass flux which the volume immediately below it is capable of passing. The gravitational settling velocity is a function only of the suspended solids concentration except when the assumption immediately above is violated. The model was extended to include the clarification zone (not included by Stenstrom) by Vitasovic in The settler was divided into n layers with the feed entering in layer m. It is assumed the feed is instantaneously and completely distributed throughout the feed layer. Thus, the region below the feed level is modelled according to Strenstrom s approach and the clarification zone according Vitasovic s extension of the model. The equations of the model are exposed below: Concentration in each layer (not valid for feed layer and thickening layer) in the settling zone: dx vdn ( X i X i ) ( J s i J s i ) ( J s i J s i ) i 1 + min,,, 1 min,,, + 1 = (2.17) dt zi, where: J s, is the settling flux z i, is the height of layer i Q v dn is defined by: v = u dn A, where Q u is the underflow volumetric flow rate and A is the cross sectional area of the settler. The concentration for the bottom layer is: dx vdn ( X n X n ) ( J s n J s n ) n 1 min, 1,, = (2.18) dt z n 22

36 Josep Carrasco Martínez In the clarification zone, from layer 2 to layer m-1 (where m is the feed layer), it is given the following equation: J = J dx i up, i+ 1 + clar, i 1 up, i clar, i dt z i J J (2.19), where the fluxes are defined as: J = v Qe vup = A (2.21) J s, i if X i+ 1 X t J clar, i = min( J s, i, J s, i+ 1 ) if X i+ 1 > X t (2.22) up, i up X i (2.20) And the equation for the feed layer is: Q X ( v v ) X ( J J ) f f + J dx clar, m 1 up dn m min s, m, s, m+ 1 m dt = A (2.23) z, where: Q f is the feed volumetric flow rate to the settler X f is the suspended solids concentration of the feed. The equation to describe the top layer becomes: m dx dt 1 J up,2 J up,1 J clar,1 = (2.24) z 1 In figure 7 it is shown graphically a general description of the one dimensional layer model. 23

37 CHAPTER 2: Wastewater Treatment Processes figure 8: General description of the traditional onedimensional layer settler model (Jeppsson; 1996) It has been shown the one dimensional layer settler model and all the equations to define it, but it hasn t said anything about the settling velocity. The determination of an appropriate settling velocity model is indispensable for modelling the secondary clarifier using the solids flux theory. In the model used in this thesis it is chosen the empirical double-exponential settling velocity function proposed by Takács et al. (1991): v s r ( ) r ( X X min ) h X X min p ( 0, min( v ', v ( e e ) = max (2.25) 0 0, where: v 0 is the maximum settling velocity r h is a settling parameter characteristic of the hindered settling zone r p is a parameter associated with the settling behaviour at low solids concentrations X min is the minimum attainable concentration of suspended solids in the effluent and it is possible to express it as: 24

38 Josep Carrasco Martínez The minimum attainable concentration of suspended solids is defined by the equation: X min = f ns X f (2.26), where f ns is the non-settleable fraction of X f (suspended solid concentration of the feed) In figure 8 it is shown the function of the double-exponential settling velocity where it is possible to see how the velocity would increase if it was defined by a single exponential function: figure 9: schematic description of the double-exponential settling velocity (equation 2.25) model suggested by Takács et al. (1991) Modelling batch processes Moreover continuous modelling processes there is another possibility which has increased in popularity the last years and it is used in many wastewater treatment plants. This one is Modelling Batch Processes. It means until now, wastewater treatment processes have been model as a continuous system, with biological treatment tanks before the settler, so the wastewater goes through the anoxic tank, after the aerobic and finally to vessel where it takes part the settling and clarification. All of it happens always with constant volume and constant flow rate. In batch processes there is no constant volume and there is no constant flow rate always. The aim of batch processes is to model all biological process in wastewater treatment, including settling and clarification, in the same tank. There is no a tank for a specific biological process, there will be several tanks with a number of distinct time phases. In the figure 9 below is shown the typical activated sludge sequenced batch reactor: 25

39 CHAPTER 2: Wastewater Treatment Processes figure 10: main sequenced batch reactor (SBR) It is possible to see in figure 9 de difference between the phases: Filling phase: The wastewater is going in the tank, so the height of the tank is increasing. It is assumed a well mixed vessel. Mixing phase: The tank is full, the height is equal to its maximum value and it is assumed a well mixed vessel. Now it is taking part the biological processes. Settling phase: The height is still constant and with the maximum value, but in this phase the solid particulates are settling on the bottom of the tank. Draw phase: Finally when the settling process has finished it starts to draw the tank and the cleaned water returns to the weirs. This is the simplest example of batch process. It can have as much phases as the designer needs. For instance it is possible to divide the mixing phase in two phases, one the anoxic phase and the other the aerobic phase. Notice that the balances are the same in all phases but the equations for each one are different depending of the phase where the process is. 26

40 PART II TITLE: Modelling the Wastewater Treatment Plant with Matlab 27

41 28

42 CHAPTER 3 Application Design Now that modelling wastewater treatment plants has been introduced it is time to expose the application designed. This chapter is dedicated to the design of the main application with Matlab, which is connected to the STAR controller. It is included the design of the main code, the structure of the programme, the flow-sheet of the code and the functions which ones it is divided to make easier update the code in the future. Nevertheless, it is not included the data-exchange and synchronization code and the simulink model, the following chapters (chapter 4 and chapter 5) are dedicated to those parts. 29

43 CHAPTER 3: Application Design 3.1 INTRODUCTION In the chapter before it has been introduce how to model and to control wastewater treatment processes to understand the contributions developed in this thesis. But now, it is going to be described the main objective of the thesis. This thesis is the result of the collaboration of the industrial electric engineering and automation department (Lund University) and VEOLIA Water Systems company. The project pretends to develop an automatic application able to communicate with the STAR controller (developed by the company), simulate a model of the wastewater treatment plat which is controlled by STAR and returns the results from the simulation to the STAR controller database. The objective of this project is to improve the control handles. The STAR controller gives to the application some initial values (update the state variables of the plant model), the application simulates the plant model and returns another values to the STAR controller. The purpose of this data exchange is to make possible to compare the expected data (data from the simulation) with the real data measured from the wastewater treatment plant. Then it is possible to check differences between the expected results and the real results, and it makes easy to find out mistakes in the control strategy. And the controller is going to ask for new data from the simulation process to compare with the real measurements periodically, it means there is one part of the application is going to be executed regularly when it is running. One of the worst problems in wastewater treatment plants is the dynamic of biological processes, it is very slow. It makes a mistake in control strategy is detected after days, even weeks sometimes. With this kind of control, comparing the real data with expected data, it is possible to detected mistakes faster, and it makes possible to reduce the waste resources along the application process of a new control strategy. Now it is defined the problem, it has to be defined the connection between the database and the application and the platform to developed the application. As STAR controller has web-based interface, the application has to be able to connect with the database through Ethernet. The platform chosen to develop the application is Matlab, which is be able to exchange data through the network and to simulate a complex model necessary to simulate wastewater treatment processes (with Simulink features). 30

44 Josep Carrasco Martínez 3.2 MAIN FLOWSHEET Once we know what the application has to do, it is necessary to set the different tasks within the application and the order of them. In the figure below is represented graphically the main tasks of the process that the application has to realise and the order of them: INITIALIZATION CONNECT TO THE DATA BASE TO READ DATA FROM CONTROLER SIMULATION OF THE PROCESS CONNECT TO THE DATA BASE TO WRITE DATA FROM THE SIMULATION figure 11: flow-sheet diagram As it is shown there are two tasks with the name of connect to the database, but one is for reading data from the database and the other to write data in the database, so they are different tasks, although it is necessary to connect to the database in both of them. It means there is one similar feature in these tasks. They are defined the main tasks of the application, but there is one feature very important and it is necessary to take care of it, because it will change the configuration of all the application. This feature is the recursive characteristic of some tasks. Therefore there is one main loop in the process where the recursive tasks will be included and there is the initialization block, necessary to start running the program and the simulation of the wastewater treatment plant. The main structure for the design is shown below: MAIN LOOP READ DATA INITIALIZATION PROCESS SIMULATION WRITE DATA figure 12: main parts of the program So there are the tasks are going to be executed only at the beginning of the application ( initialization block in figure 12) and the tasks are going to be executed each period defined by the controller ( main loop block in figure 12). Finally there are summarized the main tasks that the application has to do, but now it is necessary to expose the specifications imposed by the company: The simulation background for the prototype is Matlab/Simulink. 31

45 CHAPTER 3: Application Design The communication with the database and the STAR controller through Ethernet (XML files). The period of the main loop is 2 minutes approximately. 3.3 STRUCTURE OF THE PROGRAM In the point before (3.2 Main Flow-Sheet) it has been analyzed the main structure of the application is going to be developed, but more over the main tasks of the application, in this point it is discussed and presented the full structure of the program with its functions and all the features needed to program it. If we remember again the main diagram of the process to program (see figure 13): figure 13: diagram of the process There are two tasks that they need to connect with the database of the STAR controller, well for reading data, well for writing data. It means the application is acceding to another program that is being used by the STAR controller too. It is evident a synchronization is needed to avoid problems between both applications; the controller and the verification data application. Thus, a synchronization block must be included within connect to the database block, but which one of them? To ask this question make us to see there is more than one possibility of synchronization with the STAR controller. Below are presented some possibilities: Function of synchronization inside the block connect to the database to read : As it is shown in figure 14, the INITIALIZATION synchronization takes part when the application is going to SYNCHRONIZATION read data from the CONNECT TO database, after this THE first synchronization, DATABASE TO the program read the READ DATABASE READ data, simulate the process and write the results in the database. When all Matlab ALGORITHM the process is finished it waits for another synchronization to start again the main loop. WRITE DATABASE CONNECT TO THE DATABASE TO WRITE figure 14: synchronize when reading 32

46 Josep Carrasco Martínez Function of synchronization inside the block connect to the database to write : This time, the synchronization is made just before the application is going to connect to the database to write data, that is, the application starts to run, initialize all the variables, connect to the database to read data, simulate the process, synchronize with the controller and connect to the database to write the results. Then, it repeats the process again until the synchronization step. It means it has taken part the first access to the database without any control when the application has read the data to simulate the process. The process is shown in figure 15. Of course it is possible to program some kind of control to avoid this first access to the database without control the first time the application starts to run. figure 15: synchronize when writing INITIALIZATION READ DATABASE Matlab ALGORITHM SYNCHRONIZATION WRITE DATABASE CONNECT TO THE DATABASE TO READ CONNECT TO THE DATABASE TO WRITE Function of synchronization in both blocks, that is, there are two synchronizations: This third possibility, although longer than the others, its complexity let the application synchronize each time it is going to connect with the database. Now, there is synchronization in both blocks that they connect to the data base, as much as the application is going to read from the database as it is going to write in the database. The structure of the process now it is shown in figure 16, on the right of these lines. First there is synchronization before connecting to the database, the simulation of the process follows that step and finally there is another synchronization before writing the results in the database. Then the main loop starts again. figure 16: double synchronization INITIALIZATION SYNCHRONIZATION READ DATABASE Matlab ALGORITHM SYNCHRONIZATION WRITE DATABASE CONNECT TO THE DATABASE TO READ CONNECT TO THE DATABASE TO WRITE 33

47 CHAPTER 3: Application Design All the ways of synchronization explained before are correct to program the application, but the way to synchronize when writing has one difficult, it is necessary to make a pre-synchronization in the initialization block before starting the main loop, then we avoid the application accesses to the database without the controller allows it. The new flow-sheet is shown in figure 17. There is a pre-synchronization function after the initialization block, so now the application doesn t start to access to the database until it is allow to it. This presynchronization just would take part once at the beginning of the applications, each time it starts to run. figure 17: synchronize when writing with pre-synchronization By the other side, for synchronizing when reading or the last way (synchronizing always) it is no needed any extra-function to pre-synchronize the application because there is always a synchronization before the first reading time, something never happens in synchronizing when writing the first time that the main loop is executed. The synchronization chosen is the third case: double synchronization (before reading and before writing in the database). In the chapter after (chapter 4: data exchange ) it is explained in detail the synchronization function, and in the next point; 3.4 program code the code for both synchronization ways (synchronization when reading and synchronization always) is implemented, because it is the same code and the same function to synchronize but, this function is used once in synchronization when reading and twice in the other case. Thus they will be shown two solutions for the synchronization problem. Now it is going to be exposed the function of each blocks in the points bellow, following the main division made before: Initialization of the application. Main loop of the application. 34

48 Josep Carrasco Martínez Initialization This part of the code includes all data which need to be initialized and it is divided in several kinds of initializations: Model parameters initialization: It means, to establish the value of the constants, the initial value of the parameters for the simulations, the value for the parameters of simulation, the initial conditions of the simulation background. Model state variables initialization: This part seems unnecessary, but it is a mistake to avoid this point. Simulink always starts all state variables from cero value if there are no specific initial values for them. Thus, with a first simulation of the model it is possible to establish the initial value for the state variables trying to approximate the initial value of the state variables in the simulation process to the initial value of the state variables in the real wastewater treatment process. Control parameters initialization (to start the loop and the simulation): They have been included within the application the possibility of stopping the simulation when the application is running and the possibility to stop all the process of data acquisition, simulation and data writing (to make possible break the main loop). In this part of the code the control variables are initialized to make the main loop and the simulation run. Synchronization parameters initialization: This is another critic point. The variables used for the synchronization are modified by the STAR controller, which allows the application to read and write in the database, but at the beginning of the application running it is not possible to know the value of the synchronization variables stored in the memory, so it is suitable to initialize the variables to the expected values Main loop The main loop implementation is more complex than the initialization, here is where all processes take part, the connection with the database to read, the simulation process, the second connection with the database to write. After making reference to all theses processes it is evident the main loop is divided in three parts (see figure 6 shown before). Below these parts are defined: Connection to the database to read As it was shown before there are two steps to connect to the database, first the synchronization and after the access to the database to read the data. The two steps are explained below: Synchronization: The synchronization is important for two main reasons: to avoid the access of two applications at the same time to the same file and to ensure there is no repetition of data, it means, that the application does not simulate the process more than once when the controller needs the data only once, or there are new results of the simulation when the controller asks for them and they are not the ones of the past simulation. Summarizing, there are new 35

49 CHAPTER 3: Application Design results when the controller asks for them, there is no simulation of the process when the controller does not ask for it. Hence, the synchronization allows to forbid the application accesses to the database until the controller needs the results of the simulation, then it let the application gets the data from the database, simulate the process and write the results. To get the purpose exposed before it has been implemented one auxiliary loop to synchronize with the controller. Inside this loop the application is asking for accessing to the database until the controller answers that it is possible, then the loop is bracken and the application goes on with the steps of the process (read the data, simulate the process and write the data if there is no double synchronization). In the case chosen, the double synchronization, there are two synchronizations, one before reading the database and the other before writing the results in the data base, so for each time the controller needs data it has to synchronize with the application twice. The improvement of the double synchronization case is discussed in the point Program code, because this improvement is related with the implementation. Read from database: Once the synchronization has taken part, the application accesses to the database and gets the values stored in it within variables in order to be able to manage them in Matlab background. The values needed to the simulation are the name, the numerical value and the quality value of each variable, so the result after reading the database will be three vectors, one with all the names stored (vector name ), one with the values stored (vector value ) and the last one with the quality of each value stored (vector quality ). This file stores the values so that the component i of each vector belongs to the variable i, it means: namei name = [ name... namei... name ] 1 n var iablei = value i value = [ value1... valuei... valuen ] qualityi quality = [ quality1... qualityi qualityn ] where i = 0,... n, and n is the number of variables acquired. Matlab Algorithm The Matlab Algorithm, the most important step of the main loop. The other steps are implemented to get the variables to the simulation of the process in Matlab and to return the results of Matlab simulation to the database, it means, the other functions are programmed to communicate the simulation process with the controller. 36

50 Josep Carrasco Martínez The Matlab algorithm is divided in three parts: processing the data before the simulation and processing the data after the simulation. Bellow is shown the diagram of the Matlab algorithm: PROCESSING DATA Matlab ALGORITHM PROCESS SIMULATION figure 18: Matlab Algorithm PROCESSING DATA Processing data before the simulation: As it has been told before, the function to read the data from the database stores them in three vectors. But these three vectors contain information about the variables about the name, value and quality. To use them it is necessary to store the information in another format. This first step of the Matlab algorithm is the responsible of making the translation of the information received from the database to make possible its use in the simulation process. Process simulation: After all the steps to acquired the data and translate them, it is possible to make the simulation. In this step the application executes the necessary commands to simulate the simulink file which includes the model of the wastewater treatment plant. This model included can be whatever the company wants, from only a simple model of the wastewater treatment plant to a complex model of the wastewater treatment plant and the sensor models and with a model of the controller. The possibilities are limited only by the simulation time needed and the capacity of the computer used. Processing data after the simulation: This last step is the data treatment before sending them to the database. The simulation returns the data in a specific format, that format is not the appropriate to send them to the controller and to store them in the database the most of times. Here all data are processed and expressed in the format used by the function which writes them in the database. This format is the one used when the application reads from the database, where all data are stored in three vectors, one with the names of the variables, another with the values of the variables and the last one with the quality of the variables. The output of this step of the Matlab algorithm is the three vectors shown below: name = [ name1... namei... namen ] value = [ value1... valuei... valuen ] where i = 0,... n quality = [ quality1... qualityi qualityn ], and n is the number of variables acquired. 37

51 CHAPTER 3: Application Design Write in database As it was shown before there are two steps to connect to the database, first the synchronization and after the access to the database to read the data. The two steps are explained below: Synchronization: Here the synchronization if exactly the same function described in the point before read from database. There is one auxiliary loop asking for access to the database. When the access is allowed the loop is bracken and the application goes on to the next step: write the results in the database. Write to database: Once the synchronization has taken part, the application accesses to the database and writes the results the application has got from the simulation. The application has to write these three vectors in the database: name = [ name1... namei... namen ] value = [ value1... valuei... valuen ] where i = 0,... n quality = [ quality1... qualityi qualityn ], and n is the number of variables acquired. These three vectors have the same meaning and the same structure as the three vectors read from the database. 3.4 APPLICATION IMPLEMENTED Until now, in the points before it has told how to implement the automatic application, which simulates the wastewater treatment plant process and which is controlled by the STAR controller. There have been shown the structure of the program and the necessary blocks to get the purpose. In these last points of the chapter is presented the code programmed and the graphic interface of the application, so it will be easy to modify and to improve the code, it means, to update the code for future versions. Right now, the version of the application developed is a prototype and it is able to do all requirements which the company was asking for. In the point below it is show the application, how it works and the code. It is divided in two points; the first to expose the application and the last to explain the code Application Interface As all application software, it is needed a user interface to let the user manages the program. The user interface has been developed with GUIDE. A brief introduction about GUIDE is made in ANNEX II, and to know more about the code implemented to program the application is recommended to consult ANNEX II. The purpose of this point is to present the user interface developed. 38

52 Josep Carrasco Martínez Due to the simple actions that the user has to realise to run this application, the user interface is very simple. Bellow is shown in figure 19 the user interface developed: figure 19: User Interface The user interface has four buttons, two main buttons to run and to stop the program and another two to check that the synchronization is working right. The use of each button is: RUN PROCESS : Push this button to start the application. This button executes the file which contains all the code with the initialization block and the main loop, so once the application is opened and the user press the button RUN PROCESS it is not necessary to do any action in the program, it will run until the user presses STOP PROCESS, the user closes the application or the STAR controller makes the application to go out of the main loop using the control variables (aux_sim and aux_loop). STOP PROCESS : The process can be stopped from the controller or from the user interface. To stop it from the user interface the user just has to push the button STOP PROCESS and the program will go out of the main loop. The other two buttons are programmed to emulate the STAR controller only with the synchronization of the simulation. As the application has been developed to have double synchronization, there are two buttons, one to check the synchronization before reading from the database and another to check the synchronization before writing data in the database. READ FROM DATABASE : When the application is running it is waiting until the controller let it to access to the database before doing the simulation of the plant model. This button changes the value of the variables for the synchronization as it was the STAR controller, so if the application goes on with the simulation it means it is reading right the control variables. It is a good way to check if it is failing the Ethernet connection or the application if there is no synchronization. WRITE IN DATABASE : This button has the same function as the one explained before, but for the second synchronization. If we implement the program with single synchronization it is possible to use the same user interface, but this button doesn t have to be used, or it has to be removed. 39

53 CHAPTER 3: Application Design Program code In the following lines it is detailed all the code implemented to program the application described along this chapter. The lines in red are comments introduced within the program code, so the compiler doesn t take care about these lines to execute the application code. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% MAIN PROGRAM TO SIMULATE THE WASTE WATER TREATMENT %%% %%% PLANT %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The first part that the program executes is the initialization functions. These functions are used once each time that the button START PROCESS (see point application interface ) is pushed to start the application. The functions used in this part are shown bellow. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% INITIALIZATION %%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Here the program calls the Matlab file INIT.m. Inside this file all the variables and constants needed to the simulation of the process are defined. After, the program simulates the plant model to get the initial conditions of the state variables with the command sim( name of the file of the plant model ). The last line is to define the vector x to store the values of the initial values of the state variables. This part can be called model parameters initialization and model state variables initialization (see point Initialization described before). %Initialize parameters INIT; %file.m to initialize all parameters of the model % simulate plant to steady state sim('plantmodel'); x=xinitial; The following part is to initialize the control parameters. These parameters control the simulation and the main loop. If the variable aux_loop is equal to the value one the condition to go in the loop is complained and the application will run. The other variable is aux_sim, and if it is equal to the value one the main loop is running but there is no simulation of the wastewater treatment process model. Thus, the application has the possibility of stopping the simulation if the controller doesn t want to do it. The code initializes the value of both variables to one, so the application always starts executing the main loop and the simulation of the process. After the first time that the main loop is executed, the program read again the value of the control variables and it decides if the simulation or the main loop has to stop. In the point where it has been explained before this part was called control parameters initialization. %Initialize control parameters control_value = [1 1]; 40

54 Josep Carrasco Martínez controlloop(control_value); %read control parameters [aux_loop aux_sim] = control_check; %we are reading control.xml NOTE: check the APPENDIX II to read more about the functions controlloop and control_check. About how the application is connecting with the database, read the next chapter chapter 4. To control the synchronization with the STAR controller have been defined two variables: readv and writev. The controller will change the value of these variables to choose if it needs the application read data from the database or the applications writes in the database. In the initialization the values chosen are readv=0 and writev=1, so in the first synchronization at the beginning of the main loop, the application will wait until the controller chose the read option, it means, readv=1 and writev 1. This part is called synchronization parameters initialization. %variables to synchronize with the controller readv = 0; %when it has to read the XML file writev = 1; %when it has to write the XML file This last part of the initialization is used to initialize the value of one variable used to read the data from the database. It is explained in detail in the following chapter. % initialization variable to read from database datatag=['data']; Now, all the variables of the model and the variables of the program (synchronization variables and control variables) are initialized and the program executes the main loop to simulate the plant process each time STAR controller requires it. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% MAIN LOOP %%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% At the beginning of the main loop, the first thing the code is doing is to check the value of the control variable aux_loop (it has been initialized to the one value before). If the value is the one expected the main loop starts running. After there is a conditional instruction to check the other control variable: aux_sim. If the value is not the expected the main loop executes itself but there is no simulation. As aux_sim has been initialized to unity value this first time that the main loop is executed the simulation will run. while aux_loop = = 1 %variable used in the application to stop the simulation if aux_sim ~= 1 disp('simulation stopped') pause(5); end 41

55 CHAPTER 3: Application Design %process execution. I can stop the simulation if aux_sim not equal 1 if aux_sim = = 1 The following step once the control variables are checked is the synchronization. For the synchronization there are two possibilities: single synchronization and double synchronization. As it is shown in the code bellow, the implementation is the same in both cases, but there is one difference, in single synchronization there is one more line of code (code inside keys). As well as in double synchronization is the controller the one which changes the value of the synchronization variables always (there is one variable each time the controller synchronizes, when reading and when writing), in single synchronization it is only used the one variable ( readv ), because there is only one synchronization, when the application is going to read from the database. So, when the controller changes the value to the variable readv to indicate it is possible to read data from the database, the application has to reset this variable after going out of the synchronization loop in order to avoid that the application starts to simulate the process out of control because it read readv always as set value. The problem of the single synchronization is that the controller can t reset the synchronization variable readv. With the double synchronization this problem disappears. There are two synchronization variables: readv and writev. So, the first condition to synchronize is to have readv=1 and writev 1. After, the application will wait until the second condition: readv 1 and writev=1. It is evident is impossible to lose the control of the main loop. The controller is the one which changes the value of the synchronization variables, and like there are two stops along the main loop to synchronize the application will always simulate the plant model once each period. Below is shown the code for both cases: single synchronization and double synchronization. CASE SINGLE SYNCHRONIZATION %Synchronize with the server while readv ~= 1 %we wait for the signal of the server, so we can synchronize each 6 minutes [readf writef]=synchronizer; if (readf==1) & (writef~=1) readv=1; writev=0; break else readv=0; disp('we can not read now') end pause(15); %we wait 15 seconds until read again the file end %the variable is rise to 0 to stop the loop when it has to read data again readv=0; CASE DOUBLE SYNCHRONIZATION %Synchronize with the server while readv ~= 1 42

56 Josep Carrasco Martínez %we wait for the signal of the server, so we can synchronize each 6 minutes [readf writef]=synchronizer; if (readf==1) & (writef~=1) readv=1; writev=0; break else readv=0; disp('we can not read now') end pause(15); %we wait 15 seconds until read again the file end NOTE: the function used to synchronize with the controller is explained the next chapter chapter 4. Once the synchronization has taken part the program accesses to the database to read the data. First are defined the three vectors where the values of the variables are going to be stored: namer to store the names of the variables, valuer to store the values and qualityr to store the quality of the value read. The function readxml used to access to the database is discussed in the following chapter chapter 4. The code implemented in the main code is presented below: %Read from database namer=['']; valuer=[ ]; qualityr=[ ]; [namer,valuer,qualityr]=readxml(datatag); %file.m where we must read the data from database The next step after reading the data from the database is to execute the Matlab Algorithm, which is divided in three functions shown below: MATLAB ALGORITHM The first thing the Algorithm has to do is to translate the data read into a format useful for the model is going to be simulated in Simulink. The function read_data is responsible to do this task. An example of how to implement this function is detailed in APPENDIX II. %Initialize parameters with the new data read_data; %file.m to initialize with the new data Following the translation of the data read is executed the simulation of the process. It is done in two steps; first the options for the simulation are set with the function simset, and finally the model is simulated with the function sim. Both functions are standard functions from Matlab, for more information about them it is recommended to use the help of the program. %Simulate the model options=simset('initialstate',x(end,:),'solver','ode45'); [t,x]=sim('plantmodel',[t(end) t(end)+6/60/24],options);) 43

57 CHAPTER 3: Application Design The last step of the Algorithm is to translate the results of the simulation into the three vectors needed to send the data to the controller. To get this task is used the function wirte_data. As before with the function read_data, there is an example of how implementing this function in the APPENDIX II. %Write the new data in vectors form work space write_data; %function to write the data in three vectors CASE DOUBLE SYNCHRONIZATION This code is only present in the program when it is implemented the double synchronization. If it is used the single synchronization it is not necessary. %Synchronize with the server while writev ~= 1 %we wait for the signal of the server, so we can synchronize each 6 minutes [readf writef]=synchronizer; if (writef==1) & (readf~=1) writev=1; readv=0; break else writev=0; disp('we can not write now') end pause(15); %we wait 15 seconds until read again the file end The outputs of the Matlab Algorithm are three vectors: name, value and quality. These three vectors have the same structure than the vectors read from the database, but they have stored the values of the results of the simulation. The function writexml has been implemented to send the data to the database. The function is explained in chapter 4. %Send data to the database n=length(value); writexml(name,value,quality,n); %we write all data i an XML file end The last step of the program is to check the value of the control variables in order to know if the main loop has to go on running or the controller has ordered to stop with the simulation. %it tests if the simulation or the main control loop has to stop or not %read variable "aux_loop" and variable "aux_sim" [aux_loop aux_sim] = control_check; %we are reading control.xml end NOTE: check the APPENDIX II to read more about the function control_check. 44

58 CHAPTER 4 Data Exchange The main application implemented has been shown in the chapter before, what is its purpose, the implemented code, the user interface, all the features. And it was said that one of the most important things is the communication with the STAR controller to: synchronize the application and the controller, to read data from the database, write the data and stop the application from the controller. Now, how the application interacts with the controller is detailed in this chapter, it means, the code of all the functions used to transmit the data between the controller and the application or in the other way around, and the files where the variables are stored. 45

59 CHAPTER 4: Data Exchange 4.1 Introduction Talking again about the purpose of this thesis, in the figure below (figure 20) is shown the diagram of the project developed taking care only about the communication between all of the devices involved: figure 20: communication diagram It is possible to see that there are three main devices: STAR controller: which is connected directly with the wastewater treatment plant and it receives the measurements of the sensors that there are installed. Database: which stores the different values that the controller gets from: the sensors, the control action applied, the time, the data, at last, all data that needs to be analysed. Matlab application: Application developed in this thesis which simulates the wastewater treatment plant and gives the results to the controller, which compares the real results with the expected results got in the simulation process. And, as it was said before, these three devices are connected using the Ethernet protocol. So, the functions implemented in the main code shown in chapter 3 (point program code) must be able to connect with the controller and the database using an Ethernet protocol. Nowadays, the different platforms connected through Ethernet are using different application code: the Matlab application is running under Windows Operative System, the database is running in the same interface or another and the STAR controller is a specific device able to use Ethernet network but not running under Windows Operative System. The best way to connect them is using Web Services (see APPENDIX II to better understanding). Web Services provide an abstraction layer between the client 46

60 Josep Carrasco Martínez application and the code application, it means that there is a layer programmed between the code application and the network, so it doesn t mind if the code application of the different platforms is not the same, because after the abstraction layer it will be possible communicate all of them. This abstraction layer translates the message into a standard that can be read by the other client application. In the figure below is represented the abstraction layer: figure 21: abstraction layer Specific communication makes reference to the communication between the application and its Web Service. Agnostic communication makes references to the network, where is possible to use whatever way of communication because with web services we are using a standard for the sent messages and the received messages understood for all listeners. To program the Web Services is possible to use an amount of codes to program the web services, which makes difficult the choice: java, Visual C, Basic, C++, Perl, etc. By the other side there are a lot of possible standards that can be chosen as XML protocol, XKMS, SAML, XML-Dsig, XML-Enc, XSD, P3P, WSFL, Jabber, ebxml, SOAP, etc. But the one used by the company to communicate the database and the STAR controller is SOAP protocol, which is going to be introduced in the next point What SOAP is Simple Object Access Protocol, that is SOAP. Let define in a few lines SOAP as a standardized packaging protocol used to transmit and receive messages by applications through Ethernet. SOAP is an application of the XML specification. It means that the basis of SOAP is formed by XML messaging (applications exchange information using XML documents). The best thing of SOAP protocol is that is based in XML, and XML is not tied to any application, operative system, programming language or whatever other technical implementation. With XML is possible to share information using only a message encoded understood by the applications, which are going to transmit and receive message. 47

61 CHAPTER 4: Data Exchange This step of the project design has been made by the company, so this introduction to SOAP protocol is not going further (to know more check the APPENDIX III and the bibliography). The company has developed an intermediated application which receives and transmits the messages into SOAP protocol through the network. Now the diagram of the communication is the following: figure 22: SOAP interface Beginning from here, the code implemented has to be able to read and translate the information that is going to arrive as XML data file. Thus, the communication between the application developed with Matlab and the other devices is reduced to read and write XML files XML communication files Definitely, the Ethernet communication between the application developed in Matlab and the STAR controller and the database has been reduced to the task of writing and reading XML files. Hence, to write an XML file will be equivalent than to send a message to the controller or to the database, and to read an XML file will be equal than to receive a message. It takes us to think about another question, if to write or to read an XML file is like writing or reading a message, it will be necessary to use one XML file for each kind of message, it means, one file for control variables, another for synchronization variables, another to read data from the database and at last one for writing the results from the simulation. The four XML files that store and are used to transmit and receive the information are the following files: 48

62 Josep Carrasco Martínez database.xml : the dates from the database, that the application needs to use in the simulation, are stored within this XML file. After reading the file, these dates are stores in three vectors with the values of the variables. The structure of the file is: <?xml version="1.0" encoding="utf-8"?> <dataexchange>... <data> <name>name(1)</name> <value>value(1)</value> <quality>quality(1)</quality> </data> <data> <name>name(n)</name> <value>value(n)</value> <quality>quality(n)</quality> </data> </dataexchange><!--this is a comment--> results.xml : the Matlab application writes the results of the simulation in this file. The controller will read the values stored here. The structure of the file is: <?xml version="1.0" encoding="utf-8"?> <dataexchange>... <data> <name>name(1)</name> <value>value(1)</value> <quality>quality(1)</quality> </data> <data> <name>name(k)</name> <value>value(k)</value> <quality>quality(k)</quality> </data> </dataexchange><!--this is a comment--> synchro.xml : the value of the variables used for the synchronization is stored within synchro.xml. The controller writes the values and the Matlab application reads the content stored inside the file. The structure of the file is: <?xml version="1.0" encoding="utf-8"?> <synchronize> <sincro> <read> readf value </read> <write> writef value </write> </sincro> </synchronize> 49

63 CHAPTER 4: Data Exchange controlfile.xml : This XML file has the same function as synchro.xml, but this file stores the value of the control variables, variables that are modified by the controller and read by the Matlab application. The structure of the file is: <?xml version="1.0" encoding="utf-8"?> <control> <data> <loop> aux_loop value </loop> <simulation> aux_sim value </simulation> </data> </control> NOTE: to know more about the variables that are stored in each XML file and for what is using the application each variable, it is recommended to check the point Program code in chapter 4. The function of each variable is not the purpose of this chapter. The functions implemented to modify the files shown before within the application code are: control_check : to read controlfile.xml. This function is described in the point II.2.2 control_check code in APPENDIX II. controlloop : to write controlfile.xml. This function is described in the point II.2.1 controlloop code in APPENDIX II. synchronizer : to read synchro.xml writexml_synchro : to write synchro.xml. This function is described in the point II.1.1 writexml_synchro code in APPENDIX II. readxml : to read database.xml writexml : to write results.xml 4.2 Data-flux in the communication Now we have arrived to this point is evident that the problem of the communication of the application has been reduced to implement two functions: the function which reads the XML file and the function which writes the XML file. Because of there are four XML files, there are necessary more than one function to read and one to write, it means, it would be needed two functions for each XML file. Remembering the file database.xml only needs to be read by the application but not to be written, and results.xml to be written by the application but not to be read. The number of necessary functions is six; three functions to read and three functions to write (the six functions are shown up in point XML communication files ). It seems better to try to implement a general function to read and another to write, and use both of them for reading and writing the four XML files. The problem is that it supposes to define the functions with a lot parameters as a variables, then, each time is going to be read or write an XML file these parameters have to be introduced into these functions. Thus, as the functions are not large (the largest one near fifty code lines) and the number of variables in the Matlab work-space can be reduced, at the moment the 50

64 Josep Carrasco Martínez solution with six functions is preferred. It has to be considerer that the code of the functions to read and to write would be increased considerably if we try to write or read four different structure message with the same functions. Despite to have six functions, all of them follow the same data flux shown in the figure 23 ( figure 23.A represents the data flux when writing the XML file and figure 23.B represents the data flux when reading the XML file): Writing XML file xdoc java class xmlfilename = [ name, xml ] xmlwrite(xmlfilename, xdoc) Reading XML file XML file XML file xdoc = xmlread ( name of the File ) figure 23: data-exchange. A) write data into file.xml, B) read data from file.xml. The diagrams shown in figure 23 represent the procedures used to read and write XML files. There is one common step in both diagrams (figure 23.A and figure 23.B), this step is the definition of the variable xdoc, variable used to store the values contented in the messages expressed as a XML files. The variable is the type of org.apache.xerces.dom.documentimpl (check APPENDIX III to know more about it), which is a class needed by the command xmlwrite() to create the XML file, and is the class that the command xmlread() returns when it is reading the XML file. The steps followed to write an XML file are: 1. To create the variable xdoc of type org.apache.xerces.dom.documentimpl. 2. To create the XML file with the variable xmlfilename. 3. To use the command xmlwrite(xmlfilename, xdoc) to generate the XML file. 51

65 CHAPTER 4: Data Exchange The steps for reading the XML file are: 1. To use the command xmlread(name of the XML file) to store the XML file inside the variable called xdoc of type org.apache.xerces.dom.documentimpl. 2. To scan the variable xdoc and extract the information stored. 4.3 Data-exchange with the database In the points above it has been explained the kind of communication used between the Matlab application and the others devices connect to the network (STAR controller and database), the protocol used and the data-flux in the functions implemented to make possible this communication. Here the functions used to get data from the database and to write data inside the database are exposed explaining all the code implemented step by step Write the data in results.xml The file results.xml is the XML file that the SOAP interface developed by the company sends as a message to the database with the results of the simulation of the Wastewater Treatment process. In agreement with the company the structure of the XML file has to be the one shown in the point Communication files and below these lines: <?xml version="1.0" encoding="utf-8"?> <dataexchange>... <data> <name>name(1)</name> <value>value(1)</value> <quality>quality(1)</quality> </data> <data> <name>name(k)</name> <value>value(k)</value> <quality>quality(k)</quality> </data> </dataexchange><!--this is a comment--> As it can be appreciated, there is a number of n elements (children) called data that have three sub-elements: name, value and quality. Each element represents one variable with three properties, the name of the variable to know which variable is, the value of the measurement of this variable in the wastewater treatment plant stored in the database and the quality of this measurement. The file database.xml that has to be read by the application has to follow the same structure than the XML file results.xml. 52

66 Josep Carrasco Martínez In the following lines is explained the code implemented to write the XML file as it was shown in the lines above in this point. writexml code function archivoxml=writexml(name,value,quality,n) This first part of the code is the one which makes reference to the step one mentioned in 4.2 Data-flux in the communication, to write an XML file: to create the variable xdoc of type org.apache.xerces.dom.documentimpl. The variable created is docnode. % Create a sample XML document. %program docnode = com.mathworks.xml.xmlutils.createdocument('dataexchange'); docrootnode = docnode.getdocumentelement; Inside the same step, as the function does not know how many data children has to create, it goes in a loop that will do as much children as long was the vector name (remember that the vectors name, value and quality have the same size). for i=1:n dataelement = docnode.createelement(sprintf('data')); nameelement = docnode.createelement(sprintf('name')); valueelement = docnode.createelement(sprintf('value')); qualityelement = docnode.createelement(sprintf('quality')); end nameelement.settextcontent(sprintf('%s',name(i,:))); %name of the variable valueelement.settextcontent(sprintf('%2.2f',value(i))); %value of the variable qualityelement.settextcontent(sprintf('%2.2f',quality(i))); %quality of the variable The first part of the loop is to create the child with the three sub-elements (the lines above), and the last lines of the loop are to close each child once it has been created. dataelement.appendchild(nameelement); dataelement.appendchild(valueelement); dataelement.appendchild(qualityelement); docrootnode.appendchild(dataelement); The second step is: to create the XML file with the variable xmlfilename. To do it is defined a structure with two elements: the route where is going to be created the file and the extension of the file (note that if it is only defined the name and not the route the function xmlwrite will create the XML file in the current directory). % Save the sample XML document. xmlfilename = ['results','.xml']; %we have the file in our current directory 53

67 CHAPTER 4: Data Exchange Finally it is executed the function xmlwrite to create the XML file and finish with the third step: to use the command xmlwrite(xmlfilename, xdoc) to generate the XML file. xmlwrite(xmlfilename,docnode); NOTE: All the functions implemented to write an XML file follow the same structure that has been exposed above, so all the comment in this point is not going to be told anymore along this thesis, except if it is necessary Read the data from database.xml The function readxml is the one which will read the file database.xml, where are stored the data that the database sends to the application. The structure of the XML file that is going to be read has to be the same exposed before for results.xml. readxml code As it has been said in the point 4.2 Data-flux in the communication, the function read the XML file in two steps: 1. To use the command xmlread(name of the XML file) to store the XML file inside the variable called xdoc of type org.apache.xerces.dom.documentimpl. 2. To scan the variable xdoc and extract the information stored. function [a,b,c]=readxml(data) Definition of the auxiliary variables: dataname=['']; datavalue=[]; dataquality=[]; infolabel = 'Plot Tools'; infocbk = ''; itemfound = false; The first step is made here (to use the command xmlread(name of the XML file) ), when the information stored in the XML file passes to the variable xdoc. The function used to define the variable is xmlread, which needs one parameter; the name of the file with the extension. Thus, the function looks for the XML file in the current directory, if the file is in another directory the parameter included will be the name of the file with the extension and the route: C:/program files/application/files/database.xml, for example. xdoc = xmlread('database.xml'); 54

68 Josep Carrasco Martínez Here starts the second step. Previous to go in the loop used to scan the class where is stored the XML message, it is define the variable alllistitems. This variable stores the number of children data in the message that is the same as the number of variables stored in the message. % Find a deep list of all list item elements. alllistitems = xdoc.getelementsbytagname(sprintf('%s',data(1,:))); Once it is known the number of children data (check the structure of the message shown before) the loop scans the class storing all variables in a vectors to work in the application. % Note that the item list index is zero-based. for i = 1:allListItems.getLength %it's looking for all items with <data(i,:)> thislistitem = alllistitems.item(i-1); childnode = thislistitem.getfirstchild; With this while loop we ensure the function scans the child until it has read all the sub-elements inside each child. while ~isempty(childnode) %Filter out text, comments, and processing instructions. if childnode.getnodetype == childnode.element_node % Assume that each element has a single % org.w3c.dom.text child. childtext = char(childnode.getfirstchild.getdata);%get the data text Inside each child there are three sub-elements, the switch is used to store the value of each sub-element inside the vector that it has to be stored in. switch char(childnode.gettagname) case 'name'; %itemfound = strcmp(childtext, infolabel); dataname(i,:)=sprintf('%s',childtext);%to get the data name case 'value' ; %infocbk = childtext; datavalue(i)=sscanf(childtext,'%f');%to get the data value case 'quality' ; dataquality(i)=sscanf(childtext,'%f');%to get de data quality end end % End IF childnode = childnode.getnextsibling; end % End WHILE if itemfound break; else infocbk = ''; end end % End FOR 55

69 CHAPTER 4: Data Exchange Finally the three vectors got from the scanning of the XML file are stored inside the vectors a, b and c that the function is going to return to the Matlab work-space. %read value a=dataname; b=datavalue; c=dataquality; 4.4 Synchronization As it has said before, the synchronization is made through the communication between the application and the STAR controller. The controller writes the value of the variables used for the synchronization in the file synchro.xml, and the application reads the value of these variables from the XML file. NOTE: there is a function implemented to write the synchro.xml file, but it is used only in the initialization part of the application s main code (see CHAPTER 3: Application design point Program code ). This function is used almost in the emulator to check the synchronization code of the application. To read more about this function check the point II.1.1 writexml synchro code in APPENDIX II Read the data from synchro.xml The function implemented to read the synchronization XML file ( synchro.xml ) is synchronizer. The code is the same used to implemented readxml but with the particularities needed to decode the message written by the controller inside synchro.xml. synchronizer code As it has been said in the point 4.2 Data-flux in the communication and mentioned before, the function read the XML file in two steps: 1. To use the command xmlread(name of the XML file) to store the XML file inside the variable called xdoc of type org.apache.xerces.dom.documentimpl. 2. To scan the variable xdoc and extract the information stored. function [readf writef]=syncrhronizer readdata=[]; writedata=[]; infolabel = 'Plot Tools'; infocbk = ''; itemfound = false; FIRST STEP: xdoc = xmlread('synchro.xml'); 56

70 Josep Carrasco Martínez SECOND STEP: % Find a deep list of all listitem elements. alllistitems = xdoc.getelementsbytagname('sincro'); % Note that the item list index is zero-based. for i = 1:allListItems.getLength %it's looking for all items with <data(i,:)> thislistitem = alllistitems.item(i-1); childnode = thislistitem.getfirstchild; while ~isempty(childnode) %Filter out text, comments, and processing instructions. if childnode.getnodetype == childnode.element_node % Assume that each element has a single % org.w3c.dom.text child. childtext = char(childnode.getfirstchild.getdata);%get the data text switch char(childnode.gettagname) case 'read'; readdata(i)=sscanf(childtext,'%f');%to get the readdata value case 'write' ; %infocbk = childtext; writedata(i)=sscanf(childtext,'%f');%to get the writedata value end end % End IF childnode = childnode.getnextsibling; end % End WHILE if itemfound break; else infocbk = ''; end end % End FOR Finally the function stores the value of the synchronization variables into two variables that will return to the Matlab work-space: %read value readf=readdata; writef=writedata; 57

71 58 CHAPTER 4: Data Exchange

72 CHAPTER 5 Modelling Batch Processes with Matlab Along the past chapters the design and implementation of an automatic application in Matlab work-space has been discussed. The aim of this application is to simulate a model of the wastewater treatment plant that is being controlled by the STAR controller. The tool package used by Matlab to simulate processes and all kind of systems is Simulink. Therefore is needed a model implement within Simulink. In this chapter is exposed one possible way to implement bach processes in Matlab, starting from one biological model implemented by the department of Industrial Electric Engineering and Automation (IEA). 59

73 CHAPTER 5: Modelling Batch Processes with Matlab 5.1 Introduction In CHAPTER 1: Introduction was made a presentation about the aims of the thesis. The main aim was to implement an application to simulate a model of the wastewater treatment plant controlled by the STAR controller. So that, the main goal is to simulate a model, it means, a model of the wastewater treatment plant is needed. The application design in the chapters before has to be able to simulate the model implemented. The easiest way to get it is to implement the wastewater treatment plant model in Simulink, a tool of Matlab that shares the same work-space as Matlab, so there will be no problems to the data-exchange between the model implemented and the application. Otherwise, to decide the application to implement the model is not the only problem. There are a lot of solutions when a model of a wastewater treatment plant has to be implemented; different biological processes have to be modelled, a model for settling and clarification vessel, modelling hydraulics, and a long etc. Here in this chapter the ASM1 model developed by a task group work in collaboration with the International Water Association (IWA, formerly IAWQ and IAWPRC) in 1983 and published in 1987 has been chosen to model biological processes. For modelling settling and clarification is used the traditional one-dimensional layer settler model. Both of them have been explained in chapter 2, so this chapter is not going further in this point, to read more about it check the information in chapter 2 or the bibliography. Finally, the reader has to know that the model introduced in this chapter is not enough to simulate a complete wastewater treatment plant. The purpose of the chapter is to get a model to implement a standard block in the future, so it can be made a wastewater model library including more standard blocks ready to be used by other researchers. The block tries to include the necessary code to simulate the batch processes within a vessel (check the chapter 2 or the bibliography to know more about the batch processes). 5.2 Model developed About the introduction before, it id deduced that an extended model is needed in order to include settling and clarification and biological processes within the same model. It means that, if ASM1 model and traditional one-dimensional layer settler model are used, the new model developed must included both of them, with the particularity of using it as batch process model, hence, this model developed will not be used in the typical configurations designed to model wastewater treatment plants as a continuous model with constant effluent. 60

74 Josep Carrasco Martínez The starting point is to use the traditional one-dimensional layer model explained in chapter 2. The vessel is going to be divided in ten layers. The second step is to include the equations of the ASM1 model in each layer to model the biological processes within them. So there are the general equations to model the process of settling and clarification and there are the particulate equations of the biological processes to model the biological processes of each layer. It means that it is assumed that the concentration of the suspended solids and the soluble particles inside one layer is constant and well mixed in that layer, so there are no elements with different concentrations within the same layer. As it was said in chapter 2, the ASM1 model is going to be extended to fourteenth state variables because the TSS (total suspended solids) is included. All the things said until now are not new. The goal is only to join two models exposed before. But there are two particularities if we try to model batch process: The height now is variable, so is not a constant, it has to be included as a state variable, the fifteenth state variable in the model of each layer. There is a new input to model the flux generated by the turbines in the mixing phase (one phase that the batch process model has to have included, check chapter 2 ), this flux is called J down_up and it has its maximum value in the mixing phase and it is equal to zero when the process is in another phase. In the lines before it has been mentioned the mixing phase. In chapter 2, when we were talking about the batch process, the main characteristic was that this kind of model was not a continuous model with constant effluent, it was a discrete model with different phases. It means that the batch process model goes through several phases, to finish all the wastewater treatment in the same vessel, there are no needed several tanks and vessels, some of them for removing carbon or nitrogen and the others for settling and clarification, all the biological processes are taking part in the same vessel, but each one in a different phase. The simplest batch process was presented in chapter 2 and there are only four phases: filling phase, mixing phase, settling phase and draw phase. The batch model described in this chapter has six phases: filling phase, mixing phase, reaction phase, settling phase, draw phase and waiting phase. The model for all the phases is the same, but the different is the value of the inputs, so that is one of the most important factors in the model, to decide which ones are the model inputs. For better understanding how a batch process plant works and which ones can be the inputs, the following figures shows the secondary treatment of one wastewater treatment plant with three vessels, working all of them as batch processes: 61

75 CHAPTER 5: Modelling Batch Processes with Matlab A TANK1 B TANK1 TANK2 TANK2 TANK3 TANK3 figure 24: Wastewater Treatment Plant with three vessels. The diagram a) (on the left) represents the model plant, and the diagram b) (on the right) represents the same model plant in another phase. The model developed would represent the biological progress of one of the tanks of the wastewater treatment plant shown in figure 24. As it is evident, in one wastewater treatment plant the input flowrate of wastewater and the output flowrate of treated water is constant. It means that are necessary more than one tank to model the plant, and the tanks must be synchronized to pass all of them through all the phases keeping the total effluent of the plant constant. Looking the diagram of the figure 24 can be deduced some of the inputs of the model. One input is the input flowrate, another input is the output flowrate (the controller decides when the tank can be drawed), and the others are not evident. One is the extra flux needed to get the tank was well mixed in the filling phase and in the mixing phase. This flux represents the flux generated by the input flowrate in the filling phase and the one generated by the turbines in the mixing and reaction phase. The extra flux will be applied in both senses, up and down, so the concentration of suspended solids that is going down in the tank is going up too and the vessel is well mixed, characteristic common in these three first phases. There are two inputs more in the model: the waste sludge flowrate and the constant of the dissolved oxygen concentration s reaction. The first one is always constant, and the second one represents the increasing of dissolved oxygen in the biological phases (mixing phase and reaction phase). The inputs of the model are: Q i : input flowrate Q o : output flowrate J down_up : extra flux in filling phase and the biological phases Q u : waste sludge flowrate K l a: constant of the dissolved oxygen concentration s reaction 62

76 Josep Carrasco Martínez Model diagram The batch process model implemented has six different phases: filling phase, mixing phase, reaction phase, settling phase, draw phase and waiting phase. Each phase represents one state of the process and it is characterised by the different values of the inputs defined in the point before: Q i, Q o, J down_up, Q u, and K l a. In the figure bellow (figure 25) is represented the main diagram of the batch process phases and the order of progressing. figure 25: Batch process model diagram The input Q u is not represented, but this input will be constant along all the phases, so its value is the same always. By the other side, in figure 25 is shown the evolution of the new state variable height that depends of Q i and Q o. It has to be said the particularity of the waiting, phase, it is not representing a reaction step in the evolution of the process, as can be the settling and clarification, the mixing of wastewater. This phase is an auxiliary phase programmed to make easier the control of the different tanks in the wastewater treatment plant. It is known that the effluent of wastewater in the treatment plant is constant (see figure 24 in the page before), so if there is one tank asking for input flowrate, and after another one asks for it, this second tank will have to wait until the other one has finished the filling phase. With the output flowrate does not occurs the same because the settling phase can work as a waiting phase too. If there is one tank in the draw phase the next one can wait in the settling phase until the first one has finished. Otherwise, the control has to find the best synchronization between all the tanks of the wastewater treatment plant to try to minimize the time spent in the waiting phase. Now is going to be explained the particularities of each phase and shown the diagram of each one. 63

77 CHAPTER 5: Modelling Batch Processes with Matlab The filling phase is the first phase of the model, although the programmer of the model can chose the phase in initial conditions. It is assumed that the height of the layers have the minimum value (the level of the tank is the minimum level of wastewater) at the beginning of this phase. The characteristics of the filling phase are: figure 26: Filling Phase Tank well mixed. The value of the flux generated by the input flowrate (J up = -J uown ) is bigger than the settling flux due to the gravity force and the bulk flux due to the waste sludge flowrate, both of them are despicable in front of the value of J up. J up = -J down > 0. q out = 0. q in > 0. q u > 0. K L a = 0, there is no reaction. dh qin qout =, where A is the area of the tank. The derivative of the height is dt A positive which means that the height of the level is increasing. This is the main characteristic of the filling phase. The two main characteristics of the filling phase are that the tank is well mixed and that the value of the derivative of the height is not zero. This phase is active until the height reaches its maximum value, then it starts the following phase and the filling phase is finished. 64

78 Josep Carrasco Martínez The mixing phase is the next phase after the filling phase. There is no more input flowrate and the level of the wastewater is the maximum (maximum height). The principal characteristics are: Tank well mixed. The value of the flux generated by the input flowrate (J up = -J uown ) is bigger than the settling flux due to the gravity force and the bulk flux due to the waste sludge flowrate, both of them are despicable in front of the value of J up. J up = -J down > 0. q out = 0. q in = 0. q u > 0. K L a = 0, there is no reaction. dh = 0, the derivative of dt the height is null because there is no input and output flowrate, and it is right because the height has a constant value. figure 27: Mixing Phase The main characteristic of the mixing phase is that the tank is well mixed, as the name of the phase stands up. There is an external flux that makes practically despicable the settling flux and the flux due to the waste sludge flowrate. When the tank is in this phase is equivalent to an anoxic tank where the biological process called nitrification is taking part by the autotrophs microorganisms (see chapter 2: Wastewater Treatment Processes, point 2.1 Process description ). The next phase after the mixing phase is the reaction phase, explained in the following page. 65

79 CHAPTER 5: Modelling Batch Processes with Matlab The main characteristics in the reaction phase are: Tank well mixed. The value of the flux generated by the input flowrate (J up = -J uown ) is bigger than the settling flux due to the gravity force and the bulk flux due to the waste sludge flowrate, both of them are despicable in front of the value of J up. J up = -J down > 0. q out = 0. q in = 0. q u > 0. K L a > 0, there is reaction. dh = 0, the derivative of dt the height is null because there is no input and output flowrate, and it is right because the height has a constant value. figure 28: Reaction Phase The value of the K L a is the only difference between the mixing phase and the reaction phase. The reaction phase is equivalent to the aerobic tank in modelling continuous wastewater treatments (see chapter 2: Wastewater Treatment Processes, point 2.1 Process description ). The main characteristics of this phase are that the tank is well mixed and that there is an increment of the concentration of dissolved oxygen because of the tank is now aerated. In this phase is taking part the denitrification by the heterotrophs microorganisms principally. 66

80 Josep Carrasco Martínez Once the reaction phase has taken part, the process goes in the settling phase. This is the first phase where the vessel is not well mixed. In this phase takes part the settling of solid particles in the down layer of the settler, because now the tank is working as a settler. Although there are taking part biological processes, the principal process is settling and clarification. The main characteristics of this phase are: The tank is not well mixed. The value of the flux generated by the input flowrate (J up = J uown = 0) is zero and there are only the settling flux and the flux due to the waste sludge flowrate. J up = J down = 0. q out = 0. q in = 0. q u > 0. K L a = 0, there is no reaction. dh = 0, the derivative of the height dt is null because there is no input and output flowrate, and it is right because the height has a constant value. f figure 29: Settling Phase As it has been said, the main characteristic of this phase is the settling and clarification. Now the flux present in the three first phases is not present, so the settling flux and the flux due to the waste settling flowrate are the responsible of the settling of the solid particles in the down layer on the button of the vessel. This phase is the last treatment of the wastewater in the secondary treatment (see chapter 2: Wastewater Treatment Processes, point 2.1 Process description ). The wastewater will go out from the vessel to trespass the tertiary treatment. 67

81 CHAPTER 5: Modelling Batch Processes with Matlab This phase is certainly the real last phase of the process. The clarified wastewater goes out of the vessel, the level of the wastewater in the vessel decreases and almost all the solid bulks rest on the button layer of the vessel. After the past phases there are no solid particles in the up layers of the vessel. The main characteristics of the draw phase are: The tank is not well mixed. The value of the flux generated by the input flowrate (J up = J uown = 0) is zero and there are only the settling flux and the flux due to the waste sludge flowrate. J up = J down = 0. q out > 0, is the main characteristic, now there is output flow rate. q in = 0. q u > 0. K L a = 0, there is no reaction. dh qin qout =, where A is the area of dt A the tank. The derivative of the height is negative which means that the height of the level is decreasing. This is the main characteristic of the draw phase. figure 30: Draw Phase This phase is practically like the settling phase, the only particularity is the variation of the height in the level of the wastewater. The draw phase could be the last one, but there is one problem that has been exposed before. When the draw phase has reached the end (the height has the minimum value it can have) the process has to start again from the first phase, the filling phase. It means that it is necessary input flowrate. The input flowrate in one wastewater treatment plant is assumed is constant, so if there is another tank in the filling phase, another one can not goes from the draw phase to the filling phase because there is no input flowrate for both tanks. But the process can not be in the draw phase until there is input flowrate, because there is a minimum value for the height h of the level in the vessel. So, it is need a last phase to avoid this problematic situation. This phase is called waiting phase. 68

82 Josep Carrasco Martínez The waiting phase is the last phase of the process modelled. This phase is a transition phase from the draw phase to the filling phase. The main characteristics of the phase are the same as the ones in the settling phase, but here the height of the wastewater level has the minimum value. The characteristics are: The tank is not well mixed. The value of the flux generated by the input flowrate (J up = J uown = 0) is zero and there are only the settling flux and the flux due to the waste sludge flowrate. J up = J down = 0. q out = 0. q in = 0. q u > 0. K L a = 0, there is no reaction. dh = 0, the derivative of the height dt is null because there is no input and output flowrate, and it is right because the height has a constant value. The inputs have exactly the same value as in the settling phase. figure 31: Waiting Phase After analysing all the phases, there are some things that must be stood up. The waste sludge flowrate (q u ) is always active in all phases and thereby the flux generated by it. The gravity force is always present too; it is which generate the settling flux. By the other side, there are three phases where the vessel is well mixed, the three first phases: filling phase, mixing phase and reaction phase. And in the last three phases the vessel is not well mixed, there is more concentration of solid particles in the button of the vessel. Rather there is one data is not clear when the phases are explained. How takes part the transition between two phases. It is clear that the transition between the filling phase and the mixing phase is the value of the height, and between the draw phase and the waiting phase is the height too. And between the waiting phase and the filling phase is clear too, when the controller can give to the vessel input flowrate. But the other three transitions are not clear. To do these transitions they can be suitable more than one condition. For example it is possible to measure in the real plants where it is apply the batch process the time of each phase. Another condition is to choose a limit value of the critical concentration of solid particles in each phase (ammonium in the mixing phase, 69

83 CHAPTER 5: Modelling Batch Processes with Matlab nitrate in the reaction phase, total suspended solids in the settling phase, for example) Model equations The characteristics and differences of the phases have been explained in the point before, but, how to express it as logic equations, this is the step that has to be resolved once it is clear the model is going to be applied. The starting point is the traditional one-dimensional layer settler model, with the ASM1 model included in each layer to model the biological reactions and the settling and clarification process in the same mathematical model. This model was implemented by Ulf Jeppsson (Industrial Electrical Engineering and Automation IEA-, LTH, Sweden) and Krist V. Gernaey (CAPEC, Dept. of Chemical Engineering, DTU, Denmark) previously, so here is not going to be designed the model from the beginning. The existing model has been used to get the batch process equations. There have been introduced some modifications in the equations of the current model. In the lines bellow are shown the modified equations in the model, but is not presented the whole model that was developed before by Ulf Jeppsson and Krist V. Gernaey. Otherwise (the equations are the ones explained in chapter 2, point 2.3 Modelling of wastewater treatment processes), the reader can see the whole model if he checks the code implementation in the point after (5.3 Implementation of the model). The equations modified are: STATE VARIABLE height: dh q q = dt area in out VELOCITY OF THE BULK MOVEMENT: vdown if qin = 0 and qout = 0 qin qu v up = if qin > 0 and qout = 0, where area qout qu if q > 0 = 0 out and qin area v down = q u area DISSOLVED OXYGEN CONCENTRATION: Equation for the layers up to the feed layer: 1 Y ^ S S S H i Oi μ H dso v h S S i upa + vupb Y K + S K i O, H + S = + dt h 4,57 Y ^ S A NHi μ A Y A K NH + S NH K i Oi S O, A X Oi B, H i + S Oi X B, Ai + K L a ( S S ) Osat Oi 70

84 Josep Carrasco Martínez Equation for the layers down to the feed layer: 1 Y ^ S S S H i Oi μ H dso v h S S i down SO v i down SO Y K S K i + i O, H + S 1 = + dt h 4,57 Y ^ S A NH i μ A Y A K NH + S NH K i Oi S O, A X Oi B, H i + S Oi X B, Ai + K L a ( S S ) Osat Oi Equation for the feed layer: ds Oi dt v = in S Oin v up a v h down S Oi 1 Y ^ H μ H Y h + 4,57 Y A Y A K S S ^ μ A Si + S K Si NH S K NH i O, H + S S Oi NH i + S K Oi S O, A X Oi B, H i + S Oi X B, Ai + K L a ( S S ) Osat Oi where S a = S and SOi + 1 b = SO i Oi Oi 1 if if if if v up v up others = v others = v down down, and i indicates the layer. SUSPENDED SOLID CONCENTRATION: This equation is the same for all suspended solids. Equation for the layers up to the feed layer: dx i X i X i 1 X i = J flow J settler J down up J i i _ + settler + i dt TSSi TSSi TSS Equation for the layers down to the feed layer: dx i X i X J i flow + J + 1 i = J flow J settler J i i down _ up + dt TSSi TSSi+ 1 h Equation for the feed layer: dx i X i X i 1 = J flow J flow J settler J down up J i i 1 i _ + + dt TSS TSS i + 1 flow X i i+ 1 ( ) + J down _ up i+ 1 J h TSS settler X i i 1 ( ) + J down _ up X Iin X i 1 ( ) + v + J down _ up i 1 settleri TSS in i 1 h i+ 1 TSS i 1, where X represents the solid particles concentration of X I, X S, X B,H, X B,A, X P or X ND, and i represents the layer. The fluxes are: o J down_up = constant o J = v TSS o settler se dim entationi i vuptssi if i < m and ( qin > 0 or qout > 0) J flow i =, where m is the vdowntssi 1 if others feed layer. 71

85 CHAPTER 5: Modelling Batch Processes with Matlab To know more about the meaning of each parameter in the equations check it in chapter 2, point 2.3 Modelling of wastewater treatment processes, or see the bibliography (recommended Ulf Jeppsson s book [2] in the bibliography, in pages 372 and 373 is written the ASM1 model with all the parameters). About the fluxes and the settling equations check Ulf Jeppsson s book [2] too. 5.3 Implementation of the model In chapter 3 was described the application designed and the background of the simulation. For the simulation of the model is run Simulink, the simulation tool of Matlab. To program the equations of the model is used the object S-function. Is a Simulink object which let to program with C code or with Matlab code (m-function) a model and include it as a block in the Simulink workspace, so it is possible to use the tools of Simulink to define the value of the inputs and the representation of the outputs, the feedback of the model process. The S-function chosen is the one which let to program the model as a C file and to include it in Simulink workspace. ABOUT THE S-function : We can find the S- function in the Simulink Library Brower, as the figure 32 shows. We select the object S-function and drag it to the workspace of the Simulink file where is going to be implemented the model. figure 32: S-function in Simulink Library Browser. 72

86 Josep Carrasco Martínez Once the block of the S-function is in the Simulink workspace, the only thing it is necessary to do is to press click twice selecting the block S-Function, and the window to define the S-function Block Parameters will open. See figure 33 bellow. figure 32: defining the S-function. There are three fields to fill up: S-function name, S-function parameters and Sfunction modules. The only two necessary fields are the S-function name and the Sfunction parameters. In the first one it has to be written the name of the c-file where it is implemented the code of the S-function. The program locks for a file with the extension.c, so it is not necessary to indicate the extension of the file. In the second field they are written the input parameters used to define the value of the coefficients in the equations. These parameters have to be define within the c-code before the functions definition, in the field of the include libraries. In the following lines is presented the functions that Matlab define to implement the code of the S-function. It is recommended to use only these defined functions, because Simulink can have problems with the simulation if we try to define another functions different to the usual functions that the application can recognise. The first part is the include libraries, where it is indicated the name of the c-file, the include libraries and the constants define in Matlab workspace that the S-function is going to use to define variables: #define S_FUNCTION_NAME name_of_the_c-file #include "simstruc.h" #include <math.h> #define NAME_OF_THE_PARAMETER ssgetarg(s,0) 73

87 CHAPTER 5: Modelling Batch Processes with Matlab The second part is the function where it is defined the size of the input vector, output vector, the number of state variables continuous and discontinuous and another important parameters. If we don t write anything the value is zero: /* * mdlinitializesizes - initialize the sizes array */ static void mdlinitializesizes(simstruct *S) { sssetnumcontstates(s, 0); /*13 number of continuous states */ sssetnumdiscstates(s, 0); /* number of discrete states */ sssetnuminputs(s, 0); /* number of inputs */ sssetnumoutputs(s, 0); /* number of outputs */ sssetdirectfeedthrough(s, 0);/* direct feedthrough flag */ sssetnumsampletimes(s, 0); /* number of sample times */ sssetnumsfcnparams(s, 0); /* number of input arguments */ sssetnumrwork(s, 0); /* number of real work vector elements */ sssetnumiwork(s, 0); /* number of integer work vector elements*/ sssetnumpwork(s, 0); /* number of pointer work vector elements*/ } The following function is used to define the sample time needed to simulate the model defined. Here is defined if the function is continuous or the period of simulation if the model is a discontinuous model. /* * mdlinitializesampletimes - initialize the sample times array */ static void mdlinitializesampletimes(simstruct *S) { sssetsampletime(s, 0, CONTINUOUS_SAMPLE_TIME); sssetoffsettime(s, 0, 0.0); } In this function are defined the value of the initial conditions of the state variables of the model: /* * mdlinitializeconditions - initialize the states */ static void mdlinitializeconditions(double *x0, SimStruct *S) { } In the mdloutputs function are defined the value of the outputs of the model: /* * mdloutputs - compute the outputs */ static void mdloutputs(double *y, double *x, double *u, SimStruct *S, int tid) { } 74

88 Josep Carrasco Martínez This is the last function, where the model and the derivative functions are implemented. Here are defined all the auxiliary variables and the equations of the model: /* * mdlderivatives - compute the derivatives */ static void mdlderivatives(double *dx, double *x, double *u, SimStruct *S, int tid) { } This part of the chapter is an introduction of the S-functions, they are not explained all the functions that can be implemented in the S-function and all their features. If the reader is interested in going further with the S-function definitions and uses he can check the bibliography S-function programmed To implement the S-function it has been used the code programmed by Ulf Jeppsson and Krist V. Gernaey, following the same structure and utilising the equations implemented by them. Hence, in this point it is not going to be explained all the structure and parameters of the S-function programmed, it is only stood up the modifications made to the original file. Thereby it is possible to see the all code of the function checking the APPENDIX IV. In the following lines is explained the code implemented to write the modified equations described in Model equations in the current chapter. The first thing is to define the parameters that are needed by the equations. These parameters are declared as a constants join to the declaration of the libraries used by the program. How to declare the parameters is shown bellow: #define XINIT ssgetarg(s,0) /* initial values */ #define SEDPAR ssgetarg(s,1) /* parameters sedimentation model */ #define DIM ssgetarg(s,2) /* dimensions clarifier */ #define LAYER ssgetarg(s,3) /* Number of layers */ #define ASMPAR ssgetarg(s,4) /* parameters activated sludge model */ #define SOSAT ssgetarg(s,5) After declaring all the libraries and parameters, the next step is to implement the functions. The first function in the S-function is the mdlinitializesizes function. This function is only to indicate to the compiler the number of inputs, outputs, state variables, parameters, etc. The mdlinitializesizes function implemented is: static void mdlinitializesizes(simstruct *S) { sssetnumcontstates( S, 141); /* number of continuous states, ASM1 components + TSS for each settler layer + total height for the vessel*/ sssetnumdiscstates( S, 0); /* number of discrete states */ sssetnuminputs( S, 19); /* number of inputs, 13 ASM1 components + TSS + influent flow rate + Kla + J_down_up + Q_output+ Q_u waste sludge flowrate */ sssetnumoutputs( S, 144); /* number of outputs: 141 states 13 ASM1 components + height + TSS for each layer)+ Q_e + Q_out + Q_u*/ 75

89 CHAPTER 5: Modelling Batch Processes with Matlab } sssetdirectfeedthrough(s, 1); /* direct feedthrough flag */ sssetnumsampletimes( S, 1); /* number of sample times */ sssetnumsfcnparams( S, 6); /* number of input arguments */ sssetnumrwork( S, 0); /* number of real work vector elements */ sssetnumiwork( S, 0); /* number of integer work vector elements*/ sssetnumpwork( S, 0); /* number of pointer work vector elements*/ The functions between mdlinitializesizes function and mdloutputs function are not modified, so the next function implemented is mdloutputs function. Within this function is defined the value of all the outputs. The 141 state variables are defined as an outputs to can measure and represent the evolution of the state variables of the model. The other outputs are the effluent flowrate (Q_e), the waste sludge flowrate (Q_u) and the output flowrate (Q_o). static void mdloutputs(double *y, double *x, double *u, SimStruct *S, int tid) { int i; int j; /* Clarifier state variables */ for (i=0;i<10;i++){ for (j=0;j<14;j++){ y[(i*14)+j]=x[i+j*10]; //we have written 14 because now we have 15 states variables per each layer } //the order of outputs is from 1 to 14 layer 1, from 15 to 28 layer 2, etc } //the inputs is, from 1 to 10 the SI of all layers, from 11 to 20 the Ss of all layers, etc y[140] = x[140]; } /* Flow rates out of the vessel */ if ((u[14]>0)&&(u[17]==0)){ y[141]=u[14]-u[18]; /* Q_e */ } if ((u[14]==0)&&(u[17]>0)){ y[141]=u[17]-u[18]; /* Q_e */ } else y[141]=0; y[142]=u[18]; /* Q_u */ y[143]=u[17]; /* Q_out */ The more complex function that has to be defined is the mdlderivatives function. Within it is where is defined the model of the wastewater treatment plant. The implementation made is longer than the lines shown bellow, but here are shown the main changes made in the original S-function to program the batch process model (check the appendix IV to see the full code) static void mdlderivatives(double *dx, double *x, double *u, SimStruct *S, int tid) 76

90 Josep Carrasco Martínez The implementation of the equation of the velocity up v up, which have the solid particles presents up to the feed layer, shown in the point Model equations, in the current chapter, is shown bellow: /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%% NEW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ // Equaction of effluent if ((u[14]>0)&&(u[17]==0)){ Q_e = u[14]-q_u; /* Q_e */ } if ((u[14]==0)&&(u[17]>0)){ Q_e = u[17]-q_u; /* Q_e */ } else Q_e = 0; // Equation of the velocity up if ((u[14]>0) (u[17]>0)){ v_up = Q_e/area; } else v_up = -v_dn; v up vdown qin qu = area qout qu area // The flux for filling, mixing and reaction phase, // where the wastewater is well mixed J_d_u = u[16]; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ The line J_d_u = u[16]; is the declaration of the flux generated in filling phase, mixing phase and reaction phase to get that the vessel was well mixed. The following representative change is the code programmed to implement the sludge flux due to the liquid flow: /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%% NEW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ /* calculation of the sludge flux due to the liquid flow (upflow or downflow, depending on layer) */ for (i = 0; i < 11; i++) { //bulk movement up to the feed layer if (i < (feedlayer-eps)){ if ((u[14]>0) (u[17]>0)){ Jflow[i] = v_up*xtemp[i+130]; } else{ Jflow[i] = v_dn*xtemp[i-1+130]; } } //bulk movement down to the feed layer and in the feed layer else Jflow[i] = v_dn*xtemp[i-1+130]; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ J if if if q q q in in out = 0 > 0 > 0 and and and vuptssi if i < m and ( qin > 0 or qout > 0) = vdowntssi if others flow i 1 q q q out out in = 0 = 0 = 0 77

91 CHAPTER 5: Modelling Batch Processes with Matlab The first state variable defined is the state variable height, the main characteristic of this model. Now the height of the vessel is not a constant as in the models before. As it is assumed all the layers have the same height, first is define the state variable of the total height of the vessel, and after it is divided by the number of layers in the model: /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%% NEW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ /* height of the tank: H*/ dx[140] = (u[14]-u[17])/area; /*the heigth of the vessel*/ h = x[140]/n; /*the heigth of each layer*/ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ The other significant change in the state variables has been to include the flux needed to get the vessel was well mixed (J_d_u) within the equations of the particulate components: X I, X S, X B,H, X B,A, X P and X ND. The changes made are stood up in black letters: /* particulate component X_I */ for (i = 0; i < 10; i++) { if (i < (feedlayer-1-eps)) dx[i+20] = ((xtemp[i+20]/xtemp[i+130])*(-jflow[i]-js[i+1]- J_d_u)+(xtemp[i-1+20]/xtemp[i ])*Js[i]+(xtemp[i+1+20]/xtemp[i+1+130])*Jflow[i+1])/h + (xtemp[i+1+20]/xtemp[i+1+130])*j_d_u + reac3[i]; else if (i > (feedlayer-eps)) dx[i+20] = ((xtemp[i+20]/xtemp[i+130])*(-jflow[i+1]-js[i+1]- J_d_u)+(xtemp[i-1+20]/xtemp[i-1+130])*(Jflow[i]+Js[i]))/h + (xtemp[i-1+20]/xtemp[i-1+130])*j_d_u + reac3[i]; else dx[i+20] = ((xtemp[i+20]/xtemp[i+130])*(-jflow[i]-jflow[i+1]-js[i+1]- J_d_u)+(xtemp[i-1+20]/xtemp[i-1+130])*Js[i]+v_in*u[2])/h + (xtemp[i-1+20]/xtemp[i-1+130])*j_d_u + reac3[i]; } The last equation modified is the equation of the state variable dissolved oxygen S O. Has been included the reaction rate (KLa*(SO_sat-xtemp[i+70])) of the oxygen to model the reaction phase. The second change is to add the variables a and b within the equations. It is necessary because of the different values of the velocity up v up, which depends of q effluent (Q_e). /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%% NEW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ /* soluble component S_O */ KLa = u[15]; for (i = 0; i < 10; i++) { if(v_up==-v_dn){ a = xtemp[i-1+70]; b = xtemp[i+70]; } else{ a = xtemp[i+70]; b = xtemp[i+1+70]; } S a = S S b = S O O O i i 1 i + 1 O i if if if if v v up up others = v others = v down down if (i < (feedlayer-1-eps)) dx[i+70] = (-v_up*a +v_up*b)/h +reac8[i] + KLa*(SO_sat-xtemp[i+70]); //we have added rso (Kla!=0) 78

92 Josep Carrasco Martínez else if (i > (feedlayer-eps)) dx[i+70] = (v_dn*xtemp[i-1+70] -v_dn*xtemp[i+70])/h +reac8[i] + KLa*(SO_sat-xtemp[i+70]); //we have added rso (Kla!=0) else dx[i+70] = ((v_in*u[7] -v_up*a -v_dn*xtemp[i+70])/h +reac8[i]) + KLa*(SO_sat-xtemp[i+70]); //we have added rso (Kla!=0) } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ 5.4 Comments In the points before a batch process model has been implemented. The S-function has been programmed to model the six phases of the batch process model. The inputs that control if the model is in one or another phase are: Q i : input flowrate Q o : output flowrate J down_up : extra flux in filling phase and the biological phases Q u : waste sludge flowrate K l a: constant of the dissolved oxygen concentration s reaction Now, only rests to implement a control as it shows the figure 33: figure 33: batch process control Matlab offers a lot of possibilities to implement the control in Simulink or even in Matlab workspace as an m function. The aim of this chapter was to model batch process model, the controller is not part of it, so the chapter is not going further in this topic. 79

93 80 CHAPTER 5: Modelling Batch Processes with Matlab

94 PART III TITLE: Appendixes (Included Papers) 81

95 82

96 APPENDIX I Appendixes to CHAPTER 2 (Wastewater Treatment Processes) In this chapter there is more information about Wastewater Treatment Processes, in order to extend the one given in Chapter 2 before, for these ones who want to know more about it. But if it is needed more knowledge and to go further from this introduction to wastewater treatment process, there is the possibility of checking the bibliography. 83

97 APPENDIXES (included papers) I.1 Appendixes for MODELLING WASTEWATER TREATMENT PROCESSES The first thing it is pertinent to know is how to read the tabular form in which activates sludge stoichiometry and kinetics are conventionally presented. The kind of the tabular form is presented below: PROCESS COMPONENTS KINETICS State var. 1 State var. 2 State var. n Process 1 Value 1,1 Value 1,2 Value 1,n Kinetic 1 Process 2 Value 2,1 Value 2,2 Value 2,n Kinetic 2 Process k Value k,1 Value k,2 Value k,n Kinetic k, where, for instance, the reaction rate of the state variable 2 is: reactionra te2 = value(1,2) * kinetic(1) + value(2,2) * kinetic(2) value( k,2) * kinetic( k) I.1.1 Tabular form for simple biological kinetics PROCESS Aerobic heterotrophic growth COMPONENTS KINETICS Nutrient N Biomass B 1 S N 1 μ X B Y B K N S + N I.1.2 Tabular form for simple biological kinetics and carbon removal kinetics PROCESS Aerobic heterotrophic growth Decay of heterotrophs COMPONENTS Nutrient Oxygen Biomass 1 YH 1 Y YH H S KINETICS S O 1 μ H X H K S S S K OH S + + O 1 - f P -1 b H X H S 84

98 Josep Carrasco Martínez I.1.3 Tabular form for simple biological kinetics, carbon removal kinetics and nitrogen removal kinetics PROCESS Aerobic heterotrophi c growth Anoxic heterotrophi c growth COMPONENTS Carbo Oxygen Ammonium Nitrate Heterotroph n s biomass 1 YH 1 YH YH -i XB 1 1 YH 1 -i XB 2,86Y 1 H Y H Autotroph s biomass Aerobic autotrophic growth Y 4, 57 A Y A -i XB 1 Y A 1 Y A 1 Decay of heterotrophs XB P XP 1 f P i f i -1 Decay of autotrophs XB P XP 1 f P i f i -1 PROCESS KINETICS Aerobic heterotrophic growth Anoxic heterotrophic growth Aerobic autotrophic growth Decay of heterotrophs Decay of autotrophs S S μ H K S + S S S K K OH S O + S O X S OH NO μ H g K S S S KOH S + + O K NO + S NO η μ A K NH S NH + S NH K b H X H b A X A OA S O S + S O H X A X H 85

99 APPENDIXES (included papers) I.1.4 Tabular form for phosphorus removal kinetics PROCESS COMPONENTS S F S A S O2 S PO4 X PHA X PP X PAO Fermentation -1 1 P Release -1 Y PO4 1 - Y PO4 P Uptake - Y PHA -1 - Y PHA PAO Growth 1 -i PBM 1 PHA Breakdown PP Breakdown PAO Breakdown Y H 1-1 Y H 1-1 ν P -1 PROCESS KINETICS Fermentation P Release P Uptake PAO Growth PHA Breakdown PP Breakdown PAO Breakdown q PP K S O2 μ O2 + S PAO O2 K q FE K q PHA S PO4 K P + S S O2 O2 + S O2 K K O2 NO3 O S 2 + O2 K NO3 + S NO3 PO4 K A K S PO4 K P + S K S A X PP / X PAO S + A2 K PP + X PP / X X PHA PO4 PHA + X K / X PHA NH S PAO / X NH + S PAO NH b PHA X PHA b PP X PP b PAO X PAO K K FE S PAO IPP PHA F + S F X K MAX + K X + PHA X PAO MAX H X / X PP / X ( X / X ) PP ( X / X ) PHA PAO PAO PAO X PAO PAO X PAO 86

100 Appendixes to CHAPTER 3 (Application Design) APPENDIX II In this chapter there is more information about the application designed with Matlab; the code and the.exe application. There is nothing about the synchronization, data exchange and model design, these parts are described in chapters 4 and 5 and the appendixes of those chapters. 87

101 APPENDIXES (included papers) This appendix tries to complete the information given in chapter 3 about the implementation of the application. But first it is necessary to do a brief explanation about the communication between the application and the controller, part which is explained in detail in chapter 3. The way chosen to communicate the controller and the application through Ethernet is writing and reading XML files, so to store the value of all the variables that the controller has to update (control variables, synchronization variables, data read from the database and the results from the simulation) it is needed an XML file. It means that all the functions implemented to change or to read the values of the control variables and of the synchronization variables, they only have to be able to write or to read an XML file. About how to get this with Matlab is explained in chapter 4. Another reason for storing the variables that they are changing during the application running in XML files is that Matlab is not able to change the value of the variables in the work-space directly when it is executing a loop. It only can change the values of the variables of the work-space inside the loop, or with a function which reads the value of these variables from a file, where the values are stored. So, when the application is executing the main loop, to make possible that it reads the changes that the controller or the other buttons out of the main loop make to the control and synchronization variables, they have to change the values writing the file where they are stored, so when the reading functions inside the main loop reads the file the changes made have effect. II.1 STAR emulator to check the synchronization code The user interface designed for the application has two buttons to check the synchronization phases. An image about the user interface is shown below: figure 34: User Interface The buttons READ FROM DATABASE and WRITE IN DATABASE use the function implemented to emulate the controller only in the synchronization phases. These buttons execute the function writexml_synchro (variables), where variables is a vector with two components. This function writes the value introduced (variables) in the file XML that stores the value of the synchronization variables. 88

102 Josep Carrasco Martínez II.1.1 writexml_synchro code The function writexml_synchro uses the xmlwrite command to write an XML file where stores the value of the two synchronization variables. This function works like the function writexml uses to write in the database the results of the simulation. The function makes the XML file in three steps: to create a java object to create an XML file to write the java object which contains the variables and the values in the XML file with the function xmlwrite function archivoxml=writexml_synchro(valuep) % Create a sample XML document. docnode = com.mathworks.xml.xmlutils.createdocument('synchronize'); docrootnode = docnode.getdocumentelement; %docrootnode.setattribute('attribute','attribute_value'); dataelement = docnode.createelement(sprintf('sincro')); nameelement = docnode.createelement(sprintf('read')); valueelement = docnode.createelement(sprintf('write')); nameelement.settextcontent(sprintf('%f',valuep(1))); %name of the variable valueelement.settextcontent(sprintf('%f',valuep(2))); %value of the variable dataelement.appendchild(nameelement); dataelement.appendchild(valueelement); docrootnode.appendchild(dataelement); % Save the sample XML document. xmlfilename = ['synchro','.xml']; %we have the file in our current directory xmlwrite(xmlfilename,docnode); How to create the java object to write an XML file or read an XML file is explained in chapter 4, which is about the data-exchange and the synchronization files. II.2 Control functions In the implementation of the program there have been defined two control variables: aux_loop and aux_sim. The value of these variables is stored in the file controlfile.xml and the meaning of each variable is: aux_loop: control variable for the main loop, so if aux_loop 1 the condition to keep running the program is not complained and the program goes out of the main loop. aux_sim: control variable to stop the simulation of the plant process. The difference between aux_sim and aux_loop is that aux_sim doesn t stop the main loop. 89

103 APPENDIXES (included papers) With these variables the controller can stop the simulation if it is not necessary in some period, but also it can stop the application if there is no needed more data. Nevertheless, don t forget once the application goes out of the main loop it is not possible to start it again from the controller. II.2.1 controlloop code As the function described in the point writexml_synchro code, controlloop has the same structure, the only difference is that the two variables stored inside are the control variables and not the synchronization variables as before. This function is used once in the initialization part (check chapter 3 last point programme code) to write the initial values of the control variables. After that, only the controller will be the one which changes the values of the control variables. The code is presented below: function archivoxml=controlloop(control) % Create a sample XML document. %program docnode = com.mathworks.xml.xmlutils.createdocument('control'); docrootnode = docnode.getdocumentelement; %docrootnode.setattribute('attribute','attribute_value'); % for i=1:n dataelement = docnode.createelement(sprintf('data')); loopelement = docnode.createelement(sprintf('loop')); simelement = docnode.createelement(sprintf('simulation')); loopelement.settextcontent(sprintf('%f',control(1))); %name of the variable simelement.settextcontent(sprintf('%f',control(2))); %value of the variable dataelement.appendchild(loopelement); dataelement.appendchild(simelement); docrootnode.appendchild(dataelement); % Save the sample XML document. xmlfilename = ['controlfile','.xml']; %we have the file in our current directory xmlwrite(xmlfilename,docnode); II.2.2 control_check code As well as the function presented in the point controlloop code is a function which writes an XML file, control_check read the values of the control variables stored in the XML file controlfile. The Maltlab command used to read the XML file is xmlread. This function is divided in three steps: First it reads the XML file with the function xmlread, that stores the XML file in a java object. After it scans the java object to find the items with the name data. The item data has two children; loop is the child which has the value of the control variable aux_loop and simulation is the child which has the value of the control variable aux_sim. At last, the function stores the values in the variables that returns to the Matlab work-space. 90

104 Josep Carrasco Martínez function [loop sim]=control_check loopdata=[]; simdata=[]; infolabel = 'Plot Tools'; infocbk = ''; itemfound = false; xdoc = xmlread('controlfile.xml'); % Find a deep list of all listitem elements. alllistitems = xdoc.getelementsbytagname('data'); % Note that the item list index is zero-based. for i = 1:allListItems.getLength %it's looking for all items with <data(i,:)> thislistitem = alllistitems.item(i-1); childnode = thislistitem.getfirstchild; while ~isempty(childnode) %Filter out text, comments, and processing instructions. if childnode.getnodetype == childnode.element_node % Assume that each element has a single % org.w3c.dom.text child. childtext = char(childnode.getfirstchild.getdata);%get the data text switch char(childnode.gettagname) case 'loop'; %itemfound = strcmp(childtext, infolabel); loopdata(i)=sscanf(childtext,'%f');%to get the readdata value case 'simulation' ; %infocbk = childtext; simdata(i)=sscanf(childtext,'%f');%to get the writedata value end end % End IF childnode = childnode.getnextsibling; end % End WHILE if itemfound break; else infocbk = ''; end end % End FOR %read value loop=loopdata; sim=simdata; This kind of function is explained with more details in chapter 4, chapter about the communication of the application and the controller. 91

105 APPENDIXES (included papers) II.3 Processing data within Matlab It has been shown in chapter 3 that the Matlab algorithm contains three parts: process the data read, simulate the plant model and process the results. To do the steps of process the data read and process the results two functions have been implemented. These two functions are examples, and they depend of the model used in the application. So these functions are presented as a guide to implement them in the future. II.3.1 read_data function This function is the one which processes the data read from the database, it means, it has to translate the three vectors stored into variables useful to the simulation: name = value = quality = [ name1... namei... namen ] [ value1... valuei... valuen ] [ quality... quality quality ] 1 i n namei var iablei = value i qualityi where i = 0,... n, and n is the number of variables acquired. One simple way is to implement a loop with conditional statements that scans the vector of the names, then for the variable variabledo used in the model, when the loop finds the component namer(i) = DO, it stores the value of valuer(i) inside the variable variabledo. % file to write the data from the database to work space endloop = length (valuer); for i = 1:endloop if namer(i,:) == 'DO' variabledo = valuer(i) end if namer(i,:) == 'SS' variabless = valuer(i) end if namer(i,:) == 'Xs' variablexs = valuer(i) end if namer(i,:) == 'Hh' variablehh = valuer(i) end end 92

106 Josep Carrasco Martínez II.3.2 write_data.m function To implement the function which builds the three vectors with the results of the simulation is even easier than the case before. The only task is to write the three vectors and all the components ordered. The code is shown below: % file to write the data from the work space to database name = ['SI';'SS';'XI'] value = [reac5(end,1) reac5(end,14) reac5(end,3)] quality = [1 0 1] II.4 GUIDE application II.4.1 What s GUIDE To developed the graphical interface of the application has been used GUIDE. GUIDE is an application integrated in Matlab which makes possible in a few steps and with a little time developed graphical interfaces. By the other side, the main advantage of GUIDE is that it is a Matlab application, so all the programs developed with GUIDE can access directly to the Matlab work-space. To start GUIDE it has to be typed the command guide in Matlab work-space and it appears the window shown in the following figure: figure 35: GUIDE background Once this window is opened, the only things we have to do is to set the graphical interface that we want and to save the application. II.4.2 Application GUIDE code When the application implemented in GUIDE is saved, it is created another file with the same name which contains all internal code. This internal code contains the functions of the objects that have been included in the window of the application. GUIDE defines 93

Quick Feature Tour. Quick Feature Tour Overview

Quick Feature Tour. Quick Feature Tour Overview Quick Feature Tour Quick Feature Tour Overview This chapter highlights some of the features available in the latest version of BioWin. These are demonstrated using the "An Example" configuration installed

More information

Installing BioWin 3.1 ML under Windows 7

Installing BioWin 3.1 ML under Windows 7 McMaster Innovation Park 175 Longwood Road South Suite 114A Hamilton, Ontario L8P 0A1 CANADA P: +1 (905) 481-2607 F: + 1 (905) 481-2610 www.envirosim.com Installing BioWin 3.1 ML under Windows 7 1. Older

More information

High School Science Acid and Base Concentrations (ph and poh) Lesson Objective: Subobjective 1: Subobjective 2: Subobjective 3: Subobjective 4:

High School Science Acid and Base Concentrations (ph and poh) Lesson Objective: Subobjective 1: Subobjective 2: Subobjective 3: Subobjective 4: High School Science Acid and Base Concentrations (ph and poh) Lesson Objective: The student will determine acid and base concentrations. Subobjective 1: The student will use the ph scale to characterize

More information

FUCHS ATAD. from sewage sludge to Class A Biosolids. Air. Water. Biosolids

FUCHS ATAD. from sewage sludge to Class A Biosolids. Air. Water. Biosolids FUCHS ATAD from sewage sludge to Class A Biosolids Air Water Biosolids FUCHS ATAD Process How to make Class A Biosolids FUCHS ATAD Process: The economical and reliable way from sewage sludge and manure

More information

CFD MODELING FOR PNEUMATIC CONVEYING

CFD MODELING FOR PNEUMATIC CONVEYING CFD MODELING FOR PNEUMATIC CONVEYING Arvind Kumar 1, D.R. Kaushal 2, Navneet Kumar 3 1 Associate Professor YMCAUST, Faridabad 2 Associate Professor, IIT, Delhi 3 Research Scholar IIT, Delhi e-mail: arvindeem@yahoo.co.in

More information

Maximizing Secondary Clarifier Capacity with Threedimensional

Maximizing Secondary Clarifier Capacity with Threedimensional Maximizing Secondary Clarifier Capacity with Threedimensional Modeling Randal Samstag and Ed Wicklein Carollo Engineers Presentation Outline Introduction to the problem Comparison of models Case studies:

More information

City Of London Environmental & Engineering Services Department Wastewater Treatment Operations

City Of London Environmental & Engineering Services Department Wastewater Treatment Operations City Of London Environmental & Engineering Services Department Wastewater Treatment Operations Greenway Pollution Control Centre 2014 Annual Report February 2015 Page 1 of 87 Summary This annual report

More information

Presentation Outline. Settleability Can be Improved. The Clarifier. Maximizing Secondary Clarifier Capacity with Threedimensional

Presentation Outline. Settleability Can be Improved. The Clarifier. Maximizing Secondary Clarifier Capacity with Threedimensional Presentation Outline Maximizing Secondary Clarifier Capacity with Threedimensional Modeling Randal Samstag and Ed Wicklein Carollo Engineers Introduction to the problem Comparison of models Case studies:

More information

Dynamics Add-On User s Manual For WinGEMS 5.3

Dynamics Add-On User s Manual For WinGEMS 5.3 Dynamics Add-On User s Manual For WinGEMS 5.3 1. Dynamics 1.1. Introduction An optional feature of WinGEMS is the ability to simulate the transient response of a model with respect to time. The key dynamic

More information

Error Analysis, Statistics and Graphing

Error Analysis, Statistics and Graphing Error Analysis, Statistics and Graphing This semester, most of labs we require us to calculate a numerical answer based on the data we obtain. A hard question to answer in most cases is how good is your

More information

Seasonal variability of SVI in the secondary sedimenter of an Italian WWTP

Seasonal variability of SVI in the secondary sedimenter of an Italian WWTP Seasonal variability of SVI in the secondary sedimenter of an Italian WWTP Traverso 1, P., Zanchettin 1, D., Ghermandi 2, A.,Busetti 3, F., Badoer 4, S. 1 University of Venice, Dept. of Environm. Sc.,

More information

Using the Eulerian Multiphase Model for Granular Flow

Using the Eulerian Multiphase Model for Granular Flow Tutorial 21. Using the Eulerian Multiphase Model for Granular Flow Introduction Mixing tanks are used to maintain solid particles or droplets of heavy fluids in suspension. Mixing may be required to enhance

More information

Investigation of mixing chamber for experimental FGD reactor

Investigation of mixing chamber for experimental FGD reactor Investigation of mixing chamber for experimental FGD reactor Jan Novosád 1,a, Petra Danová 1 and Tomáš Vít 1 1 Department of Power Engineering Equipment, Faculty of Mechanical Engineering, Technical University

More information

UNDERSTANDING FROTH BEHAVIOUR WITH CFD

UNDERSTANDING FROTH BEHAVIOUR WITH CFD UNDERSTANDING FROTH BEHAVIOUR WITH CFD Jan Cilliers Rio Tinto Professor of Mineral Processing Royal School of Mines Imperial College London Outline Froths and Foams Modelling of Flotation Froths 3 Case

More information

BioMASS v2.0: A NEW TOOL FOR BIOPROCESS SIMULATION

BioMASS v2.0: A NEW TOOL FOR BIOPROCESS SIMULATION Clemson University TigerPrints All Theses Theses 5-2011 BioMASS v2.0: A NEW TOOL FOR BIOPROCESS SIMULATION Y Phan-thien Clemson University, nhuy2711@gmail.com Follow this and additional works at: https://tigerprints.clemson.edu/all_theses

More information

Using the complex-step derivative approximation method to calculate local sensitivity functions of highly nonlinear bioprocess models

Using the complex-step derivative approximation method to calculate local sensitivity functions of highly nonlinear bioprocess models 1 Using the complex-step derivative approximation method to calculate local sensitivity functions of highly nonlinear bioprocess models D.J.W. De Pauw and P.A. Vanrolleghem Department of Applied Mathematics,

More information

Interface Level Analyzers & Sensors

Interface Level Analyzers & Sensors products dedicated to solving problems Algae Control Ammonia Interface Level Analyzers & Sensors Calibration Chlorine Conductivity Cooling Tower Monitoring Dissolved Oxygen Interface Level Nitrate/Nitrite

More information

Detection and Analysis of Sludge Bulking Events Using Data Mining and Machine Learning Approach

Detection and Analysis of Sludge Bulking Events Using Data Mining and Machine Learning Approach Marquette University e-publications@marquette Master's Theses (2009 -) Dissertations, Theses, and Professional Projects Detection and Analysis of Sludge Bulking Events Using Data Mining and Machine Learning

More information

Validation for Data Classification

Validation for Data Classification Validation for Data Classification HILARIO LÓPEZ and IVÁN MACHÓN and EVA FERNÁNDEZ Departamento de Ingeniería Eléctrica, Electrónica de Computadores y Sistemas Universidad de Oviedo Edificio Departamental

More information

CFD Modelling in the Cement Industry

CFD Modelling in the Cement Industry CFD Modelling in the Cement Industry Victor J. Turnell, P.E., Turnell Corp., USA, describes computational fluid dynamics (CFD) simulation and its benefits in applications in the cement industry. Introduction

More information

MATHEMATICS CONCEPTS TAUGHT IN THE SCIENCE EXPLORER, FOCUS ON EARTH SCIENCE TEXTBOOK

MATHEMATICS CONCEPTS TAUGHT IN THE SCIENCE EXPLORER, FOCUS ON EARTH SCIENCE TEXTBOOK California, Mathematics Concepts Found in Science Explorer, Focus on Earth Science Textbook (Grade 6) 1 11 Describe the layers of the Earth 2 p. 59-61 Draw a circle with a specified radius or diameter

More information

Real time data validation. Methodology guidelines, comments, examples of application and prototype software tool for on-line (RTC) data validation

Real time data validation. Methodology guidelines, comments, examples of application and prototype software tool for on-line (RTC) data validation Real time data validation Methodology guidelines, comments, examples of application and prototype software tool for on-line (RTC) data validation 212, 213 PREPARED The European Commission is funding the

More information

Tutorial: Modeling Liquid Reactions in CIJR Using the Eulerian PDF transport (DQMOM-IEM) Model

Tutorial: Modeling Liquid Reactions in CIJR Using the Eulerian PDF transport (DQMOM-IEM) Model Tutorial: Modeling Liquid Reactions in CIJR Using the Eulerian PDF transport (DQMOM-IEM) Model Introduction The purpose of this tutorial is to demonstrate setup and solution procedure of liquid chemical

More information

PLC 22 WETLANDS & NITRIFYING BIO TOWERS SCADA SYSTEM OPERATION MANUAL. Revision 1.0 May 30, 2006

PLC 22 WETLANDS & NITRIFYING BIO TOWERS SCADA SYSTEM OPERATION MANUAL. Revision 1.0 May 30, 2006 PLC 22 WETLANDS & NITRIFYING BIO TOWERS SCADA SYSTEM OPERATION MANUAL Revision 1.0 May 30, 2006 PLC 22 WETLANDS & NITRIFYING BIO TOWERS SCADA SYSTEM OPERATION MANUAL Revision 1.0 May 30, 2006 Table of

More information

Gaussian Mixture Models method and applications

Gaussian Mixture Models method and applications Gaussian Mixture Models method and applications Jesús Zambrano PostDoctoral Researcher School of Business, Society and Engineering www.mdh.se FUDIPO project. Machine Learning course. Oct.-Dec. 2017 Outline

More information

NV17-79 Interactive Operator Round Table Discussion swmoa.org 2 20-Apr May-17 D I I D D I

NV17-79 Interactive Operator Round Table Discussion swmoa.org 2 20-Apr May-17 D I I D D I NV17-66 PREPAREDNESS TOOLS AND RESOURCES 1 08-Mar-17 03-May-17 D D D D D D Proposed Methodology for Determining RO Unit Integrity for Pathogen Removal Credit NV17-71 and Regulatory Compliance swmoa.org

More information

TECHNICAL PROBLEM The author's work, software application "BALBYKAN", solves the problem of hydraulic

TECHNICAL PROBLEM The author's work, software application BALBYKAN, solves the problem of hydraulic 1 SOFTWARE APPLICATION "BALBYKAN" FOR HYDRAULIC CALCULATION, ENGINEERING DESIGN, AND SIMULATION OF SEWERAGE SYSTEMS AUTHOR: Pavle Babac, Civil Engineer, MSc ABSTRACT The author's work, software application

More information

Analyzer. On-line Measuring

Analyzer. On-line Measuring Analyzer On-line Measuring Water and wastewater treatment still require analyzers for on-line measuring, justifying their presence next to commonly more reasonable in-situ sensor systems. Especially for

More information

Development of the Compliant Mooring Line Model for FLOW-3D

Development of the Compliant Mooring Line Model for FLOW-3D Flow Science Report 08-15 Development of the Compliant Mooring Line Model for FLOW-3D Gengsheng Wei Flow Science, Inc. October 2015 1. Introduction Mooring systems are common in offshore structures, ship

More information

1. Introduction. 2. Modelling elements III. CONCEPTS OF MODELLING. - Models in environmental sciences have five components:

1. Introduction. 2. Modelling elements III. CONCEPTS OF MODELLING. - Models in environmental sciences have five components: III. CONCEPTS OF MODELLING 1. INTRODUCTION 2. MODELLING ELEMENTS 3. THE MODELLING PROCEDURE 4. CONCEPTUAL MODELS 5. THE MODELLING PROCEDURE 6. SELECTION OF MODEL COMPLEXITY AND STRUCTURE 1 1. Introduction

More information

TYPE 529: RADIANT SLAB

TYPE 529: RADIANT SLAB TYPE 529: RADIANT SLAB General Description This component is intended to model a radiant floor-heating slab, embedded in soil, and containing a number of fluid filled pipes. The heat transfer within the

More information

The viscous forces on the cylinder are proportional to the gradient of the velocity field at the

The viscous forces on the cylinder are proportional to the gradient of the velocity field at the Fluid Dynamics Models : Flow Past a Cylinder Flow Past a Cylinder Introduction The flow of fluid behind a blunt body such as an automobile is difficult to compute due to the unsteady flows. The wake behind

More information

Application of MCNP Code in Shielding Design for Radioactive Sources

Application of MCNP Code in Shielding Design for Radioactive Sources Application of MCNP Code in Shielding Design for Radioactive Sources Ibrahim A. Alrammah Abstract This paper presents three tasks: Task 1 explores: the detected number of as a function of polythene moderator

More information

A Verification Study of ABAQUS AC3D8R Elements for Acoustic Wave Propagation

A Verification Study of ABAQUS AC3D8R Elements for Acoustic Wave Propagation A Verification Study of ABAQUS AC3D8R Elements for Acoustic Wave Propagation by Michael Robert Hubenthal A Project Submitted to the Graduate Faculty of Rensselaer Polytechnic Institute in Partial Fulfillment

More information

Screen3 View. Contents. Page 1

Screen3 View. Contents. Page 1 Screen3 View Contents Introduction What is EPA's SCREEN3 Model? What is the Screen3 View Interface? Toollbar Buttons Preliminary Considerations Source Inputs Screen3 Options Running SCREEN3 Model Graphic

More information

Fluent User Services Center

Fluent User Services Center Solver Settings 5-1 Using the Solver Setting Solver Parameters Convergence Definition Monitoring Stability Accelerating Convergence Accuracy Grid Independence Adaption Appendix: Background Finite Volume

More information

Example 13 - Shock Tube

Example 13 - Shock Tube Example 13 - Shock Tube Summary This famous experiment is interesting for observing the shock-wave propagation. Moreover, this case uses the representation of perfect gas and compares the different formulations:

More information

Calculate a solution using the pressure-based coupled solver.

Calculate a solution using the pressure-based coupled solver. Tutorial 19. Modeling Cavitation Introduction This tutorial examines the pressure-driven cavitating flow of water through a sharpedged orifice. This is a typical configuration in fuel injectors, and brings

More information

Prof. Fanny Ficuciello Robotics for Bioengineering Visual Servoing

Prof. Fanny Ficuciello Robotics for Bioengineering Visual Servoing Visual servoing vision allows a robotic system to obtain geometrical and qualitative information on the surrounding environment high level control motion planning (look-and-move visual grasping) low level

More information

17. SEISMIC ANALYSIS MODELING TO SATISFY BUILDING CODES

17. SEISMIC ANALYSIS MODELING TO SATISFY BUILDING CODES 17. SEISMIC ANALYSIS MODELING TO SATISFY BUILDING CODES The Current Building Codes Use the Terminology: Principal Direction without a Unique Definition 17.1 INTRODUCTION { XE "Building Codes" }Currently

More information

System Identification Algorithms and Techniques for Systems Biology

System Identification Algorithms and Techniques for Systems Biology System Identification Algorithms and Techniques for Systems Biology by c Choujun Zhan A Thesis submitted to the School of Graduate Studies in partial fulfillment of the requirements for the degree of Doctor

More information

CPIB SUMMER SCHOOL 2011: INTRODUCTION TO BIOLOGICAL MODELLING

CPIB SUMMER SCHOOL 2011: INTRODUCTION TO BIOLOGICAL MODELLING CPIB SUMMER SCHOOL 2011: INTRODUCTION TO BIOLOGICAL MODELLING 1 COPASI COPASI / Parameter estimation Markus Owen COPASI stands for COmplex PAthway SImulator. It is for the simulation and analysis of biochemical

More information

Dispersion Modelling for Explosion Risk Analysis

Dispersion Modelling for Explosion Risk Analysis Dispersion Modelling for Explosion Risk Analysis Tim Jones, Principal Consultant, MMI Engineering, The Brew House, Wilderspool Park, Greenall s Avenue, Warrington, WA4 6HL The understanding of the explosion

More information

Tutorial 1. Introduction to Using FLUENT: Fluid Flow and Heat Transfer in a Mixing Elbow

Tutorial 1. Introduction to Using FLUENT: Fluid Flow and Heat Transfer in a Mixing Elbow Tutorial 1. Introduction to Using FLUENT: Fluid Flow and Heat Transfer in a Mixing Elbow Introduction This tutorial illustrates the setup and solution of the two-dimensional turbulent fluid flow and heat

More information

MODELING PARTICLE DEPOSITION IN VENTILATION DUCTS

MODELING PARTICLE DEPOSITION IN VENTILATION DUCTS MODELING PARTICLE DEPOSITION IN VENTILATION DUCTS MR Sippola 1* and WW Nazaroff 1,2 1 Dept. of Civil and Environmental Engineering, University of California, Berkeley, CA, USA 2 Indoor Environment Dept.,

More information

Introduction to C omputational F luid Dynamics. D. Murrin

Introduction to C omputational F luid Dynamics. D. Murrin Introduction to C omputational F luid Dynamics D. Murrin Computational fluid dynamics (CFD) is the science of predicting fluid flow, heat transfer, mass transfer, chemical reactions, and related phenomena

More information

Transfer and pouring processes of casting by smoothed particle. hydrodynamic method

Transfer and pouring processes of casting by smoothed particle. hydrodynamic method Transfer and pouring processes of casting by smoothed particle hydrodynamic method M. Kazama¹, K. Ogasawara¹, *T. Suwa¹, H. Ito 2, and Y. Maeda 2 1 Application development div., Next generation technical

More information

Flow Meter. The most flexible flow meter

Flow Meter. The most flexible flow meter Flow Meter The most flexible flow meter Keep Smart Monitoring Simple The Signature from Teledyne Isco is not just another open channel flow meter it is a highly flexible monitoring platform, adapting right

More information

Modeling Flow Through Porous Media

Modeling Flow Through Porous Media Tutorial 7. Modeling Flow Through Porous Media Introduction Many industrial applications involve the modeling of flow through porous media, such as filters, catalyst beds, and packing. This tutorial illustrates

More information

Lagrangian methods and Smoothed Particle Hydrodynamics (SPH) Computation in Astrophysics Seminar (Spring 2006) L. J. Dursi

Lagrangian methods and Smoothed Particle Hydrodynamics (SPH) Computation in Astrophysics Seminar (Spring 2006) L. J. Dursi Lagrangian methods and Smoothed Particle Hydrodynamics (SPH) Eulerian Grid Methods The methods covered so far in this course use an Eulerian grid: Prescribed coordinates In `lab frame' Fluid elements flow

More information

Integration of Analytical Instruments with Computer Scripting

Integration of Analytical Instruments with Computer Scripting 476288JLAXXX10.1177/221106821347628 8Journal of Laboratory AutomationCarvalho 2013 Technology Brief Integration of Analytical Instruments with Computer Scripting Journal of Laboratory Automation 18(4)

More information

Hydrocyclones and CFD

Hydrocyclones and CFD Design of Hydrocyclone Separation Equipment Using CFD Coupled with Optimization Tools David Schowalter 1, Rafiqul Khan 1, Therese Polito 2, and Tim Olson 3. (1) Fluent Inc., 10 Cavendish Court, Lebanon,

More information

ADAPTIVE TILE CODING METHODS FOR THE GENERALIZATION OF VALUE FUNCTIONS IN THE RL STATE SPACE A THESIS SUBMITTED TO THE FACULTY OF THE GRADUATE SCHOOL

ADAPTIVE TILE CODING METHODS FOR THE GENERALIZATION OF VALUE FUNCTIONS IN THE RL STATE SPACE A THESIS SUBMITTED TO THE FACULTY OF THE GRADUATE SCHOOL ADAPTIVE TILE CODING METHODS FOR THE GENERALIZATION OF VALUE FUNCTIONS IN THE RL STATE SPACE A THESIS SUBMITTED TO THE FACULTY OF THE GRADUATE SCHOOL OF THE UNIVERSITY OF MINNESOTA BY BHARAT SIGINAM IN

More information

MIKE 21 & MIKE 3 FLOW MODEL FM. Transport Module. Short Description

MIKE 21 & MIKE 3 FLOW MODEL FM. Transport Module. Short Description MIKE 21 & MIKE 3 FLOW MODEL FM Short Description MIKE213_TR_FM_Short_Description.docx/AJS/EBR/2011Short_Descriptions.lsm//2011-06-17 MIKE 21 & MIKE 3 FLOW MODEL FM Agern Allé 5 DK-2970 Hørsholm Denmark

More information

Chapter 15 Introduction to Linear Programming

Chapter 15 Introduction to Linear Programming Chapter 15 Introduction to Linear Programming An Introduction to Optimization Spring, 2015 Wei-Ta Chu 1 Brief History of Linear Programming The goal of linear programming is to determine the values of

More information

µ = Pa s m 3 The Reynolds number based on hydraulic diameter, D h = 2W h/(w + h) = 3.2 mm for the main inlet duct is = 359

µ = Pa s m 3 The Reynolds number based on hydraulic diameter, D h = 2W h/(w + h) = 3.2 mm for the main inlet duct is = 359 Laminar Mixer Tutorial for STAR-CCM+ ME 448/548 March 30, 2014 Gerald Recktenwald gerry@pdx.edu 1 Overview Imagine that you are part of a team developing a medical diagnostic device. The device has a millimeter

More information

MIKE 21 & MIKE 3 Flow Model FM. Transport Module. Short Description

MIKE 21 & MIKE 3 Flow Model FM. Transport Module. Short Description MIKE 21 & MIKE 3 Flow Model FM Transport Module Short Description DHI headquarters Agern Allé 5 DK-2970 Hørsholm Denmark +45 4516 9200 Telephone +45 4516 9333 Support +45 4516 9292 Telefax mike@dhigroup.com

More information

FAILURE MODE ANALYSIS USING MULTILEVEL FLOW MODELS

FAILURE MODE ANALYSIS USING MULTILEVEL FLOW MODELS FAILURE MODE ANALYSIS USING MULTILEVEL FLOW MODELS Bengt Öhman* * Department of Information Technology, Lund Institute of Technology, Box 118, 221 00 Lund, Sweden. Fax: +46 46 222 4714, E-mail: bengt@it.lth.se

More information

Predicting methane and biogas production with the biogas package

Predicting methane and biogas production with the biogas package Predicting methane and biogas production with the biogas package Sasha D. Hafner (sasha.hafner@eng.au.dk) and Charlotte Rennuit February 5, 2018 Theory for predicting biogas production based on substrate

More information

COMPUTATIONAL FLUID DYNAMICS ANALYSIS OF ORIFICE PLATE METERING SITUATIONS UNDER ABNORMAL CONFIGURATIONS

COMPUTATIONAL FLUID DYNAMICS ANALYSIS OF ORIFICE PLATE METERING SITUATIONS UNDER ABNORMAL CONFIGURATIONS COMPUTATIONAL FLUID DYNAMICS ANALYSIS OF ORIFICE PLATE METERING SITUATIONS UNDER ABNORMAL CONFIGURATIONS Dr W. Malalasekera Version 3.0 August 2013 1 COMPUTATIONAL FLUID DYNAMICS ANALYSIS OF ORIFICE PLATE

More information

Using the Discrete Ordinates Radiation Model

Using the Discrete Ordinates Radiation Model Tutorial 6. Using the Discrete Ordinates Radiation Model Introduction This tutorial illustrates the set up and solution of flow and thermal modelling of a headlamp. The discrete ordinates (DO) radiation

More information

Denitrification controller sysline XR 35N

Denitrification controller sysline XR 35N Technical Information TI 129C/07/e/ Denitrification controller sysline XR 35N Microprocessor-controlled evaluation instrument for denitrification control via the redox potential of the activated sludge

More information

Revision of the SolidWorks Variable Pressure Simulation Tutorial J.E. Akin, Rice University, Mechanical Engineering. Introduction

Revision of the SolidWorks Variable Pressure Simulation Tutorial J.E. Akin, Rice University, Mechanical Engineering. Introduction Revision of the SolidWorks Variable Pressure Simulation Tutorial J.E. Akin, Rice University, Mechanical Engineering Introduction A SolidWorks simulation tutorial is just intended to illustrate where to

More information

Chapter 15. Light Waves

Chapter 15. Light Waves Chapter 15 Light Waves Chapter 15 is finished, but is not in camera-ready format. All diagrams are missing, but here are some excerpts from the text with omissions indicated by... After 15.1, read 15.2

More information

Chapter 4. The Classification of Species and Colors of Finished Wooden Parts Using RBFNs

Chapter 4. The Classification of Species and Colors of Finished Wooden Parts Using RBFNs Chapter 4. The Classification of Species and Colors of Finished Wooden Parts Using RBFNs 4.1 Introduction In Chapter 1, an introduction was given to the species and color classification problem of kitchen

More information

Elucidating the Mechanism Governing Particle Alignment and Movement by DEP Yu Zhao 1, Jozef Brcka 2, Jacques Faguet 2, Guigen Zhang *,1,3,4 1

Elucidating the Mechanism Governing Particle Alignment and Movement by DEP Yu Zhao 1, Jozef Brcka 2, Jacques Faguet 2, Guigen Zhang *,1,3,4 1 Elucidating the Mechanism Governing Particle Alignment and Movement by DEP Yu Zhao 1, Jozef Brcka 2, Jacques Faguet 2, Guigen Zhang *,1,3,4 1 Department of Bioengineering, Clemson University, Clemson,

More information

Modeling Evaporating Liquid Spray

Modeling Evaporating Liquid Spray Tutorial 17. Modeling Evaporating Liquid Spray Introduction In this tutorial, the air-blast atomizer model in ANSYS FLUENT is used to predict the behavior of an evaporating methanol spray. Initially, the

More information

Sweeping Jet Flushing Method for EDM

Sweeping Jet Flushing Method for EDM International Conference on Multidisciplinary Research & Practice P a g e 192 Sweeping Jet Flushing Method for EDM Kishor K Kulkarni # Production Engineering, ShivajiUniversity/Ashokrao Mane Group of Institution

More information

PSG2 / Serpent a Monte Carlo Reactor Physics Burnup Calculation Code. Jaakko Leppänen

PSG2 / Serpent a Monte Carlo Reactor Physics Burnup Calculation Code. Jaakko Leppänen PSG2 / Serpent a Monte Carlo Reactor Physics Burnup Calculation Code Jaakko Leppänen Outline Background History The Serpent code: Neutron tracking Physics and interaction data Burnup calculation Output

More information

ISO INTERNATIONAL STANDARD. Particle size analysis Laser diffraction methods Part 1: General principles

ISO INTERNATIONAL STANDARD. Particle size analysis Laser diffraction methods Part 1: General principles INTERNATIONAL STANDARD ISO 13320-1 First edition 1999-11-01 Particle size analysis Laser diffraction methods Part 1: General principles Analyse granulométrique Méthodes par diffraction laser Partie 1:

More information

PLC 4 PRIMARY SEDIMENTATION SYSTEM SCADA SYSTEM OPERATION MANUAL. Revision 1.0 May 15, 2006

PLC 4 PRIMARY SEDIMENTATION SYSTEM SCADA SYSTEM OPERATION MANUAL. Revision 1.0 May 15, 2006 PLC 4 PRIMARY SEDIMENTATION SYSTEM SCADA SYSTEM OPERATION MANUAL Revision 1.0 May 15, 2006 PLC 4 PRIMARY SEDIMENTATION SYSTEM SCADA SYSTEM OPERATION MANUAL Revision 1.0 May 15, 2006 Table of Contents 1

More information

ONE DIMENSIONAL (1D) SIMULATION TOOL: GT-POWER

ONE DIMENSIONAL (1D) SIMULATION TOOL: GT-POWER CHAPTER 4 ONE DIMENSIONAL (1D) SIMULATION TOOL: GT-POWER 4.1 INTRODUCTION Combustion analysis and optimization of any reciprocating internal combustion engines is too complex and intricate activity. It

More information

Retrofitting sewage plants with lightning and surge protection measures

Retrofitting sewage plants with lightning and surge protection measures 904 Retrofitting sewage plants with lightning and surge protection measures A more efficient use of drinking water is growing in significance, especially against a backdrop of increasingly scarce drinking

More information

Engineering Effects of Boundary Conditions (Fixtures and Temperatures) J.E. Akin, Rice University, Mechanical Engineering

Engineering Effects of Boundary Conditions (Fixtures and Temperatures) J.E. Akin, Rice University, Mechanical Engineering Engineering Effects of Boundary Conditions (Fixtures and Temperatures) J.E. Akin, Rice University, Mechanical Engineering Here SolidWorks stress simulation tutorials will be re-visited to show how they

More information

Backward facing step Homework. Department of Fluid Mechanics. For Personal Use. Budapest University of Technology and Economics. Budapest, 2010 autumn

Backward facing step Homework. Department of Fluid Mechanics. For Personal Use. Budapest University of Technology and Economics. Budapest, 2010 autumn Backward facing step Homework Department of Fluid Mechanics Budapest University of Technology and Economics Budapest, 2010 autumn Updated: October 26, 2010 CONTENTS i Contents 1 Introduction 1 2 The problem

More information

2.1 System Dynamics Tool: STELLA Version 10 Tutorial 1. Introduction to Computational Science: Modeling and Simulation for the Sciences, 2nd Edition

2.1 System Dynamics Tool: STELLA Version 10 Tutorial 1. Introduction to Computational Science: Modeling and Simulation for the Sciences, 2nd Edition 2.1 System Dynamics Tool: STELLA Version 10 Tutorial 1 Introduction to Computational Science: Modeling and Simulation for the Sciences, 2nd Edition Angela B. Shiflet and George W. Shiflet Wofford College

More information

Evaluation and Comparison of Models and Modeling Tools Simulating Nitrogen Processes in Treatment Wetlands

Evaluation and Comparison of Models and Modeling Tools Simulating Nitrogen Processes in Treatment Wetlands Evaluation and Comparison of Models and Modeling Tools Simulating Nitrogen Processes in Treatment Wetlands Stina Edelfeldt and Peter Fritzson Linköping University Post Print N.B.: When citing this work,

More information

Mathematics Scope & Sequence Grade 8 Revised: June 2015

Mathematics Scope & Sequence Grade 8 Revised: June 2015 Mathematics Scope & Sequence 2015-16 Grade 8 Revised: June 2015 Readiness Standard(s) First Six Weeks (29 ) 8.2D Order a set of real numbers arising from mathematical and real-world contexts Convert between

More information

Adarsh Krishnamurthy (cs184-bb) Bela Stepanova (cs184-bs)

Adarsh Krishnamurthy (cs184-bb) Bela Stepanova (cs184-bs) OBJECTIVE FLUID SIMULATIONS Adarsh Krishnamurthy (cs184-bb) Bela Stepanova (cs184-bs) The basic objective of the project is the implementation of the paper Stable Fluids (Jos Stam, SIGGRAPH 99). The final

More information

Mass-flux parameterization in the shallow convection gray zone

Mass-flux parameterization in the shallow convection gray zone Mass-flux parameterization in the shallow convection gray zone LACE stay report Toulouse Centre National de Recherche Meteorologique, 15. September 2014 26. September 2014 Scientific supervisor: Rachel

More information

ENV3104 Hydraulics II 2017 Assignment 1. Gradually Varied Flow Profiles and Numerical Solution of the Kinematic Equations:

ENV3104 Hydraulics II 2017 Assignment 1. Gradually Varied Flow Profiles and Numerical Solution of the Kinematic Equations: ENV3104 Hydraulics II 2017 Assignment 1 Assignment 1 Gradually Varied Flow Profiles and Numerical Solution of the Kinematic Equations: Examiner: Jahangir Alam Due Date: 27 Apr 2017 Weighting: 1% Objectives

More information

ENGINEERING PHYSICS CURRICULUM GUIDE

ENGINEERING PHYSICS CURRICULUM GUIDE ENGINEERING PHYSICS CURRICULUM GUIDE The following course schedule represents the suggested curriculum for a typical student in the Engineering Physics Program. Substitutions may be made for some courses

More information

Experimental Data Confirms CFD Models of Mixer Performance

Experimental Data Confirms CFD Models of Mixer Performance The Problem Over the years, manufacturers of mixing systems have presented computational fluid dynamics (CFD) calculations to claim that their technology can achieve adequate mixing in water storage tanks

More information

Numerical Simulations of Granular Materials Flow around Obstacles: The role of the interstitial gas

Numerical Simulations of Granular Materials Flow around Obstacles: The role of the interstitial gas Numerical Simulations of Granular Materials Flow around Obstacles: The role of the interstitial gas Avi Levy, Dept. Mech. Eng., Ben Gurion University, Beer Sheva, Israel. Mohamed Sayed, CHC, National Research

More information

Turbulencja w mikrokanale i jej wpływ na proces emulsyfikacji

Turbulencja w mikrokanale i jej wpływ na proces emulsyfikacji Polish Academy of Sciences Institute of Fundamental Technological Research Turbulencja w mikrokanale i jej wpływ na proces emulsyfikacji S. Błoński, P.Korczyk, T.A. Kowalewski PRESENTATION OUTLINE 0 Introduction

More information

Computational analysis of hydrodynamics and light distribution in algal photo-bioreactors

Computational analysis of hydrodynamics and light distribution in algal photo-bioreactors Computational analysis of hydrodynamics and light distribution in algal photo-bioreactors Varun Loomba 1,2, Eric von Lieres 2, Gregor Huber 1 1 Forschungszentrum Jülich, Institute of Bio- and Geosciences,

More information

Claros Collect Getting Started Guide

Claros Collect Getting Started Guide Claros Collect 2018.2 Getting Started Guide Version Date 2018.2 7/31/2018 2018.1 6/1/2018 Table of Contents Introduction to Claros Collect... 3 Technical Requirements for Claros Collect... 3 Getting Started:...

More information

EES Program Overview

EES Program Overview EES Program Overview EES (pronounced 'ease') is an acronym for Engineering Equation Solver. The basic function provided by EES is the numerical solution of a set of algebraic equations. EES can also be

More information

INVESTIGATION OF HYDRAULIC PERFORMANCE OF A FLAP TYPE CHECK VALVE USING CFD AND EXPERIMENTAL TECHNIQUE

INVESTIGATION OF HYDRAULIC PERFORMANCE OF A FLAP TYPE CHECK VALVE USING CFD AND EXPERIMENTAL TECHNIQUE International Journal of Mechanical Engineering and Technology (IJMET) Volume 10, Issue 1, January 2019, pp. 409 413, Article ID: IJMET_10_01_042 Available online at http://www.ia aeme.com/ijmet/issues.asp?jtype=ijmet&vtype=

More information

Sci.Int.(Lahore),28(1), ,2016 ISSN ; CODEN: SINTE 8 201

Sci.Int.(Lahore),28(1), ,2016 ISSN ; CODEN: SINTE 8 201 Sci.Int.(Lahore),28(1),201-209,2016 ISSN 1013-5316; CODEN: SINTE 8 201 A NOVEL PLANT PROPAGATION ALGORITHM: MODIFICATIONS AND IMPLEMENTATION Muhammad Sulaiman 1, Abdel Salhi 2, Eric S Fraga 3, Wali Khan

More information

Process State Estimation in a Wastewater Biological Treatment

Process State Estimation in a Wastewater Biological Treatment Process State Estimation in a Wastewater Biological Treatment IVÁN MACHÓN and HILARIO LÓPEZ and ANTONIO ROBLES Departamento de Ingeniería Eléctrica, Electrónica de Computadores y Sistemas Universidad de

More information

CFD STUDY OF MIXING PROCESS IN RUSHTON TURBINE STIRRED TANKS

CFD STUDY OF MIXING PROCESS IN RUSHTON TURBINE STIRRED TANKS Third International Conference on CFD in the Minerals and Process Industries CSIRO, Melbourne, Australia 10-12 December 2003 CFD STUDY OF MIXING PROCESS IN RUSHTON TURBINE STIRRED TANKS Guozhong ZHOU 1,2,

More information

Congestion Control. Andreas Pitsillides University of Cyprus. Congestion control problem

Congestion Control. Andreas Pitsillides University of Cyprus. Congestion control problem Congestion Control Andreas Pitsillides 1 Congestion control problem growing demand of computer usage requires: efficient ways of managing network traffic to avoid or limit congestion in cases where increases

More information

Compressible Flow in a Nozzle

Compressible Flow in a Nozzle SPC 407 Supersonic & Hypersonic Fluid Dynamics Ansys Fluent Tutorial 1 Compressible Flow in a Nozzle Ahmed M Nagib Elmekawy, PhD, P.E. Problem Specification Consider air flowing at high-speed through a

More information

Using ANSYS and CFX to Model Aluminum Reduction Cell since1984 and Beyond. Dr. Marc Dupuis

Using ANSYS and CFX to Model Aluminum Reduction Cell since1984 and Beyond. Dr. Marc Dupuis Using ANSYS and CFX to Model Aluminum Reduction Cell since1984 and Beyond Dr. Marc Dupuis 1980-84, 2D potroom ventilation model Physical model 1980-84, 2D potroom ventilation model Experimental results

More information

Mining Engineering Technician: Speciality Mine Exploitation

Mining Engineering Technician: Speciality Mine Exploitation Mining Engineering Technician: Speciality Mine Exploitation FIRST YEAR PHYSICAL BASES OF ENGINEERING 9220001 Core 1st 1st semester 6 7.2 Mechanics. Electricity. Thermodynamics. Fluid mechanics. Classes

More information

Express Introductory Training in ANSYS Fluent Workshop 02 Using the Discrete Phase Model (DPM)

Express Introductory Training in ANSYS Fluent Workshop 02 Using the Discrete Phase Model (DPM) Express Introductory Training in ANSYS Fluent Workshop 02 Using the Discrete Phase Model (DPM) Dimitrios Sofialidis Technical Manager, SimTec Ltd. Mechanical Engineer, PhD PRACE Autumn School 2013 - Industry

More information

Using the Scaling Equations to Define Experimental Matrices for Software Validation

Using the Scaling Equations to Define Experimental Matrices for Software Validation Using the Scaling Equations to Define Experimental Matrices for Software Validation Richard R. Schultz, Edwin Harvego, Brian G. Woods, and Yassin Hassan V&V30 Standards Committee Presentation Content Description

More information

Simulation of Curtain Airbag with Arbitrary. Eulerian- Lagrangian Method

Simulation of Curtain Airbag with Arbitrary. Eulerian- Lagrangian Method Simulation of Curtain Airbag with Arbitrary Eulerian- Lagrangian Method Dmitri Fokin, Eivind Dessarud Altair Engineering Claes Ljungqvist Saab Automobile AB Abstract: Computer simulation is a powerful

More information

Tips and FAQ Revised: Nov 13, Aspen Plus Tips. Tips and Frequently Asked Questions

Tips and FAQ Revised: Nov 13, Aspen Plus Tips. Tips and Frequently Asked Questions Aspen Plus Tips Tips and Frequently Asked Questions This quick start guide is intended to supply first time Aspen Plus users with helpful tips and advice to accelerate the learning curve associated with

More information