%\documentclass[10pt,a4paper]{article}
%\usepackage[utf8]{inputenc}
%\usepackage{amsmath}
%\usepackage{amsfonts}
%\usepackage{amssymb}
%\usepackage{listings}
%\usepackage{graphicx}
%\author{Richard Torenvliet - 6138861}
%\title{Flood Simulation Browser}
%\maketitle

\section{Introduction}
UrbanFlood is a European project that aims to create an early warning system in European cities\cite{UrbanFlood}. In the today's changing climate, more and more cities have to deal with floods more often. An article of \cite{floodarticle}. A lot of research went in the possible solutions for specific problems. Due to extreme rainfall, rising water or long lasting drought, the instruments that protect the civilians of a certain area are negatively influenced. The project involves setting up a system that can make estimates on how a levee would behave in the near future. Vigilance against weak spots in the levee is needed 24/7. To do this they placed sensors in the levee that can be monitored remotely via internet. But this not the only concern. They also developed a system that can create flood simulations of a certain area. This is used for testing dikes in a possible scenario but also for educative proposes. This subject is discussed in the present document.

This thesis concerns the Flood Simulation Browser. The concept of this browser is to illustrate/visualize a flood in a particular area. With this technology people can see the flow that the water will take. When a dike breaks it is important to know where the water will flow. Information about which locations in the area will be under water first can result in a successful evacuation plan. This system already exists on a multi-touch table\cite{touchtable}. The touch table is used in workshops for an interactive way of informing about the risk of floods. The disadvantage of the multi touch table is that it is only accessible in certain occasions. If the system were to be more accessible it makes it more likely that someone with right authority can take
% (the tablet can be at night stand of the dijkgraaf)\todo{wat is dijkgraaf}  
better decisions about placing/reinforcing a levee or creating evacuation plans. Moreover, if this system is more accessible, civilians of a certain area that is threatened by water, have the ability to gain knowledge of where the water will go first. They then are able to take the the right crucial decisions, based on this knowledge in the hour of need. To solve the problem of accessibility a solution has to be found.

Tablets are devices that support the same multi-touch gestures and are more accessible than the multi-touch table. That's why the aim of this thesis will be an implementation of the Flood Simulation Browser on such a device. In particular iPad\cite{ipad} and Android\cite{android} tablets. Users can take use of this application in an intuitive way, to get more intelligence about the complex situation at hand. They have the ability to choose from several simulations that were already made for a specific area and also new simulations. In order to reach more accessibility, a deployment for both iPad and Android is preferred. The search for such a solution is second part of this thesis.

A third objective of this study is testing the scalability of the server. By testing how much requests the server can handle at once it helps the urban flood project to estimate how many users can use the application simultaneously. The original multi touch application on the multi touch table was only one client for the server. It's important to know that an early warning system stays online under the heavy load of a multitude of clients.

This thesis covers the design choices that where made in order to reach those goal. 
The first step is to get an idea of the existing simulation system this application will make use of This includes a description of where this application is situated in the Urban Flood Project as a whole. The study also includes an examination of the capabilities of the different devices available, as well as a requirement analysis specifically for this application. The resulting app will extend the simulation with a use-ability and above all mobility factor. Of course, performance is one of the main issues here. 

This concludes the following research questions.

\begin{itemize}
\item Is it possible to implement the Flood Simulation Browser on tablet in a useful and intuitive way?
\item Can this be done crossplatform?
\item Is the current server of the API adequate to serve a large number of clients
\end{itemize}

The first part of this document will describe the global information needed to answer the research questions. The second part describes the implementation, considering the findings of the first part.

\part{Discovering the subject}
\label{part:Discovering}
\section{Flood Simulation System}
Two systems are involved in creating the backbone and resource for the Flood Simulation Browser(F.S.B). One part is the system where the client application directly communicates to and where the API is stalled, specifically at \url{sangkil.science.uva.nl}. The API is used by the client applications to get the appropriate data. The other is used by API to create new simulations when a request at client side is made. The system at \texttt{sangkil} makes use of the "Common Information Space"(CIS)\cite{CIS}. This communication system is never used directly by the end user. New simulations are started via this communcation system, which is also more widely used in the Early Warning System to share information between different systems, e.g. monitoring data of the dikes and the alarm(Attention Level Manager). The systems are needed for retrieving data about a simulation and ultimately to display the simulations. The F.S.B. is a GUI that can display the simulations on a map. The simulations itself were made by the HR Wallingford's\cite{wallingford} simulation software and generated in the cloud\cite{cloud}. The simulations can then be retrieved from \url{sangkil.science.uva.nl}. 

The simulation programs of HR Wallingsford runs in the cloud. The cloud services are running on virtual Windows machines that can start the simulation if the right parameters are provided. For instance, the location and how much water the user wants to generate. The flood simulation system performs a complex simulation. In the Netherlands the AHN(Actueel Hoogtebestand Nederland) \cite{AHN} data is used to do such a simulation. The AHN is a height map that holds detailed information about the height of an area. With this data the flow of the water can be calculated and turned in to images. These images are used by the client's application, this an important part the F.S.B. With calls(GET or POST) to the API at \url{sangkil}, it returns a set of simulations that are present on the machine. The important thing to note is that the final simulations are images. These images are ready to be displayed on a map, e.g. Google Maps. 
Not only does the system have the capability to calculate the flow of water, but it can also calculate the estimated route that people take when a flooding takes place. It can calculate how much people would survive a simulated flood, keeping in mind that this project is all about saving people, this is interesting information.
 
\section{Flood Simulation App}
\subsection{Platform considerations}
\subsubsection{Phonegap}
As stated in the introduction the application is meant for tablets, but not specifically for iOS or Android. Which means cross-platform. How to maintain the cross-platform demand on the application is one of the subjects of this project. This means that the application is not a native implementation and consists of one code-base and runs on more devices. There is a tool called PhoneGap \cite{PhoneGap} that uses HTML5\cite{HTML5}, CSS3\cite{C3} and Javascript to build the app. In essence the developer builds a mobile website and PhoneGap can wrap this in an application. The native web-engine is used to render the mobile website. PhoneGap can result in a huge speed-up in development time, which is a huge advantage. The speed up can be obtained by the fact that previously gained skills of webdevelopment can be re-used. Therefore there is no need to learn a new programming language or sdk\cite{SDK} for native apps. For example Objective C for iOS and Java for Android. The disadvantage can be that the application feels more like a mobile website than a real app. In addition, the end product depends on the support of today's web-standards. Not all browsers have full support for HTML5 and CSS3, which forms the bases of a successful implementation of the application. For a list of supported elements, websites like caniuse.com \cite{CSS3} can be used to determine the percentage of support for a certain element/feature. But that does not really help. Nevertheless, the lack of the native feel oan application can be remedied. For example, frameworks where native-like elements are created for you while coding in a programming language already known by a webdeveloper also exist.

\subsubsection*{Titanium}
This solution is Titanium Mobile, the Appcelerator \cite{Titanium-Appcelerator}. Titanium Mobile can build mobile applications that are in fact native applications. By programming in Javascript and call functions to create native elements the application can be created. The framework builds semi-native code, unlike the previously discussed PhoneGap. The development for this platform is fast and an application for both iOS and Android are quickly off the ground. But there is also a disadvantage to using Titanium. The applications are big, around 11MB no matter what. Because of the fact that the logic will still be in javascript(compiled), Titanium has to ship their javascript engine to the device. But not only do Titanium generated apps take a lot of space, it also has trouble with memory. This is partly from own experience. The application is sometimes killed for no apparent reason. With a little research on the web, I found that I was not the only one facing this problem, see this blog-post\cite{memoryleak}. The blog-post discusses this issue, both developers and users discuss this issue in the reactions. Although this blog post refers to version 1.6 and 2.0 is already out, we consider the uncertainty about this behaviour of Titanium too great of a risk for the present project.

Developing and testing on iOS provides expected behaviour and a large part of native elements are supported. But for Android the native elements are mostly \textbf{not} the elements you thought they would look like. To reach cross-platform apps, the developer needs to constantly keep track if they're building an element for iOS or for Android. It might be stated that the functionalities of different platforms are not evenly supported. iOS is by far the most supported platform. This only provides an advantage if the project only meant to run on iOS. The idea of Titanium Mobile is great, it works fine but will delay developing time when you truly want to reach crossplatform. Also the fact that this application needs a map that supports overlays for the simulation images is a big disadvantage. By searching trough the documentation \footnote{\url{http://docs.appcelerator.com/titanium/2.1/index.html\#!/api/Titanium.Map}}, the only thing it supports is adding an annotation. An annotation is just a marker placed on the map with the ability to get de latitude and longitude of the marker. To sum up, Titanium lacks support for both platform and map object, at the same time it can surprise the developer in an unpleasant way by taking a lot storage and a buggy garbage collection.

Building crossplatform and creating native elements could mean a risk for completing the application. A browser is the only thing that has the most equality on both devices, i.e. both Android's and iOS's native browsers are based on the webkit engine\cite{webkit}. Webkit is an open source web engine that is used by both Safari and Chrome.

\subsubsection*{Javascipt frameworks}
As already explained, PhoneGap creates an app out of a website. This website can be built in any way the developer likes, using web technologies supported on the native device. There are frameworks that can speed up the development to make an intuitive application. Two frameworks that are considered are: jQuery Mobile \cite{jQuery-Mobile} and  Sencha Touch 2\cite{sencha}. 
\begin{description}
\item [jQuery Mobile]
This Javascript framework is build out of one Javascript file and one CSS file that the developer includes. By giving certain HTML elements a data attribute, which is a HTML5 element, the framework uses this to create views. A page is made by declaring a div adding \texttt{data-role="page"}. Such a page can be given a footer like div \texttt{data-role="footer"}. 
Switching frame one page to the other can be as simple as giving a html anchor's \texttt{href} to an \texttt{id} of another page. Listing \ref{fig:jquery} provides an example that will result in two pages, this is to illustrate the easy use of this frame work. Both pages have a button. Both buttons link to the other page (foo, bar), so tapping on one button will change the page to the other page. jQuery Mobile catches the requests that is made when a user taps on a button. It then uses Ajax to handle the request and push the new page in the view. 

\begin{lstlisting}[caption={jQuery Mobile, pages example}, label={lst:jquery}]
<div data-role="page" id='bar'>
	<a #href='foo' data-role="button">switch to foo</a>
</div>
<div data-role='page' id='foo'>
	<a #href='bar' data-role="button">switch to bar</a>
</div>
\end{lstlisting}

Creating two pages is quickly done, the downside of jQuery mobile is that in order to create an application where views look alike, you have to repeat yourself. You have to create pages with other id's and with the same look/elements but with different information. The conclusion for jQuery mobile is that it is easy and the developer does indeed use HTML5, CSS3 to create views.  But it is not easy to built a modular application. It is always possible to create such a modular application yourself, but when creating an application which is not such a framework the developer will run in to creating a framework in stead of the intended application.

\item [Sencha Touch 2]
Sencha touch 2 is a framework that is based on the Model View Controller design pattern \cite{MVC}. It encourages the developer to use this pattern. The way of developing really differs from jQuery mobile. Where jQuery mobile sets you free to do whatever you like, Sencha Touch constraints the developer using components that are available in Sencha Touch. The difference can be easily explained with an example.

In the items array, see Listing \ref{lst:sencha}, the items in that array can be anything supported by Sencha Touch like lists, a tabview, a map, etcetera. The difference between jQuery and Sencha Touch is clearly noticable in the listings \ref{lst:jquery} and \ref{lst:sencha}.

A real convenience of the Sencha Touch 2 framework, provides a command-line tool to build a starting environment. It creates files where the developer can start from. It is recommended to use this as a starting point. The advantage is an application that is structured out of the box with a design pattern that is a well known standard for these kind of applications(MVC). 

Also, with Sencha Touch 2 there is no need for PhoneGap. Sencha Touch 2 provides the functionality to run the code on your simulator or native device with the command line tool of sencha. Testing for Android and iOS became much more simple, resulting in less developing time. Running PhoneGap for Android, needs Eclipse\cite{eclipse} to build, for iOS the developer needs to build in Xcode\cite{xcode}. When testing on both devices the developer needs to be able to test in both environments, and testing from the command-line is a lot easier than running both environments. 
 
A disadvantage of Sencha Touch could be, as seen in listing \ref{lst:sencha}, the syntax of Sencha Touch is not so easy at first. So the learning curve could be very steep.
The last argument that has a great influence on deciding which framework to use, could be that Sencha Touch provides an add-on that has the capability to create multi-touch charts. The original implementation of the urban flood browser on the multi-touch table has this feature. It would be a great extension of the project if this was possible. So with an eye on the future it could save a lot trouble, and it could add up to a more intuitive design.

\vspace{1cm}
\begin{lstlisting}[caption=Sencha Touch application example. This example creates an application with the name 'foo'.  The html can be placed inside the items array, label={lst:sencha}]

Ext.application({
    name: 'foo',
    launch: function() {
        Ext.create("Ext.tab.Panel", {
            fullscreen: true,
            items: [
                {
                    title: 'bar',
                    iconCls: 'bar',
                    html: 'bar'
                }
            ]
        });
    }
});
\end{lstlisting}
\end{description}

\subsubsection{Overview frameworks}
The following table is an overview of the previously discussed properties of tools; Titanium, jQuery Mobile in combination with Phonegap and Sencha Touch. \\

+ is positive, - is negative, -- strong negative, ++ strongly positive \\
\begin{tabular}{|c|c|c|c|c|c|c|c|}
\hline 
   & cross & learn. curve & modular & docs & supported comp. & perform. & dev time \\ 
\hline 
Titanium & - & - & - & - & -- & - & + \\ 
\hline 
jQuery Mobile & + & -- & -- & + & - & - & ++ \\
\hline 
Sencha Touch 2 & + & - & + & + & + & - & + \\ 
\hline 

\end{tabular} 

Sencha Touch 2 has the most positive signs based on the previous sections. Therefore the platform Sencha Touch is selected as the tool to implement the F.S.B.

\subsection{Requirements Analysis}
\label{sec:requirements}
Requirement analysis for this project exists out of an inventory of tasks that the application has to be able to perform. For example, displaying a list or controls or a graph. The application needs components for interaction and displaying of data. The components are described in the following. 
\begin{description}
\item \textbf{List}
First, the users need to be able to see different simulations and be able to distinguish where certain simulations are located. The locations are mostly named by cities. The corresponding simulations have to be retrieved from the server and displayed in a list. Those list-items are the individual simulations, so it makes sense that when tapping on a list item, the simulation of the related item is going to be displayed. 
\item \textbf{Map}
The form of these simulations are important. The simulations are in the form of images. These images are images from above and can be placed on the map. In order to display these images, there has to be a map available. This is the most important object of the application and has to be prominent place in the view.
\item \textbf{Controls}
As stated before, the flood simulations are in the form of multiple images that are placed on the map. A requirement for these simulation images is that the user can control which image it wants to see in a chronological way, To do this, the user would need controls. These controls need to be appear in the viewport when the user has tapped on a list item of a simulation.
\item \textbf{Chart}
The flood simulations contain information about how much water is present in a certain timestep in a specific location. This information needs to be displayed in such a way that it can be interpreted by the user. This requires a chart with the timesteps on the x-axis and another value like volume on the y-axis. To determine the zone which contains the information, latitude and longitude information is needed again.
\item \textbf{Simulation's Switcher} 
Next to flood simulation, also population dynamics simulations are available. Therefore controls are needed to change the simulation type. These simulations also have a location and time steps, so the same map can be used to display these simulations.

\end{description}
These requirements are taken in to account in the applications design. The next section will cover design choices in the App's design.
\subsection{App Design} 
\label{sec:appdesign}
The application will be used on tablets so that a lot of space can be used. On tablets the screen is larger than on mobile phones. Which can result in a bigger travel distance of the user's hands. The GUI design has to be built with the considerations of the interaction capability of the users. For instance, unlike with mobile phones, according to Clark(2012) a leading designer in creating multi-touch applications, people tend to hold a tablet on the top halve of the tablet when holding with both hands, Figure \ref{fig:perimeter}. The focus of the user is going from top to bottom. The top elements of the application will draw the first attention of the user. That's why Clark(2012) advises to place the important controls on the top half of the view. The components that are important have to be placed in the left or right top, concerning the perimeter of the thumbs, Figure \ref{fig:perimeter}. The F.S.B.'s design heeds Clark's advice.
\begin{figure}[H]
\center
\includegraphics[scale=0.3]{touch.png}
\caption{Portrait touch perimeter(Clark, 2012)}
\label{fig:perimeter}
\end{figure}
First of all the flood simulations are done within different cities. This can typically be a list of cities. The list is scrollable and can be seen as an "infinite" array of cities around the world. Every city has its own array of simulations to show. It therefore makes sense to also show these in a list. When a city is selected, the user has no use of the capability to select other cities and its simulations. That's why the list of cities are pushed out of the viewport and the list of simulations is pushed in. 
It also makes sense to have one Map object in the view, where one city (latitude, longitude) can be shown at a time. The map object is the most important component of the F.S.B. and therefore takes the biggest space. It also makes it easier to pan and zoom the map.
The list component where cities and simulations are placed is at the left side of the view. It could also be the right side but it would not matter. Since two hands are more or less symmetrical, so placing the list object left or right would not be a problem. It does matter concerning controls. Controls to change the timestep of a simulation are definitely needed. A simulation consists of multiple images on different time steps. By giving the user control of which image is seen at which time step is a crucial feature in the browser. Since the list is placed in on the left side of the screen, the controls appear in the right top part of the screen. That way the perimeter of the movement of the thumbs are taken in to account.
\begin{figure}[H]
\center
\includegraphics[scale=0.3]{ui/citieslistsme.png}
\caption{Cities list out of final application}
\label{citieslist}
\end{figure}

\begin{figure}
\center
\includegraphics[scale=0.3]{ui/simselected_full.png}
\caption{When Amsterdam is selected, the map moves the center of the map to Amsterdam. In this screenshot, a simulation is also selected}
\label{simullist}
\end{figure}

The F.S.B. that is already built for the multi-touch table has the ability to submit new simulations to be simulated in the cloud. The spot of the simulation can be arbitrary on the map, by simply touching a place on the map and alter some parameters, the cloud service calculates a new simulation. Although this feature can be an seen as an extension of my project, with time left this feature can be build in. That's why it can be discussed in the App's design. The controls of these parameters need to be somewhere in view, by placing this in the neighbourhood where the user touches the map could be intuitive. However, this should never happen when the user is just navigating over the map, the user has to know that if he or she is the mode of with picking a place where to create a new simulation. 

Furthermore, it's an important feature to display data of a simulation in certain area. The API provides this data. It holds information about how much water flows in that area over time. This data is the volume of water per time step. The API requests latitude, longitude values, it then returns data of a location that is closest to this point. When a user taps on the map a marker is put down to annotate the just selected area, next the chart appears with the just selected data. Charts are great way to display this data. See Figure \label{fig:senchachart} for the final implementation.

\begin{figure}[H]
\center
	\includegraphics[scale=0.3]{ui/chart.png} \\
\caption{Chart functionality in final application}
\label{fig:senchachart}
\end{figure}

\subsection{Scalability}
\label{sec:scalability}
The second assignment of this thesis is to test the scalability of the server. The server address is \url{sangkil.science.uva.nl}. To test this server it is required to exclude any other parameter of the client. That way, the maximum values of the server are tested and not the limitations of the client. To get these values, the server \url{mangkus.science.uva.nl}, that is located in the same network as \url{sangkil.science.uva.nl}, is used for testing. The servers have the exact same specifications, so this is ideal for testing the maximum values of sangkil.science.uva.nl. Again, this is not a realistic test but it is meant to find the maximum values.
For stress testing the server a tool called siege \cite{Siege} is used. With this tool it is possible to launch requests to a url with $n$-nodes and $k$-connections executed per second. Siege registers the following data:
\begin{itemize}
\item Transactions - total hits
\item Availability - percentage of total succeeded hits
\item Elapsed Time - seconds
\item Data Transferred - MB
\item Response Time - seconds
\item Transaction Rate - $\frac{Transactions}{Elapsed Time}$
\item Throughput - MB/s
\item Concurrency - rate of concurrency
\item Succesful transaction - number of succeeded hits
\item Failed transactions - number of failed hits
\item Longest transaction - seconds
\item Shortest transaction - seconds
\end{itemize}
With this data new insight can be provided. By increasing the number of simultaneous connections, values could start to change. To really give the server a stress test, it is possible to provide a list of urls which can randomly be picked and executed. This simulates a more likely scenario and provides more insight on how the server would behave in a real situation. The expectation is that the response time might grow as the number of clients starts to grow. With more clients to serve, it could take longer if there are more clients active. If processor power is limited, maximum available memory is reached or even the implementation of the server for handling requests could all have an effect in the response time, or any other variable. The research for which variables changes, together with the cause and the solution is a part of this project and will be documented in the end report. 


%\section{Conclusion}
%The project will be implemented with the framework Sencha Touch 2. All encountered issues will be discussed in the end report. This %nformation can be used in future projects relating to creating cross-platform applications. Also all data about the scalability of the erver %will be documented. The urban flood project can in turn use this data in future plans to invest in more server power. If they do not need %to invest in more power this is also important.
%This project will ultimately result in a cross-platform application that can be used by the public or government to gain information %about a certain area.

\section*{End of Part one}
Part \ref{part:Discovering} describes the questions and some answers on what the approach of tackling this problem is going to be. For an understanding of what global problems are faced in this project, it will be sufficient to have read part one. Part \ref{part:implementation} holds information about how the implementation is made, the problems that where discovered in process, results are displayed and discussed and ultimately ending with the conclusion of this project. Note that filenames are addressed in this part. The code can be found on github, \url{git@github.com:icyrizard/FloodSimulation-Browser.git}

\part{Implementation Details}
\label{part:implementation}
\section{Server API}
A clear understanding of which requests have to be done in order to gain the right information, is needed before beginning with any implementation. The full api is referenced in the appendix A, B and C. The appendix is referenced and used for explanations in the following sections.

\section{Sencha Touch 2}
The final choice for the development of this application was made in favor of Sencha Touch 2.  Sencha Touch provides cross-platform capability and is based on web technology. Although Sencha Touch comes with a unique syntax, based on Ext, the content, look and logic is based on web languages.
Part \ref{part:Discovering} section \ref{sec:appdesign} the design of a touch application is discussed. The application is going to be created with the findings described in that section. 
%The requirements of the application discussed in section \ref{sec:requirements} are created in 

Sencha Touch is based on MVC with the addition of stores. Stores can hold information of whatever the application needs, more about this in a moment. The model is used for the communication with the database, the controller stands between the model and the view. The controller can steer between views and handle logic. The application has no direct need of models, since there is no database that has to be updated. Stores can handle enough communication between the server and the application. 

\subsection{Stores and Lists}
\label{sec:storelist}
The stores in this application are used for filling the lists. In particular the cities list en \texttt{simulationslist}. A list object is defined as follows.

\begin{figure}[H]
\begin{lstlisting}
store = Ext.create('Ext.data.Store'{
    fields: ['name', 'corners', 'visbounds', 'area_id', 'center', 'size'],
	proxy: {
			type: 'rest',
			url: 'http://sangkil.science.uva.nl:8003/area/list.json',
			reader: {
				type: 'json',
				rootProperty: 'areas'
			},
		}
});
Ext.create('Ext.List', {
	title: 'locations',
	store: 'citystore',
	itemTpl: '<div>{name}</div>',
});
\end{lstlisting}
\caption{List of cities}
\label{fig:sencha}
\end{figure}
The store is automatically updated when the values change on the server. When something changes in the store, the list is also automatically updated. The specified fields are available in the list, containing the name of the field between brackets \texttt{\{ \}}, the field name of record $n$ is placed in list item $n$. Five stores are present in the application. \texttt{SimulationStore.js}, \texttt{SimulationDetailStore.js}, \texttt{LsmStore.js}, \texttt{SimulationsSummary.js}, \texttt{ChartStore.js}. 
\begin{itemize}
\item SimulationStore.js \\
\texttt{fields: ['name', 'corners', 'visbounds', 'area\_id', 'center']} \\
Is in sync with \url{http://sangkil.science.uva.nl:8003/area/list.json} on the server. Locally the store is in sync with the view \texttt{List.js}. Basically this store returns information of the simulation locations that are available. The most important data are the name, center, visbounds and area\_id. With the name for displaying in the list-item; the center for changing the map's center to the location of the simulation and the visbounds are used for the image overlay. The visbounds are used to scale the image on the tiled map, it contains the lat,lng information of the south west and north east locations of the square. When the user taps on a list-item, the data of longitude and latitude information is used to change the center of the map and push a new list over the current list, since a tap event on a list-item returns the tapped item and the store used for creating this list. The second list holds information about which all the simulations available.
\item FloodDetailStore.js \\
\texttt{Fields: ['name', 'center', 'corners', 'size', 'extents', \\
'visbounds', 'vissize', 'projection', 'dikes']} \\
Is in sync with multiple urls, \url{http://sangkil.science.uva.nl:8003/area/<area\_id>/info.json}, where the area is the area that is selected in List.js. This store adds information of dikes. The rest of the data is already present in the SimulationStore.js. The dikes consists of eight values, which are 4 corners with a latitude and longitude value. This means that a polygon can be formed from these four locations and displayed on the map.
\item LsmDetailStore.js \\
\texttt{Fields: ['area\_id', 'test\_id', 'submitted']} \\
This store holds information of the population dynamics, meaning how the evacuation of the individuals will proceed. 
\item SimulationSummary.js \\
\texttt{Fields :['area\_id', 'test\_id', 'submitted']},\\
Syncs with \url{http://sangkil.science.uva.nl:8003/drfsm/list.json?summary}. This returns a JSON string that holds a list of all the simulations. A store can be filtered on a certain value. All the simulations have an area\_id specified. The store is filtered on the area\_id selected in List.js. Note that filters stay present, so before doing anything the store has to be cleared of all the filters.
\item ChartStore.js \\
\texttt{Fields: ['time', 'volume']}\\
This store is used for creating the chart. The chart expects a jsonStore with data and fields to plot. The data is retrieved from the server at run time of the application in \texttt{Api.js} and set in the store by the setData function.
\end{itemize}

\begin{figure}[H]
\center
\includegraphics[scale=0.5]{ui/citieslist.png}
\caption{A list of cities in the final application}
\end{figure}


\subsection{Layouts and xtype}
Layouts in Sencha Touch provide a structure for placing components and are fairly easy to create. A layout keyword is placed in the Container component which functions as a container for other components. That way the developer can build a hierarchical view. Child components are placed in the items key array. These can be any component the developer likes. A layout in this application is used once in \url{app/view/main.js}. 

\begin{figure}[H]
\center
\includegraphics[scale=1]{ui/docktop.png}
\caption{layout with hbox}
\label{fig:layout}
\end{figure}

Next to the type layout hbox also vbox exists, which divides the viewport vertically.  The xtype keyword tells Sencha Touch which component to place in the container. Flex 1 or flex 2 tells the container on which side of the container the components needs to situated. See \ref{fig:layout_impl} for how these are used to as a reference. The image of figure \ref{fig:layout} is implemented in figure \ref{fig:layout_impl}.

\begin{figure}[H]
\begin{lstlisting}
Ext.define("app.view.Main", {
    extend: 'Ext.Container',
    config: {
        title: "Simulation Browser",
        layout: "hbox",
        fullscreen: true,
        items: [
        {
            xtype: 'listpanel',
            flex: 1,
        },
        {    
            xtype: 'simulationpanel',
            flex: 2
        }],
    }
});
\end{lstlisting}
\caption{Layout in \texttt{app/view/Main.js}}
\label{fig:layout_impl}
\end{figure}
The xtype keyword matches the keyword out of the component where the xtype is defined. It serves as shortcut to the full component. Components that are created can get a unique xtype value and be referred to by other components to call functions or for displaying  of that component, this is widely used throughout the application.
 

\subsection{Controllers}
Controllers perform the logic in the application. They react on events, fired by the elements in the view. In Sencha Touch the events are configured in the control configuration. References to components in the view are created in the ref attribute in the config attribute. A reference may consist of a css selector or an xtype name, or both. References are used in the functions below the config field, \texttt{this.getMap()}. Controllers are declared like the following.
\begin{lstlisting}
Ext.define('app.controller.Main', {
	extend: 'Ext.app.Controller',
	config: {
		refs: {  
			map : Map      
		}
		
		control:{
			#button: {
				tap: tappedButton
			}
		}        
   }   
	tappedButton: function(){
		this.getMap().dofunction();
	}
});
\end{lstlisting}
In the application two controllers exists, a \texttt{app/controller/main.js} controller for handling logic for the general view and simulations. Another controller named \\
\texttt{app/controller/chartController.js} is used for dealing with the chart information. Both make use of loading stores, getting a component to be pushed in to the view when the right event is passed. And when the view needs more data than stores can get, the controllers make use of the \texttt{app/Api.js}. 

\subsection{Map}
The map object in Sencha Touch 2 is created by creating a view and extending Ext.map. Since Sencha Touch 2 became available Google Maps is a build-in type. Because of the way the map is really an instance of the google maps api. I decided to let the Map view extend that api, and let the controller call those functions just like it would when it talks to the google maps api. This choice is made not only done for convenience but the ability to create multiple controllers to talk to the same map would be a bigger advantage than placing this in a separate controller. Also by initiating a map that is based on another tiled map object like open street view that uses the same function names. A quick change between different maps could be established. 

A map object is declared like the following.
\begin{lstlisting}{Ext.Map},label={lst:Map}]
Ext.define('app.view.Map', {
	extend: "Ext.Map",
		id: 'mapa',
		xtype: 'SimulationMap',
	config: {
		useLoadMask : true,
		mapOptions : 
		}
	},
	
	func: function(){
	}
});	
\end{lstlisting}
In the application the Map object extends and uses the Google API. Overlays are used for placing simulations images on the map. When the maprender event is fired, it returns a reference to the Google API and Ext Map component. The Google Maps API specified in the documentation is used for creating overlays and adding markers on a certain Lat, Lng. The most important feature is initializing the first image by calling \texttt{createOverlayImage} function when a simulation is tapped in the list and creating overlays for the rest of the timesteps. These images are stepped through in the nextImage and prevImage function. Which are controlled when a button in the control panel is tapped.

\subsection{Controls}
The controls to change the simulation step when a simulation is selected, appears in the right top of the screen. The component has four controls; forward, backwards, play forward, play backwards. Because off the fact that the controls take space of the map, the background of the controls is transparent for creating the feeling of more space.
\begin{figure}[H]
\center
\includegraphics[scale=0.7]{ui/controls.png}
\caption{Controls}
\label{fig:controls}
\end{figure}
By tapping on the upper button, the next image is placed on the map. The right button plays through the simulation automatically. The left and bottom button both do the opposite. Also a pause button stops calling the next or prevImage function out the map object. As previously discussed, the controls appear in the right top of the screen. If the user needs the controls on the bottom part of the screen, the user can also tap and drag the controls. Because the space of the tablet is limited the user can make the decision of placing the controls somewhere else, note that the controls are constrained to the right side of the screen. The reason is that the controls are meant to be used by the user's right hand.
 
\subsection{Chart Display}
The chart data is displayed when the user taps on a simulation image on the map. The google maps API supports the click event, the event has a payload where the latitude and longitude data can be obtained. A marker is put down at that location and the API (at \texttt{sangkil}) is called to retrieve the izid of the tapped lat,lng. When the izid is known, a second request has to be done to obtain the corresponding .csv file. See listing \ref{lst:csvrequest} for the requests.

\begin{lstlisting}[caption={requests for flood data}, label={lst:csvrequests}]
/* obtain izid */
http://sangkil.science.uva.nl:8003/area/<area_id>/izid.json?latlng=
<lat>,<lng> 
/* obtain csv file */
http://sangkil.science.uva.nl:8003/drfsm/<test_id>/results/izid/<izid>.csv 
\end{lstlisting}
 
A response looks like the following.
\begin{lstlisting}[caption={csv response}, label={lst:csvresponse}]
time,izid,volume,level,dischargex,dischargey
600,5022,838.082,-4.841897,0.0,0.0
900,5022,852.3604,-4.835319,356.0,0.001675895
...
\end{lstlisting}
The first value is the time step of the simulation, the third is the volume. The chart will display the volume (in cubic meters) on the y-axis and the time steps on the x-axis. By simply splitting on a "," and placing the value at position 0 and position 2 of every line except line 0, in a separate array and feed in to \texttt{ChartStore.js}, as discribed in section \ref{sec:storelist}, and plot the data.

The plot is made with Sencha Chart. The chart has to be rendered to a certain container. In application this is a Ext.Panel, that supports the showBy() function. Which means that the panel with the chart can be placed in the view at a certain position. In the items array, xytpe: 'chart' is placed, Sencha now knows what kind of component to place inside the Ext.Panel. The chart itself has a couple of fields that are necessary in order to plot the data. First of all the name of the jsonStore,


\begin{lstlisting}[caption=Chart component app/view/Chart.js, label="chartcomponent" ]
Ext.define('app.view.Chart', {
	extend: 'Ext.Panel',
    id: 'flood-chart',
	xtype: 'floodChart',
    requires: ['Ext.data.Store'],
    config: [{
    	items: [{
			xtype: 'chart',
			store: 'chartStore',
			axes: [
				{
					type: 'Numeric',
					position: 'left',
					fields: ['volume']
				},
				{
					type: 'Category',
					position: 'bottom',
					fields: ['Time Steps']
				}			
			]
			series: [{
				 type: 'line',
                xField: ['time'],
                yField: ['volume'],
            }],
    	}]
    }]
}):
\end{lstlisting}

The \emph{series} attribute in the Chart configuration means what kind of plots are going to displayed. So it is possible to create more series and display different types of data in the chart. Also because the chart can be fairly large, this component is also made draggable for the user to create more space.

\begin{figure}[H]
\center
\includegraphics[scale=0.5]{ui/chart_full.png}
\caption{The chart in the final application}
\end{figure}

\section{Scalability}
The server \url{sangkil.science.uva.nl} is tested on scalability. The server specifications are two Intel(R) Xeon(R) CPU E5620  @ 2.40GHz processors, with both 4 cores and 8 threats and 23GiB of memory. An important part to notice when testing a server is how well it performs depending on the number of peers it is serving. By looking at how the response time will change if the number of clients increases, can tell how the rate of scalability. The number of clients a server can serve simultaneously is of course the number 1 issue in scalability. So how do the values change when connections, and therefore client numbers, start to rise.

To test the server, all bottlenecks at client side have to be brought down to a minimum. \url{mangkus.science.uva.nl} is the address of another server with the same specifications. The \texttt{mangkus} server is situated in the same server rack as \texttt{sangkil}, and has the exact same specifications. The TCP/IP packages do not have to travel around the world in order to reach the destination, so the response time when not in a stress test could be in optimum state. 

\subsection{Testing}
So testing the sangkil server is done from the server mangkus. A tool siege is used for testing the server, previously discussed in section \ref{sec:scalability} in part one.
\begin{lstlisting}
$ siege -i -b -f file.txt -c $1 -r $2
-i		randomly picking request out of file.txt
-b		no delay between the next request a client does
-c		concurrent processes
-r		number of repetitions
\end{lstlisting}

Testing is done by changing the concurrent processes and keeping the repetitions the same, and testing that for different repetitions.  That way a little grid search can be preformed to find a weakness in the server. The results of this search are discussed in the following sections. Note that a maximum of 500 clients could be tested by Siege, anything above that would result in a failure at server \texttt{mangkus}. 

\subsection{Results and Analysis}
In the first series of tests the repetitions number is the same and the amount of concurrent clients is changed. The amount of concurrency is displayed on the x-axis. Note that it could be that a concurrent value that is tested is not been reached by the server. Concurrency means the amount of clients averagely served by the server for testing at a certain concurrent number. So 500 clients with 10 repetitions could mean that the server does not reach a concurrent level of 500 clients. The reason is that the requests happens so fast that their is no point in time the server handles the full amount of clients that are requesting data.
\begin{figure}[H]
\center
\includegraphics[scale=0.6]{server/siege_10r.png}
\caption{10 repetitions, concurrency 10, 50, 100, 200, 300, 400, 500}
\label{fig:10r}
\end{figure}
See top left graph of figure \ref{fig:10r}. These results suggests that with 10 repetitions and a rising number of concurrent clients the response time increases some what linearly.  100 more clients can be roughly the same as an increase of response time of 0.1/0.2 seconds. 

The throughput, top right graph, rises when the number of clients rises. This is a good sign when talking about scalability. When the throughput rises when client numbers are rising it means that it can transfer more data when more clients are requesting data. 

The transfer rate(left bottom graph) is the average number of requests that are handled per second. This rate does increase when more clients are requesting url's but it stops at 350.

The availability (right bottom graph) drops when concurrency increases. But it does not drop much. That is a positive and negative finding. When the amount of users starts to rise the availability needs to be 100\%. A drop of 0.4\% means that roughly 20 requests ($5000 * 0.004$) out of the 5000 requests in total, would not be answered. The fact that it has a denial of service is worrying, but 0.4\% is not drastic.	

\vspace{0.5cm}
\begin{figure}[H]
\center
\includegraphics[scale=0.6]{server/siege_50r.png}
\caption{50 repetitions, concurrency 10, 50, 100, 200, 300, 400, 500}
\end{figure}
The same conclusion can be drawn concerning the response time. Notice that the linear increase is roughly the same, but the concurrent clients are now more than in the previous test.
The Throughput is higher than in the previous test. This means that the server's bandwidth sends more MB/s when more clients are requesting data. It would be interesting to see if this number would climb further.

The transfer rate rises more than with 10 repetitions. That means that there capable of dealing with more clients.

The availability is lower than with 10 repetitions, a drop of 0.6\% now means ($2500 * 0.08$) 200 requests that result in a failure. That is a higher than before.
\begin{figure}[H]
\center
\includegraphics[scale=0.6]{server/siege_100r.png}
\caption{100 repetitions, concurrency 10, 50, 100, 200, 300, 400, 500}
\end{figure}
The transfer rate rises more than with 10 repetitions. That means that there capable of dealing with more clients.
All the values stay roughly the same with as 50 repetitions. The walk of the availability graph looks the same as the one with 50 repetitions. But now ($50000 * 0.007$) 350 requests are not answered.

\begin{figure}[H]
\center
\includegraphics[scale=0.6]{server/siege_200r.png}
\caption{200 repetitions, concurrency 10, 50, 100, 200, 300, 400, 500}
\end{figure}

It does not seem to matter how much repetitions are preformed by a certain number of concurrent clients. This suggests that the only weak spot of the server concerning the response time depends on how much clients at a time are demanding a request. It looks like it does not matter how much repetitions those clients preform, it has no influence on the response time. The throughput does rise when the amount of repetitions go up, but stops rising at around 440 connections. 
These results also suggest that a turning point at between 200 and 300 concurrent clients exists, and the availability starts to drop. How much this would be when the amount of clients are doubled, is not clear at this moment. What is more clear is that the response time at 400/500 clients sometimes goes over the 1 second. Because the response time grows linearly with the amount of clients, it suggests that when the amount of clients grow even larger, it will still climb linearly. That means the response time of a 1000 clients is around 2 seconds.
Considering that this an application that is only used for research, the number of clients would not be 500 that are requesting at the same time. Above all, an average response time of 0.1 second when a couple of clients are active is enough, when using the application without noticing any server delay.

\section{Deployment}
For installing the application to a device the sencha's command line tool is used. In the root folder \texttt{packager.json} can be found. In this file the field for building the application has to changed. See below, listing \ref{lst:packager}.
\begin{lstlisting}[caption={packager.json},label={lst:packager}]
	/**
	 * @cfg {String} platform
	 * @required
	 * This is the platform where you will be running your application.
	 * Available options are:
	 *  - iOSSimulator
	 *  - iOS
	 *  - Android
	 *  - AndroidEmulator
	"platform":"iOS",
\end{lstlisting}
Now by executing the command.
\label{appnative}
\begin{lstlisting}[caption={command to build native},label={lst:buildnative}]
$ sencha app build native
\end{lstlisting}
The application is packaged. All the javascript code's dependencies are resolved, minified and placed in the \texttt{build} folder. The \texttt{build} contains two folders. One \texttt{package} and one \texttt{native} folder. In the \texttt{package} folder the developer can see what result of the minification is, and can also test in the browser if everything still works. The native files are placed in the \texttt{native} folder. When executing for Android the applications extension will be a .apk,  for iOS it will be a .app file.  The file can be transferred to the device and installed. On Android it is easier that iOS. When building for Android the result of the command(listing \ref{lst:buildnative}) runs the application when done with packaging. When building for iOS, sencha creates a .app file that can be transferred to the device by Itunes\footnote{How to do this can be found in the video ``Getting started'' at: \url{http://docs.sencha.com/touch/2-0/\#!/guide/getting\_started}}.

The deployment can be distributed to other devices. On Android devices it's possible to install .apk files directly to the device from the command line. The generated .apk file can also be distributed to other Android devices and can be installed without the use of the command line tool of Sencha Touch.
For iOS this is more difficult. When a developer is in the possession of an Apple's developer account the UUID(Unique Identifier) needs to be added to the provisioning portal. This grants the device to install applications that are also registered by the developers account. If the application only needs to tested on iOS, it is possible to jailbreak the iPad without need an Apple's developer account. How to jailbreak the iPad to is desribed here \url{http://greenpois0n.com/}. For enabling to install without a developers account apps, ``Appsync'' has to be installed.\footnote{\url{http://www.ijailbreak.com/cydia/install-cracked-apps-ios-5-0-1-with-appsync-installous/}}

\subsection{Get the app}
The .apk and .ipa are located on github in the \texttt{www/build/native} folder. \\
\begin{lstlisting}
$ git clone git@github.com:icyrizard/FloodSimulation-Browser.git
\end{lstlisting}
Also the .apk and .ipa can be build from the code in the \texttt{www} folder. \\


\section{Does Sencha Touch suffice}
\label{sec:suffice}
Sencha Touch 2 is used in this project for the cross-platform capabilities. One of the research question was to find the best tool to meet the requirement of cross-platform. Let's start with the fact that everything works both on a Asus tf300t Transformer Pad with Android 4.0.3, iPad 2 with iOS 5.1.1 and the browsers Safari and Chrome. In Safari and Chrome the application runs smooth, all the animations and tap and drag are fast. The frame-rate of the animation stay the same high frame rate. Also on the iPad 2, everything is smooth and fast and no problems occurred. Unfortunately the application on the Asus tf300t runs very slow. Scrolling through a list runs slow, changing from the cities list to the simulations list runs slow. Even the google maps object which is has nothing to do with the implementation of Sencha Touch 2 or the F.S.B implementation, runs slow. The frame rate of an animation is far less than on the iPad 2 and for navigating through the map the same difference in speed is big. 

An explanation for this can only be guessed. The first could be that the resolution of the Asus tf300t is higher than the iPad 2. 1280 * 800 resolution for the tf300t and a smaller 1024 * 768. That is a difference 1024000 - 786432 = 237568 pixels. 

Because of the fact that both webkit browsers have similarly Javascript engines, Nitro on iOS and V8 on Android, the only thing that could effect the performance so much, would suggest a difference in another part of the rendering process. iOS renders CSS animations via the GPU of the Phone. Although the new Android 4.0.3 supports hardware acceleration, it also has to be utilized by the browser. If it is the case and Android 4.0.3 does not use the GPU for animations and iOS does, it could explain the drastic difference in speed. 

\section{Conclusion}
This thesis has described the process and requirements to create the F.S.B for tablets. Almost all the problems have been tackled, the problems of the picking the best suitable tools. 1.The app's design; 2. The communication with the API;3. Selecting simulations and the ability to play through them; 4. Creating image overlays of the images delivered by the API; 5. Creating a chart of a certain area when the map is tapped and deploying it to both Android and iPad. That means that the application works on tablets, that have a native webkit browser.
Although the final performance of Sencha Touch 2 on Android could be considered as the biggest drawback of this project, the application does work on Android. If it is due to a difference in resolution of the screen or an implementation of the native Android browser, meaning the rendering of CSS animation via the GPU, the performance is a fact and cannot be denied. So it is possible to create a cross-platform application that exists out of one code and can be build to both Android and iPad. 

The server scalability did good for a server that exists out of one physical system. When the number of clients rise to 500, the average response time rises above 1 second, which is acceptable. Judging from the fact that the response time rises linearly with the amount of clients, if the amount of clients rises to 5000, the response time will be around 10 seconds. Which is not an acceptable response time. An important thing to note is that it did not seem to matter whether the clients fired 10, 50, 100 or 200 requests. The response time climbed the same way linearly. 
When talking about the availability, when the amount of clients rises above 200 clients, the requests start to fail. But the drop in availability is so small that would be hardly noticeable.

The last findings about an intuitive design can not be fully answered. Whether or not this application is intuitive, is not tested and is also difficult to test. In the apps design, the guide lines of Clark(2012) are taken in to account. The chances of the app is indeed intuitive is thereby enlarged, but proof of this fact is not available at this moment.

\section{Discussion}
In section \ref{sec:suffice} the issue ``if Sencha Touch suffices the cross-platform demand'' is discussed and the conclusion more or less was that it does the job wel but not animation/performance wise. More research has to be done to solve this animation issue to increase the use-ability of this application. It well could be that the Mobile Browsers are not all the same and do not fully support the today's standards of HTML5 and CSS3. At this moment a future project can be at best natively programmed if performance is an issue. Another possibility could be Kivy \cite{kivy} for android. Kivy makes it possible to use OpenGL \cite{opengl} and multitouch gestures and program at a higher level in Python\cite{python}. But in this case the performance of the application on Android does the job and the performance is just more a convenience than a necessity. 
There are also a couple of things that could be improved in the application itself. For example, when the list of the individual simulations is loaded, the image of the last simulation step is put in the image container of that list item. This is an image only of the water, and is less informative than a sceenshot with the exact location with the overlay image. This can be processed at server side and a screenshot of the simulation \textbf{with} the map then would be available as a callback by the API. If the google maps API would support a to take screenshot with the an overlay it would also be solved, but unfortunately this is not the case. Either way, if this is implemented in the application it would look a lot better. Also, the user can see where the simulation is done a lot faster, what than results in more intuitiveness. 

Another improvement of the application would be that the Lsm data(population dynamics) is seen together with the simulation. This is not possible at the moment, at client side and at servers side. Because of the fact that there is no way of telling which flood simulation corresponds to which lsm simulation. Nevertheless if this is possible, more knowledge about how a flood will influence the changes of survival in a certain area is valuable data. Also more information can be given via the chart. The current chart shows information about how much the cubic meters of water per time step flows in that area, it only shows one line at a time. It would be nice to select a multitude of places and see what the difference is between one area and another. This could be done by placing a marker for every tap event and by deleting a certain marker, that this removes that data from the chart. In Sencha Touch this is not so easy to do, because the Sencha API lacks in functionality to add and remove series on the fly. Therefore there was no time left to accomplish this. But it would be a big extension of the application. 
A last point about the application's shortcoming is already shortly discussed. The map object can be replaced by another map, for example OpenStreetMaps. This results in a complete Open implementation of the application.

The scalability test on \texttt{sangkil.science.uva.nl} is another point that can be improved. The test can be expanded if the concurrent processes are more than 500. The test was limited due to errors in the mangkus server, when the tool Siege had to create more than 500 concurrent clients. Nevertheless, it would be better to test the sangkil server with a lot more clients. At 500 processes the server begins to have issues with availability and response time. But what will happen when the number of clients raises to 5000? Would the server perform worse and worse, or will it perform be the same. The results of the tests suggests that the response time climbs linearly, the throughput has a limit of roughly 14MB/s, so transferring more and more data would not happen due to the bandwidth limit and the response time is estimated to grow more and more.

The application is now bound to the use of tablets, and can be locally executed by opening the \texttt{index.html} in the browser. This application could easily run on the server but some minor changes have to be made. Simply of the fact that browsers block a requests that is done on server A to a different server B, via Javascript. This is called cross domain scripting. Browsers block these to prevent cross side scripting to take place. A solution is, the JSONP\cite{jsonp} format. By simply telling the server to wrap a function name(that the developer desides) around the JSON package, and than calling that function, the problem is resolved.

The applications can now be used in the field. An Android or iPad can be taken to a location and can be used to see what the effects of a dyke breach can be. Although the simulations have to be done before hand, the user can take the tablet and go to the specific place. From there the user can visually see what the best route of escape is, in the contrary to using the multi-touch table. Where all simulations are seen in-doors and the plans are also made in-doors. This application is the first step towards a tool that can be used in the field, with more improvements on the application itself, it well could be a perfect tool to aid the decision makers and ultimately bring the Urban Flood project to a higher level.

