Sei sulla pagina 1di 55

IITB SUMMER INTERNSHIP 2016

XCOS ON WEB

Supervised By Dr. D.B. Phatak

MEMBERS: MENTORS:
Amit Kumar Yadav Mr. Adhitya Kamakshidasan
Chhavi Agarwal Ms. Inderpreet Arora
Jitesh Kumar Jha Mr. Srikant Patnaik
Kumar Saarang Singh
Nimish Singhal
Pooja M Soundalgekar

1
ACKNOWLEDGEMENT

By doing this project, we would like to thank all those who have been
instrumental in helping us achieving the desired outcome. We would
like to thank Prof. D. B. Phatak and IIT-B for providing us with this
opportunity and having faith in our abilities. We would like to thank
our mentors Mr. Adhitya and Ms. Inderpreet for being a constant
support and giving us a broader picture of the whole scenario. Their
constant endeavor and guidance has helped us complete the project
within the stipulated deadline. It would be very difficult to not
mention Mr. B. Chhatri for all the administrative help and making our
working environment comfortable. Last but not the least, we would
like to thank our fellow interns for helping us out with all the
problems that we faced and making our internship experience an
enjoyable one.

2
Summer Internship 2016 Project
Approval Certificate

Department of Computer Science and Engineering,


Indian Institute of technology, Bombay

The project entitled ' XCOS on Web' submitted by Mr. Amit Kumar
Yadav and Ms. Chhavi Agarwal is approved for Summer Internship
2016, at Department of Computer Science and Engineering, IIT
Bombay.

.. ..
Prof. Deepak B. Phatak Mr. Adhitya Kamakshidasan
Dept. of CSE, IITB Project Mentor
Principal Investigator

..
Ms. Inderpreet Arora
Project Mentor

..
Mr. Srikant Patnaik
Project Mentor

Place: IIT Bombay


Date: July 2, 2016
3
DECLARATION

I declare that this written submission represents my ideas in my own


words and where others ideas or words have been included, I have
adequately cited and referenced the original sources. I also declare
that I have adhered to all principles of academic honesty and integrity
and have not misrepresented or fabricated or falsified any
idea/data/fact/source in my submission. I understand that any
violation of the above will be cause for disciplinary action by the
Institute and can also evoke penal action from the sources which have
thus not been properly cited or from whom proper permission has not
been taken when needed.

Amit Kumar Yadav


Motilal Nehru National Institute of Technology, Allahabad

Chhavi Agarwal
National Institute of Technology, Kurukshetra
4
Table Of Contents
ACKNOWLEDGEMENT ......................................................................................................... 2
Summer Internship 2016 Project Approval Certificate ............................................................. 3
DECLARATION ....................................................................................................................... 4
INTRODUCTION ..................................................................................................................... 7
OVERALL SYSTEM DESIGN: ............................................................................................... 8
GRAPHICAL USER INTERFACE ........................................................................................ 10
1. Set Scope Parameters .................................................................................................... 11
2. Right Click Functionality:............................................................................................. 12
3. Color Wheel: ................................................................................................................. 16
4. Port Constraints............................................................................................................. 17
5. Tooltip:.......................................................................................................................... 18
6. Setup: ............................................................................................................................ 19
7. Set Context Window: .................................................................................................... 20
8. Export Xcos: ................................................................................................................. 21
DATA STRUCTURE .............................................................................................................. 22
1. Purpose:......................................................................................................................... 22
2. Mapping: ....................................................................................................................... 22
3. Data Types: ................................................................................................................... 23
3.1. ScilabString(): ........................................................................................................ 23
3.2. ScilabBoolean(): .................................................................................................... 23
3.3. ScilabDouble(): ...................................................................................................... 24
4. Lists: .............................................................................................................................. 24
4.1. list():....................................................................................................................... 24
4.2. mlist(): ................................................................................................................... 24
4.3. tlist(): ..................................................................................................................... 25
5. Scilab Functions: ........................................................................................................... 25
5.1. sci2exp(): ............................................................................................................... 25
5.2. colon_operator(): ................................................................................................... 26
5.3. zeros(): ................................................................................................................... 26
5.4. ones(): .................................................................................................................... 26
5.5. size(): ..................................................................................................................... 26
6. Functions not defined by Scilab:................................................................................... 27
6.1. getData(): ............................................................................................................... 27
6.2. isEmpty(): .............................................................................................................. 27

5
7. Various cases defined for each block: .......................................................................... 27
7.1. "get" case: .............................................................................................................. 27
7.2. "set" case: .............................................................................................................. 27
7.3. "define" case: ......................................................................................................... 28
7.4. "internal" case: ....................................................................................................... 28
7.5. "details" case: ........................................................................................................ 28
XSLT........................................................................................................................................ 29
1. Transformation of structure of XML produced by gui ................................................. 30
1.1. JAXB ..................................................................................................................... 31
1.2. XSLT ..................................................................................................................... 32
2. XSLT Overview ............................................................................................................ 34
3. XSLT Description ......................................................................................................... 34
PARSER .................................................................................................................................. 37
1. CONVERTING DATA STRUCTURES ...................................................................... 37
2. How it works? ............................................................................................................... 44
SERVER .................................................................................................................................. 45
TECHNOLOGY USED ........................................................................................................... 49
FLOW CHART ........................................................................................................................ 50
LEARNING ............................................................................................................................. 51
CHALLENGES FACED AND THAT WERE RESOLVED! ................................................ 52
CONCLUSION ........................................................................................................................ 53
FUTURE WORK ..................................................................................................................... 54
REFERENCES ........................................................................................................................ 55

6
INTRODUCTION

Scilab is an open source software for numerical computation.

Xcos is an open source graphic simulator available with Scilab. Scilab


can be installed on all major Operating Systems. Xcos is a graphical
editor to design hybrid dynamical systems models. Models can be
designed, loaded, saved, compiled and simulated. All Xcos standard
blocks are grouped by categories (signal processing, electrical,
hydraulics, derivative, integral, etc.).

The main aim of this project has been to port core functionalities of
Xcos to a browser-only version that can be used without installing
additional plugins or software. The advantage is that such software is
available to all, 24 hours a day and from any place. Students and
interested users can access it via a Web browser on any machine that
has Internet connection.

7
OVERALL SYSTEM DESIGN:

We have tried to replicate the Xcos GUI completely except for their
bugs.

Xcos provides users with a palette browser which contains all the
blocks and an editor where we can drag and drop the required blocks.
Similarly, we provide a sidebar which contains all the blocks and a
drawing space where users can drag and drop the blocks.

For Xcos, Scilab uses mxGraph at the very core and wrap the vertices
and edges of the graph with their custom data types and values to
make them apt for simulation. They pack all the required data as an
XcosDiagram and save it in .xcos format.

Speaking plainly, a .xcos file contains all the data which is required
by Scilab engine to simulate the graph.

8
The data and values for all the blocks are added as soon as the blocks
are being dragged and dropped on the editor. The entire graph object
is then encoded using mxGraph's pre-defined functions. The encoded
XML is very much similar to that of the .xcos file but still not
completely the same. The few minor differences are then corrected
using a stylesheet, which contains the rules to be applied whenever a
particular tag is encountered. Once the transformation is completed,
we have a .xcos XML with us. This XML is then sent to the server.

The server has a Java servlet which calls the Scilab engine with
proper parameters and the received XML. The simulation is
performed and result is sent back to the server which is then displayed
appropriately.

9
GRAPHICAL USER INTERFACE

We have created the above Graphical User Interface, which is similar


to Scilab's Xcos. User can drag and drop the required blocks from the
left palette box. This GUI has been created with the help of mxGraph
which is open source JavaScript library. Scilab uses JGraphX library
which provides Graphical User Interface for java. mxGraph library is
quite similar to JGraphX. Links can be drawn from one port to
another. The scope parameters can also be changed by double clicking
a block. Along with it, many more functionalities have been added to
make the user feel comfortable with Xcos On Web, same way as he is
with Scilab's Xcos. Few of the functionalities have been described
below:

10
1. Set Scope Parameters

On double click of any block, a modal window for updating block


parameters appears on the GUI.
Submit button saves the modified parameter list into an object and
updates the values.
Reset button resets the changed parameter values into default values.

11
2. Right Click Functionality:

Implement right click menu for block, connections and graph editor
separately.
A function is used to add items to the right click menu. The cell value
is used to make separate menus for right click on graph editor, block
and connections.

For the graph editor:


a) Undo, Redo, Paste, Select All, Zoom In, Zoom Out features.
b) Diagram Background: Sets the background color for the graph
using a color wheel selection window. Color wheel is explained
after menu for connection.

12
For the blocks:
a) Block Parameters: Shows the modal window to update the block
parameters.
b) Cut, Copy the blocks.
c) Delete: This is a custom delete functionality such that when a
block is deleted, the function for deleteBlock loops through all
the wires whose root parent is the block to be deleted. These
wires are put into an array and then all of them are deleted.
Undo will give all of them back. Dangling wires are those which
are not directly connected to a port but are connected to set of
wires whose last wire is connected to a port.
d) Format has rotate feature where vertex is rotated by a right angle
by exploiting the mxGeometry object(Set of geometrical
properties assigned to each vertex) then children ports of that
vertex are rotated by changing the direction of the ports and
changing the 'x' and 'y' coordinates value of the ports. Border
color and fill color feature also use the color wheel selection
window.
There is an image below with border color set to red and fill color set
to blue.

13
For the connections:
a) Delete: Custom delete feature.
b) Format has Border Color, Text Color: Border color is the colour
of the connection.
There is an image below where the edge color is changed to dark
pink.
14
15
3. Color Wheel:

Color Wheel is a range of colors on a wheel from which a user can


select a color and also select the shade of that color from the square
inside the color wheel.
We have implemented color wheel functionality using the link
http://acko.net/blog/farbtastic-jquery-color-picker-plug-in/ . Put in JS
code for selection of colors dynamically and then updating the
graph/block or edge style. This requires Jquery for dynamic changes
to the selection of colors.

16
4. Port Constraints:

a) An Implicit output port can be only connected to an Implicit


input port.
b) An Explicit output port can be only connected to an Explicit
input port.
c) An Command output port can be only connected to an Control
input port.
d) Port cannot have multiple connections starting from it.

These constraints have to be checked just after a connection is


formed, for connections which do not satisfy the above constraints an
error message has to be printed and the connection has to be deleted
and also removed from the undo history.

17
5. Tooltip:

Tooltip is displayed when we hover on any block. It displays


following details of that block:

1. Block Name
2. Simulation Function Name
3. UID
4. Style
5. Flip
6. Mirror
7. Input, Output Ports
8. Control and Command Ports
9. Port Coordinates

These details are being taken from the instance of the block stored in
the graph.

18
6. Setup:

This function provides users with a form where they can specify the
parameters, like finalIntegrationTime etc. required to handle the flow
of simulation.

19
7. Set Context Window:

This function gives users a place to declare variables. These variables


can be used as the values of a few blocks and also in the expressions
throughout the graph.

20
8. Export Xcos:

This function takes the entire graph as a parameter and encodes it in


raw XML format. A few additional tags are added and the entire
diagram is transformed using the stylesheet file. The result of this
function is the .xcos XML and is sent to the server for simulation.

21
DATA STRUCTURE

1. Purpose:

It is not possible to call Scilab every single time we drag and drop a
block on to the canvas. A better idea is to call the functions with a
Browser based solution. We found the need to convert the data
structures to JavaScript.
When a block is dragged and dropped on Graph its corresponding
function is called.
For e.g. new CONST_m().define();
In that function the value of its model, graphics, gui and docs are set
according to the values mentioned in .sci files using various functions
like scicos_model etc. Now the instance of super block is returned
back to generate the xcos.
For e.g. return new BasicBlock(attributes)

2. Mapping:

Scilab provides us with the sci files for each block and internal
function used by Xcos. We went through all the sci files and
translated each sci file in Javascript. Main part was the mapping of sci
files into efficient and effective Javascript functions and concepts.

Basic Mapping:
[2;2] ->[[2],[2]]
[2,2] -> [2,2]

22
3. Data Types:

3.1. ScilabString():

Any value which is a String ,i.e. in double quotes "*" is stored as data
of ScilabString. Earlier we used array as the data structure for storing
all strings. But due the requirement of the data tags for each value,
array was not the appropriate data structure.

Hence, we made a new data structure "data"

For each value a new object of data is created and the string is stored
as array. line and column are use to indicate the index of particular
element in the matrix. width and height indicates number of rows and
columns of matrix.

3.2. ScilabBoolean():

ScilabBoolean is similar to ScilabString but it is used to store boolean


values - true and false. The value passed is first converted to String
and then further processed as strings.

23
3.3. ScilabDouble():
ScilabDouble stores the float values as 'realPart' rather than 'value' as
in ScilabString and ScilabBoolean. Rest of the function is the same as
in upper two data structures.

ScilabInteger():

The data-type Integer has the following types:


int32
int16
int8
uint32
uint16
uint8
ScilabInteger is used for storing integer values. Another attribute
intPrecision is added to denote the type of integer value. The
arguments are passed to ScilabInteger function to get the 'data' part.

4. Lists:

4.1. list():

List returns an Array. Any element which is passed as an argument to


this list is stored in the array. It has been implemented as an array for
the sake of similarity with the sci files.

4.2. mlist():

Mlist returns an object. Here an object is created as opposed to an


array, since the elements needed to be stored as key value pairs. All
the scicos_block have been assigned some default value but once the
scicos_block is called its attributes needs to be updated according to
that particular block. If the mlist is stored as an object instead of array
it can be directly updated by using the keys. Hence we do not need to
remember the index at with particular key is stored.
24
For example
var model = scicos_model();
model.sim = new ScilabString(["output"]);

4.3. tlist():

Tlist also returns an object just like mlist. The only difference is it has
no attribute of name varName as in mlist(). The first arguments is the
array of keys and rest of the arguments are corresponding value of
those keys.

for (var i = 1, j = 0; i < arguments.length; i++, j++) {


this.ScilabMList[arguments[0][j]] = arguments[i];
}

5. Scilab Functions:

5.1. sci2exp():

It is used to convert Array/Matrix to String or format which is


understandable by Scilab.
Inverse array in Scilab: [1;2;3]
Inverse array in JavaScript: [[1],[2],[3]]
Normal array in Scilab: [1,2,3]
Normal array in JavaScript: [1,2,3]

It first checks if the argument is list. If so, it appends list in the string
which will be returned and again call the sci2exp function with the
elements of list as arguments. If not, then it checks if the array is null.
However, if it is null, it returns "[]" string. Otherwise, it checks if it is
a 2D array or not. If it is inverse array it insert ';' between every 2
elements. Otherwise inserts ','.

Therefore, a String formed in below for cases will be:


1. list() -> "list()"
2. [] -> "[]"
25
3. [1] -> "1"
4. [1,2,3] -> "[1,2,3]"
5. [[1],[2],[3]] -> "[1;2;3]"

5.2. colon_operator():

It is used to convert a matrix into column matrix(m*1) by traversing


column wise.
For e.g.
[[1,2],[3,4]] -> [[1],[3],[2],[4]]

5.3. zeros():

This function internally uses math.zeros and math.size to return the


matrix of size mentioned with 0 as elements.

5.4. ones():

This function internally uses math.ones and math.size to return the


matrix of size mentioned with 1 as elements.

5.5. size():

This function returns the size of the matrix. First argument is the
matrix whose size needs to be known and second argument which size
is needed:
no. of rows
no. of columns
no. of rows * no. of columns

For the rest of the mathematical functions used in Scilab, external


library math.js is used.

26
6. Functions not defined by Scilab:

6.1. getData():

This function is used to retrieve data back from Scilab data types. It
returns array of the values stored in the argument.

6.2. isEmpty():

This function returns true, if the arguments has no elements.

7. Various cases defined for each block:

7.1. "get" case:

This function is being called when a user double click on a block to


set its parameters. When the window opens, the previous value of all
the variables need to be displayed.
It creates a object whose key are the variable name to be whose value
is to be displayed and value contains array of strings, where first
element is the String to be displayed on the left hand side and second
argument is the string which contains the value of variable.

7.2. "set" case:

Set function is called once the user has entered all the parameters and
click submit. It returns the object with the same format as it was
passed by "get" case. The String passed are parsed using function like
inverse (converts string into column matrix) and the value of all
parameters are assigned to the corresponding variable.

Accordingly, the value of scicos_block parameters are updated and


the XML is updated of that particular block.

27
7.3. "define" case:

This function is called whenever a user drags a particular block. Its


XML is created and stored in graph.

7.4. "internal" case:

This function is called whenever a block which is dragged and is used


internally within that block. It returns the complete scicos_block.

7.5. "details" case:

It returns the whole scicos_block, which can be used to view details


of particular block in gui and to view tooltip which is displayed while
hovering a particular block.

The XML formed by dragging a block is of the following format:

28
XSLT

XSL stands for eXtensible Stylesheet Language, and is a style sheet


language for XML documents. XSLT is used to transform an XML
document into another XML document, or another type of document
that is recognized by a browser, like HTML and XHTML.

We took help of XCOS's XML Schema ( XML Schema defines the


legal building blocks of an XML document ) to convert XML
generated by GUI into Scilab compatible XML.

29
1. Transformation of structure of XML produced by GUI

Description of the task:

Our entire project is to take the entire Xcos functionality of Scilab and
put it on the web. To achieve this, we have to do following things:
1. Imitating the GUI.
2. Producing a XML document, which will be similar but not same as
Xcos diagram.
3. Attaching the data to our XML doc, so that the simulation is
performed without any problem.
4. Sending the diagram to the server, where Scilab is always running
and the result is sent back.

Step 2 and 3 are important because the diagram that we produce from
our GUI is not compatible with Scilab-Xcos, even though both of
them are created using mxGraph.
So, the job here is to bring certain modifications to our XML
document, so that it resembles the Xcos diagram counterpart and then,
only, we can send the diagram to the server to get the results back.

Solutions:
Searching through various methods to tackle this task, me and my
colleague Amit came across two approaches:

1. JAXB (Java Architecture for XML Binding)


2. XSLT (XML Stylesheet Language Transformations)

Before I dive into the two approaches, I would like to explain a bit
about XML schema definition files.

XSD (XML Schema Definition)


This file keeps the name of all the tags, their allowed attributes and
children in an XML documentation.
A XML document must follow the schema strictly, if it has one.
Xcos has a schema for all the Xcos Diagrams, XcosFiles.xsd.

30
1.1. JAXB

This approach was purely based on Java API for XML binding. The
library used the schema file to create various classes and
corresponding methods for all the elements.
Once, that was done, any valid XML document ( an XML document
is said to be valid according to a schema, if it contains only those tags
that are defined in the schema and strictly in the defined order ) can
be passed to the functions and the document can be Unmarshalled,
meaning that all the elements are converted to Java objects and the
functions can be applied to them to extract details from each one of
them.
Once, the data was extracted, we can start creating a new document,
using this data.

This approach can be used as follows:


1. Pass the mxGraph.xsd schema to the program to create required
classes.
2. Pass the XML document that is generated by the GUI.
3. Extract the data from each of the elements.
4. Pass the XcosFiles.xsd schema to the program to create the other
set of classes.
5. Use the data extracted in Step 3 to create a new document, which
will be compatible with Xcos.

Pros:
This approach has a major advantage that the XML can be treated as
Java objects, and hence, allowing us to use the entire Java library to
perform the tranformation.

Cons:
The cons of this approach were more like, where would be run the
Java program to do the transformation and how.
Also, once the XML gets complicated, which is likely the case, the
automation would simply fail or the logic would become overly
complex.

31
1.2. XSLT

An XSL file contains various templates which act as functions. These


templates are defined for various tags and elements that can be found
in the input XML document. Upon encountering these tags, the
corresponding templates get called and the styling information
contained in them is applied.
For example, we can write a templated to insert a comment I am a
comment whenever a node with the name NODE is encountered.
This idea can be extended to insert a new node itself, with various
attributes and children, whenever a particular node is encountered.

Now, the stylesheet is created using the XSD file for the Xcos
diagram and is applied to the input XML document. The rules of
transformation are specified in the stylesheet itself. So, now when the
input is given the XSL file, the specified transformations take place
and the new XML is generated.

Pros:
The advantage of using this approach is that we need not worry about
writing loops to cover all the children of a particular node. We can
simply use a single instruction and the stylesheet will iterate through
all the children, applying templates, wherever necessary.
Adding information about a new tag is also very simple.
Making changes to the stylesheet is simple enough.
The transformation can be done on the client side as a simple
Javascript code can be used to do the transformation using a given
stylesheet.

32
Now, we were able to do the transformation using the written
stylesheet. So, the last task was to implement this transformation on
the client side. After referring to a few online resources, I was able to
find a way to implement this transformation code on the GUI itself,
allowing us to directly convert our XML to the compatible Xcos
diagram.

Result:
Now, we can simply drag and drop blocks on our GUI and use the
provided button to create an Xcos compatible XML using XSLT
which can be sent to the server for further processing and simulations.

33
2. XSLT Overview

XSLT "xsl:template" Element : The "xsl:template" element is


used to build templates and its match attribute is used to
associate a template with an XML element.
XSLT "xsl:value-of" Element : The "xsl:value-of" element is
used to extract the value of an XML element and add it to the
output stream of the transformation.
XSLT "xsl:if" Element : The "xsl:if" Element is used to put a
conditional if test against the content of the XML file.
XSLT "xsl:choose" Element : The "xsl:choose" element is used
in conjunction with "xsl:when" and "xsl:otherwise" to express
multiple conditional tests.
XSLT "xsl:apply-templates" Element : The "xsl:apply-
templates" element applies a template to the current element or
to the current element's child nodes.
XSLT "xsl:element" Element : The "xsl:element" element is
used to create an element node in the output document and
"xsl:attribute" element is used to add attributes to elements.

3. XSLT Description

First of all we use"xsl:template match="/" " to define the whole


document and make element "XcosDiagram" for our Scilab
compatible XML.
Then we use "xsl:template match="mxCell" " and "xsl:choose"
Element to express multiple conditional tests according to
"style" attribute of "mxCell".
Then we define templates for all the xcos' blocks and ports with
the help of XCOS's xsd (XML Schema) which are recursively
called by "xsl:apply-templates/" as and when encountered by
GUI generated XML.

34
According to XCOS's xsd (XML Schema) following elements
can occur inside "root" element of GUI generated XML and we
have to define template for each of them using XCOS's xsd.

- "BasicBlock"
- "CommandPort"
- "ControlPort"
- "ExplicitInputPort"
- "ExplicitOutputPort"
- "ImplicitInputPort"
- "ImplicitOutputPort"
- "mxCell"
- "AfficheBlock"
- "BigSom"
- "CommandControlLink"
- "ConstBlock"
- "EventInBlock"
- "EventOutBlock"
- "ExplicitInBlock"
- "ExplicitLink"
- "ExplicitOutBlock"
- "GainBlock"
- "GroundBlock"
- "ImplicitInBlock"
- "ImplicitLink"
- "ImplicitOutBlock"
- "PrintBlock"
- "Product"
- "RoundBlock"
- "SplitBlock"
- "Summation"
- "SuperBlock"
- "TextBlock"
- "VoltageSensorBlock"

35
For example, "ExplicitLink" element can have "id" ,"style" ,"value" as
its attribute. So we will define its template as :

<xsl:template name="ExplicitLink" match="ExplicitLink">


<xsl:element name="ExplicitLink">
<xsl:if test="@id">
<xsl:attribute name="id">
<xsl:value-of select="@id" />
</xsl:attribute>
</xsl:if>
<xsl:if test="@style">
<xsl:attribute name="style">
<xsl:value-of select="@style" />
</xsl:attribute>
</xsl:if>
<xsl:if test="@value">
<xsl:attribute name="value">
<xsl:value-of select="@value" />
</xsl:attribute>
</xsl:if>
<xsl:apply-templates />
</xsl:element>
</xsl:template>

36
PARSER

1. CONVERTING DATA STRUCTURES

It is not possible to call Scilab every single time we drag and


drop a block on to the canvas.
Better idea: Call the functions with a Browser based solution.
We found the need to convert the data structures to JavaScript
but conversion by hand is tedious, inefficient and irritating.
We made use of regex in python to do the mapping.

Solution: Build a simple engine to parse Scilab's data structures into


equivalent JavaScript!
Hence we converted the define case of scilab block files into
equivalent JavaScript file

For example, ANDBLK .sci file

function [x,y,typ]=ANDBLK(job,arg1,arg2)
x=[];
y=[];
typ=[];
select job
case "set" then
x=arg1
case "define" then
andlog=ANDLOG_f("define")
andlog.graphics.orig=[194,133]
andlog.graphics.sz=[60,60]
andlog.graphics.flip=%t
andlog.graphics.pout=9
andlog.graphics.pein=[4;11]

input_port1=CLKIN_f("define")
input_port1.graphics.orig=[149,287]

37
input_port1.graphics.sz=[20,20]
input_port1.graphics.flip=%t
input_port1.graphics.exprs="1"
input_port1.graphics.peout=4
input_port1.model.ipar=1

output_port=CLKOUT_f("define")
output_port.graphics.orig=[450,83]
output_port.graphics.sz=[20,20]
output_port.graphics.flip=%t
output_port.graphics.exprs="1"
output_port.graphics.pein=8
output_port.model.ipar=1

input_port2=CLKIN_f("define")
input_port2.graphics.orig=[141,330]
input_port2.graphics.sz=[20,20]
input_port2.graphics.flip=%t
input_port2.graphics.exprs="2"
input_port2.graphics.peout=6
input_port2.model.ipar=2

ifthel=IFTHEL_f("define")
ifthel.graphics.orig=[331,137]
ifthel.graphics.sz=[60,60]
ifthel.graphics.flip=%t
ifthel.graphics.pin=9
ifthel.graphics.pein=12
ifthel.graphics.peout=[8;0]

split=CLKSPLIT_f("define")
split.graphics.orig=[234;275.78348]
split.graphics.pein=6,
split.graphics.peout=[11;12]

diagram=scicos_diagram()

38
diagram.objs(1)=andlog
diagram.objs(2)=input_port1
diagram.objs(3)=output_port

diagram.objs(4)=scicos_link(xx=[169;214;214],yy=[297;297;19
8.71],..
ct=[5,-1],from=[2,1],to=[1,1])
diagram.objs(5)=input_port2

diagram.objs(6)=scicos_link(xx=[161;234;234],yy=[340;340;27
5.78],..
ct=[5,-1],from=[5,1],to=[10,1])
diagram.objs(7)=ifthel

diagram.objs(8)=scicos_link(xx=[351;351;450],yy=[131.29;93;
93],..
ct=[5,-1],from=[7,1],to=[3,1])

diagram.objs(9)=scicos_link(xx=[262.57;322.43],yy=[163;167],
..
ct=[1,1],from=[1,1],to=[7,1])
diagram.objs(10)=split

diagram.objs(11)=scicos_link(xx=[234;234],yy=[275.78;198.71
],..
ct=[5,-1],from=[10,1],to=[1,2])

diagram.objs(12)=scicos_link(xx=[234;361;361],yy=[275.78;27
5.78;202.71],..
ct=[5,-1],from=[10,2],to=[7,1])
x=scicos_block()
x.gui="ANDBLK"
x.graphics.sz=[2,2]
x.graphics.gr_i=[];
x.graphics.pein=[0;0]
x.graphics.peout=0
x.model.sim="csuper"

39
x.model.evtin=[1;1]
x.model.evtout=1
x.model.blocktype="h"
x.model.firing=%f
x.model.dep_ut=[%f %f]
x.model.rpar=diagram;

end
endfunction

Equivalent JavaScript file for ANDBLK:

function ANDBLK() {

ANDBLK.prototype.define = function ANDBLK() {

var andlog = new ANDLOG_f().internal();


andlog.graphics.orig = new ScilabDouble([194, 133]);
andlog.graphics.sz = new ScilabDouble([60, 60]);
andlog.graphics.flip = new ScilabBoolean([true]);
andlog.graphics.pout = new ScilabDouble([9]);
andlog.graphics.pein = new ScilabDouble([4], [11]);
andlog.model.uid = new ScilabString([count]);
andlog.doc = list(new ScilabString([count++]));

var input_port1 = new CLKIN_f().internal();


input_port1.graphics.orig = new ScilabDouble([149, 287]);
input_port1.graphics.sz = new ScilabDouble([20, 20]);
input_port1.graphics.flip = new ScilabBoolean([true]);
input_port1.graphics.exprs = new ScilabString(["1"]);
input_port1.graphics.peout = new ScilabDouble([4]);
input_port1.model.ipar = new ScilabDouble([1]);
input_port1.model.uid = new ScilabString([count]);
input_port1.doc = list(new ScilabString([count++]));

var output_port = new CLKOUT_f().internal();


40
output_port.graphics.orig = new ScilabDouble([450, 83]);
output_port.graphics.sz = new ScilabDouble([20, 20]);
output_port.graphics.flip = new ScilabBoolean([true]);
output_port.graphics.exprs = new ScilabString(["1"]);
output_port.graphics.pein = new ScilabDouble([8]);
output_port.model.ipar = new ScilabDouble([1]);
output_port.model.uid = new ScilabString([count]);
output_port.doc = list(new ScilabString([count++]));

var input_port2 = new CLKIN_f().internal();


input_port2.graphics.orig = new ScilabDouble([141, 330]);
input_port2.graphics.sz = new ScilabDouble([20, 20]);
input_port2.graphics.flip = new ScilabBoolean([true]);
input_port2.graphics.exprs = new ScilabString(["2"]);
input_port2.graphics.peout = new ScilabDouble([6]);
input_port2.model.ipar = new ScilabDouble([2]);
input_port2.model.uid = new ScilabString([count]);
input_port2.doc = list(new ScilabString([count++]));

var ifthel = new IFTHEL_f().internal();


ifthel.graphics.orig = new ScilabDouble([331, 137]);
ifthel.graphics.sz = new ScilabDouble([60, 60]);
ifthel.graphics.flip = new ScilabBoolean([true]);
ifthel.graphics.pin = new ScilabDouble([9]);
ifthel.graphics.pein = new ScilabDouble([12]);
ifthel.graphics.peout = new ScilabDouble([8], [0]);
ifthel.model.uid = new ScilabString([count]);
ifthel.doc = list(new ScilabString([count++]));

var split = new CLKSPLIT_f().internal();


split.graphics.orig = new ScilabDouble([234, 275.78348]);
split.graphics.pein = new ScilabDouble([6]);
split.graphics.peout = new ScilabDouble([11], [12]);
split.model.uid = new ScilabString([count]);
split.doc = list(new ScilabString([count++]));

41
var diagram = scicos_diagram();
diagram.objs.push(andlog);
diagram.objs.push(input_port1);
diagram.objs.push(output_port);
diagram.objs.push(input_port2);
diagram.objs.push(ifthel);
diagram.objs.push(split);
diagram.objs.push(scicos_link({
xx: new ScilabDouble([169], [214], [214]),
yy: new ScilabDouble([297], [297], [198.71]),
ct: new ScilabDouble([5, -1]),
from: new ScilabDouble([2, 1, 0]),
to: new ScilabDouble([1, 1, 1])
}));
diagram.objs.push(scicos_link({
xx: new ScilabDouble([161], [234], [234]),
yy: new ScilabDouble([340], [340], [275.78]),
ct: new ScilabDouble([5, -1]),
from: new ScilabDouble([4, 1, 0]),
to: new ScilabDouble([6, 1, 1])
}));
diagram.objs.push(scicos_link({
xx: new ScilabDouble([351], [351], [450]),
yy: new ScilabDouble([131.29], [93], [93]),
ct: new ScilabDouble([5, -1]),
from: new ScilabDouble([5, 1, 0]),
to: new ScilabDouble([3, 1, 1])
}));
diagram.objs.push(scicos_link({
xx: new ScilabDouble([262.57], [322.43]),
yy: new ScilabDouble([163], [167]),
ct: new ScilabDouble([1, 1]),
from: new ScilabDouble([1, 1, 0]),
to: new ScilabDouble([5, 1, 1])
}));
diagram.objs.push(scicos_link({
xx: new ScilabDouble([234], [234]),

42
yy: new ScilabDouble([275.78], [198.71]),
ct: new ScilabDouble([5, -1]),
from: new ScilabDouble([6, 1, 0]),
to: new ScilabDouble([1, 2, 1])
}));
diagram.objs.push(scicos_link({
xx: new ScilabDouble([234], [361], [361]),
yy: new ScilabDouble([275.78], [275.78], [202.71]),
ct: new ScilabDouble([5, -1]),
from: new ScilabDouble([6, 2, 0]),
to: new ScilabDouble([5, 1, 1])
}));
this.x = scicos_block();
this.x.gui = new ScilabString(["ANDBLK"]);
this.x.graphics.sz = new ScilabDouble([2, 2]);
this.x.graphics.gr_i = new ScilabDouble();
this.x.graphics.pein = new ScilabDouble([0], [0]);
this.x.graphics.peout = new ScilabDouble([0]);
this.x.model.sim = new ScilabString(["csuper"]);
this.x.model.evtin = new ScilabDouble([1], [1]);
this.x.model.evtout = new ScilabDouble([1]);
this.x.model.blocktype = new ScilabString(["h"]);
this.x.model.firing = new ScilabBoolean([false]);
this.x.model.dep_ut = new ScilabBoolean([false, false]);
this.x.model.rpar = diagram;
return new BasicBlock(this.x);
}
ANDBLK.prototype.details = function ANDBLK() {
return this.x;
}

43
2. How it works?

It searches for all the .sci files in Scilab which are the
block files in xcos's palette.
Then it removes all the comments and append all single
Scilab statement into one file.
Then it extracts the code of "case "define"" and parse it
line by line using regex.
It split the content of line from "=" symbol and analyze
both parts for ScilabInteger ,ScilabDouble , ScilabString
,list and mlist ,etc.
It can also handle for loops and if statements.
We have also defined one epsilon case which will handle
scicos_link , list and standard_define functions.

44
SERVER

The backend server is using NGINX. NGINX is a free, open-source,


high-performance HTTP server and reverse proxy. NGINX is known
for its high performance, stability, rich feature set, simple
configuration, and low resource consumption.

For static content, which NGINX excels at, the files will be served
quickly and directly to the client. For dynamic content, for instance
servlet files, NGINX will proxy the request to Apache, which can
then process the results and return the rendered page. NGINX can
then pass the content back to the client.

The speed of loading is increased by using enable compression,


leverage browser caching, optimized images and minified JavaScript.
Using these techniques the pagespeed rating of Google has been
increased from 35 to 86.

45
The Xcos file generated earlier is passed to the server. A Java servlet
invokes a Scilab instance which simulates the Xcos diagram. The
result is returned back to the user within the browser. A Java Servlet
takes the xcos file in JSON format via AJAX request, the contents are
stored in a file to create an xcos file at server side. This xcos file is
then passed to Scilab by executing from the command line. The png
so formed is then passed back to the user.

When we draw the required diagram, and press the button simulate, it
will internally generate an XML file using data structure. That XML
will be parsed by XSLT and a string will contain required xcos data.
This string will be passed to the server in JSON format via AJAX
request. The server runs on NGINX with Apache Tomcat running
behind it for dynamic contents. Once the server gets a request, it
opens a scilab instance and loads Xcos libraries. The string which was
passed is retrieved there and a temporary file is created with text as
Xcos string. Now this file is passed to the xcos using the below
function:

importXcosDiagram("SCI/modules/xcos/demos/batch_simulation.zco
s")

Then we simulate the xcos using the xcos_simulate:

Info=xcos_simulate(scs_m, needcompile)

scs_m: A diagram data structure.

needcompile: An integer. If it equals 4, then the simulator will


perform a complete compilation of the diagram.

This function is used to simulate xcos diagrams in batch mode. It


requires the scs_m structure which can be obtained by loading in
Scilab the .zcos file

Then it is simulated in the backend and png of the simulation is


returned back to client. This is being done using command:

46
xs2png(fig, file_name)

fig : handle of the figure to export.


file_name : string, name of the exported file.

xs2png exports the display of a graphic window into a PNG file.

There are even other formats in which we can take the output back
from Scilab like gif, svg etc. according to our requirements.

47
48
TECHNOLOGY USED

mxGraph
XSLT
JavaScript
Python
Java Servlet
NGINX
Apache Tomcat

49
FLOW CHART

50
LEARNING

During our first week we were assigned the task of reducing the page
load time. For a good user experience the site must get loaded in less
than 5 seconds. Various options which could be used were CSS
Sprites, Leverage Browser Caching and Enabling compression. Then
I studied about NGINX.

NGINX is a free, open-source, high-performance HTTP server and


reverse proxy. NGINX is known for its high performance, stability,
rich feature set, simple configuration, and low resource consumption.

For static content, which NGINX excels at, the files will be served
quickly and directly to the client. For dynamic content, for instance
PHP files, NGINX will proxy the request to Apache, which can then
process the results and return the rendered page. NGINX can then
pass the content back to the client.

It is not about getting the things done. But the quality of the code
matters, that is how optimized the code is. After thinking of a
particular solution we should ask ourselves is this the best way or if it
can be improvised further. It is about getting things done in the most
efficient way keeping in mind that in the long term new
functionalities might be added and it should be easy then to
accommodate changes.

This was the first time we worked with Java Servlets. The
conventional configuration for this partnership is to place NGINX in
front of Apache Tomcat as a reverse proxy for running servlets.
Servlet take the xcos file in JSON format via AJAX request, the
contents are stored in a file to create an xcos file at server side. This
xcos file is then passed to Scilab by executing from the command
line. The png so formed is then passed back to the user.

51
CHALLENGES FACED AND THAT
WERE RESOLVED!

Calling block using window[name]/eval along with mxcodec


for encoding
Rewriting the function for accommodating the 2D
arrays(scilabdouble, scilabstring and scilabinteger)
Javascript function needs to be written in such a way that when
we encode them to XML format from JSON format the tags
formed should resemble the XCOS format.
o For example, data tag needs to there at all places, whereas
if we generally store it in array it returns the array tag
The default values assigned to the attributes of functions like
scicos_model needs to be updated for each block. But in the
earlier implementations it was stored as an array(because array
tag was required in Xcos format). Later we converted into object
as key value pairs, so that they can be updated easily. XSLT is
being used to change the tag name from object to array.
The main problem was to store the separate instances for each
block and even for different copies of same block. Since Firefox
version less than 35 do not support classes, hence it became a
huge problem. Later on I resolved it using functions and a little
change in code.
Now the ports of each block needs to be created using the
javascript details of each block. The documentation helped a lot
in this.
No. of output ports->height of out
No. of input ports->height of in
No. of control ports->height of evtin
No. of command ports->height of evtout
Type of output port -> out_implicit
Type of input port -> in_implicit

52
CONCLUSION

The introduced application enables to prepare Xcos block scheme in


online environment that in next step can be used for control of
dynamical systems in frame of virtual and remote laboratories. Since
it is developed by wide spread technologies it can be combined with
the most of solutions that enable to use Scilab via Internet.

53
FUTURE WORK
We plan to use this application for virtual labs project, which is
funded by MHRD, Government of India. Hence, we believe that the
following features would make it directly usable for virtual labs:

1. Having dynamic interaction between the server and client. This


would enable the user to change the input runtime.
2. Plotting the graphs at the client end. This would be continuous
data to be sent from the server to the client. The plots so
obtained would be more usable to the user.
3. Error Handling. The current setup handles the connectivity
errors at the client end. To make it more faster, we plan to have
more error checks at the browser such as, compilation error,
algebraic loop error, etc.
4. Super block implementation. This feature will enable the user to
club several blocks into single block and re use it for other
simulations.

We are currently working on the above challenging features that


involve 2 way data communication.

54
REFERENCES

https://www.kirp.chtf.stuba.sk/pc11/data/papers/016.pdf
https://www.scilab.org/scilab/gallery/xcos
https://www.w3schools.com/xsl
https://stackoverflow.com
https://www.w3schools.com/js
https://www.coursera.org
https://jgraph.github.io/mxgraph

55

Potrebbero piacerti anche