






'''simple docstring'''

# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce
def     __lowercase  (_lowercase     )   ->     List[str]:


     """simple docstring"""
     return (torch.arange(state.num_processes     ) + 1.0 + (state.num_processes * state.process_index)).to(state.device     )
def     __lowercase  (_lowercase     )   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       Any				   =				create_tensor(_lowercase     )
     __lowerCamelCase						:       Optional[int]				   =				gather(_lowercase     )
     assert gathered_tensor.tolist() == list(range(1,						state.num_processes**2 + 1     )     )
def     __lowercase  (_lowercase     )   ->     str:


     """simple docstring"""
     __lowerCamelCase						:       List[str]				   =				[state.process_index]
     __lowerCamelCase						:       List[str]				   =				gather_object(_lowercase     )
     assert len(_lowercase     ) == state.num_processes, f"{gathered_obj}, {len(_lowercase     )} != {state.num_processes}"
     assert gathered_obj == list(range(state.num_processes     )     ), f"{gathered_obj} != {list(range(state.num_processes     )     )}"
def     __lowercase  (_lowercase     )   ->     Dict:


     """simple docstring"""
     __lowerCamelCase						:       Tuple				   =				create_tensor(_lowercase     )
     __lowerCamelCase						:       List[str]				   =				broadcast(_lowercase     )
     assert broadcasted_tensor.shape == torch.Size([state.num_processes]     )
     assert broadcasted_tensor.tolist() == list(range(1,						state.num_processes + 1     )     )
def     __lowercase  (_lowercase     )   ->     Optional[Any]:


     """simple docstring"""
     # We need to pad the tensor with one more element if we are the main process
     # to ensure that we can pad
     if state.is_main_process:
          __lowerCamelCase						:       Dict				   =				torch.arange(state.num_processes + 1     ).to(state.device     )
     else:
          __lowerCamelCase						:       str				   =				torch.arange(state.num_processes     ).to(state.device     )
     __lowerCamelCase						:       List[str]				   =				pad_across_processes(_lowercase     )
     assert padded_tensor.shape == torch.Size([state.num_processes + 1]     )
     if not state.is_main_process:
          assert padded_tensor.tolist() == list(range(0,						state.num_processes     )     ) + [0]
def     __lowercase  (_lowercase     )   ->     Optional[Any]:


     """simple docstring"""
     # For now runs on only two processes
     if state.num_processes != 2:
          return
     __lowerCamelCase						:       int				   =				create_tensor(_lowercase     )
     __lowerCamelCase						:       int				   =				reduce(_lowercase,						"""sum"""     )
     __lowerCamelCase						:       Any				   =				torch.tensor([4.0, 6]     ).to(state.device     )
     assert torch.allclose(_lowercase,						_lowercase     ), f"{reduced_tensor} != {truth_tensor}"
def     __lowercase  (_lowercase     )   ->     Union[str, Any]:


     """simple docstring"""
     # For now runs on only two processes
     if state.num_processes != 2:
          return
     __lowerCamelCase						:       Union[str, Any]				   =				create_tensor(_lowercase     )
     __lowerCamelCase						:       Any				   =				reduce(_lowercase,						"""mean"""     )
     __lowerCamelCase						:       Tuple				   =				torch.tensor([2.0, 3]     ).to(state.device     )
     assert torch.allclose(_lowercase,						_lowercase     ), f"{reduced_tensor} != {truth_tensor}"
def     __lowercase  (_lowercase     )   ->     Dict:


     """simple docstring"""
     # For xla_spawn (TPUs)
     main()
def     __lowercase  ()   ->     List[str]:


     """simple docstring"""
     __lowerCamelCase						:       List[str]				   =				PartialState()
     state.print(f"State: {state}"     )
     state.print("""testing gather"""     )
     test_gather(_lowercase     )
     state.print("""testing gather_object"""     )
     test_gather_object(_lowercase     )
     state.print("""testing broadcast"""     )
     test_broadcast(_lowercase     )
     state.print("""testing pad_across_processes"""     )
     test_pad_across_processes(_lowercase     )
     state.print("""testing reduce_sum"""     )
     test_reduce_sum(_lowercase     )
     state.print("""testing reduce_mean"""     )
     test_reduce_mean(_lowercase     )


if __name__ == "__main__":
   main()











'''simple docstring'''

from statistics import mean

import numpy as np
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     list:


     """simple docstring"""
     __lowerCamelCase						:       str				   =				0
     # Number of processes finished
     __lowerCamelCase						:       List[Any]				   =				0
     # Displays the finished process.
     # If it is 0, the performance is completed if it is 1, before the performance.
     __lowerCamelCase						:       int				   =				[0] * no_of_process
     # List to include calculation results
     __lowerCamelCase						:       Optional[int]				   =				[0] * no_of_process

     # Sort by arrival time.
     __lowerCamelCase						:       int				   =				[burst_time[i] for i in np.argsort(_lowercase     )]
     __lowerCamelCase						:       Union[str, Any]				   =				[process_name[i] for i in np.argsort(_lowercase     )]
     arrival_time.sort()

     while no_of_process > finished_process_count:
          __lowerCamelCase						:       Tuple				   =				0
          while finished_process[i] == 1:
               i += 1
          if current_time < arrival_time[i]:
               __lowerCamelCase						:       List[str]				   =				arrival_time[i]

          __lowerCamelCase						:       Dict				   =				0
          # Index showing the location of the process being performed
          __lowerCamelCase						:       Optional[Any]				   =				0
          # Saves the current response ratio.
          __lowerCamelCase						:       List[str]				   =				0
          for i in range(0,						_lowercase     ):
               if finished_process[i] == 0 and arrival_time[i] <= current_time:
                    __lowerCamelCase						:       Optional[int]				   =				(burst_time[i] + (current_time - arrival_time[i])) / burst_time[
                        i
                    ]
               if response_ratio < temp:
                    __lowerCamelCase						:       List[Any]				   =				temp
                    __lowerCamelCase						:       str				   =				i

        # Calculate the turn around time
          __lowerCamelCase						:       Optional[Any]				   =				current_time + burst_time[loc] - arrival_time[loc]
          current_time += burst_time[loc]
          # Indicates that the process has been performed.
          __lowerCamelCase						:       Optional[Any]				   =				1
          # Increase finished_process_count by 1
          finished_process_count += 1

     return turn_around_time
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     list:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				[0] * no_of_process
     for i in range(0,						_lowercase     ):
          __lowerCamelCase						:       Tuple				   =				turn_around_time[i] - burst_time[i]
     return waiting_time


if __name__ == "__main__":
   UpperCAmelCase__						:List[Any]          =			5
   UpperCAmelCase__						:Tuple          =			["""A""", """B""", """C""", """D""", """E"""]
   UpperCAmelCase__						:Tuple          =			[1, 2, 3, 4, 5]
   UpperCAmelCase__						:List[Any]          =			[1, 2, 3, 4, 5]

   UpperCAmelCase__						:Union[str, Any]          =			calculate_turn_around_time(
       process_name, arrival_time, burst_time, no_of_process
   )
   UpperCAmelCase__						:Optional[int]          =			calculate_waiting_time(
       process_name, turn_around_time, burst_time, no_of_process
   )

   print("""Process name \tArrival time \tBurst time \tTurn around time \tWaiting time""")
   for i in range(0, no_of_process):
      print(
          f'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t'''
          f'''{turn_around_time[i]}\t\t\t{waiting_time[i]}'''
      )

   print(f'''average waiting time : {mean(waiting_time):.5f}''')
   print(f'''average turn around time : {mean(turn_around_time):.5f}''')



