Advertisement
Hetfield96

Untitled

Dec 7th, 2019
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.81 KB | None | 0 0
  1.  #%% md
  2.  
  3. ### Task Description
  4.  
  5. #%%
  6.  
  7. '''
  8. В цехе находятся 2 станка.
  9. В цех поступают детали в среднем через каждые 35 минут (здесь и далее подразумевается, что все времена распределены экспоненциально).
  10. Обработка детали производится на одном из двух станков.
  11. Первый обрабатывает деталь в среднем за 30 минут, при этом отвергает 10 % деталей, считая их бракованными.
  12. Второй обрабатывает деталь в среднем за 50 минут, при этом отвергает 20 % деталей, считая их бракованными.
  13. Если деталь была забракована в первый раз, то ее попробуют обработать еще раз после всех деталей, стоящих в очереди (будь то в очереди на первичную или вторичную обработку)
  14. Детали, которые были отвергнуты 2 раза, считаются отходами и не обслуживаются цехом.
  15. Детали, которые были отвергнуты на любом станке передаются на повторную обработку на второй станок.
  16. Моделирование проводится на 500 деталей.
  17. '''
  18. ;
  19.  
  20. #%%
  21.  
  22. '''
  23. Каждый из станков имеет цену обработки (или попытки обработки) детали.
  24. Для первого станка цена обработки составляет 5$. Для второго - 2$.
  25. Цена готового изделия составляет 12 долларов.
  26.  
  27. Предпринимателю, который владеет цехом, поступило предложение об обмене второго станка. Новый станок имеет цену обработки в 3 $. Время обработки - 40 минут в среднем. Вероятность браковки - 10%.
  28.  
  29. Задача: выяснить какой из станков (старый 2-й или новый) будет более выгодный?
  30. а) прибыль
  31. б) прибыль \ сек
  32. '''
  33. ;
  34.  
  35. #%%
  36.  
  37. import random
  38. import math
  39. import matplotlib.pyplot as plt
  40. %matplotlib inline
  41.  
  42. #%% md
  43.  
  44. ## Variables
  45.  
  46. #%%
  47.  
  48. # constants
  49. n = 500
  50. price_for_item = 12 # $
  51.  
  52. work_price_first_machine = 5 # $
  53. work_price_second_machine = 2 # $
  54. work_price_third_machine = 3 # $
  55.  
  56. decline_first_machine = 10 # %
  57. decline_second_machine = 20 # %
  58. decline_third_machine = 10 # %
  59.  
  60. arrival_rate = 35 # min
  61. first_machine_speed = 30 # min
  62. second_machine_speed = 50 # min
  63. third_machine_speed = 40 # min
  64.  
  65. first_reject_amount = 0
  66. first_success_amount = 0
  67. second_reject_amount = 0
  68. second_success_amount = 0
  69.  
  70. garbage_amount = 0
  71. finished_amount = 0
  72. repeat_amount = 0
  73.  
  74. # simulation variables
  75. x = list(range(n))
  76. current_time = 0
  77. first_machine_time = 0
  78. second_machine_time = 0
  79.  
  80. # collections of elements
  81. customers_time_copy = []
  82. customers_status_copy = []
  83.  
  84. customers_time = [] # arrive times distributed exponentially will be stored here
  85. customers_status = [] # str variable for each
  86.  
  87. #%% md
  88.  
  89. ### Arrival times generation
  90.  
  91. #%%
  92.  
  93. def get_random_arrival_time():
  94.     return round(random.expovariate(1.0/arrival_rate))
  95.  
  96. #%%
  97.  
  98. def get_service_time_value(service_rate):
  99.     return round(random.expovariate(1.0 / service_rate))
  100.  
  101. #%%
  102.  
  103. customers_time = []
  104.  
  105. def through_time_generation():
  106.     curr_time = 0
  107.     waiting_time = 0
  108.  
  109.     for i in x:
  110.         waiting_time = get_random_arrival_time()
  111.         customers_time.append(curr_time + waiting_time)
  112.         curr_time += waiting_time
  113.  
  114. ## this works incorrectly
  115. ## because sometimes time is going in other direction
  116. def through_const_generation():
  117.     value = 0
  118.    
  119.     for i in x:
  120.         value = get_random_arrival_time()
  121.         customers_time.append(i * arrival_rate + value)
  122.  
  123. ## HERE I'M CALLING FUNCTION
  124. ## THAT IS WORKING IN THIS WAY:
  125. ## every iteration generating exp-distributed value with rate=35 (lambda = 1/rate)
  126. ## and curr_time_{i} has sum of all generated waiting_times (on previous row) till i-th iteration
  127.  
  128. through_time_generation()
  129. #through_const_generation()
  130.  
  131. between_arrival_times = []
  132. for i in range(1, n):
  133.     between_arrival_times.append(customers_time[i] - customers_time[i-1])
  134.  
  135. print('Array of times between arrivals:')
  136. print(between_arrival_times)
  137. print('\n\nE(x) of times between arrivals')
  138. print(sum(between_arrival_times)/n)
  139.    
  140. fig, ax = plt.subplots()
  141. ax.plot(range(n - 1), between_arrival_times, label = 'Times between arrivals', color='blue')
  142.  
  143. sorted_between_arrival_times = sorted(between_arrival_times)
  144.  
  145. ax.plot(range(n - 1), sorted_between_arrival_times, label = 'Sorted times between arrivals', linewidth= 4, color='orange')
  146. ax.legend()
  147. plt.show()
  148.  
  149. #%% md
  150.  
  151. ## Setup for other variables states
  152.  
  153. #%%
  154.  
  155. for i in x:
  156.     customers_status.append('arrive')
  157.  
  158. ## setting all initial times to status 'arrive'
  159.  
  160. #%% md
  161.  
  162. ## Functions Implementation
  163.  
  164. #%%
  165.  
  166. # choose machine
  167. def number_of_machine_to_work_on():
  168.     rnd = random.random()
  169.     if (rnd < 0.5):
  170.         #print('goes to machine #1 in experiment')
  171.         return 1
  172.     else:
  173.         #print('goes to machine #2 in experiment')
  174.         return 2
  175.  
  176. #%%
  177.  
  178. # returns true if machine doesn't decline item
  179. def work_with_item(percentage_for_decline):
  180.     r = random.random()
  181.    
  182.     if (r < percentage_for_decline / 100):
  183.         return 0
  184.     return 1
  185.  
  186. #%%
  187.  
  188. def first_machine():
  189.     global current_time
  190.     global first_success_amount
  191.     global first_reject_amount
  192.     global first_machine_time
  193.    
  194.     #print('current_time = ', current_time)
  195.     #print('first_machine_time = ', first_machine_time)
  196.  
  197.     if (work_with_item(decline_first_machine)):
  198.         first_success_amount += 1
  199.        
  200.         if (first_machine_time <= current_time):
  201.             # work is done for this item
  202.             first_machine_time = current_time + get_service_time_value(first_machine_speed)
  203.             customers_time.append(first_machine_time)
  204.             customers_status.append('finished')
  205.         else:
  206.             # work is done after current-working-item finished working
  207.             first_machine_time += get_service_time_value(first_machine_speed)
  208.             customers_time.append(first_machine_time)
  209.             customers_status.append('finished')
  210.     else:
  211.         first_reject_amount += 1
  212.         customers_time.append(first_machine_time)
  213.         customers_status.append('repeat')
  214.  
  215. #%%
  216.  
  217. def second_machine(isRepeating):
  218.     global current_time
  219.     global second_success_amount
  220.     global second_reject_amount
  221.     global second_machine_time
  222.     global garbage_amount
  223.    
  224.     #print('current_time = ', current_time)
  225.     #print('second_machine_time = ', second_machine_time)
  226.    
  227.     if (work_with_item(decline_second_machine)):
  228.         second_success_amount += 1
  229.        
  230.         if (second_machine_time <= current_time):
  231.             # work is done for this item
  232.             second_machine_time = current_time + get_service_time_value(second_machine_speed)
  233.             customers_time.append(second_machine_time)
  234.             customers_status.append('finished')
  235.         else:
  236.             # work is done after current-working-item finished working
  237.             second_machine_time += get_service_time_value(second_machine_speed)
  238.             customers_time.append(second_machine_time)
  239.             customers_status.append('finished')
  240.     else:
  241.         if (isRepeating == 1):
  242.             customers_time.append(second_machine_time)
  243.             customers_status.append('garbage')
  244.             return
  245.        
  246.         second_reject_amount += 1
  247.         customers_time.append(second_machine_time)
  248.         customers_status.append('repeat')
  249.  
  250. #%%
  251.  
  252. def third_machine(isRepeating):
  253.     global current_time
  254.     global second_success_amount
  255.     global second_reject_amount
  256.     global second_machine_time
  257.     global garbage_amount
  258.    
  259.     #print('current_time = ', current_time)
  260.     #print('second_machine_time = ', second_machine_time)
  261.    
  262.     if (work_with_item(decline_third_machine)):
  263.         second_success_amount += 1
  264.        
  265.         if (second_machine_time <= current_time):
  266.             # work is done for this item
  267.             second_machine_time = current_time + get_service_time_value(third_machine_speed)
  268.             customers_time.append(second_machine_time)
  269.             customers_status.append('finished')
  270.         else:
  271.             # work is done after current-working-item finished working
  272.             second_machine_time += get_service_time_value(third_machine_speed)
  273.             customers_time.append(second_machine_time)
  274.             customers_status.append('finished')
  275.     else:
  276.         if (isRepeating == 1):
  277.             customers_time.append(second_machine_time)
  278.             customers_status.append('garbage')
  279.             return
  280.        
  281.         second_reject_amount += 1
  282.         customers_time.append(second_machine_time)
  283.         customers_status.append('repeat')
  284.  
  285. #%% md
  286.  
  287. ## Simulation with machine №2
  288.  
  289. #%%
  290.  
  291. i = 0 # current arrival that is supported
  292.  
  293. customers_time_copy = customers_time.copy()
  294. customers_status_copy = customers_status.copy()
  295.  
  296. while (i < len(customers_time)):
  297.     #print('Item # ', i)
  298.    
  299.     if (i < n):
  300.         current_time = customers_time[i]
  301.    
  302.     # we have to synchronize 2-nd machine and current time
  303.     #if (i == n):
  304.         #print('amount of works done on 2nd machine before repeating:', second_success_amount + second_reject_amount)
  305.         #print('first_machine_time = ', first_machine_time)
  306.         #print('second_machine_time = ', second_machine_time)
  307.         #print('current_time = ', current_time)
  308.    
  309.     # ARRIVALS
  310.     if (customers_status[i] == 'arrive'):
  311.         machine_number = number_of_machine_to_work_on()
  312.         if (machine_number == 1):
  313.             first_machine()
  314.         if (machine_number == 2):
  315.             second_machine(0)
  316.    
  317.     # FINISHED
  318.     if (customers_status[i] == 'finished'):
  319.         #print('finished')
  320.         finished_amount += 1
  321.        
  322.     # REPEAT
  323.     if (customers_status[i] == 'repeat'):
  324.         #print('repeat')
  325.         second_machine(1)
  326.         repeat_amount += 1
  327.    
  328.     # GARBAGE
  329.     if (customers_status[i] == 'garbage'):
  330.         #print('garbage')
  331.         garbage_amount += 1
  332.        
  333.     i += 1
  334.  
  335. #%% md
  336.  
  337. ## Results
  338.  
  339. #%%
  340.  
  341. current_time = second_machine_time
  342.  
  343. print('Rejects: first [', first_reject_amount, '], second [', second_reject_amount, ']')
  344. print('Successes: first [', first_success_amount, '], second [', second_success_amount, ']')
  345. print('Garbage items: ', garbage_amount)
  346. print('Finishes: ', finished_amount)
  347. print('Repeats: ', repeat_amount)
  348.  
  349. print('Time spent: ', current_time, 'seconds')
  350.  
  351. money_earned = price_for_item * (finished_amount)
  352.  
  353. money_spent = work_price_first_machine * (first_success_amount + first_reject_amount)
  354. money_spent += work_price_second_machine * (second_success_amount + second_reject_amount)
  355.  
  356. profit = money_earned - money_spent
  357.  
  358. print('Money earned: ', money_earned, '$')
  359. print('Money spent: ', money_spent, '$')
  360.  
  361. print('Profit money: ', profit, '$')
  362. print('Profit($)\sec:', profit / current_time)
  363.  
  364. #%% md
  365.  
  366. ## Simulation with machine №3
  367.  
  368. #%%
  369.  
  370. first_reject_amount = 0
  371. first_success_amount = 0
  372. second_reject_amount = 0
  373. second_success_amount = 0
  374.  
  375. second_machine_time = 0
  376. first_machine_time = 0
  377.  
  378. garbage_amount = 0
  379. finished_amount = 0
  380. repeat_amount = 0
  381.  
  382. current_time = 0
  383.  
  384. i = 0 # current arrival that is supported
  385.  
  386. customers_time = customers_time_copy
  387. customers_status = customers_status_copy
  388.  
  389. while (i < len(customers_time)):
  390.     #print('Item # ', i)
  391.        
  392.     if (i < n):
  393.         current_time = customers_time[i]
  394.    
  395.     # we have to synchronize 2-nd machine and current time
  396.     '''
  397.    if (i == n):
  398.        print('amount of works done on 2nd machine before repeating:', second_success_amount + second_reject_amount)
  399.        print('first_machine_time = ', first_machine_time)
  400.        print('second_machine_time = ', second_machine_time)
  401.        print('current_time = ', current_time)
  402.    '''
  403.    
  404.     # ARRIVALS
  405.     if (customers_status[i] == 'arrive'):
  406.         #print('arrive')
  407.         machine_number = number_of_machine_to_work_on()
  408.         if (machine_number == 1):
  409.             first_machine()
  410.         if (machine_number == 2):
  411.             third_machine(0)
  412.    
  413.     # FINISHED
  414.     if (customers_status[i] == 'finished'):
  415.         #print('finished')
  416.         finished_amount += 1
  417.        
  418.     # REPEAT
  419.     if (customers_status[i] == 'repeat'):
  420.         #print('repeat')
  421.         third_machine(1)
  422.         repeat_amount += 1
  423.    
  424.     # GARBAGE
  425.     if (customers_status[i] == 'garbage'):
  426.         #print('garbage')
  427.         garbage_amount += 1
  428.        
  429.     i += 1
  430.  
  431. #%%
  432.  
  433. current_time = second_machine_time
  434.  
  435. print('Rejects: first [', first_reject_amount, '], second [', second_reject_amount, ']')
  436. print('Successes: first [', first_success_amount, '], second [', second_success_amount, ']')
  437. print('Garbage items: ', garbage_amount)
  438. print('Finishes: ', finished_amount)
  439. print('Repeats: ', repeat_amount)
  440.  
  441. print('Time spent: ', current_time, 'seconds')
  442.  
  443. money_earned = price_for_item * (finished_amount)
  444.  
  445. money_spent = work_price_first_machine * (first_success_amount + first_reject_amount)
  446. money_spent += work_price_third_machine * (second_success_amount + second_reject_amount)
  447.  
  448. profit = money_earned - money_spent
  449.  
  450. print('Money earned: ', money_earned, '$')
  451. print('Money spent: ', money_spent, '$')
  452.  
  453. print('Profit money: ', profit, '$')
  454. print('Profit($)\sec:', profit / current_time)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement