You are on page 1of 18

Languages for modeling the RED active queue management algorithms: Modelica vs.

Julia
Anna Maria Yu. Apreutesey,1, * Anna V. Korolkova,1, † and Dmitry S. Kulyabov1, 2, ‡
1
Department of Applied Probability and Informatics,
Peoples’ Friendship University of Russia (RUDN University),
6 Miklukho-Maklaya St, Moscow, 117198, Russian Federation
2
Laboratory of Information Technologies
Joint Institute for Nuclear Research
6 Joliot-Curie, Dubna, Moscow region, 141980, Russian Federation
This work is devoted to the study of the capabilities of the Modelica and Julia programming
languages for the implementation of a continuously discrete paradigm in modeling hybrid systems
that contain both continuous and discrete aspects of behavior. A system consisting of an incoming
stream that is processed according to the Transmission Control Protocol (TCP) and a router that
processes traffic using the Random Early Detection (RED) algorithm acts as a simulated threshold
arXiv:2007.09488v1 [cs.NI] 18 Jul 2020

system.
Keywords: active queue management, simulation, Modelica, Julia, Random Early Detection

* 1032193049@pfur.ru
† korolkova-av@rudn.ru
‡ kulyabov-ds@rudn.ru
2

I. INTRODUCTION

The possible methods for investigating complex systems are the construction of a discrete event model, the
construction of a continuous model, and hybrid modeling [1]. Such hybrid systems combine the operation of continuous
and discrete elements, for example, systems with a discrete control device and a control object with a continuous nature
of operation [2]. The system for the further research is the hybrid model of the interaction of the data transmission
process via the Transmission Control Protocol (TCP) and the Random Early Detection (RED) algorithm as an
algorithm of regulating the flow state. When modeling TCP-like traffic, the liquid (continuous) approach can be used,
but it is especially important to consider discrete transitions between TCP states and a discrete packet drop function
in RED-type algorithms. It is the hybrid approach that reflects these important features of the simulated system.

A. The structure of the article

The structure of the article is as following. The II section describes the basic principles and the mathematical model
of the operation of the congestion control mechanism in the TCP protocol with the RED queue management algorithm.
The III section provides general information about the physical modeling language Modelica which implements, among
other things, a hybrid paradigm, and this section also presents the implementation of the algorithm in the Modelica
language. The IV section provides information on the Julia programming language and the DifferentialEquations
package for solving various differential equations. Also in this section some features of the Julia language are presented in
the context of hybrid modeling by using the example of the RED module implementation for active traffic management.

B. Notations and conventions

In the work we will use the following variables and notation. The main parameters of the system are follows:
• 𝑤(𝑡) is the average TCP window size (in packets);
• 𝑞(𝑡) is the average queue length (in packets);
• 𝑞^(𝑡) is the exponentially weighted moving average of the queue length;
• 𝑇 (𝑞, 𝑡) is the Round Trip Time (RTT, sec);
• 𝑁 (𝑡) is the number of TCP sessions;
• 𝐶 corresponds to the speed of procession of packets in the queue.

II. RANDOM EARLY DETECTION AS AN ACTIVE QUEUE MANAGMENT ALGORITHM

The authors have repeatedly described the research problems, the features of the phenomenon under study, the
construction of a mathematical model [3, 4].
In data transmission networks, there is a global synchronization, during which TCP sources send packets synchronously
and also stop transmission synchronously. Such a stable self-oscillating mode of the system operation affects the quality
of network service, throughput and latency negatively. The use of Active Queue Management algorithms, like RED [5],
to control traffic reduces the probability of global synchronization, but it does not completely eliminate it. For some
values of the initial parameters in the router settings, self-oscillations of the main parameters occur in the system.
An active queue management policy with a RED type algorithm is used to control and prevent congestions in the
queues of routers. Algorithms for managing the state of traffic can be represented as control modules in network
equipment. The advantage of this algorithm is its efficiency and relatively simple implementation on network equipment.
Let us describe a model for transmitting TCP-like traffic in which the dynamic flow rate is regulated by an RED
type algorithm. The model consists of two elements - the packet-generating TCP source and the receiver, which is the
queue of the router. It processes incoming packets in accordance with the control algorithm and notifies the source
that the packets have reached their destination. The source and receiver interact through an intermediate link in
accordance with the control algorithm, i.e. the value of the average queue length affects the source parameters, in
particular, the size of the TCP congestion window.
A mathematical model of the interaction of an incoming TCP stream and a router that processes traffic using a
RED-type control algorithm is the autonomous system of three differential equations [6–9]:
3

1 𝑤(𝑡) 𝑤(𝑡 − 𝑇 (𝑡))


𝑤(𝑡)
˙ = 𝜗(𝑤max − 𝑤) − 𝑝(𝑡 − 𝑇 (𝑡)), (1)
𝑇 (𝑡) 2 𝑇 (𝑡 − 𝑇 (𝑡))

⎪ 𝑁 (𝑡)𝑤(𝑡)

⎨(1 − 𝑝(𝑡)) 𝑇 (𝑡) − 𝐶, 𝑞(𝑡) > 0,
𝑞(𝑡)
˙ = [︂ ]︂ (2)

⎪ 𝑁 (𝑡)𝑤(𝑡)
⎩max (1 − 𝑝(𝑡)) − 𝐶, 0 , 𝑞(𝑡) = 0,
𝑇 (𝑡)
˙𝑞^(𝑡) = −𝑤𝑞 𝐶 𝑞^(𝑡) + 𝑤𝑞 𝐶𝑞(𝑡), (3)
The (1) equation describes the dynamic change of the average TCP window size. The 1/𝑇 (𝑞, 𝑡) element reflects
the slow start TCP state, during which the window size increases per RTT. The 𝜗(𝑤max − 𝑤) component, which is a
Heaviside function, limits the growth of the TCP window. The (1−𝑝(𝑡))𝑤(𝑡)𝑁 (𝑡)/𝑇 (𝑞, 𝑡) component in the (2) equation
reflects the increase in the queue length when packets arrive which corresponds to the average packet arrival rate.
The (3) equation reflects the change of the 𝑞^(𝑡) - exponentially weighted moving average of the queue length function
operating as a low-pass filter. It is introduced for some smoothing outliers of the queue length. As soon as the 𝑞^(𝑡) value
exceeds some predetermined threshold value, the router finds out that the system has started overloading and reports
this to the source.
The RED algorithm is controlled by the 𝑝(^ 𝑞 ) - piecewise probabilistic packet drop function which can be written as
a system of nonlinear equations.


⎨0, 0 6 𝑞^(𝑡) < 𝑞min ,
𝑞^(𝑡)−𝑞min
𝑝(^
𝑞) = 𝑝 , 𝑞min 6 𝑞^(𝑡) 6 𝑞max , (4)
⎪ 𝑞max −𝑞min max

1, 𝑞^(𝑡) > 𝑞max .
This function depends on the threshold values of the queue size 𝑞min and 𝑞max , as well as the 𝑝max parameter that
sets the part of packets that will be discarded if 𝑞^ reaches the maximum value.

III. MODELING IN THE MODELICA LANGUAGE

The Modelica language was developed by the non-profit organization Modelica which also develops a freely distributed
library based on it. This object-oriented language of physical modeling is used to solve a wide range of problems [10, 11].
Modelica is well suited for component-oriented modeling of complex systems consisting of various physical components,
also having control components and elements oriented to individual processes. Let us demonstrate the application of
this language to hybrid modeling of communication network algorithms [2].
The basis of the language is represented by classes that can be inherited. In Modelica classes contain methods
and fields that can have types of variability such as constant, parameter and variable. In addition to methods and
fields, the class contains functions and equations which are defined in the equation section. One of the mandatory
requirements of the Modelica program is the coincident number of variables and equations.
Let us declare the variables and parameters used as initial ones.
Real p(start = 0.0) "Drop probability";
Real w(min = 1.0, max = wmax, start = 1.0, fixed = true) "TCP window";
Real q(max = R, start = 0.0, fixed = true) "Instant queue length";
Real q_avg(start = 0.0) "EWMS queue length";

parameter Real N(start = 60.0) "Number of TCP sessions";


parameter Real c(start = 10.0) "Service intensity, Mbps";
parameter Real packet_size(start = 500.0) "Package size, bit";
parameter Real T(start = 0.05) "RTT";
parameter Real thmin(start = 0.25) "Normalized lower threshold";
parameter Real thmax(start = 0.5) "Normalized upper threshold";
parameter Real R(start = 300.0) "Queue size";
parameter Real wq(start = 0.0004) EWMS parameter";
parameter Real pmax(start = 0.1) "Maximum drop probability";
parameter Real wmax(start = 32.0) "Max window size";
parameter Real C = 125000.0 * c / packet_size "Service intensity, packets";
4

The congestion control algorithm in the queues of the RED router in Modelica is implemented as a Red class [12].
A discrete drop function is easily set in the main class using the standard if operator:

class Red
equation
p = if q_avg < thmin * R
then 0.0
else if q_avg > thmax * R
then 1.0
else (q_avg / R - thmin) * pmax / (thmax - thmin);

In this implementation, the discrete element of the system interacts well with continuous elements, the behaviour of
which is also implemented in the main class of the program using three equations:

equation
der(w) = wAdd(w, wmax, T) + (-0.5) * w * delay(w, T, T) * delay(p, T, T) / delay(T, T, T);
der(q) = qAdd(pre(q), w, T, C, N, R);
der(q_avg) = wq * C * (q - q_avg);

In Modelica the der operator defines a time derivative. The delay is realized very simply with the help of the delay
operator, which makes it possible to work with the delay of both continuous and discrete system elements.
The wAdd function limits the size of the TCP window:

function wAdd
input Real wIn, wmax, T;
output Real wOut;
algorithm
wOut := if noEvent(wIn >= wmax) then 0.0 else 1.0 / T;
end wAdd;

The qAdd function sets the change in the average queue length depending on the discrete packet drop function:

function qAdd
input Real q, w, T, C, N, R;
output Real qOut;
protected Real q1, q2;
algorithm
q1 := N * w / T - C;
q2 := q + q1;
qOut := if q2 > R then R - q else if q2 > 0.0 then q1 else -q;
end qAdd;

Additional restrictions on the size of 𝑤(𝑡) and 𝑞(𝑡) variables are set using the when operator in the Red class:

when w <= 1.0


then reinit(w, 1.0);
end when;
when q >= R
then reinit(q, R);
end when;

As a result of system modeling the dynamics of the change in 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡) parameters was obtained, presented
in figure 1. The graph shows that for some parameter values in the system there is a stable self-oscillating mode of
operation.

IV. MODELING IN THE JULIA LANGUAGE

Julia is a high-level language designed for scientific and engineering calculations [2, 13–15].
5

Figure 1. 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡) parameters behaviour based on Modelica modeling results

Let us describe the implementation of an Active Queue Management algorithm with a RED control algorithm in
Julia1 .
In this implementation, we used the DifferentialEquations package [16], designed for effective solution of differential
equations of various types, such as ordinary differential equations, stochastic ordinary differential equations, differential
algebraic and hybrid equations, as well as delay differential equations.
To install the package we will use the following command in Julia REPL:
using Pkg
Pkg.add("DifferentialEquations")
We will enable the package using the command:
using DifferentialEquations
We set the vector of the initial system parameters p = (T, N, C, wq, q_min, q_max, R, p_max, w_max). The
pr variable which is a function of the packet drop probability, acts as a global variable.
T = 0.5
N = 60.0
C = 10 * 1000000.0 / (8.0 * 500)
wq = 0.0004
q_min = 0.25
q_max = 0.50
R = 300.0
p_max = 0.1
w_max = 32.0
p = (T, N, C, wq, q_min, q_max,
R, p_max, w_max)
pr = 0.0
Since the original system of differential equations contains delayed arguments, we define the history function h(p, t)
which depends on the parameters vector p and time t. Next, we define the delay of the 𝑤(𝑡 − 𝑇 (𝑡)) variable in
(1) equation:
h(p, t) = zeros(1)
tau = T
lags = [tau]
For our task, the Red dynamic function describing the behaviour of differential equations and setting constraints for
𝑤, 𝑞, 𝑞^(𝑡) parameters in DifferentialEquations will have the following form:

1 We used the Julia-1.4.1.


6

function Red(du, u, h, p, t)
w, q, q_avg = u
hist1 = h(p, t - T)[1]
du[1] = 1.0 / T -
-(w * hist1 * pr / (2.0 * T))
du[2] = qAdd(q,w,T,C,N,R)
du[3] = -wq * C * q_avg + wq * C * q
end

In the Red function, we also set constraints for the 𝑤, 𝑞, 𝑞^(𝑡) parameters.

if (w <= 1.0)
w = 1.0
end
if (q >= R)
q = R
end
if (q_avg >= R)
q_avg = R
end

Next we define the 𝑞 parameter change function.

function qAdd(q,w,T,C,N,R)
q1 = N * w / T - C
q2 = q + q1
if q2 > R
return R - q
elseif q2 > 0
return q1
else
return -q
end
end

One of the powerful tools of the DifferentialEquations package is callbacks, for which two functions are defined. A
condition function is needed to check if an event has occurred. The affect function is executed if an event has occurred.
The discrete packet drop function is implemented as a controller which is updated every 0.01 seconds until the tf
simulation time is reached. The tstops array defines the sampling intervals of the condition check, the function checks
if t is one of the sample element.

tf = 30.0
tstops = collect(0:0.01:tf)
function condition_control_loop(u,t,integrator)
(t in tstops)
end

Next, we determine the affect function, which is the controller. The control_loop! function at each step calculates
the new value of the packet drop probability function 𝑝 depending on the current values of the 𝑤, 𝑞, 𝑞^(𝑡) parameters in
accordance with the formula (4).

function control_loop!(integrator)
global pr

w = integrator.u[1]
q = integrator.u[2]
q_avg = integrator.u[3]

if (q_avg < q_min * R)


pr = 0.0
7

Figure 2. 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡) parameters behaviour based on Julia modeling results

elseif (q_avg > q_max * R)


pr = 1.0
else pr = p_max * (q_avg/R - q_min) / (q_max - q_min)
end
end

Then we define a discrete type callback:

cb = DiscreteCallback(condition_control_loop, control_loop!)

Finally, we define the vector of the system initial state, the simulation time and call the DDEProblem package solver.
The Red function, vector of initial states, simulation time, and variables delay parameters are passed to its arguments:

u0 = [1.0, 0.0, 0.0]


tspan = (0.0, tf)
prob = DDEProblem(Red, u0, h, tspan, p, constant_lags=lags)
alg = MethodOfSteps(Tsit5())
sol = solve(prob, alg, callback = cb, tstops=tstops)

As a result of the simulation, we obtain a graph demonstrating the behaviour of the TCP Reno window size and
the average queue length, i.e. reflecting the dynamics of a queue in a router (or gateway) with a queue management
module using the RED algorithm (fig. 2).

V. RESULTS

As a result of the study, two software complexes created in the programming languages Modelica and Julia were
obtained. Both of these complexes implement the same mathematical model of a data transmission network with an
active traffic control module operating according to the RED algorithm.
A numerical experiment conducted within the framework of both software systems gives comparable results(see
fig. 1 and fig. 2).

VI. DISCUSSION

Modelica and Julia languages are both domain-specific languages. However, Julia is considered as the common
language of scientific calculations, Modelica is considered as a specialized language for modeling of dynamic, continuous
and hybrid systems.
The mathematical model of the RED algorithm is formulated using a hybrid approach. Therefore, in the framework
of the Modelica language, its implementation turned out to be quite simple. In this language ordinary differential
equations are written with a delayed argument with the help of high-level tools quite easily. In addition, the use of
discrete elements is implemented very clearly.
8

Julia language is aimed at solving a wider range of tasks. Therefore, it does not have as many syntax tools as
the more specialized Modelica. In particular, the implementation of the hybrid paradigm in Julia requires a higher
qualification of the programmer than when working with the Modelica language.
For specialized applications, Julia requires a greater level of knowledge than specialized languages such as Modelica.
Julia is also a metalanguage and it can serve as the basis for the construction of other languages. For example, the
Modia extension [17, 18] was made to migrate programs from Modelica to Julia (and possibly in the opposite direction).

VII. CONCLUSION

The authors demonstrated the application of the continuous-discrete approach to the modeling of non-linear systems
with control. The simulated system is the system consisting of an incoming stream processed according to the TCP
protocol, as well as a router that processes traffic using a RED algorithm.
By comparing software implementations in the Modelica and Julia programming languages, the simplicity of hybrid
systems modeling in Modelica is demonstrated, where continuous system elements, implemented by using a system of
differential equations, interact with a discrete packet drop function quite well. Restrictions for some system parameters
are set using the when operator. Implementation of the delay is also possible for system elements of any nature of
functioning.
Julia also provides the ability to model systems according to a hybrid paradigm. The DifferentialEquations package
allows to solve systems of differential equations of various kinds, including delay differential equations. The continuous
probabilistic function has been successfully implemented using the callback option. A delayed argument to a continuous
function is implemented using the h(p, t) history function.
Thus, the authors studied the capabilities of the Modelica and Julia programming languages in modeling of hybrid
systems containing both continuous and discrete aspects of behaviour. The numerical simulation of the process
of transmitting data via TCP and the process of regulating the flow state using the RED algorithm in the event
of congestion has been performed, graphs demonstrating changes in the main parameters of the system have been
obtained.

ACKNOWLEDGMENTS

The publication has been funded by Russian Foundation for Basic Research (RFBR) according to the research
project No 19-01-00645.

[1] A. V. Korolkova, T. R. Velieva, P. A. Abaev, L. A. Sevastianov, D. S. Kulyabov, Hybrid Simulation Of Active Traffic
Management, Proceedings 30th European Conference on Modelling and Simulation (2016) 685–691doi:10.7148/2016-0685.
[2] D. Färnqvist, K. Strandemar, K. H. Johansson, J. P. Hespanha, Hybrid Modeling of Communication Networks Using
Modelica, in: The 2nd International Modelica Conference, 2002, pp. 209–213.
[3] A. V. Korolkova, D. S. Kulyabov, T. R. Velieva, I. S. Zaryadov, Essay on the study of the self-oscillating regime in the
control system, in: M. Iacono, F. Palmieri, M. Gribaudo, M. Ficco (Eds.), 33 European Conference on Modelling and
Simulation, ECMS 2019, Vol. 33 of Communications of the ECMS, European Council for Modelling and Simulation, Caserta,
2019, pp. 473–480. doi:10.7148/2019-0473.
[4] D. S. Kulyabov, A. V. Korolkova, T. R. Velieva, E. G. Eferina, L. A. Sevastianov, The Methodology of Studying of Active
Traffic Management Module Self-oscillation Regime, in: W. Zamojski, J. Mazurkiewicz, J. Sugier, T. Walkowiak, J. Kacprzyk
(Eds.), DepCoS-RELCOMEX 2017. Advances in Intelligent Systems and Computing, Vol. 582 of Advances in Intelligent
Systems and Computing, Springer International Publishing, Cham, 2018, pp. 215–224. doi:10.1007/978-3-319-59415-6_
21.
[5] S. Floyd, V. Jacobson, Random Early Detection Gateways for Congestion Avoidance, IEEE/ACM Transactions on
Networking 1 (4) (1993) 397–413. doi:10.1109/90.251892.
[6] V. Misra, W.-B. Gong, D. Towsley, Fluid-Based Analysis of a Network of AQM Routers Supporting TCP Flows with an
Application to RED, ACM SIGCOMM Computer Communication Review 30 (4) (2000) 151–160. doi:10.1145/347057.
347421.
[7] V. Misra, W.-B. Gong, D. Towsley, Stochastic Differential Equation Modeling and Analysis of TCP-Windowsize Behavior,
Proceedings of PERFORMANCE 99 (1999).
[8] A. V. Korolkova, D. S. Kulyabov, L. A. Sevastianov, Combinatorial and Operator Approaches to RED Modeling, Mathe-
matical Modelling and Geometry 3 (3) (2015) 1–18.
9

[9] M. Hnatič, E. G. Eferina, A. V. Korolkova, D. S. Kulyabov, L. A. Sevastyanov, Operator Approach to the Master Equation for
the One-Step Process, EPJ Web of Conferences 108 (2016) 02027. arXiv:1603.02205, doi:10.1051/epjconf/201610802027.
[10] P. Fritzson, Principles of Object-Oriented Modeling and Simulation with Modelica 2.1, Wiley-IEEE Press, 2003.
[11] P. Fritzson, Introduction to Modeling and Simulation of Technical and Physical Systems with Modelica, John Wiley &
Sons, Inc., Hoboken, NJ, USA, 2011. doi:10.1002/9781118094259.
[12] A.-M. Y. Apreutesey, A. V. Korolkova, D. S. Kulyabov, Modeling RED algorithm modifications in the OpenModelica, in: D. S.
Kulyabov, K. E. Samouylov, L. A. Sevastianov (Eds.), Proceedings of the Selected Papers of the 9th International Conference
"Information and Telecommunication Technologies and Mathematical Modeling of High-Tech Systems" (ITTMM-2019),
Moscow, Russia, April 15-19, 2019, Vol. 2407 of CEUR Workshop Proceedings, Moscow, 2019, pp. 5–14.
[13] J. Bezanson, S. Karpinski, V. B. Shah, A. Edelman, Julia: A Fast Dynamic Language for Technical Computing (2012)
1–27arXiv:1209.5145.
[14] J. Bezanson, A. Edelman, S. Karpinski, V. B. Shah, Julia: A fresh approach to numerical computing, SIAM Review 59 (1)
(2017) 65–98. arXiv:1411.1607, doi:10.1137/141000671.
[15] A. Joshi, R. Lakhanpal, Learning Julia, Packt Publishing, 2017.
[16] C. Rackauckas, Q. Nie, DifferentialEquations.jl – A Performant and Feature-Rich Ecosystem for Solving Differential
Equations in Julia, Journal of Open Research Software 5 (May) (2017). doi:10.5334/jors.151.
[17] H. Elmqvist, T. Henningsson, M. Otter, Systems Modeling and Programming in a Unified Environment Based on Julia,
in: T. Margaria, B. Steffen (Eds.), Leveraging Applications of Formal Methods, Verification and Validation: Discussion,
Dissemination, Applications. ISoLA 2016, Vol. 9953 of Lecture Notes in Computer Science, Springer, Cham, 2016, pp.
198–217. doi:10.1007/978-3-319-47169-3_15.
[18] M. Otter, H. Elmqvist, Transformation of Differential Algebraic Array Equations to Index One Form, in: Proceedings
of the 12th International Modelica Conference, Prague, Czech Republic, May 15-17, 2017, Vol. 132, 2017, pp. 565–579.
doi:10.3384/ecp17132565.
Возможности гибридного моделирования нелинейных систем с управлением в
языках Modelica и Julia
А. М. Ю. Апреутесей,1, * А. В. Королькова,1, † и Д. С. Кулябов1, 2, ‡
1
Кафедра прикладной информатики и теории вероятностей,
Российский университет дружбы народов,
117198, Москва, ул. Миклухо-Маклая, д. 6
2
Лаборатория информационных технологий,
Объединённый институт ядерных исследований,
ул. Жолио-Кюри 6, Дубна, Московская область, Россия, 141980
Данная работа посвящена изучению возможностей языков программирования Modelica и
Julia для реализации непрерывно-дискретной парадигмы при моделировании гибридных систем,
содержащих как непрерывные, так и дискретные аспекты поведения. В качестве моделируемой
пороговой системы выступает система, состоящая из входящего потока, обрабатываемого соглас-
но протоколу Transmission Control Protocol (TCP), а также маршрутизатора, обрабатывающего
arXiv:2007.09488v1 [cs.NI] 18 Jul 2020

трафик по алгоритму типа Random Early Detection (RED).


Ключевыеслова: активное управление трафиком, имитационное моделирование, Modelica, Julia, Random
Early Detection

* 1032193049@pfur.ru
† korolkova-av@rudn.ru
‡ kulyabov-ds@rudn.ru
2

I. ВВЕДЕНИЕ

Среди возможных методов исследования сложных систем можно выделить построение дискретно–событийной
модели, построение непрерывной модели, а также гибридное моделирование [1]. В подобных гибридных систе-
мах сочетается работа непрерывных и дискретных элементов, например, системы с дискретным устройством
управления и объектом управления с непрерывным характером функционирования [2]. В качестве исследуе-
мой системы выступает модель взаимодействия процесса передачи данных по протоколу Transmission Control
Protocol (TCP) и процесса регулирования состояния потока при возникновении перегрузок, в качестве которого
рассматривается алгоритм Random Early Detection (RED). При моделировании TCP-подобного трафика можно
воспользоваться жидкостным (непрерывным) подходом, однако особенно важно учитывать дискретные переходы
между TCP состояниями и функцию сброса пакетов в алгоритмах типа RED, гибридный подход отразит эти
важные особенности моделируемой системы.

A. Структура статьи

Структура статьи следующая. В разделе II описываются основные принципы и математическая модель


функционирования механизма управления перегрузками в протоколе TCP с алгоритмом управления очередями
RED. В разделе III дается общая информация об языке физического моделирования Modelica, реализующем в том
числе гибридную парадигму, представлена реализация алгоритма на языке Modelica. Раздел IV дает информацию
о языке программирования Julia и о библиотеке DifferentialEquations для решения дифференциальных уравнений
различных видов. Также в данном разделе представлены некоторые возможности языка Julia в контексте
гибридного моделирования на примере реализации модуля активного управления трафиком RED.

B. Обозначения и соглашения

В работе будем использовать следующие переменные и обозначения. Основные параметры рассматриваемой


системы:
• 𝑤(𝑡) — средний размера TCP-окна (в пакетах);
• 𝑞(𝑡) — средний размер очереди (в пакетах);
• 𝑞^(𝑡) — экспоненциально взвешенное скользящее среднее значения длины очереди;
• 𝑇 (𝑞, 𝑡) — время двойного оборота (Round Trip Time, RTT, сек);
• 𝑁 (𝑡) — число TCP-сессий;
• 𝐶 — скорость обработки пакетов в очереди.

II. АЛГОРИТМ АКТИВНОГО УПРАВЛЕНИЯ ОЧЕРЕДЬЮ RANDOM EARLY DETECTION

Авторами неоднократно описывались проблематика исследования, особенности изучаемого явления, построение


математической модели [3, 4].
В сетях передачи данных имеет место глобальная синхронизация, при которой TCP источники синхронно
отправляют пакеты и также синхронно прекращают передачу. Такой устойчивый автоколебательный режим
работы системы отрицательным образом сказывается на показателях качества обслуживания сети, на пропуск-
ной способности и латентности. Использование для управления трафиком алгоритмов активного управления
очередью, таких как RED, снижает вероятность возникновения глобальной синхронизации, но не устраняет
её полностью, при некоторых значениях начальных параметров в настройках маршрутизаторов в системе
возникают автоколебания основных параметров.
Алгоритм активного управления очередью с алгоритмом управления типа RED используется для контроля
и предотвращения перегрузок в очередях маршрутизаторов [5]. Алгоритмы управления состоянием трафика
могут быть представлены как модули управления в сетевом оборудовании. Преимуществом данного алгоритма
является его эффективность и относительно простая реализация на сетевом оборудовании.
Опишем модель передачи TCP-подобного трафика с регулируемой алгоритмом типа RED динамической ин-
тенсивностью потока. Модель состоит из двух элементов — генерирующего пакеты TCP-источника и получателя,
3

в качестве которого выступает очередь маршрутизатора, обрабатывающая поступившие пакеты в соответствии с


алгоритмом управления и уведомляющая источник о доставке пакетов. Источник и получатель взаимодействуют
через промежуточное звено в соответствии с алгоритмом управления, т.е. значение средней длины очереди
влияет на параметры источника, в частности, на размер окна перегрузки TCP.
Математическая модель взаимодействия входящего TCP-потока и маршрутизатора, обрабатывающего тра-
фик по алгоритму управления типа RED, представляет собой автономную систему трёх дифференциальных
уравнений [6–9]:

1 𝑤(𝑡) 𝑤(𝑡 − 𝑇 (𝑡))


𝑤(𝑡)
˙ = 𝜗(𝑤max − 𝑤) − 𝑝(𝑡 − 𝑇 (𝑡)), (1)
𝑇 (𝑡) 2 𝑇 (𝑡 − 𝑇 (𝑡))

⎪ 𝑁 (𝑡)𝑤(𝑡)

⎨(1 − 𝑝(𝑡)) 𝑇 (𝑡) − 𝐶, 𝑞(𝑡) > 0,
𝑞(𝑡)
˙ = [︂ ]︂ (2)

⎪ 𝑁 (𝑡)𝑤(𝑡)
⎩max (1 − 𝑝(𝑡)) − 𝐶, 0 , 𝑞(𝑡) = 0,
𝑇 (𝑡)
𝑞^˙(𝑡) = −𝑤𝑞 𝐶 𝑞^(𝑡) + 𝑤𝑞 𝐶𝑞(𝑡), (3)

Уравнение (1) описывает динамическое изменение среднего размера TCP окна 𝑤(𝑡). Элемент 1/𝑇 (𝑞, 𝑡) отражает
фазу медленного старта TCP, во время которой размер окна увеличивается за единицу времени двойного оборота.
Компонента 𝜗(𝑤max − 𝑤), являющаяся функцией Хэвисайда, ограничивает роста TCP-окна.
Компонента (1 − 𝑝(𝑡))𝑤(𝑡)𝑁 (𝑡)/𝑇 (𝑞, 𝑡) в уравнении (2) отражает увеличение длины очереди при поступлении
пакетов, что соответствует средней интенсивности поступления пакетов.
Уравнение (3) отражает изменение функции экспоненциально взвешенного скользящего среднего значения
длины очереди 𝑞^(𝑡), которое вводится для некоторого сглаживания выбросов мгновенного значения размера
очереди 𝑞(𝑡), функционируя как фильтр низких частот. Как только значение 𝑞^(𝑡) превышает некое заданное
пороговое значение, маршрутизатор узнает о том, что в системе началась перегрузка и сообщает об этом
источнику.
Непосредственно за управление по алгоритму RED отвечает кусочная вероятностная функция сброса пакета
𝑞 ), которая может быть записана как система нелинейных уравнений.
𝑝(^



⎨0, 0 6 𝑞^(𝑡) < 𝑞min ,
𝑞^(𝑡)−𝑞min
𝑝(^
𝑞) = 𝑝 , 𝑞min 6 𝑞^(𝑡) 6 𝑞max , (4)
⎪ 𝑞max −𝑞min max

1, 𝑞^(𝑡) > 𝑞max .

Данная функция зависит от пороговых значений размера очереди 𝑞min и 𝑞max , а также параметра 𝑝max ,
задающего часть пакетов, которые будут отброшены в случае, если 𝑞^ достигнет максимального значения.

III. МОДЕЛИРОВАНИЕ НА ЯЗЫКЕ MODELICA

Язык Modelica разработан некоммерческой организацией Modelica, которая также разрабатывает на его
основе свободно распространяемую библиотеку. Этот язык, позиционируемый как объектно-ориентированный
язык физического моделирования, применяется для решения широкого круга задач [10, 11]. Modelica хорошо
применима для компонентно-ориентированного моделирования сложных систем, состоящих из различных
физических компонентов, также имеющих компоненты управления и элементы, ориентированные на отдельные
процессы. Продемонстрируем применение данного языка к гибридному моделированию алгоритмов сетей
связи [2].
Основу языка составляют имеющие возможность наследоваться классы, которые содержат в себе все элементы
наследуемого класса. В Modelica классы содержат методы и поля, которые могут иметь такие типы изменчивости
как константа, параметр и переменная. Помимо методов и полей в классе содержатся функции и связывающие
переменные уравнения, которые задаются в разделе equation. Одним из обязательных требований программы
на Modelica является совпадающее число переменных и уравнений.
Объявим переменные и приведем параметры, используемые в качестве начальных.

Real p(start = 0.0) "Вероятность сброса";


Real w(min = 1.0, max = wmax, start = 1.0, fixed = true) "Окно";
Real q(max = R, start = 0.0, fixed = true) "Мгновенная длина очереди";
4

Real q_avg(start = 0.0) "EWMS длины очереди";

parameter Real N(start = 60.0) "Количество сессий";


parameter Real c(start = 10.0) "Интенсивность обслуживания, Mbps";
parameter Real packet_size(start = 500.0) "Размер пакета, bit";
parameter Real T(start = 0.05) "Время двойного оборота";
parameter Real thmin(start = 0.25) "Нормализованный нижний порог";
parameter Real thmax(start = 0.5) "Нормализованный верхний порог";
parameter Real R(start = 300.0) "Размер очереди";
parameter Real wq(start = 0.0004) "Параметр EWMS";
parameter Real pmax(start = 0.1) "Максимальная вероятность сброса";
parameter Real wmax(start = 32.0) "Максимальный размер окна";
parameter Real C = 125000.0 * c / packet_size "Интенсивность обслуживания, packets";

Алгоритм контроля перегрузки в очередях маршрутизатора RED на языке Modelica реализован в виде класса
Red [12]. Дискретная функция сброса легко задается в основном классе с помощью стандартного оператора if:

class Red
equation
p = if q_avg < thmin * R
then 0.0
else if q_avg > thmax * R
then 1.0
else (q_avg / R - thmin) * pmax / (thmax - thmin);

В данной реализации алгоритма RED дискретный элемент системы хорошо взаимодействует с непрерывными
элементами, поведение которых также реализовано в основном классе программы с помощью трех уравнений:

equation
der(w) = wAdd(w, wmax, T) + (-0.5) * w * delay(w, T, T) * delay(p, T, T) / delay(T, T, T);
der(q) = qAdd(pre(q), w, T, C, N, R);
der(q_avg) = wq * C * (q - q_avg);

На языке Modelica оператор der задает производную по времени. Запаздывание в Modelica реализуется крайне
просто с помощью оператора delay, который дает возможность работать с запаздыванием как непрерывных,
так и дискретных элементов системы.
Функция wAdd ограничивает рост размера TCP-окна:

function wAdd
input Real wIn, wmax, T;
output Real wOut;
algorithm
wOut := if noEvent(wIn >= wmax) then 0.0 else 1.0 / T;
end wAdd;

Функция qAdd задает изменение среднего размера очереди в зависимости от дискретной функции сброса
пакетов:

function qAdd
input Real q, w, T, C, N, R;
output Real qOut;
protected Real q1, q2;
algorithm
q1 := N * w / T - C;
q2 := q + q1;
qOut := if q2 > R then R - q else if q2 > 0.0 then q1 else -q;
end qAdd;

Дополнительные ограничения в размере переменных 𝑤(𝑡) и 𝑞(𝑡) задаются с помощью оператора when в классе
Red:
5

Рис. 1. Поведение параметров 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡) по результатам моделирования на языке Modelica

when w <= 1.0


then reinit(w, 1.0);
end when;
when q >= R
then reinit(q, R);
end when;

В результате моделирования системы была получена динамика изменения 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡), представленная
на рис. 1. График демонстрирует, что при некоторых значениях параметров в системе возникает устойчивый
автоколебательный режим функционирования.

IV. МОДЕЛИРОВАНИЕ НА ЯЗЫКЕ JULIA

Язык Julia — это язык высокого уровня, предназначенный для научных и инженерных расчётов [2, 13–15].
Опишем реализацию алгоритма активного управления очередью с алгоритмом управления типа RED на языке
Julia1 .
В данной реализации использовалась библиотека DifferentialEquations [16], предназначенная для эффектив-
ного решения дифференциальных уравнений различных видов, таких как обыкновенные дифференциальные
уравнения, стохастические обыкновенные дифференциальные уравнения, дифференциально-алгебраические и
гибридные уравнения, а также дифференциальные уравнения с запаздыванием.
Для установки пакета используем следующую команду в Julia REPL:

using Pkg
Pkg.add("DifferentialEquations")

Подключим пакет, используя команду:

using DifferentialEquations

Зададим вектор начальных параметров системы p = (T, N, C, wq, q_min, q_max, R, p_max, w_max). Пе-
ременная pr, являющаяся функцией вероятности сброса пакетов, выступает как глобальная переменная.

T = 0.5
N = 60.0
C = 10 * 1000000.0 / (8.0 * 500)
wq = 0.0004
q_min = 0.25

1 Мы использовали версию Julia 1.4.1.


6

q_max = 0.50
R = 300.0
p_max = 0.1
w_max = 32.0
p = (T, N, C, wq, q_min, q_max,
R, p_max, w_max)
pr = 0.0
Так как в исходной системе дифференциальных уравнений присутствуют запаздывающие аргументы, опре-
делим функцию истории h(p, t), которая зависит от вектора параметров p и времени t. Далее определим
запаздывание переменной 𝑤(𝑡 − 𝑇 (𝑡)) в уравнении (1):
h(p, t) = zeros(1)
tau = T
lags = [tau]
Для предложенной нами задачи динамическая функция Red, описывающая поведение дифференциальных
уравнений и задающая ограничения для параметров 𝑤, 𝑞, 𝑞^(𝑡), в DifferentialEquations будет иметь следующий
вид:
function Red(du, u, h, p, t)
w, q, q_avg = u
hist1 = h(p, t - T)[1]
du[1] = 1.0 / T -
-(w * hist1 * pr / (2.0 * T))
du[2] = qAdd(q,w,T,C,N,R)
du[3] = -wq * C * q_avg + wq * C * q
end
В функции Red также зададим ограничения для параметров 𝑤, 𝑞, 𝑞^(𝑡).
if (w <= 1.0)
w = 1.0
end
if (q >= R)
q = R
end
if (q_avg >= R)
q_avg = R
end
Далее зададим функцию изменения параметра 𝑞.
function qAdd(q,w,T,C,N,R)
q1 = N * w / T - C
q2 = q + q1
if q2 > R
return R - q
elseif q2 > 0
return q1
else
return -q
end
end
Одним из мощных инструментов пакета DifferentialEquations являются обратные вызовы (callbacks), для
работы с которыми определяются две функции. Функция условия (condition function) необходима для проверки
того, произошло ли некоторое событие. Воздействующая функция (affect function) будет выполняться, если
событие произошло.
Дискретная функция сброса пакетов реализуется как контроллер, который обновляется каждые 0.01 сек
до достижения времени моделирования tf. Массив tstops определяет интервалы выборки проверки условия,
функция condition_control_loop проверяет является ли t одним из экземпляров выборки:
7

Рис. 2. Поведение параметров 𝑤(𝑡), 𝑞(𝑡), 𝑞^(𝑡) по результатам моделирования на языке Julia

tf = 30.0
tstops = collect(0:0.01:tf)
function condition_control_loop(u,t,integrator)
(t in tstops)
end

Далее определим функцию воздействия, которая и является контроллером. Функция control_loop! на каждом
шаге вычисляет новое значение вероятностной функции сброса пакетов 𝑝 в зависимости от текущих значений
параметров 𝑤, 𝑞, 𝑞^(𝑡) в соответствии с формулой (4):

function control_loop!(integrator)
global pr

w = integrator.u[1]
q = integrator.u[2]
q_avg = integrator.u[3]

if (q_avg < q_min * R)


pr = 0.0
elseif (q_avg > q_max * R)
pr = 1.0
else pr = p_max * (q_avg/R - q_min) / (q_max - q_min)
end
end

Зададим обратный вызов дискретного типа:

cb = DiscreteCallback(condition_control_loop, control_loop!)

Наконец, определим вектор начального состояния системы, время моделирования и вызовем решатель пакета
DDEProblem, в аргументы которого передается функция Red, вектор начальных состояний системы, время
моделирования и параметры задержки переменных:

u0 = [1.0, 0.0, 0.0]


tspan = (0.0, tf)
prob = DDEProblem(Red, u0, h, tspan, p, constant_lags=lags)
alg = MethodOfSteps(Tsit5())
sol = solve(prob, alg, callback = cb, tstops=tstops)

В результате моделирования получим график изменения размера окна TCP Reno, отражающий динамику
управления перегрузкой TCP, а также график среднего размера очереди, отражающий динамику очереди в
маршрутизаторе (или шлюзе) с модулем управления очередью по алгоритму RED (рис. 2).
8

V. РЕЗУЛЬТАТЫ

В результате исследования получены два программных комплекса, созданных на языках программирования


Modelica и Julia. Оба этих комплекса реализуют одну и ту же математическую модель сети передачи данных с
модулем активного управления трафиком, работающим по алгоритму RED.
Численный эксперимент, проведённый в рамках обоих программных комплексов, даёт сопоставимые результаты
(см. рис. 1 и рис. 2).

VI. ОБСУЖДЕНИЕ

Оба языка программирования, и Modelica, и Julia являются предметно-ориентированными языками. Впрочем,


Julia при этом рассматривается как общий язык научных расчётов, а Modelica как специализированный язык
моделирования динамических систем, непрерывных и гибридных.
Математическая модель алгоритма RED сформулирована в рамках гибридного подхода. Поэтому в рамках
языка Modelica её реализация вышла достаточно простой. На этом языке очень естественно, с помощью
высокоуровневых средств производится запись обыкновенных дифференциальных уравнений с запаздывающим
аргументом. Кроме того, использование дискретных элементов реализовано весьма наглядно.
Язык Julia направлен на решение более широкого круга задач. Поэтому он не обладает таким количеством
синтаксического сахара, как более специализированная Modelica. В частности, реализация гибридной парадигмы
в Julia требует более высокой квалификации программиста, чем при работе с языком Modelica.
Для специализированного применения Julia требует большего уровня знаний, нежели специализированные
языки, такие, как Modelica. Впрочем, Julia является также и метаязыком, и может служить основой для
конструирования других языков. Например, расширение Modia [17, 18] было сделано для миграции программ с
Modelica на Julia (и, возможно, и в обратном направлении).

VII. ЗАКЛЮЧЕНИЕ

Авторами было продемонстрировано применение непрерывно-дискретного подхода к моделированию нели-


нейных систем с управлением. В качестве моделируемой системы выступала система, состоящая из входящего
потока, обрабатываемого согласно протоколу TCP, а также маршрутизатора, обрабатывающего трафик по
алгоритму типа RED.
В результате сравнения программных реализаций на языках программирования Modelica и Julia проде-
монстрирована простота моделирования гибридных систем в Modelica, где непрерывные элементы системы,
реализованные с помощью системы дифференциальных уравнений, хорошо взаимодействует с дискретной
функцией сброса пакетов. Ограничения для некоторых параметров системы задается с помощью оператора
when. Реализация запаздывания также возможна для элементов системы любого характера функционирования.
Julia также дает возможность моделировать системы согласно гибридной парадигме. Пакет DifferentialEquations
позволяет решать системы дифференциальных уравнений различных видов, в том числе и дифференциальные
уравнения с запаздыванием. Непрерывная вероятностная функция успешно реализована с использованием
опции обратных вызовов. Запаздывающий аргумент непрерывной функции был реализован с помощью функции
истории h(p, t).
Таким образом, авторами были изучены возможности языков программирования Modelica и Julia при модели-
ровании гибридных систем, содержащих как непрерывные, так и дискретные аспекты поведения. Проведено
численное моделирование процесса передачи данных по протоколу TCP и процесса регулирования алгорит-
мом RED состояния потока при возникновении перегрузок, получены графики, демонстрирующие изменения
основных параметров системы.
9

БЛАГОДАРНОСТИ

Публикация подготовлена при при финансовой поддержке РФФИ в рамках научного проекта № 19-01-00645.

[1] Korolkova A. V., Velieva T. R., Abaev P. A., Sevastianov L. A., Kulyabov D. S. Hybrid Simulation Of Active Traffic
Management // Proceedings 30th European Conference on Modelling and Simulation. — 2016. — 6. — P. 685–691.
[2] Färnqvist D., Strandemar K., Johansson K. H., Hespanha J. P. Hybrid Modeling of Communication Networks Using
Modelica // The 2nd International Modelica Conference. — 2002. — P. 209–213.
[3] Korolkova A. V., Kulyabov D. S., Velieva T. R., Zaryadov I. S. Essay on the study of the self-oscillating regime in the
control system // 33 European Conference on Modelling and Simulation, ECMS 2019 / Ed. by M. Iacono, F. Palmieri,
M. Gribaudo, M. Ficco. — Vol. 33 of Communications of the ECMS. — Caserta : European Council for Modelling and
Simulation, 2019. — 6. — P. 473–480.
[4] Kulyabov D. S., Korolkova A. V., Velieva T. R., Eferina E. G., Sevastianov L. A. The Methodology of Studying of Active
Traffic Management Module Self-oscillation Regime // DepCoS-RELCOMEX 2017. Advances in Intelligent Systems and
Computing / Ed. by W. Zamojski, J. Mazurkiewicz, J. Sugier, T. Walkowiak, J. Kacprzyk. — Cham : Springer International
Publishing, 2018. — Vol. 582 of Advances in Intelligent Systems and Computing. — P. 215–224.
[5] Floyd S., Jacobson V. Random Early Detection Gateways for Congestion Avoidance // IEEE/ACM Transactions on
Networking. — 1993. — Vol. 1, no. 4. — P. 397–413.
[6] Misra V., Gong W.-B., Towsley D. Fluid-Based Analysis of a Network of AQM Routers Supporting TCP Flows with an
Application to RED // ACM SIGCOMM Computer Communication Review. — 2000. — 10. — Vol. 30, no. 4. — P. 151–160.
[7] Misra V., Gong W.-B., Towsley D. Stochastic Differential Equation Modeling and Analysis of TCP-Windowsize Behavior //
Proceedings of PERFORMANCE. — 1999. — Vol. 99.
[8] Korolkova A. V., Kulyabov D. S., Sevastianov L. A. Combinatorial and Operator Approaches to RED Modeling //
Mathematical Modelling and Geometry. — 2015. — Vol. 3, no. 3. — P. 1–18.
[9] Hnatič M., Eferina E. G., Korolkova A. V., Kulyabov D. S., Sevastyanov L. A. Operator Approach to the Master Equation
for the One-Step Process // EPJ Web of Conferences. — 2016. — Vol. 108. — P. 02027. — arXiv : 1603.02205.
[10] Fritzson P. Principles of Object-Oriented Modeling and Simulation with Modelica 2.1. — Wiley-IEEE Press, 2003. — 939 p.
[11] Fritzson P. Introduction to Modeling and Simulation of Technical and Physical Systems with Modelica. — Hoboken, NJ,
USA : John Wiley & Sons, Inc., 2011.
[12] Apreutesey A.-M. Y., Korolkova A. V., Kulyabov D. S. Modeling RED algorithm modifications in the OpenModelica //
Proceedings of the Selected Papers of the 9th International Conference "Information and Telecommunication Technologies and
Mathematical Modeling of High-Tech Systems" (ITTMM-2019), Moscow, Russia, April 15-19, 2019 / Ed. by D. S. Kulyabov,
K. E. Samouylov, L. A. Sevastianov. — Vol. 2407 of CEUR Workshop Proceedings. — Moscow, 2019. — 4. — P. 5–14.
[13] Bezanson J., Karpinski S., Shah V. B., Edelman A. Julia: A Fast Dynamic Language for Technical Computing. — 2012. —
P. 1–27. — arXiv : 1209.5145.
[14] Bezanson J., Edelman A., Karpinski S., Shah V. B. Julia: A fresh approach to numerical computing // SIAM Review. —
2017. — 1. — Vol. 59, no. 1. — P. 65–98. — arXiv : 1411.1607.
[15] Joshi A., Lakhanpal R. Learning Julia. — Packt Publishing, 2017. — 316 p.
[16] Rackauckas C., Nie Q. DifferentialEquations.jl – A Performant and Feature-Rich Ecosystem for Solving Differential Equations
in Julia // Journal of Open Research Software. — 2017. — Vol. 5, no. May.
[17] Elmqvist H., Henningsson T., Otter M. Systems Modeling and Programming in a Unified Environment Based on Julia //
Leveraging Applications of Formal Methods, Verification and Validation: Discussion, Dissemination, Applications. ISoLA
2016 / Ed. by T. Margaria, B. Steffen. — Cham : Springer, 2016. — Vol. 9953 of Lecture Notes in Computer Science. —
P. 198–217.
[18] Otter M., Elmqvist H. Transformation of Differential Algebraic Array Equations to Index One Form // Proceedings of the
12th International Modelica Conference, Prague, Czech Republic, May 15-17, 2017. — Vol. 132. — 2017. — jul. — P. 565–579.

You might also like