Snej69420 6 mesi fa
parent
commit
1854fe83bb
4 ha cambiato i file con 79 aggiunte e 25 eliminazioni
  1. 20 9
      src/AtomicDEVS.jl
  2. 4 5
      src/CoupledDEVS.jl
  3. 1 1
      src/DEVS2Agents.jl
  4. 54 10
      src/Tracer.jl

+ 20 - 9
src/AtomicDEVS.jl

@@ -1,4 +1,7 @@
 import DataStructures
+using TimerOutputs
+
+const engine_timer = TimerOutput()
 
 @enum Transitions NONE INTERNAL EXTERNAL CONFLUENT
 
@@ -25,8 +28,12 @@ time_advance(agent, model) = error("time_advance not implemented for $(typeof(ag
 output!(agent, model) = nothing
 
 function simulate_devs!(model, duration::Float64=Inf)
-    if model.logging
-        print_initial_conditions(model)
+    if model.logging !== nothing && isempty(model.event_logs)
+        if model.logging == ""
+            print_initial_conditions(model)
+        else
+            log_initial_conditions!(model)
+        end
     end
 
     function stop_condition(model, step_number)
@@ -38,13 +45,17 @@ function simulate_devs!(model, duration::Float64=Inf)
 
     step!(model, stop_condition)
 
-    if model.logging
-        print_trace(model)
+    if model.logging !== nothing
+        if model.logging == ""
+            print_trace(model)
+        else
+            export_trace_to_csv(model, model.logging)
+        end
     end
 end
 
 function send_message!(agent, model, port::Symbol, msg)
-    if model.logging
+    if model.logging !== nothing
         if !haskey(model.out_log, agent.id)
             model.out_log[agent.id] = Dict{Symbol, Vector{Any}}()
         end
@@ -71,7 +82,7 @@ function send_message!(agent, model, port::Symbol, msg)
 end
 
 function route_outputs!(model)
-    if model.logging
+    if model.logging !== nothing
         empty!(model.out_log)
     end
     empty!(model.active_receivers)
@@ -183,8 +194,8 @@ function devs_step!(agent, model)
     end
 
     if is_last_in_batch && !isempty(model.imminent)
-        route_outputs!(model)
-        transition!(model, current_time, agent.id)
+        @timeit engine_timer "route outputs" route_outputs!(model)
+        @timeit engine_timer "transitions" transition!(model, current_time, agent.id)
     end
 end
 
@@ -213,7 +224,7 @@ format_state(agent) = string(agent)
 format_message(msg) = string(msg)
 
 function log_transition!(model, current_time, agent, trans_type)
-    if model.logging
+    if model.logging !== nothing
         in_bag = Dict{Symbol, Vector{Any}}() # copy
         for (k, v) in pairs(agent.inbox)
             if !isempty(v)

+ 4 - 5
src/CoupledDEVS.jl

@@ -11,8 +11,7 @@ Base.@kwdef struct DEVSProperties{M}
     imminent::Vector{Int} = Int[]
     requeue_buffer::Vector{Int} = Int[]
 
-    # logging
-    logging::Bool = false
+    logging::Union{Nothing, String} = nothing
     event_logs::Vector{Any} = []
     out_log::Dict{Int, Any} = Dict{Int, Any}()
 end
@@ -68,7 +67,7 @@ end
 add_in_port!(node::CoupledDEVS, port::String) = add_in_port!(node, Symbol(port))
 add_out_port!(node::CoupledDEVS, port::String) = add_out_port!(node, Symbol(port))
 
-function connect!(parent::CoupledDEVS, source::PortRef, target::PortRef)
+function connect!(parent::CoupledDEVS, source::PortRef, target::PortRef; Z::Function=identity)
     push!(parent.couplings, (source.model_name, source.port_name, target.model_name, target.port_name))
 end
 
@@ -177,7 +176,7 @@ function build_standalone_agents(top_model::CoupledDEVS)
     return agent_list, path_to_id
 end
 
-function initialize_abm(agent_list::Vector{Any}, events::Tuple, path_to_id::Dict{String, Int}, logging::Bool)
+function initialize_abm(agent_list::Vector{Any}, events::Tuple, path_to_id::Dict{String, Int}, logging::Union{Nothing, String})
     concrete_types = unique(typeof.(agent_list))
     AgentUnion = Union{concrete_types...}
 
@@ -277,7 +276,7 @@ function allocate_routing_buffers!(model)
     end
 end
 
-function compile_devs(top_model::CoupledDEVS; logging::Bool=false)
+function compile_devs(top_model::CoupledDEVS; logging::Union{Nothing, String}=nothing)
     agent_list, path_to_id = build_standalone_agents(top_model) # Built Atomic DEVS (Agents)
     model = initialize_abm(agent_list, (UniversalEvent, ), path_to_id, logging) # Initialise Sim Engine
     resolve_direct_couplings!(model, top_model) # Flatten Graph

+ 1 - 1
src/DEVS2Agents.jl

@@ -14,7 +14,7 @@ module DEVS2Agents
     export format_state, format_message, INTERNAL, EXTERNAL, CONFLUENT
 
     export CoupledDEVS, add_submodel!, connect!, compile_devs, ModelRef, PortRef, self
-    export print_trace, print_initial_conditions
+    export print_trace, print_initial_conditions, export_trace_to_csv
 
     export DelayedAtomic, State, Message, Passive, Active
 end

+ 54 - 10
src/Tracer.jl

@@ -1,15 +1,27 @@
-function print_initial_conditions(model)
-    # Sort for deterministic output
+using DelimitedFiles
+using Printf
+
+function _get_sorted_initial_conditions(model)
     path_to_id = model.path_to_id
     sorted_paths = sort(collect(keys(path_to_id)))
 
-    println("\n__  Current Time:   0.000000 __________________________________________ \n")
+    return ((path, path_to_id[path], model[path_to_id[path]]) for path in sorted_paths)
+end
+
+function log_initial_conditions!(model)
+    for (path, id, agent) in _get_sorted_initial_conditions(model)
+        state_str = format_state(agent)
+        ta = time_advance(agent, model)
 
-    for path in sorted_paths
-        id = path_to_id[path]
-        agent = model[id]
+        # Push the INIT row at t=0.0
+        push!(model.event_logs, (0.0, id, :INIT, nothing, nothing, state_str, ta))
+    end
+end
 
-        # These call the model-specific overrides via multiple dispatch
+function print_initial_conditions(model)
+    println("\n__  Current Time:   0.000000 __________________________________________ \n")
+
+    for (path, id, agent) in _get_sorted_initial_conditions(model)
         state_str = format_state(agent)
         ta = time_advance(agent, model)
 
@@ -38,13 +50,12 @@ function print_trace(model)
             current_log_time = time
         end
 
-        # Check if this is the first entry at this specific timestamp
+        # first entry
         is_first_at_time = log === model.event_logs[findfirst(x -> x[1] == time, model.event_logs)]
         leading_nl = is_first_at_time ? "" : "\n"
 
         print("$(leading_nl)\t$(trans_type) TRANSITION in model <$agent_name>\n")
 
-        # --- Formatted Input Ports ---
         print("\t\tInput Port Configuration:\n")
         if in_bag !== nothing && !isempty(in_bag)
             for (port, msgs) in in_bag
@@ -58,7 +69,6 @@ function print_trace(model)
 
         print("\t\tNew State: $state_str\n")
 
-        # --- Formatted Output Ports ---
         print("\t\tOutput Port Configuration:\n")
         if out_msg !== nothing && !isempty(out_msg)
             for (port, msgs) in out_msg
@@ -73,4 +83,38 @@ function print_trace(model)
         next_time_str = next_ta == Inf ? "inf" : string(time + next_ta)
         print("\t\tNext scheduled internal transition at time $next_time_str\n")
     end
+end
+
+function export_trace_to_csv(model, filepath::String)
+    id_to_path = Dict(v => k for (k, v) in model.path_to_id)
+    sort!(model.event_logs, by = x -> x[1])
+
+    open(filepath, "w") do io
+        write(io, "time,model_path,transition_type,next_ta,inputs,outputs,state\n")
+
+        for log in model.event_logs
+            time, id, trans_type, in_bag, out_msg, state_str, next_ta = log
+            model_path = get(id_to_path, id, "Unknown")
+
+            trans_str = string(trans_type)
+
+            format_arr(arr) = "[" * join(arr, ", ") * "]"
+
+            in_str = "none"
+            if in_bag !== nothing && !isempty(in_bag)
+                in_str = join(["$k:$(format_arr(in_bag[k]))" for k in sort(collect(keys(in_bag)))], " | ")
+            end
+
+            out_str = "none"
+            if out_msg !== nothing && !isempty(out_msg)
+                out_str = join(["$k:$(format_arr(out_msg[k]))" for k in sort(collect(keys(out_msg)))], " | ")
+            end
+
+            time_str = @sprintf("%.6f", time)
+            ta_str = next_ta == Inf ? "inf" : @sprintf("%.6f", next_ta)
+            safe_state = replace(state_str, "\n" => " ", "\r" => "")
+
+            write(io, "$time_str,$model_path,$trans_str,$ta_str,$in_str,$out_str,$safe_state\n")
+        end
+    end
 end