Добавил:
СПбГУТ * ИКСС * Программная инженерия Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Курсовой проект / ММвСС. Программа на C++ для курсовой работы (выглядит не очень, но работает правильно)

.doc
Скачиваний:
114
Добавлен:
15.01.2020
Размер:
71.17 Кб
Скачать

Код программы

#include <iostream>

#include <fstream>

#include <iomanip>

#include <vector>

#include <algorithm>

#include <ctime>

#include <numeric>

#include <sstream>

int DC, ACCURACY;

using namespace std;

using float_type = long double;

void original_Floyd_Warshall(vector<vector<float_type>> &matrixR1, vector<vector<int>> &matrixR2) {

int n = matrixR1.size(); // алгоритм работает правильно при условии matrixR1 = distance_matrix

float_type x, y;

for (int i = 0; i < n; ++i) {

iota(matrixR2[i].begin(), matrixR2[i].end(), 1);

}

for (int k = 0; k < n; ++k) {

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

if (i != j && i != k && j != k) {

x = matrixR1[i][k] + matrixR1[k][j];

y = matrixR1[i][j];

if (x < y) {

matrixR1[i][j] = x;

matrixR2[i][j] = matrixR2[i][k];

}

}

}

}

}

}

vector<vector<float_type>> load_intensity(const vector<vector<float_type>> &matrixY, vector<vector<int>>

&matrixR2) {

int n = matrixY.size();

vector<vector<float_type>> matrixY_hatch(n, vector<float_type>(n, 0));

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

matrixY_hatch[i][matrixR2[i][j] - 1] += matrixY[i][j];

for (int k = matrixR2[i][j] - 1; k != j; k = matrixR2[k][j] - 1) {

matrixY_hatch[k][matrixR2[k][j] - 1] += matrixY[i][j];

}

}

}

return matrixY_hatch;

}

vector<vector<int>> gen_streams_matrix(vector<vector<float_type>> &matrixY_hatch, float_type quality) {

int n = matrixY_hatch.size();

float_type p_max = 1. - quality;

vector<vector<int>> matrixV(n, vector<int>(n, 0));

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

int v = 0;

if (matrixY_hatch[i][j] != 0) {

v = 1;

float_type p = 1, y = matrixY_hatch[i][j], numerator = y, sum = y;

while (p > p_max) {

++v;

numerator = ( numerator / v ) * y;

sum += numerator;

p = numerator / sum;

}

}

matrixV[i][j] = v;

}

}

return matrixV;

}

void calc_delays(const vector<vector<int>> &Rij,

const vector<vector<int>> &Aij,

const vector<vector<float_type>> &Bij,

vector<vector<float_type>> &Tij,

float_type L) {

int n = Tij.size();

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

if (Rij[i][j] == j + 1 && i != j) {

Tij[i][j] = ( 8. * L ) / ( Bij[i][j] - Aij[i][j] ); // задержка M/M/1

} else { Tij[i][j] = 0; }

}

}

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

if (Rij[i][j] != j + 1) {

Tij[i][j] += Tij[i][Rij[i][j] - 1];

for (int k = Rij[i][j] - 1; k != j; k = Rij[k][j] - 1) {

Tij[i][j] += Tij[k][Rij[k][j] - 1];

}

}

}

}

}

float_type calc_O(const vector<vector<float_type>> &Tij, float_type T0) {

double O = 0;

for (auto &str : Tij) {

for (auto &t : str) {

O += ( t - T0 / 2 ) * ( t - T0 / 2 );

}

}

return O;

}

vector<vector<float_type>> optimize_BMatrix_sub(const vector<vector<int>> &Rij,

const vector<vector<int>> &Aij,

vector<vector<float_type>> &Bij,

float_type T0,

float_type L) {

int bestI = 0, bestJ = 0, n = Bij.size();

float_type q = 1e+10, bestO = q;

vector<vector<float_type>> Tij(n, vector<float_type>(n, 0));

while (true) {

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

if (Bij[i][j] != 0) {

Bij[i][j] += DC;

calc_delays(Rij, Aij, Bij, Tij, L);

Bij[i][j] -= DC;

float_type O = calc_O(Tij, T0);

if (O < bestO) {

bestO = O, bestI = i, bestJ = j;

}

}

}

}

if (bestO < q) {

Bij[bestI][bestJ] += DC;

q = bestO;

} else { break; }

}

return Tij;

}

bool check_optimize(const vector<vector<float_type>> &Tij, float_type T0) {

return find_if(Tij.begin(), Tij.end(), [&T0](auto v) {

return any_of(v.begin(), v.end(), [&T0](auto x) {

return x > T0 / 2;

}) != 0;

}) == Tij.end();

}

pair<float_type, vector<vector<float_type>>> optimize_BMatrix(const vector<vector<int>> &Rij,

const vector<vector<int>> &Aij,

vector<vector<float_type>> &Bij,

float_type T0,

float_type L,

bool is_optimizeT0) {

auto old_T0 = T0, dT = T0 / ACCURACY;

auto Tij = optimize_BMatrix_sub(Rij, Aij, Bij, T0, L);

while (is_optimizeT0 && !check_optimize(Tij, old_T0) && ( T0 -= dT ) > 1e-20) {

Tij = optimize_BMatrix_sub(Rij, Aij, Bij, T0, L);

}

return make_pair(T0, Tij);

}

template <class T>

void print_vector(std::ostream &os, const vector<T> &matrix) {

for (auto &s : matrix)

os << s << ' ';

os << endl << endl;

}

template <class T>

void print_matrix(std::ostream &os, const vector<vector<T>> &matrix) {

for (auto &s : matrix) {

for (auto &t : s)

os << t << ' ';

os << endl;

}

os << endl;

}

int main() {

/* Считывание данных с файла */

auto start = clock();

int n, a0, optimizeT0;

float_type y0, L, quality, T0;

ifstream file_in("input_file.txt");

if (!file_in.is_open()) {

cout << "Error opening file 'input_file.txt'" << endl;

return 1;

}

stringstream s;

while (!file_in.eof()) {

string param;

getline(file_in, param);

s << param.substr(0, param.find(';')) << ' ';

}

file_in.close();

s >> n >> y0 >> a0 >> L >> quality >> T0 >> optimizeT0 >> DC >> ACCURACY;

vector<float_type> subscribers(n, 0);

for (auto &sub : subscribers)

s >> sub;

vector<vector<float_type>> distance_matrix(n, vector<float_type>(n, 0));

for (auto &str : distance_matrix)

for (auto &d : str)

s >> d;

/* Расчет и запись результатов в выходной файл */

cout << "Please, wait!.." << endl;

ofstream file_out("output_file.txt");

if (!file_out.is_open()) {

cout << "Error opening file 'output_file.txt'" << endl;

return 2;

}

file_out << setprecision(std::numeric_limits<float_type>::digits10);

/* 1. Интенсивности производимого в узлах сети трафика */

file_out << "1. Интенсивности производимого в узлах сети трафика" << endl;

vector<float_type> matrixY(subscribers);

transform(matrixY.begin(), matrixY.end(), matrixY.begin(), [&y0](auto n) { return n * y0; });

print_vector(file_out, matrixY);

/* 2. Коэффициенты распределения трафика по направлениям связи */

file_out << "2. Коэффициенты распределения трафика по направлениям связи" << endl;

auto sum = accumulate(matrixY.begin(), matrixY.end(), 0.L);

vector<float_type> matrixK(matrixY);

transform(matrixK.begin(), matrixK.end(), matrixK.begin(), [&sum](auto n) { return n / sum; });

print_vector(file_out, matrixK);

/* 3. Матрица интенсивностей трафика в направлениях связи */

file_out << "3. Матрица интенсивностей трафика в направлениях связи" << endl;

vector<vector<float_type>> matrixYij(n, vector<float_type>(n, 0));

for (int i = 0; i < n; ++i)

for (int j = 0; j < n; ++j)

matrixYij[i][j] = matrixY[i] * matrixK[j];

print_matrix(file_out, matrixYij);

/* 4. Матрицы кратчайших расстояний и кратчайших маршрутов между вершинами графа */

vector<vector<float_type>> matrixR1(distance_matrix);

vector<vector<int>> matrixR2(n, vector<int>(n, 0));

original_Floyd_Warshall(matrixR1, matrixR2);

file_out << "4.1. Матрица кратчайших расстояний между вершинами графа" << endl;

print_matrix(file_out, matrixR1);

file_out << "4.2. Матрица кратчайших маршрутов между вершинами графа" << endl;

print_matrix(file_out, matrixR2);

/* 5. Матрица интенсивностей нагрузок на линиях связи */

file_out << "5. Матрица интенсивностей нагрузок на линиях связи" << endl;

auto matrixY_hatch = load_intensity(matrixYij, matrixR2);

print_matrix(file_out, matrixY_hatch);

/* 6. Матрица потоков */

file_out << "6. Матрица потоков" << endl;

auto streams_matrix = gen_streams_matrix(matrixY_hatch, quality);

print_matrix(file_out, streams_matrix);

/* 7. Матрица интенсивности трафика ПД для линий связи */

file_out << "7. Матрица интенсивности трафика ПД для линий связи" << endl;

vector<vector<int>> Aij(streams_matrix);

for (auto &str : Aij) {

transform(str.begin(), str.end(), str.begin(), [&a0](auto v) { return v * a0; });

}

print_matrix(file_out, Aij);

/* 8. Матрица пропускных способностей */

file_out << "8. Матрица пропускных способностей (бит/с)" << endl;

vector<vector<float_type>> Bij(n, vector<float_type>(n, 0));

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

Bij[i][j] = ( Aij[i][j] ) ? ( Aij[i][j] + ( 8. * L ) / T0 ) : 0;

}

}

print_matrix(file_out, Bij);

cout << "1-8 Time: " << ( clock() - start ) / 1000.L << " s." << endl;

start = clock();

/* 9. и 10. Матрицы задержек и оптимизированных пропускных способностей */

auto pair = optimize_BMatrix(matrixR2, Aij, Bij, T0, L, static_cast<bool>(optimizeT0));

file_out << "9. Матрица задержек" << endl;

print_matrix(file_out, pair.second);

file_out << "10. Матрица оптимизированных пропускных способностей (бит/с)" << endl;

print_matrix(file_out, Bij);

file_out << "Оптимизированное T: " << pair.first << endl;

file_out.close();

cout << "Optimization Time: " << ( clock() - start ) / 1000.L << " s." << endl;

cout << "Done. Data was written to file 'output_file.txt'!" << endl;

}

Файл с входными данными «input_file.txt» для программы

; Комментарий начинается с ;

; Порядок и количество чисел во входном файле должны быть одними и теми же

; [Основные параметры]

20 ; n - количество узлов в сети связи (влияет на матрицу расстояний и вектор кол-ва абонентов)

0.1 ; y0 - интенсивность удельной абонентской нагрузки (Эрл)

85600 ; a0 - скорость потока для кодека (бит/с)

200 ; L - длина пакета (байт, не бит!)

0.98 ; (98%) q - доля вызовов, обслуженных с гарантированным качеством

0.1 ; T0 - начальное требование к величине задержки (сек)

0 ; оптимизация величины задержки T0: 1 - оптимизировать, 0 - не оптимизировать

10000 ; DC - шаг изменения пропускной способности (чем меньше, тем точнее, но дольше)

10000 ; ACCURACY - точность (чем больше, тем точнее, но дольше)

; [Количество абонентов в каждом узле связи]

6580 4091 4272 7028 8554 5530 7131 6179 8168 8737 2610 6691 3031 1201 6305 9593 8619 6808 5623 1473

; [Матрица расстояний]

; Там, где нет прямого пути, должно быть большое число (например, 90000000000)

0 34.49588418 90000000000 34.62873101 90000000000 90000000000 27.19784379 57.56898522 90000000000 90000000000 90000000000 13.3461535 90000000000 23.27514291 90000000000 55.08523583 90000000000 40.41705728 19.877249 90000000000

34.49588418 0 96.07354999 15.25732875 90000000000 90000000000 90000000000 90000000000 80.42518497 90000000000 90000000000 96.37038112 90000000000 35.14534831 90000000000 33.35024714 90000000000 75.75070262 39.03695941 72.11233974

90000000000 96.07354999 0 21.70084119 38.61907125 54.83081937 90000000000 90000000000 90000000000 71.40205503 90000000000 5.624562502 58.88312459 90000000000 90000000000 90000000000 90000000000 41.72714353 90000000000 41.20844007

34.62873101 15.25732875 21.70084119 0 90000000000 90000000000 33.88914466 90000000000 90000000000 49.19576049 89.13988471 97.23739028 32.52148032 43.08785796 90000000000 27.76278853 90000000000 17.277807 90000000000 90000000000

90000000000 90000000000 38.61907125 90000000000 0 90000000000 90000000000 59.86605287 90000000000 90000000000 90000000000 90000000000 67.84968972 82.18536973 90000000000 29.61130738 90000000000 90000000000 10.86907983 61.78618073

90000000000 90000000000 54.83081937 90000000000 90000000000 0 90000000000 60.85025668 34.3339622 88.30015063 90000000000 66.00028872 89.05064464 91.21629596 32.31169581 86.21379733 90.86205363 90000000000 90000000000 99.6157825

27.19784379 90000000000 90000000000 33.88914466 90000000000 90000000000 0 98.15047383 89.67960477 71.1760819 74.71998334 90000000000 59.08287168 90000000000 30.65889478 90000000000 90000000000 90000000000 12.01284528 90000000000

57.56898522 90000000000 90000000000 90000000000 59.86605287 60.85025668 98.15047383 0 90000000000 90000000000 90000000000 17.14271903 52.38561034 90000000000 90000000000 14.59316611 90000000000 57.78555274 36.37256026 60.31021476

90000000000 80.42518497 90000000000 90000000000 90000000000 34.3339622 89.67960477 90000000000 0 90000000000 90000000000 85.3002131 9.224516153 55.07417321 90000000000 83.05736184 79.35104966 25.89040399 90000000000 65.21392465

90000000000 90000000000 71.40205503 49.19576049 90000000000 88.30015063 71.1760819 90000000000 90000000000 0 82.26520419 90000000000 24.80298877 38.71943355 90000000000 14.98219371 90000000000 90000000000 61.73030734 90000000000

90000000000 90000000000 90000000000 89.13988471 90000000000 90000000000 74.71998334 90000000000 90000000000 82.26520419 0 21.79401517 90000000000 87.93790936 90000000000 94.02931333 90000000000 90000000000 90000000000 90000000000

13.3461535 96.37038112 5.624562502 97.23739028 90000000000 66.00028872 90000000000 17.14271903 85.3002131 90000000000 21.79401517 0 15.70829749 48.60438704 90000000000 80.9660852 3.185600042 26.37099624 90000000000 90000000000

90000000000 90000000000 58.88312459 32.52148032 67.84968972 89.05064464 59.08287168 52.38561034 9.224516153 24.80298877 90000000000 15.70829749 0 90000000000 15.25397897 90000000000 65.35020471 62.00705171 90000000000 55.03235459

23.27514291 35.14534831 90000000000 43.08785796 82.18536973 91.21629596 90000000000 90000000000 55.07417321 38.71943355 87.93790936 48.60438704 90000000000 0 7.486122847 17.9464519 20.26621699 90000000000 35.05436778 24.96415973

90000000000 90000000000 90000000000 90000000000 90000000000 32.31169581 30.65889478 90000000000 90000000000 90000000000 90000000000 90000000000 15.25397897 7.486122847 0 41.11779332 90000000000 90000000000 90000000000 90000000000

55.08523583 33.35024714 90000000000 27.76278853 29.61130738 86.21379733 90000000000 14.59316611 83.05736184 14.98219371 94.02931333 80.9660852 90000000000 17.9464519 41.11779332 0 90000000000 90000000000 34.93718505 67.04439521

90000000000 90000000000 90000000000 90000000000 90000000000 90.86205363 90000000000 90000000000 79.35104966 90000000000 90000000000 3.185600042 65.35020471 20.26621699 90000000000 90000000000 0 90000000000 5.313688517 16.6418612

40.41705728 75.75070262 41.72714353 17.277807 90000000000 90000000000 90000000000 57.78555274 25.89040399 90000000000 90000000000 26.37099624 62.00705171 90000000000 90000000000 90000000000 90000000000 0 90000000000 90000000000

19.877249 39.03695941 90000000000 90000000000 10.86907983 90000000000 12.01284528 36.37256026 90000000000 61.73030734 90000000000 90000000000 90000000000 35.05436778 90000000000 34.93718505 5.313688517 90000000000 0 90000000000

90000000000 72.11233974 41.20844007 90000000000 61.78618073 99.6157825 90000000000 60.31021476 65.21392465 90000000000 90000000000 90000000000 55.03235459 24.96415973 90000000000 67.04439521 16.6418612 90000000000 90000000000 0