Инструментальная среда имитационного моделирования распределенных систем мобильных агентов



страница21/21
Дата07.03.2016
Размер2.3 Mb.
1   ...   13   14   15   16   17   18   19   20   21

Приложение 34 Program.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows.Forms;


namespace Automata {

static class Program {

///

/// Главная точка входа для приложения.

///

[STAThread]

static void Main() {

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());

}

}

}



Приложение 35 State.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;
namespace Automata {

class Arc {

public static int IN = 1;

public static int OUT = 2;

public Place p,p0;

public Port port;

public int in_out;

public Arc(Place i_place, Port i_port) {

p = i_place;

port = i_port;

}

}
class Res {



public Type type;

public string name;

}
class Const:Res {

public int id; //номер константы в модели

public Const(string i_name) {

name = i_name;

}

}

class Var:Res {



public Var(string i_name) {

name = i_name;

}

}
class Port {



public Type type;

public string name;

public Port(string i_name) {

name = i_name;

}

}
class Place {



public string name;

public bool is_expanded = true;

public int id; //номер места в модели

public List list_in = new List();

public List list_out = new List();

public List list_inst = new List();

public Place(string i_name) {

name = i_name;

}

public void set_is_expanded(bool i_is_expanded){



is_expanded = i_is_expanded;

}
}


class Type {

public int id; // номер типа в модели

public string name;

public List list_const = new List();

public List list_var = new List();

public List


list_port = new List
();

public List list_trans = new List();

public List list_states = new List();

public Hashtable States = new Hashtable();

public List list_regs = new List();

public Hashtable Registers = new Hashtable();

public State initial_state;

public Type(string i_name) {

name = i_name;

}

}


class Term {

public static int c = 1;

public static int v = 2;

public Port port;

public int cv;

public Res res;

public State state = null;

public Term(Port i_port, Const i_con) {

port = i_port;

res = i_con; cv = Term.c;

}

public Term(Port i_port, Var i_var) {



port = i_port;

res = i_var; cv = Term.v;

}

}
class Transition {



public static int default_priority = 100;

public static float default_duration = 0;

public static float default_wait = 0;

public char symbol = 'o';

public string name = null;

public int id; // номер перехода в данном состоянии (внутренний id)

public string chart_name = null;

public State state_from, state_to;

public int priority = Transition.default_priority;

public Double duration_min = Transition.default_duration

, duration_max = Transition.default_duration;

public Double wait_min = Transition.default_wait

, wait_max = Transition.default_wait;

// public double time_enable = -1.0;

public Transition(State i_state_from, State i_state_to) {

state_from = i_state_from;

state_to = i_state_to;

if(name == null) {

name = state_from.name + "->" + state_to.name;

chart_name = name;

}

// time_enable = -1.0;



}

public List list_reset = new List(); // only for registers of type rt_timer

public List list_constr = new List();

public List list_term_in = new List();

public List list_term_out = new List();

public double get_wait_time() {

return Lib.get_random_from_interval(wait_min,wait_max);

}

public double get_duration_time() {



return Lib.get_random_from_interval(duration_min,duration_max);

}

public bool has_timed_constraints() {



if(list_constr.Count > 0 || list_reset.Count > 0) {

return true;

}

return false;



}

}

class State {



public string name;

public string chart_name;

public Type type;

public char symbol = 'o';

public int id; //номер состояния в типе

public List list_trans = new List();

public State(string i_name, Type i_type) {

name = i_name;

chart_name = i_name;

type = i_type;

}

}
enum RegType { rt_int, rt_timer };



class Register {
public string name;

public RegType reg_type;

public int id; // номер регистра в типе

public Register(string i_name, RegType i_reg_type) {

name = i_name;

reg_type = i_reg_type;

}

}
enum ConstraintRelation { gt, ge, lt, le, eq };


class Constraint {

public int a=0, b=0, c=0;

public Register r1 = null, r2 = null;

public ConstraintRelation rel=ConstraintRelation.gt;

public string title() {

return title(false);

}

public string title(bool i_esc) {



string ss = r1.name;

if(r2 != null) {

ss += (b == -1) ? "-" : "+";

ss += r2.name;

}

switch (rel){



case ConstraintRelation.lt: ss += i_esc ? "<" : "<";break;

case ConstraintRelation.le: ss += i_esc ? "≤" : "<=";break;

case ConstraintRelation.gt: ss += i_esc ? ">" : ">";break;

case ConstraintRelation.ge: ss += i_esc ? "≥" : ">=";break;

case ConstraintRelation.eq: ss += "=";break;

}

ss += ""+c;


return ss;

}

}


class Instance {

public static int flag_busy = 1;

public static int flag_free = 2;

public static int flag_consumed = 3;

public Const con;

public State current_state;

double saved_global_time = 0.0;

public bool is_visual = false;

public double[] registers = new double[0];

public double[] trans_fire_time = new double[0];

// public Transition current_trans;

public Step current_step;

public int n_last_trace = -1;

public int flag = flag_free;

public Place place;

public Model model;

public void set_place(Place i_place) {

place = i_place;

place.list_inst.Add(this);

}

public Instance(Model i_model,Const i_con, State i_state) {



con = i_con;

model = i_model;

current_state = i_state;

}

public Instance(Model i_model, Const i_con) {



con = i_con;

model = i_model;

if(con.type.initial_state != null) {

current_state = con.type.initial_state;

}

}

public void set(State i_state) {



if(this.current_state == i_state) {

return; // nothing to do

}

//Model.write_change(this,;



}

public void discharge_transition(Transition trans) {

trans_fire_time[trans.id] = -1.0;

}

public bool charge_transition(Transition trans, double i_fire_time) {



if(trans_fire_time[trans.id] == -1.0) {

trans_fire_time[trans.id] = i_fire_time;

return true;

} else {


return false; // already enabled

}

}



public bool is_ready_to_fire(Transition trans, double i_current_time

, double i_fire_time) {

if(i_fire_time <= i_current_time) {

return true; // is already ready to fire!

}

if(trans_fire_time[trans.id] > i_current_time



|| trans_fire_time[trans.id] == -1.0

) {


return false; // is not yet ready to fire

}

return true; // is ready to fire!



}

private bool check_charge_transition2(Transition trans

, double i_current_time, double i_fire_time) {

/*

Form1.log("trans.id=" + trans.id



+ " trans_fire_time[id]=" + trans_fire_time[trans.id]

+ " i_current_time=" + i_current_time

+ " i_fire_time=" + i_fire_time

);

*/



if(is_ready_to_fire(trans, i_current_time, i_fire_time)) {

// Form1.log("return true");

return true;

}

// Form1.log("charge and return false");



charge_transition(trans, i_fire_time);

return false;

}

// Timers!



public void start_timers(double i_global_time) {

registers = new double[con.type.list_regs.Count];

for(int i = 0; i < registers.Length; i++) {

registers[i] = 0.0;

}

saved_global_time = i_global_time;



}

public void move_timers(double i_global_time) {

double delta_t = Math.Round(i_global_time - saved_global_time,2);

foreach(Register reg in con.type.list_regs) {

if(reg.reg_type == RegType.rt_timer) {

registers[reg.id] += delta_t;

}

}

saved_global_time = i_global_time;



}

public void reset_timers(Transition trans, double i_global_time) {

move_timers(i_global_time);

foreach(Register reg in trans.list_reset) {

registers[reg.id] = 0.0;

}

}



public double get_satisfy_time(Transition trans) {

/*

* Возвращает:



* 0 - если выполняется сейчас

* -1 - не выполнится никогда

* >0 - когда выполнится

* Должны использоваться данные из таймеров.

*

*/

double ret_value = 0.0;



double x1=0, x2=0, c0=0;

foreach(Constraint constr in trans.list_constr){

Form1.log(""+constr.title());

if(constr.r1 == null) {

x1 = 0;

} else {


x1 = this.registers[constr.r1.id];

}

if(constr.r2 == null) {



x2 = 0;

} else {


x2 = this.registers[constr.r2.id];

}

c0 = constr.a * x1 + constr.b * x2;



Form1.log("get_satisfy_time: x1=" + x1 + " x2=" + x2 + " c0=" + c0 + " c=" + constr.c);

bool constr_true = false;

switch(constr.rel) {

case ConstraintRelation.lt:

constr_true = (c0 < constr.c);

Form1.log("lt=" + constr_true);

break;

case ConstraintRelation.le:



constr_true = (c0 <= constr.c);

Form1.log("le=" + constr_true);

break;

case ConstraintRelation.gt:



constr_true = (c0 > constr.c);

Form1.log("gt=" + constr_true);

break;

case ConstraintRelation.ge:



constr_true = (c0 >= constr.c);

Form1.log("ge=" + constr_true);

break;

case ConstraintRelation.eq:



constr_true = (c0 == constr.c);

Form1.log("eq=" + constr_true);

break;

default:


break;

}

if(constr_true) {



Form1.log("get_satisfy_time: do_nothing");

// do_nothing

} else { // констрейнт не сейчас выполняется

if(constr.a + constr.b == 0) { // никогда не выполнится

ret_value = -1;

} else {


double t = 0.0;

t = (constr.c - constr.a * x1 - constr.b * x2) / (constr.a + constr.b);

Form1.log("get_satisfy_time: t="+t);

if(t < 0) { // никогда не выполнится

ret_value = -1;

}else{


double round_t = Math.Round(t,2);

if(round_t < t) {

round_t += 0.01;

}

switch(constr.rel) {



case ConstraintRelation.lt:

case ConstraintRelation.gt:

if(round_t == t){

round_t += 0.01;

}

break;


default:

break;


}

Form1.log("get_satisfy_time: round_t=" + round_t);

t = round_t;

if((ret_value == 0 || ret_value > t && ret_value > 0) && t>0) {

ret_value = t;

}

}



}

}

}



return ret_value;

}

// Timers!



public void reset_transitions() {

trans_fire_time = new double[current_state.list_trans.Count()];

for(int i=0; i

trans_fire_time[i] = -1.0;

}

}

}



class Bind {

public Term term; // Входной term из проверяемого перехода

public Instance inst; // соответствующий "пассивный" ресурс

public Arc arc; // Входная дуга

public Bind(Term i_term, Instance i_inst, Arc i_arc) {

term = i_term;

inst = i_inst;

arc = i_arc;

}

}

class Outcome {



public Term term;

public Arc arc;

public Outcome(Term i_term, Arc i_arc){

term = i_term;

arc = i_arc;

}

}



class Step {

public Instance inst; // активный ресурс

public Transition trans; // его проверяемый переход

public string title;

public double start_time; //время старта

public double finish_time; //время завершения

// public int start_n_trace; //номер такта

public Hashtable Binds = new Hashtable();

public Hashtable Vars_in = new Hashtable();

public Hashtable Vars_out = new Hashtable();

public List Outcomes = new List();

public Step(Instance i_inst, Transition i_trans) {

inst = i_inst;

trans = i_trans;

title = inst.place.name + ": "

+ inst.con.name + "/" + inst.current_state.name

+ " --> " + trans.name;

foreach(Constraint constr in trans.list_constr) {

title += "[" + constr.title() + "]";

}

}



}

class Applicant {

public Instance inst;

public List steps = new List();

public Applicant(Instance i_inst) {

inst = i_inst;

}

}

class Point { // TimePoint



public Double time = 0.0;

public List steps = new List();

public int fire_count = 0;

public Point(Double i_time) {

time = i_time;

steps = new List();

}

}
class AgentStateTotal{



public State state;

public double total_time = 0.0;

public int count = 0;

}

class AgentTransTotal {



public Transition trans;

public double total_time = 0.0;

public int count = 0;

}
class AgentTotal {

public Const con;

public int state_count_total = 0, state_count_posible = 0;

public int trans_count_total = 0, trans_count_posible = 0;

public double unstate_total_time = 0.0;

public int unstate_count = 0;

//public List list_states = new List();

public Hashtable states = new Hashtable(); // (AgentStateTotal.state,AgentStateTotal)

public Hashtable transes = new Hashtable(); // (AgentTransTotal.trans,AgentTransTotal)

}
class Trace { // история изменения объектов

public Const con;

public State state;

public Place place;

public Step step;

public Transition trans;

public double time_start;

public double time_finish;

public int n_start;

public int n_finish;

public string show() {

string ss = "" + this.n_start + "\tfin=" + this.n_finish;

ss += "\ttime(" + this.time_start +" - "+ this.time_finish+")";

ss += ": \t\t"+this.con.name;

if (this.place != null){

ss += ":"+place.name;

}

if(this.state != null) {



ss += " " + this.state.name;

}

if(this.trans != null) {



ss += " " + this.trans.state_from.name+" -> "+

this.trans.state_to.name;

}

return ss;



}

}
class Marking {

public string name;

public int last_eq_n_trace; //номер последнего шага с совпадением

public int count; // кол-во попаданий

public bool like = false;

public int[] hash;

public Hashtable places = new Hashtable();

//public Place current_place;

public Marking(string i_name) {

name = i_name;

}

}



class Bound {

public string name;

public Place place = null;

public Type type = null;

public int limit = 0;

public int max_value = 0;

public int min_value = 0;

public int count = 0;

public Bound(string i_name) {

name = i_name;

}
}

}


1 Здесь и далее в таблице приведены ссылки на статью и определения из статьи [3].

Каталог: data -> 2013
2013 -> Программа предназначена для преподавателей, ведущих данную дисциплину, учебных ассистентов и студентов направления подготовки «Журналистика»
2013 -> Программа дисциплины концепции и концептуальный анализ в математике и гуманитарном знании
2013 -> "Применение инструментов конкурентной разведки для анализа конкурентоспособности компании"
2013 -> Программа учебной дисциплины «Психология»
2013 -> Сетевой образовательный клуб «Некрасовская республика»: самоорганизация, саморазвитие, сотворчество. «Некрасовская республика»
2013 -> Информационное сопровождение бизнес проектов


Поделитесь с Вашими друзьями:
1   ...   13   14   15   16   17   18   19   20   21


База данных защищена авторским правом ©uverenniy.ru 2019
обратиться к администрации

    Главная страница