Is it possible to further functionalize this code for descrete event simulation












0












$begingroup$


I have one machine, which produces parts. In machine_failure_rate% it produces faulty parts which need to be produced again. Thus, we end up with a simple queuing problem. Can the following code be futher functionalized? I have the feeling, I can get rid of time_parts, but all I have in mind deteriorates the code as I need further lookups in the production_df data frame to look for "what was produced / what needs to be produced now?". The following script is running:



input_rate <- 1/60 # input rate [1/min, 1/input_rate corresponds to interarrival time in min]
n <- 1000 # number of parts
dt <- 1 # timestep = time to transfer faulty parts back to production. [min]

machine_production_rate <- 1/40 # production rate [1/min]
machine_failure_rate <- 0.2 # machine failure rate


# Sum all interarrival times
set.seed(123456)
t_event <- cumsum(rpois(n, 1/input_rate))

# Create initial list of tasks. Produces parts will be cut off.
time_parts <- data.frame(id = c(1:n),
t = t_event,
stringsAsFactors = FALSE)


# ========= Functions ==========================================================
create_machine <- function(failure_rate, production_rate) {
machine <- list()
machine$failure_rate <- failure_rate
machine$production_rate <- production_rate
machine$is_occupied <- FALSE
return(machine);
}

update_machine <- function(ind_production_df, machine, production_df) {
if (machine$is_occupied) {
if (production_df$po_start[ind_production_df] + 1/machine$production_rate <= t) {
machine$is_occupied <- FALSE
}
}
return(machine)
}

production_summary <- function(production_df, machine, input_rate) {
no_of_failures <- sum(production_df$no_failures)
total_production_time <- max(production_df$po_start) + 1/machine$production_rate
uptime <- (no_of_failures + n)/machine$production_rate
print(paste0("Estimated machine$failure_rate ",
round(no_of_failures/(no_of_failures + n), 2),
" [theory ", round(machine$failure_rate, 2), "]"))
print(paste0("Up-time ", uptime,
", of total time ", total_production_time, ". Auslastung ",
round(uptime/total_production_time, 2),
" [theory ", round(input_rate/machine$production_rate*1/(1 - machine$failure_rate), 2), "]"))
}


# ========= DE simulation ======================================================
machine <- create_machine(machine_failure_rate, machine_production_rate)
production_df <- data.frame(id = time_parts$id,
time = time_parts$t,
po_start = rep(0, nrow(time_parts)),
no_failures = rep(0, nrow(time_parts)),
stringsAsFactors = FALSE)

t <- 0
while (length(time_parts$t) > 0) {
ind_production_df <- which(production_df$id == time_parts$id[1])

machine <- update_machine(ind_production_df, machine, production_df)

if (!machine$is_occupied & time_parts$t[1] <= t) {
# A machine is available and a part needs to be produced
machine$is_occupied <- TRUE
production_df$po_start[ind_production_df] <- t
if (runif(1) < machine$failure_rate) {
# bad part
time_parts$t[1] <- time_parts$t[1] + dt
time_parts <- time_parts[sort(time_parts$t, index.return = TRUE)$ix, ]

production_df$no_failures[ind_production_df] <-
production_df$no_failures[ind_production_df] + 1
t <- t + min(time_parts$t[1], dt)
} else {
# good part
if (production_df$po_start[ind_production_df] + 1/machine$production_rate >= t &&
nrow(time_parts) >= 2) {
time_parts <- time_parts[2:(nrow(time_parts)), ]
} else {
time_parts <- time_parts[FALSE, ]
}
t <- t + 1/machine$production_rate
machine$is_occupied <- FALSE
}
} else {
# machine is occupied or no part needs to be produced
t <- t + min(time_parts$t[1], dt)
}
}


# ========= Results ============================================================
production_summary(production_df, machine, input_rate)


Backround: I think about a generalisation (more machines, more input-sources, more complex rules how/when/... parts a produces). I fear that I will end up with tons of unreadable and unmaintainable code-lines if I proceed like this.










share|improve this question









New contributor




Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    I have one machine, which produces parts. In machine_failure_rate% it produces faulty parts which need to be produced again. Thus, we end up with a simple queuing problem. Can the following code be futher functionalized? I have the feeling, I can get rid of time_parts, but all I have in mind deteriorates the code as I need further lookups in the production_df data frame to look for "what was produced / what needs to be produced now?". The following script is running:



    input_rate <- 1/60 # input rate [1/min, 1/input_rate corresponds to interarrival time in min]
    n <- 1000 # number of parts
    dt <- 1 # timestep = time to transfer faulty parts back to production. [min]

    machine_production_rate <- 1/40 # production rate [1/min]
    machine_failure_rate <- 0.2 # machine failure rate


    # Sum all interarrival times
    set.seed(123456)
    t_event <- cumsum(rpois(n, 1/input_rate))

    # Create initial list of tasks. Produces parts will be cut off.
    time_parts <- data.frame(id = c(1:n),
    t = t_event,
    stringsAsFactors = FALSE)


    # ========= Functions ==========================================================
    create_machine <- function(failure_rate, production_rate) {
    machine <- list()
    machine$failure_rate <- failure_rate
    machine$production_rate <- production_rate
    machine$is_occupied <- FALSE
    return(machine);
    }

    update_machine <- function(ind_production_df, machine, production_df) {
    if (machine$is_occupied) {
    if (production_df$po_start[ind_production_df] + 1/machine$production_rate <= t) {
    machine$is_occupied <- FALSE
    }
    }
    return(machine)
    }

    production_summary <- function(production_df, machine, input_rate) {
    no_of_failures <- sum(production_df$no_failures)
    total_production_time <- max(production_df$po_start) + 1/machine$production_rate
    uptime <- (no_of_failures + n)/machine$production_rate
    print(paste0("Estimated machine$failure_rate ",
    round(no_of_failures/(no_of_failures + n), 2),
    " [theory ", round(machine$failure_rate, 2), "]"))
    print(paste0("Up-time ", uptime,
    ", of total time ", total_production_time, ". Auslastung ",
    round(uptime/total_production_time, 2),
    " [theory ", round(input_rate/machine$production_rate*1/(1 - machine$failure_rate), 2), "]"))
    }


    # ========= DE simulation ======================================================
    machine <- create_machine(machine_failure_rate, machine_production_rate)
    production_df <- data.frame(id = time_parts$id,
    time = time_parts$t,
    po_start = rep(0, nrow(time_parts)),
    no_failures = rep(0, nrow(time_parts)),
    stringsAsFactors = FALSE)

    t <- 0
    while (length(time_parts$t) > 0) {
    ind_production_df <- which(production_df$id == time_parts$id[1])

    machine <- update_machine(ind_production_df, machine, production_df)

    if (!machine$is_occupied & time_parts$t[1] <= t) {
    # A machine is available and a part needs to be produced
    machine$is_occupied <- TRUE
    production_df$po_start[ind_production_df] <- t
    if (runif(1) < machine$failure_rate) {
    # bad part
    time_parts$t[1] <- time_parts$t[1] + dt
    time_parts <- time_parts[sort(time_parts$t, index.return = TRUE)$ix, ]

    production_df$no_failures[ind_production_df] <-
    production_df$no_failures[ind_production_df] + 1
    t <- t + min(time_parts$t[1], dt)
    } else {
    # good part
    if (production_df$po_start[ind_production_df] + 1/machine$production_rate >= t &&
    nrow(time_parts) >= 2) {
    time_parts <- time_parts[2:(nrow(time_parts)), ]
    } else {
    time_parts <- time_parts[FALSE, ]
    }
    t <- t + 1/machine$production_rate
    machine$is_occupied <- FALSE
    }
    } else {
    # machine is occupied or no part needs to be produced
    t <- t + min(time_parts$t[1], dt)
    }
    }


    # ========= Results ============================================================
    production_summary(production_df, machine, input_rate)


    Backround: I think about a generalisation (more machines, more input-sources, more complex rules how/when/... parts a produces). I fear that I will end up with tons of unreadable and unmaintainable code-lines if I proceed like this.










    share|improve this question









    New contributor




    Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I have one machine, which produces parts. In machine_failure_rate% it produces faulty parts which need to be produced again. Thus, we end up with a simple queuing problem. Can the following code be futher functionalized? I have the feeling, I can get rid of time_parts, but all I have in mind deteriorates the code as I need further lookups in the production_df data frame to look for "what was produced / what needs to be produced now?". The following script is running:



      input_rate <- 1/60 # input rate [1/min, 1/input_rate corresponds to interarrival time in min]
      n <- 1000 # number of parts
      dt <- 1 # timestep = time to transfer faulty parts back to production. [min]

      machine_production_rate <- 1/40 # production rate [1/min]
      machine_failure_rate <- 0.2 # machine failure rate


      # Sum all interarrival times
      set.seed(123456)
      t_event <- cumsum(rpois(n, 1/input_rate))

      # Create initial list of tasks. Produces parts will be cut off.
      time_parts <- data.frame(id = c(1:n),
      t = t_event,
      stringsAsFactors = FALSE)


      # ========= Functions ==========================================================
      create_machine <- function(failure_rate, production_rate) {
      machine <- list()
      machine$failure_rate <- failure_rate
      machine$production_rate <- production_rate
      machine$is_occupied <- FALSE
      return(machine);
      }

      update_machine <- function(ind_production_df, machine, production_df) {
      if (machine$is_occupied) {
      if (production_df$po_start[ind_production_df] + 1/machine$production_rate <= t) {
      machine$is_occupied <- FALSE
      }
      }
      return(machine)
      }

      production_summary <- function(production_df, machine, input_rate) {
      no_of_failures <- sum(production_df$no_failures)
      total_production_time <- max(production_df$po_start) + 1/machine$production_rate
      uptime <- (no_of_failures + n)/machine$production_rate
      print(paste0("Estimated machine$failure_rate ",
      round(no_of_failures/(no_of_failures + n), 2),
      " [theory ", round(machine$failure_rate, 2), "]"))
      print(paste0("Up-time ", uptime,
      ", of total time ", total_production_time, ". Auslastung ",
      round(uptime/total_production_time, 2),
      " [theory ", round(input_rate/machine$production_rate*1/(1 - machine$failure_rate), 2), "]"))
      }


      # ========= DE simulation ======================================================
      machine <- create_machine(machine_failure_rate, machine_production_rate)
      production_df <- data.frame(id = time_parts$id,
      time = time_parts$t,
      po_start = rep(0, nrow(time_parts)),
      no_failures = rep(0, nrow(time_parts)),
      stringsAsFactors = FALSE)

      t <- 0
      while (length(time_parts$t) > 0) {
      ind_production_df <- which(production_df$id == time_parts$id[1])

      machine <- update_machine(ind_production_df, machine, production_df)

      if (!machine$is_occupied & time_parts$t[1] <= t) {
      # A machine is available and a part needs to be produced
      machine$is_occupied <- TRUE
      production_df$po_start[ind_production_df] <- t
      if (runif(1) < machine$failure_rate) {
      # bad part
      time_parts$t[1] <- time_parts$t[1] + dt
      time_parts <- time_parts[sort(time_parts$t, index.return = TRUE)$ix, ]

      production_df$no_failures[ind_production_df] <-
      production_df$no_failures[ind_production_df] + 1
      t <- t + min(time_parts$t[1], dt)
      } else {
      # good part
      if (production_df$po_start[ind_production_df] + 1/machine$production_rate >= t &&
      nrow(time_parts) >= 2) {
      time_parts <- time_parts[2:(nrow(time_parts)), ]
      } else {
      time_parts <- time_parts[FALSE, ]
      }
      t <- t + 1/machine$production_rate
      machine$is_occupied <- FALSE
      }
      } else {
      # machine is occupied or no part needs to be produced
      t <- t + min(time_parts$t[1], dt)
      }
      }


      # ========= Results ============================================================
      production_summary(production_df, machine, input_rate)


      Backround: I think about a generalisation (more machines, more input-sources, more complex rules how/when/... parts a produces). I fear that I will end up with tons of unreadable and unmaintainable code-lines if I proceed like this.










      share|improve this question









      New contributor




      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I have one machine, which produces parts. In machine_failure_rate% it produces faulty parts which need to be produced again. Thus, we end up with a simple queuing problem. Can the following code be futher functionalized? I have the feeling, I can get rid of time_parts, but all I have in mind deteriorates the code as I need further lookups in the production_df data frame to look for "what was produced / what needs to be produced now?". The following script is running:



      input_rate <- 1/60 # input rate [1/min, 1/input_rate corresponds to interarrival time in min]
      n <- 1000 # number of parts
      dt <- 1 # timestep = time to transfer faulty parts back to production. [min]

      machine_production_rate <- 1/40 # production rate [1/min]
      machine_failure_rate <- 0.2 # machine failure rate


      # Sum all interarrival times
      set.seed(123456)
      t_event <- cumsum(rpois(n, 1/input_rate))

      # Create initial list of tasks. Produces parts will be cut off.
      time_parts <- data.frame(id = c(1:n),
      t = t_event,
      stringsAsFactors = FALSE)


      # ========= Functions ==========================================================
      create_machine <- function(failure_rate, production_rate) {
      machine <- list()
      machine$failure_rate <- failure_rate
      machine$production_rate <- production_rate
      machine$is_occupied <- FALSE
      return(machine);
      }

      update_machine <- function(ind_production_df, machine, production_df) {
      if (machine$is_occupied) {
      if (production_df$po_start[ind_production_df] + 1/machine$production_rate <= t) {
      machine$is_occupied <- FALSE
      }
      }
      return(machine)
      }

      production_summary <- function(production_df, machine, input_rate) {
      no_of_failures <- sum(production_df$no_failures)
      total_production_time <- max(production_df$po_start) + 1/machine$production_rate
      uptime <- (no_of_failures + n)/machine$production_rate
      print(paste0("Estimated machine$failure_rate ",
      round(no_of_failures/(no_of_failures + n), 2),
      " [theory ", round(machine$failure_rate, 2), "]"))
      print(paste0("Up-time ", uptime,
      ", of total time ", total_production_time, ". Auslastung ",
      round(uptime/total_production_time, 2),
      " [theory ", round(input_rate/machine$production_rate*1/(1 - machine$failure_rate), 2), "]"))
      }


      # ========= DE simulation ======================================================
      machine <- create_machine(machine_failure_rate, machine_production_rate)
      production_df <- data.frame(id = time_parts$id,
      time = time_parts$t,
      po_start = rep(0, nrow(time_parts)),
      no_failures = rep(0, nrow(time_parts)),
      stringsAsFactors = FALSE)

      t <- 0
      while (length(time_parts$t) > 0) {
      ind_production_df <- which(production_df$id == time_parts$id[1])

      machine <- update_machine(ind_production_df, machine, production_df)

      if (!machine$is_occupied & time_parts$t[1] <= t) {
      # A machine is available and a part needs to be produced
      machine$is_occupied <- TRUE
      production_df$po_start[ind_production_df] <- t
      if (runif(1) < machine$failure_rate) {
      # bad part
      time_parts$t[1] <- time_parts$t[1] + dt
      time_parts <- time_parts[sort(time_parts$t, index.return = TRUE)$ix, ]

      production_df$no_failures[ind_production_df] <-
      production_df$no_failures[ind_production_df] + 1
      t <- t + min(time_parts$t[1], dt)
      } else {
      # good part
      if (production_df$po_start[ind_production_df] + 1/machine$production_rate >= t &&
      nrow(time_parts) >= 2) {
      time_parts <- time_parts[2:(nrow(time_parts)), ]
      } else {
      time_parts <- time_parts[FALSE, ]
      }
      t <- t + 1/machine$production_rate
      machine$is_occupied <- FALSE
      }
      } else {
      # machine is occupied or no part needs to be produced
      t <- t + min(time_parts$t[1], dt)
      }
      }


      # ========= Results ============================================================
      production_summary(production_df, machine, input_rate)


      Backround: I think about a generalisation (more machines, more input-sources, more complex rules how/when/... parts a produces). I fear that I will end up with tons of unreadable and unmaintainable code-lines if I proceed like this.







      r






      share|improve this question









      New contributor




      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 20 mins ago







      Christoph













      New contributor




      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 25 mins ago









      ChristophChristoph

      1013




      1013




      New contributor




      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Christoph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Christoph is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212825%2fis-it-possible-to-further-functionalize-this-code-for-descrete-event-simulation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Christoph is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Christoph is a new contributor. Be nice, and check out our Code of Conduct.













          Christoph is a new contributor. Be nice, and check out our Code of Conduct.












          Christoph is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212825%2fis-it-possible-to-further-functionalize-this-code-for-descrete-event-simulation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Список кардиналов, возведённых папой римским Каликстом III

          Deduzione

          Mysql.sock missing - “Can't connect to local MySQL server through socket”