예제 #1
0
 static void Main(string[] args)
 {
     using (new MPI.Environment(ref args))
     {
         int matrixSize         = 50;
         Intracommunicator comm = Communicator.world;
         if (comm.Rank == 0)
         {
             DateTime       startTime = DateTime.Now;
             MatrixMultiply mp        = new MatrixMultiply(comm.Size, matrixSize);
             //mp.Show();
             comm.Send <MatrixMultiply>(mp, 1, 0);
             Console.WriteLine("Sending MatrixMyltiply");
             Matrix res = mp.MultiplyForRank(comm.Rank);
             comm.Receive <MatrixMultiply>(Communicator.anySource, 0);
             Console.WriteLine("Recieve MatrixMultiply");
             comm.Send <Matrix>(res, 1, 1);
             Console.WriteLine("Sending Matrix result");
             //res = comm.Receive<Matrix>(Communicator.anySource, 1);
             Console.WriteLine("Recieve Matrix result");
             //res.Show();
             DateTime endTime = DateTime.Now;
             Console.WriteLine("Test multiply" + (startTime - endTime).ToString());
         }
         else
         {
             MatrixMultiply mp = comm.Receive <MatrixMultiply>(comm.Rank - 1, 0);
             comm.Send <MatrixMultiply>(mp, (comm.Rank + 1) % comm.Size, 0);
             Matrix res = mp.MultiplyForRank(comm.Rank);
             Matrix m   = comm.Receive <Matrix>(comm.Rank - 1, 1);
             comm.Send <Matrix>(m.Append(res), (comm.Rank + 1) % comm.Size, 1);
         }
     }
 }
예제 #2
0
        /// <summary>
        /// While the actor is alive:
        ///     find a move position,
        ///     update map with other actor's moves,
        ///     and communicate move intentions with map
        /// </summary>
        public void AliveLoop()
        {
            while (!shouldDie)
            {
                Tuple <Coordinates, int> searchResult = GetDirection();
                MoveEvent(searchResult.Item2);
                // If we did not find a path, we stay where we are.
                Coordinates targetCoordinates = searchResult.Item2 == NO_PATH
                    ? currentTile.Position
                    : searchResult.Item1;

                comm.Send(new MoveRequest {
                    Rank = rank, DesiredTile = targetCoordinates
                }, MAP_RANK, DEFAULT_TAG);

                bool waitingMoveResponse = true;
                // We wait to receive our new position.
                while (waitingMoveResponse)
                {
                    waitingMoveResponse = !HandleMessage(comm.Receive <Message>(MAP_RANK, DEFAULT_TAG));
                }
            }
            // We confirme to the map that we are dead.
            comm.Send(new DeathConfirmation {
                Rank = rank
            }, MAP_RANK, DEFAULT_TAG);
        }
예제 #3
0
        static void Main(string[] args)
        {
            using (new MPI.Environment(ref args))
            {
                Intracommunicator comm = Communicator.world;
                //root
                if (Communicator.world.Rank == 0)
                {
                    Console.WriteLine("Root sent a message to Rank 1");

                    comm.Send("blah", 1, 0);

                    //nonblocking receive
                    Request receive = comm.ImmediateReceive <string>(1, 0);

                    Console.WriteLine("We are performing a nonblocking receive, so we can print instantly.");
                    receive.Wait();
                }
                //not the root
                else
                {
                    comm.Receive <string>(0, 0);

                    //Rank 1 will wait half a second before sending response
                    System.Threading.Thread.Sleep(5000);

                    Console.WriteLine("We waited half a second before sending something to the root.");
                    comm.Send("blah", 0, 0);
                    Console.WriteLine("If root was blocking, he wouldn't have been able to print until now!");
                }
            }
        }
예제 #4
0
        public static void DoTest(string[] args)
        {
            Intracommunicator comm = Communicator.world;

            if (comm.Rank == 0)
            {
                Console.WriteLine("Rank 0 is alive and running on " + MPI.Environment.ProcessorName);
                for (int dest = 1; dest < comm.Size; ++dest)
                {
                    Console.Write("Pinging process with rank " + dest + "...");
                    comm.Send("Ping!", dest, 0);
                    string destHostname = comm.Receive <string>(dest, 1);
                    Console.WriteLine(" Pong!");
                    Console.WriteLine("  Rank " + dest + " is alive and running on " + destHostname);
                }
            }
            else
            {
                var brk = System.Environment.GetEnvironmentVariable("BreakUnitTestOutcomeTest");
                if (!string.IsNullOrEmpty(brk))
                {
                    int rankToBreak = int.Parse(brk);
                    if (rankToBreak == comm.Rank)
                    {
                        MPIDebug.Assert(false, "Force failure of an assertion in BreakUnitTestOutcomeTest");
                    }
                }
                comm.Receive <string>(0, 0);
                comm.Send(MPI.Environment.ProcessorName, 0, 1);
            }
        }
예제 #5
0
        static List <int> CompareExchange(Intracommunicator comm, List <int> partList, int j, SortTypes type, bool evenIter)
        {
            int evenNode;
            int oddNode;

            if (evenIter)
            {
                evenNode = 2 * j;
                oddNode  = 2 * j + 1;
            }
            else
            {
                evenNode = 2 * j + 1;
                oddNode  = 2 * j + 2;
            }

            if (comm.Rank == evenNode)
            {
                partList.AddRange(comm.Receive <List <int> >(oddNode, 1));

                switch (type)
                {
                case SortTypes.Increase:
                {
                    partList.Sort();

                    break;
                }

                case SortTypes.Decrease:
                {
                    partList.Sort();
                    partList.Reverse();

                    break;
                }
                }

                int distribution = partList.Count / 2;

                comm.Send(partList.Skip(distribution).ToList(), oddNode, 2);
                partList = partList.Take(distribution).ToList();
            }
            else if (comm.Rank == oddNode)
            {
                comm.Send(partList, evenNode, 1);

                partList = comm.Receive <List <int> >(evenNode, 2);
            }

            return(partList);
        }
예제 #6
0
        static List <Timetable> generateTimetable(Intracommunicator comm)
        {
            RequestList           requestList = new RequestList();
            List <ReceiveRequest> reqs        = new List <ReceiveRequest>();

            var classes = System.IO.File.ReadAllLines("input.txt").OfType <string>().Select(line =>
            {
                var l = line.Trim().Split(';');
                return(new Class(l[1], l[0]));
            }).ToList();


            int id = 1;


            foreach (Class c in classes)
            {
                if (id == comm.Size)
                {
                    id = 1;
                }

                Timetable t = new Timetable();
                t.Table[Day.MONDAY][8].Add(c);

                var clone = copy(classes);
                clone.Remove(c);

                comm.Send(false, id, 1);
                comm.Send(new Payload {
                    timetable = t.toList(), classes = clone, day = Day.MONDAY, hour = 8
                }, id, 0);
                reqs.Add(comm.ImmediateReceive <List <Pair <Day, List <Pair <int, List <Class> > > > > >(id++, 0));
                requestList.Add(reqs.Last());
            }

            requestList.WaitAll();

            for (int i = 1; i < comm.Size; i++)
            {
                comm.Send(true, i, 1);
            }

            return(reqs.Select(r =>
            {
                r.Wait();
                return new Timetable((List <Pair <Day, List <Pair <int, List <Class> > > > >)r.GetValue());
            }).Where(t => t.Table.Count != 0).ToList());
        }
예제 #7
0
        /// <summary>
        /// Informs every other processes that the game started and provides the map and position informations
        /// </summary>
        private void SignalGameStartToAllActors()
        {
            StartSignal startSignal = new StartSignal {
                Map = map
            };

            lock (comm)
            {
                foreach (ActorProcess actor in actors)
                {
                    startSignal.Position = actor.Position;
                    comm.Send(startSignal, actor.Rank, 0);
                }
            }
        }
예제 #8
0
        public static void Process(Intracommunicator comm, bool isCannibal)
        {
            string    myStringID  = StringIdentityOFProcess(processId) + ": ";
            Random    random      = new Random();
            int       waitingTime = random.Next(1000 * 10 + processId * 500);//koliko ćemo cekati tj. kad će biti spreman za ukrcaj
            Stopwatch timer       = new Stopwatch();

            timer.Start();
            bool isInside = false;

            while (true)
            {
                Badge currBadge = comm.Receive <Badge>(MPI.Unsafe.MPI_ANY_SOURCE, 0);
                if (currBadge.RED_PILL)
                {
                    break;
                }
                Console.WriteLine(myStringID + "Primio značku od procesa " + StringIdentityOFProcess(currBadge.source));
                System.Threading.Thread.Sleep(500);
                currBadge.source = processId;
                if (isInside)
                {
                    Console.WriteLine(myStringID + "Već sam u čamcu! Šaljem značku procesu: "
                                      + StringIdentityOFProcess(currBadge.GetNeighProcessId(processId)));
                    comm.Send <Badge>(currBadge, currBadge.GetNeighProcessId(processId), 0);
                }
                else if (timer.ElapsedMilliseconds < waitingTime)
                {
                    Console.WriteLine(myStringID + "Ne želim još uci u čamac, šaljem značku procesu: "
                                      + StringIdentityOFProcess(currBadge.GetNeighProcessId(processId)));
                    comm.Send <Badge>(currBadge, currBadge.GetNeighProcessId(processId), 0);
                }
                else if (!currBadge.CanEntry(isCannibal))
                {
                    Console.WriteLine(myStringID + "Ne mogu ući u čamac, šaljem značku procesu: "
                                      + StringIdentityOFProcess(currBadge.GetNeighProcessId(processId)));
                    comm.Send <Badge>(currBadge, currBadge.GetNeighProcessId(processId), 0);
                }
                else
                {
                    currBadge.GetInBoat(isCannibal, processId);
                    Console.WriteLine(myStringID + "Ulazim u čamac!");
                    isInside = true;
                    comm.Send <Badge>(currBadge, currBadge.GetNeighProcessId(processId), 0);
                }
            }
            timer.Stop();
        }
예제 #9
0
 private void Migrate()
 {
     Array.Copy(individuos, migratedOut, migratedOut.Length);
     comm.Send(migratedOut, processTo, 0);
     comm.Receive(processFrom, 0, out migratedIn);
     Array.Copy(migratedIn, individuos, migratedIn.Length);
 }
예제 #10
0
        private void SendLoop()
        {
            while (keepRunning)
            {
                INodeMessage message;
                while (!nodeMessages.TryDequeue(out message))
                {
                    if (!keepRunning)
                    {
                        return;
                    }
                }

                if (message == null)
                {
                    throw new InvalidOperationException("Cannot write a null message");
                }

                var targetNode = message.NodeId;
                if (message is NodeAvailabilityChange change)
                {
                    targetNode = RootNode;
                }

                var serializedMessage = messageSerializer.SerializeMessage(message);
                communicator.Send(serializedMessage, targetNode, MPIMessageTags.SerializedMessagesTag);
            }
        }
예제 #11
0
        static private void AskForFork(int neighbourId, Intracommunicator comm)
        {
            comm.Send <bool>(true, neighbourId, 0);
            string pom = "";

            for (int i = 0; i < comm.Rank; i++)
            {
                pom += SPACING;
            }
            Console.WriteLine(pom + "asking for fork" + neighbourId.ToString());
        }
예제 #12
0
        static private void TraziVilicu(Intracommunicator comm, int idSusjeda)
        {
            comm.Send <bool>(true, idSusjeda, 0);
            string pomak = "";

            for (int l = 0; l < comm.Rank; l++)
            {
                pomak += RAZMAK;
            }
            System.Console.WriteLine(pomak + "TrazimVilicu" + idSusjeda);
        }
예제 #13
0
 private static void PingPong(Intracommunicator comm)
 {
     if (comm.Rank == 0)
     {
         Console.WriteLine("Rank 0 is alive and running on " + MPI.Environment.ProcessorName);
         for (int dest = 1; dest < comm.Size; ++dest)
         {
             Console.Write("Pinging process with rank " + dest + "...");
             comm.Send("Ping!", dest, 0);
             string destHostname = comm.Receive <string>(dest, 1);
             Console.WriteLine(" Pong!");
             Console.WriteLine("  Rank " + dest + " is alive and running on " + destHostname);
         }
     }
     else
     {
         comm.Receive <string>(0, 0);
         comm.Send(MPI.Environment.ProcessorName, 0, 1);
     }
 }
예제 #14
0
        static void Main(string[] args)
        {
            using (new MPI.Environment(ref args))
            {
                Intracommunicator comm = Communicator.world;

                if (comm.Rank == 0)
                {
                    Console.WriteLine("Root: Let's play a game of telephone!");

                    string originalMsg = "chicago";

                    Console.WriteLine("Root: The inital word is: \"" + originalMsg + "\".");
                    comm.Send(originalMsg, 1, 0);

                    //example of a blocking Receieve
                    string msg = comm.Receive <string>(Communicator.anySource, 0);

                    //not printed until the message is received.
                    if (msg.Equals(originalMsg))
                    {
                        Console.WriteLine("Root: Good job guys! You got it!");
                    }
                    else
                    {
                        Console.WriteLine("Root: Close enough...");
                    }
                }
                else
                {
                    //more blocking Recieves
                    string msg = comm.Receive <string>(comm.Rank - 1, 0);

                    string newMsg = jumble(msg);

                    Console.WriteLine(comm.Rank + ": " + newMsg);

                    comm.Send(newMsg, (comm.Rank + 1) % comm.Size, 0);
                }
            }
        }
예제 #15
0
 static void Main(string[] args)
 {
     using (new MPI.Environment(ref args))
     {
         Intracommunicator cls = Communicator.world;
         if (cls.Rank == 0)
         {
             Console.WriteLine("Происходит регистрация сервера!");
             ServiceHost host = new ServiceHost(typeof(Simple), new Uri("http://localhost:1050/MyMPI"));
             host.AddServiceEndpoint(typeof(ISimpleNum), new BasicHttpBinding(), "");
             host.Open();
             bool       end  = false;
             List <int> list = new List <int>();
             list.Add(-1);
             list.Add(-1);
             while (!end)
             {
                 Console.WriteLine("Сервер запущен!");
                 //Console.ReadLine();
                 Console.Write("Хотите закончить работу сервера(вызовите команду end): ");
                 string a = Console.ReadLine();
                 if (a == "end")
                 {
                     end = true;
                     for (int i = 1; i < cls.Size; i++)
                     {
                         cls.Send <List <int> >(list, i, 0);
                     }
                 }
             }
             host.Close();
         }
         else
         {
             Console.WriteLine("Создаём объекты вычисления!");
             Simple part = new Simple();
             while (true)
             {
                 List <int> a = part.GetNum(0);
                 if ((a.Count > 0) && (a[0] == -1))
                 {
                     break;
                 }
                 //
                 //тут прописывал просто (a[0] == -1) и пробовал
                 //((a!=null)&&(a[0] == -1)) но это было ошибочно(на зачёте), так как и пустой  List имеет ссылку
                 //То есть проблема на самом деле не была в List, но при особом желание везде можно вставить
                 //вместо List, ArrayList "всё практически останется также"
                 //
             }
         }
     }
 }
예제 #16
0
    static void main(string[] args)
    {
        using (MPI.Environment env = new MPI.Environment(ref args))
        {
            Intracommunicator comm = MPI.Communicator.world;
            if (comm.Size < 2)
            {
                // Our ring needs at least two processes
                System.Console.WriteLine("The Ring example must be run with at least two processes.");
                System.Console.WriteLine("Try: mpiexec -np 4 ring.exe");
            }
            else if (comm.Rank == 0)
            {
                // Rank 0 initiates communication around the ring
                string data = "Hello, World!";

                // Send "Hello, World!" to our right neighbor
                comm.Send(data, (comm.Rank + 1) % comm.Size, 0);

                // Receive data from our left neighbor
                comm.Receive((comm.Rank + comm.Size - 1) % comm.Size, 0, out data);

                // Add our own rank and write the results
                data += " 0";
                System.Console.WriteLine(data);
            }
            else
            {
                // Receive data from our left neighbor
                String data;
                comm.Receive((comm.Rank + comm.Size - 1) % comm.Size, 0, out data);

                // Add our own rank to the data
                data = data + " " + comm.Rank.ToString() + ",";

                // Pass on the intermediate to our right neighbor
                comm.Send(data, (comm.Rank + 1) % comm.Size, 0);
            }
        }
    }
예제 #17
0
        static void Main(string[] args)
        {
            Random random = new Random();

            using (new MPI.Environment(ref args))
            {
                Intracommunicator com = MPI.Communicator.world;

                int lider = 0;
                int rand  = random.Next(100 + com.Rank);
                Console.WriteLine("Firul " + com.Rank + " genereaza: " + rand);


                if (com.Rank == 0)
                {
                    for (int i = 1; i < 10; i++)
                    {
                        int rand1 = com.Receive <int>(i, 0);
                        if (rand <= rand1)
                        {
                            lider = i;
                            rand  = rand1;
                        }
                    }

                    for (int i = 1; i < 10; i++)
                    {
                        com.Send <int>(lider, i, 0);
                    }
                    Console.WriteLine("Liderul este" + lider);
                }
                else
                {
                    com.Send <int>(rand, 0, 0);
                    com.Receive(0, 0, out lider);
                }

                com.Dispose();
            }
        }
예제 #18
0
파일: Program.cs 프로젝트: und3rsrl/ADP
        static void Main(string[] args)
        {
            Random random = new Random();

            using (new MPI.Environment(ref args))
            {
                Intracommunicator comm = MPI.Communicator.world;

                int master = -1;

                int myNumber = random.Next(10);

                for (int j = 0; j < 2; j++)
                {
                    for (int i = 0; i < comm.Size; i++)
                    {
                        if (i == comm.Rank)
                        {
                            continue;
                        }

                        comm.Send(myNumber, i, 0);
                        int receivedNumber = comm.Receive <int>(i, 0);

                        if (receivedNumber > myNumber)
                        {
                            if (receivedNumber == myNumber)
                            {
                                if (comm.Rank > i)
                                {
                                    master = comm.Rank;
                                }
                                else
                                {
                                    master = i;
                                }
                            }
                            else
                            {
                                master = i;
                            }
                        }
                        else
                        {
                            master = comm.Rank;
                        }
                    }
                }

                Console.WriteLine("Proces " + comm.Rank + ": " + master + "/ My number : " + myNumber);
            }
        }
예제 #19
0
    public static void main(string[] args)
    {
        using (new MPI.Environment(ref args))
        {
            int cant = 2;
            Intracommunicator comm = Communicator.world;
            if (comm.Rank == 0)
            {
                Console.WriteLine("Rank 0 is alive and running on " + MPI.Environment.ProcessorName);
                for (int dest = 1; dest < comm.Size; ++dest)
                {
                    Console.Write("Pinging process with rank " + dest + "...");
                    double[] vals = { 6, 9 };
                    comm.Send(vals, dest, 0);
                    Console.Write("Sended");

                    double[] values = new double[2];
                    comm.Receive(dest, 1, ref values);
                    Console.Write("Devolver");

                    foreach (double v in values)
                    {
                        Console.WriteLine(v);
                    }

                    //Console.WriteLine(" Pong!");
                    //Console.WriteLine("  Rank " + dest + " is alive and running on " + destHostname);
                }
            }
            else
            {
                double[] values = new double[2];
                comm.Receive(0, 0, ref values);
                Console.Write("Received " + comm.Rank);
                values[0]++;
                comm.Send(values, 0, 1);
            }
        }
    }
예제 #20
0
파일: Program.cs 프로젝트: wormst/prirChess
    static void Main(string[] args)
    {
        using (new MPI.Environment(ref args))
        {
            Intracommunicator comm = Communicator.world;

            if (comm.Rank == 0)
            {
                RunEngine();

                for (int i = 1; i < comm.Size; i++)
                {
                    comm.Send(new InterProcessData()
                    {
                        ShallQuit = true
                    }, i, 0);
                }
            }
            else
            {
                PieceMoves.InitiateChessPieceMotion();

                while (true)
                {
                    var data = comm.Receive <InterProcessData>(0, 0);

                    if (data.ShallQuit)
                    {
                        break;
                    }

                    MoveContent bestMove = Search.Execute(data.ExamineBoard, data.pos, data.depth, data.GameBook);
                    comm.Send(bestMove, 0, 0);
                }
            }
        }
    }
예제 #21
0
 static bool parseRequest(Intracommunicator comm, Fork fork, bool isLeft, int id, int Id)
 {
     if (fork.HasFork && !fork.IsClean)
     {
         fork.HasFork = false;
         fork.IsClean = true;
         comm.Send <Message>(new Message(Id, FORK_RESPONSE), id, 0);
         Console.WriteLine(indentation + "Saljem vilicu " + id);
         return(false);
     }
     else
     {
         return(true);
     }
 }
예제 #22
0
 static void main(string[] args)
 {
     using (new MPI.Environment(ref args))
     {
         Intracommunicator comm = Communicator.world;
         if (comm.Rank == 0)
         {
             Console.WriteLine("Rank 0 is alive and running on " + MPI.Environment.ProcessorName);
             for (int dest = 1; dest < comm.Size; ++dest)
             {
                 Console.Write("Pinging process with rank " + dest + "...");
                 comm.Send("Ping!", dest, 0);
                 string destHostname = comm.Receive <string>(dest, 1);
                 Console.WriteLine(" Pong!");
                 Console.WriteLine("  Rank " + dest + " is alive and running on " + destHostname);
             }
         }
         else
         {
             comm.Receive <string>(0, 0);
             comm.Send(MPI.Environment.ProcessorName, 0, 1);
         }
     }
 }
예제 #23
0
 static void Main(string[] args)
 {
     using (new MPI.Environment(ref args))
     {
         Intracommunicator comm = Communicator.world;
         //root
         if (Communicator.world.Rank == 0)
         {
             Console.WriteLine("Sending a message and blocking");
             comm.Send("blah", 1, 0);
             Console.WriteLine("Note: This was not printed until the message was recieved.");
         }
         //not the root
         else
         {
             comm.Receive <string>(0, 1);
             Console.WriteLine("Recieved the Message. Note: This was not printed until the message was received.");
         }
     }
 }
예제 #24
0
 static private void MakeDecision(Fork fork, int neighbourId, Intracommunicator comm)
 {
     if (fork.haveFork)
     {
         if (!fork.Dirty)
         {
             return;
         }
         else if (fork.Dirty)
         {
             string pom = "";
             fork.haveFork = false;
             for (int i = 0; i < comm.Rank; i++)
             {
                 pom += SPACING;
             }
             Console.WriteLine(pom + "sending fork" + neighbourId.ToString());
             comm.Send <bool>(true, neighbourId, 1);
         }
     }
 }
예제 #25
0
 static private void OdluciStoSaVilicom(Intracommunicator comm, Vilica Vilica, int susjed)
 {
     if (Vilica.ImamVilicu)
     {
         if (Vilica.Stanje == StanjeVilice.cisto)
         {
             return;
         }
         else if (Vilica.Stanje == StanjeVilice.prljavo)
         {
             string pomak = "";
             Vilica.ImamVilicu = false;
             for (int p = 0; p < comm.Rank; p++)
             {
                 pomak += RAZMAK;
             }
             System.Console.WriteLine(pomak + "SaljemVilicu" + susjed);
             comm.Send <bool>(true, susjed, 1);
         }
     }
 }
예제 #26
0
        public override void synchronize()
        {
            Intracommunicator localComm = mpi.localComm(this);

            int[] peers = mpi.ranksOf(this, "receive");

            double a = data.a;
            double b = data.b;
            int    N = peers.Length;

            double interval = (b - a) / N;

            double x = a;

            foreach (int r in peers)
            {
                localComm.Send <double>(new double[2] {
                    x, x + interval
                }, r, 0);
                x += interval;
            }
        } // end activate method
예제 #27
0
    private static void sync()
    {
        byte foo = (byte)99;

        if (self == 0)
        {
            comm.Send(foo, other, 41);
            comm.Receive(other, 41, out foo);
            comm.Send(foo, other, 41);
        }
        else
        {
            comm.Receive(other, 41, out foo);
            comm.Send(foo, other, 41);
            comm.Receive(other, 41, out foo);
        }
    }
예제 #28
0
        static private void ProsljediVilicu(Intracommunicator comm, Vilica vilica, int susjed)
        {
            if (vilica.ImamVilicu)
            {
                if (vilica.Stanje == StanjeVilice.cista)
                {
                    return;
                }
                else if (vilica.Stanje == StanjeVilice.prljava)
                {
                    string pomak = "";
                    for (int i = 0; i < comm.Rank; ++i)
                    {
                        pomak += RAZMAK;
                    }

                    Console.WriteLine(pomak + "Saljem vilicu " + susjed);

                    vilica.ImamVilicu = false;
                    comm.Send(true, susjed, 1);
                }
            }
        }
예제 #29
0
        public void Migrate(int subPopulationSize, bool onlyBest = true)
        {
            Intracommunicator comm = Intracommunicator.world;

            if (comm.Size < 2)
            {
                return;
            }
            var indexes       = GetSubPopulationIndexes(subPopulationSize, onlyBest);
            var subPopulation = GetSubPopulation(indexes);
            int to            = (comm.Rank + 1) % comm.Size;
            int from          = (comm.Rank + comm.Size - 1) % comm.Size;

            comm.Send(subPopulation, to, 0);
            Individuo[] guests = new Individuo[subPopulationSize];
            comm.Receive(from, 0, out guests);
            int i = 0;

            foreach (var index in indexes)
            {
                _population[index] = guests[i];
                i++;
            }
        }
예제 #30
0
            public IObjectiveScores <MpiSysConfig>[] EvaluateScore(MpiSysConfig systemConfiguration)
            {
                int rank = comm.Rank;

                if (rank == 0)
                {
                    for (int i = 1; i < comm.Size; i++)
                    {
                        comm.Send(systemConfiguration, i, Convert.ToInt32(MpiMessageTags.SystemConfigurationMsgTag));
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Info("Process " + comm.Rank + " has sent the sys configs to evaluate");
                    }
                    IObjectiveScores <MpiSysConfig>[] allscores = new IObjectiveScores <MpiSysConfig> [comm.Size - 1];
                    IObjectiveScores <MpiSysConfig>   objscore  = null;
                    if (log.IsDebugEnabled)
                    {
                        log.Info("Process " + comm.Rank + " waiting to receive results from all slave processes");
                    }
                    for (int i = 1; i < comm.Size; i++)
                    {
                        comm.Receive(i, Convert.ToInt32(MpiMessageTags.EvalSlaveResultMsgTag), out objscore);
                        allscores[i - 1] = objscore;
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Info("Process " + comm.Rank + " has received all the scores evaluated ");
                    }
                    return(allscores);
                }
                else
                {
                    throw new NotSupportedException("MpiObjectiveEvaluator is designed to work with MPI process rank 0 only");
                }
            }
예제 #31
0
        public static bool[] genetskiAlgoritamParalelno(Intracommunicator comm, int MyRank,int brojEmigranata, int velicinaPopulacije, int brojGeneracija, double vjrojatnostKrizanja, double vjerojatnostMutacije, bool rouletteWheel, bool uniformno, List<int> varijable, List<Zagrada> Formula, Dictionary<int, List<Zagrada>> veze_var_zagrada)
        {
            Random rand = new Random();
            double postotak = 0.1;
            int count = 0;
            int PaziOdKudaIdeNova;
            Populacija trenutna = new Populacija(velicinaPopulacije, varijable.Count, varijable, veze_var_zagrada, rand);
            List<Zagrada> mojDioFormule = mojeZagrade(varijable, veze_var_zagrada);
            trenutna.EvaluirajPopulacijuSTezinama(mojDioFormule, varijable, veze_var_zagrada);
            if (trenutna.populacija[0].dobrota == 1) return trenutna.populacija[0].bitovi;
            double[] vjerojatnosti = new double[varijable.Count];
            for (int i = 1; i <= brojGeneracija; i++)
            {
                PaziOdKudaIdeNova = brojEmigranata;
                azurirajVjerojatnosti(vjerojatnosti, varijable, veze_var_zagrada);
                Populacija novaGeneracija = new Populacija(velicinaPopulacije);
                trenutna.KopirajElitu(novaGeneracija, brojEmigranata, vjerojatnosti, varijable, veze_var_zagrada, rand);
                if (count > (int)brojGeneracija * postotak)
                {
                    Console.WriteLine(MyRank);
                    count = 0;
                    postotak += 0.1;
                    PaziOdKudaIdeNova = 2 * brojEmigranata;
                    for (int k = brojEmigranata, l = 0; k < 2 * brojEmigranata ; k++, l++)
                    {
                        if (MyRank == 0)
                        {
                            comm.Send(novaGeneracija.populacija[l].bitovi, 1, 0);
                            comm.Send(novaGeneracija.populacija[l].brojVarijabli, 1, 0);
                            comm.Send(novaGeneracija.populacija[l].brojZadovoljenihZagrada, 1, 0);
                            comm.Send(novaGeneracija.populacija[l].dobrota, 1, 0);

                            bool[] b = new bool[varijable.Count];
                            double fit;
                            int brZagovoljenih, brVar;
                            comm.Receive(comm.Size - 1, 0, ref b);
                            brVar = comm.Receive<int>(comm.Size - 1, 0);
                            brZagovoljenih = comm.Receive<int>(comm.Size - 1, 0);
                            fit = comm.Receive<double>(comm.Size - 1, 0);
                            novaGeneracija.populacija[k] = new Jedinka(b, fit, brZagovoljenih, brVar);
                        }
                        else
                        {
                            bool[] b = new bool[varijable.Count];
                            double fit;
                            int brZagovoljenih, brVar;
                            comm.Receive(MyRank - 1, 0, ref b);
                            brVar = comm.Receive<int>(MyRank - 1, 0);
                            brZagovoljenih = comm.Receive<int>(MyRank - 1, 0);
                            fit = comm.Receive<double>(MyRank - 1, 0);
                            novaGeneracija.populacija[k] = new Jedinka(b, fit, brZagovoljenih, brVar);

                            comm.Send(novaGeneracija.populacija[l].bitovi, (MyRank + 1) % comm.Size, 0);
                            comm.Send(novaGeneracija.populacija[l].brojVarijabli, (MyRank + 1) % comm.Size, 0);
                            comm.Send(novaGeneracija.populacija[l].brojZadovoljenihZagrada, (MyRank + 1) % comm.Size, 0);
                            comm.Send(novaGeneracija.populacija[l].dobrota, (MyRank + 1) % comm.Size, 0);
                        }
                    }
                    if (MyRank == 1) Console.WriteLine("Sad sam razmijenio podatke");
                }
                count++;
                for (int j = PaziOdKudaIdeNova ; j < velicinaPopulacije; j += 2)
                {
                    Jedinka prviRoditelj = trenutna.OdaberiRoditelja(true, rand);
                    Jedinka drugiRoditelj = trenutna.OdaberiRoditelja(true, rand);
                    Jedinka prvoDijete = new Jedinka(varijable.Count);
                    Jedinka drugoDijete = new Jedinka(varijable.Count);
                    trenutna.Krizanje(vjrojatnostKrizanja, prviRoditelj, drugiRoditelj, prvoDijete, drugoDijete, false, veze_var_zagrada, varijable, rand);
                    prvoDijete.Mutacija(vjerojatnostMutacije, varijable, veze_var_zagrada, rand);
                    drugoDijete.Mutacija(vjerojatnostMutacije, varijable, veze_var_zagrada, rand);
                    novaGeneracija.populacija[j] = prvoDijete;
                    novaGeneracija.populacija[j + 1] = drugoDijete;
                }
                novaGeneracija.EvaluirajPopulacijuSTezinama(mojDioFormule, varijable, veze_var_zagrada);
                trenutna = novaGeneracija;
                if (MyRank == 1) Console.WriteLine(trenutna.VratiNajboljuDobrotu());
                if (trenutna.populacija[0].dobrota == 1) return trenutna.populacija[0].bitovi;
            }
            bool[] ret = null;
            return ret;
        }
예제 #32
0
파일: Netpipe_cs.cs 프로젝트: jmhal/MPI.NET
    static void Main(string[] args)
    {
        // Whether we should use the unsafe, Direct interface to MPI.
        // When false, use the normal MPI.NET interface.
        bool useDirectInterface = false;

        using (MPI.Environment env = new MPI.Environment(ref args))
        {
            if (args.Length > 0 && args[0] == "/direct")
            {
                useDirectInterface = true;
                System.Console.WriteLine("Using direct MPI interface.");
            }
            else
                System.Console.WriteLine("Using MPI.NET interface.");

            comm = MPI.Communicator.world;
            if (comm.Size != 2)
            {
                if (comm.Rank == 0)
                    System.Console.WriteLine("Only two processes allowed.  Rerun with -np 2");
                return;
            }
            else
            {
                self = comm.Rank;
                other = (comm.Rank + 1) % 2;
            }

            System.Console.WriteLine(comm.Rank + ": " + MPI.Environment.ProcessorName);

            bwstats = new Stats[nSamp];

            testLatency();
            testSyncTime();
            comm.Broadcast(ref latency, 0);

            if (self == 0)
            {
                System.Console.WriteLine("Latency: {0:F9}", latency);
                System.Console.WriteLine("Sync Time: {0:F9}", synctime);
                System.Console.WriteLine("Now starting main loop");
            }

            int i, j, n, nq;
            int inc = 1, len;
            int start = 0, end = 1024 * 1024 * 1024;
            int bufflen = start;
            double tlast = latency;

            for (n = nq = 0, len = start; tlast < stopTime && len <= end; len += inc, nq++)
            {
                if (nq > 2 && (nq % 2 != 0)) inc *= 2;
                int ipert, pert;
                for (ipert = 0, pert = (inc > PERT + 1) ? -PERT : 0;
                     pert <= PERT;
                     ipert++, n++, pert += (inc > PERT + 1) ? PERT : PERT + 1)
                {
                    int nRepeat = bufflen == 0 ?
                                  latencyReps :
                                  (int)Math.Max((RUNTM / ((double)bufflen / (bufflen - inc + 1.0) * tlast)),
                                                TRIALS);
                    comm.Broadcast(ref nRepeat, 0);

                    bufflen = len + pert;
                    byte[] sendBuffer = new byte[bufflen]; // Align the data?  Some day.  Maybe.
                    byte[] recvBuffer = new byte[bufflen];
                    if (self == 0)
                        System.Console.Write("{0,3:D}: {1,9:D} bytes {2,7:D} times ---> ", n, bufflen, nRepeat);

                    bwstats[n].t = 1e99;
                    double t1 = 0, t2 = 0;
                    
                    for (i = 0; i < TRIALS; i++)
                    {
                        sync();
                        double t0 = when();
                        if (useDirectInterface)
                        {
                            // Use the unsafe, direct interface to MPI via P/Invoke
                            unsafe
                            {
                                fixed (byte* sendPtr = sendBuffer, recvPtr = recvBuffer)
                                {
                                    for (j = 0; j < nRepeat; j++)
                                    {
                                        if (self == 0)
                                        {
                                            Unsafe.MPI_Send(new IntPtr(sendPtr), bufflen, Unsafe.MPI_BYTE, other, 142, Unsafe.MPI_COMM_WORLD);
                                            Unsafe.MPI_Recv(new IntPtr(recvPtr), bufflen, Unsafe.MPI_BYTE, other, 242, Unsafe.MPI_COMM_WORLD, out *Unsafe.MPI_STATUS_IGNORE);
                                        }
                                        else
                                        {
                                            Unsafe.MPI_Recv(new IntPtr(recvPtr), bufflen, Unsafe.MPI_BYTE, other, 142, Unsafe.MPI_COMM_WORLD, out *Unsafe.MPI_STATUS_IGNORE);
                                            Unsafe.MPI_Send(new IntPtr(sendPtr), bufflen, Unsafe.MPI_BYTE, other, 242, Unsafe.MPI_COMM_WORLD);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (j = 0; j < nRepeat; j++)
                            {
                                if (self == 0)
                                {
                                    comm.Send(sendBuffer, other, 142);
                                    comm.Receive(other, 242, ref recvBuffer);
                                }
                                else
                                {
                                    comm.Receive(other, 142, ref recvBuffer);
                                    comm.Send(sendBuffer, other, 242);
                                }
                            }
                        }
                        double t = (when() - t0) / (2.0 * nRepeat);
                        t2 += t*t;
                        t1 += t;
                        bwstats[n].t = Math.Min(bwstats[n].t, t);
                        bwstats[n].variance = t2 / TRIALS - t1 / TRIALS * t1 / TRIALS;
                        tlast = bwstats[n].t;
                        bwstats[n].bits = bufflen * sizeof(byte)*8;
                        bwstats[n].bps = bwstats[n].bits / (bwstats[n].t * 1024 * 1024);
                        bwstats[n].repeat = nRepeat;
                    }
                    if (self == 0)
                        System.Console.WriteLine("{0,9:F2} Mbps in {1:F9} sec", bwstats[n].bps, tlast);
                }
            }
        }
    }