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); } } }
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); } }
private static void MpiTest(string[] args) { using (new MPI.Environment(ref args)) { Console.WriteLine("Rank: " + Communicator.world.Rank + "(running on " + MPI.Environment.ProcessorName + ")"); Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { Request req = comm.ImmediateSend("Rosie", 1, 0); Console.WriteLine(req.Test() != null ? "COMPL" : "NOT COMPL"); string msg = comm.Receive <string>(Communicator.anySource, Communicator.anyTag); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg)); req = comm.ImmediateSend("Rosie", 1, 0); Console.WriteLine(req.Test() != null ? "COMPL" : "NOT COMPL"); msg = comm.Receive <string>(Communicator.anySource, Communicator.anyTag); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg)); } else { string msg = comm.Receive <string>(comm.Rank - 1, 0); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg)); Request req = comm.ImmediateSend(msg + "," + comm.Rank, (comm.Rank + 1) % comm.Size, 0); Console.WriteLine(req.Test() != null ? "COMPL" : "NOT COMPL"); msg = comm.Receive <string>(comm.Rank - 1, 0); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg)); req = comm.ImmediateSend(msg + "," + comm.Rank, (comm.Rank + 1) % comm.Size, 0); Console.WriteLine(req.Test() != null ? "COMPL" : "NOT COMPL"); } } }
/// <summary> /// Start the alive process /// </summary> public void Start() { StartSignal startSignal = comm.Receive <StartSignal>(0, 0); // We wait for the broadcast of the start of the game. map = startSignal.Map; currentTile = map.GetTileByCoordinates(startSignal.Position); AliveLoop(); }
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); }
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); }
public T ReceiveMessage <T> (int tag) where T : IMessage { _comm.Receive <T>(Communicator.anySource, tag, out T rcvdMsg, out CompletedStatus rcvdStatus); Clock = Math.Max(Clock, rcvdMsg.Clock) + 1; Logger.LogReceived(MyRank, rcvdStatus.Source, rcvdStatus.Tag, Clock); return(rcvdMsg); }
public override void synchronize() { Intracommunicator localComm = mpi.localComm(this); int[] ranks_of_collector = mpi.ranksOf(this, "collect"); int root_collect = ranks_of_collector[0]; int[] ranks_of_sender = mpi.ranksOf(this, "send"); int number_of_senders = ranks_of_sender.Length; // RECEIVE THE SIZE FROM ONE OF THE SENDERS. No overhead ... int size = localComm.Receive <int>(Intracommunicator.anySource, 0); double[] dummy_result = new double[size]; double[] local_result = localComm.Reduce <double>(dummy_result, Operation <double> .Add, root_collect); double result = 0.0D; foreach (double r in local_result) { result += r; } data.Value = result; } // end activate method
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!"); } } }
private void ReadMessagesLoop() { while (keepReading) { var messageString = communicator.Receive <string>(RootNode, MPIMessageTags.SerializedMessagesTag); var message = messageSerializer.DeserializeMessage <INodeMessage>(messageString); switch (message) { case DocumentTokenizedMessage tokenizedMessage: documentTokenizedSubject.OnNext(tokenizedMessage.Document); break; case DocumentNormalizedMessage normalizedMessage: documentNormalizedSubject.OnNext(normalizedMessage.Document); break; case NodeAvailabilityChange availabilityChange: availabilityChangesSubject.OnNext(availabilityChange); break; case WorkAssignment assignment: assignmentsSubject.OnNext(assignment); break; } } }
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); } }
public override void synchronize() { Intracommunicator localComm = mpi.localComm(this); int root = mpi.ranksOf(this, "distribute")[0]; double[] limits = new double[2]; localComm.Receive <double>(root, 0, ref limits); data.a = limits[0]; data.b = limits[1]; } // end activate method
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); } } }
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); } } }
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(); } }
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); } }
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); } } }
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); } } }
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(); }
private static void SerializationTest2(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { var test = new MonitorMessage <ProdConsInternals <int> >() { InternalState = new ProdConsInternals <int>() { N = 100, Full = new ConditionalVar() { WaitingQueue = new List <int>() { 1 } }, Empty = new ConditionalVar() { WaitingQueue = new List <int>() { 2 } } }, LastCsEntrySyncNumber = 0, }; Request req = comm.ImmediateSend(test, 1, 0); req.Test(); } else { MonitorMessage <ProdConsInternals <int> > msg = comm.Receive <MonitorMessage <ProdConsInternals <int> > > (Communicator.anySource, Communicator.anyTag); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg.InternalState.Full.WaitingQueue.First())); } } }
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."); } } }
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); } }
private static void SerializationTest(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { ConditionalVar testCon = new ConditionalVar { WaitingQueue = new List <int> { 1, 2, 3, 4, 5 } }; Request req = comm.ImmediateSend(testCon, 1, 0); req.Test(); } else { ConditionalVar msg = comm.Receive <ConditionalVar>(Communicator.anySource, Communicator.anyTag); Console.WriteLine(string.Format("#{0} received message [{1}]", comm.Rank, msg.WaitingQueue[0])); } } }
static void Main(string[] args) { int[] numere = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int suma = 0; using (new MPI.Environment(ref args)) { Intracommunicator comm = MPI.Communicator.world; for (int proces = 0; proces <= comm.Size - 1; proces++) { if (comm.Rank == 0) { for (int i = 1; i < comm.Size; i++) { suma += comm.Receive <int>(i, 0); } Console.WriteLine("Suma este: " + suma); } } } }
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); } } } }
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++; } }
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"); } }
static void Main(string[] _args) { using (new MPI.Environment(ref _args)) { Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { // program for rank 0 string programName = "Gauss-Seidel Linear System of Equations Solver"; string programVer = "1.0 (parallel)"; string programAuthor = "Quy N.H."; Console.WriteLine(programName + " v" + programVer + " by " + programAuthor + "\n"); bool testing = false; string[] args = _args; if (testing) { args = "-o output.txt -b 200 -t 10".Split(new char[] { ' ' }); } // parse args string inputFile = "", outputFile = ""; bool benchmarkMode = false, showEquation = false, generateInput = false, showBenchmark = false; int benchmarkSize = 3; int benchmarkTime = 1; int i = 0; while (i < args.Length) { string arg = args[i]; if (arg.StartsWith("--")) { arg = arg.Substring(2); switch (arg) { case "input": if (i + 1 < args.Length) { inputFile = args[i + 1]; } break; case "output": if (i + 1 < args.Length) { outputFile = args[i + 1]; } break; case "show-equation": showEquation = true; break; case "show-benchmark": showBenchmark = true; break; case "generate-input": generateInput = true; break; case "benchmark": if (i + 1 < args.Length && int.TryParse(args[i + 1], out benchmarkSize)) { benchmarkMode = true; i++; } ; break; case "times": if (i + 1 < args.Length && int.TryParse(args[i + 1], out benchmarkTime)) { benchmarkMode = true; i++; } ; break; } } else if (arg.StartsWith("-")) { arg = arg.Substring(1); switch (arg) { case "i": if (i + 1 < args.Length) { inputFile = args[i + 1]; } break; case "o": if (i + 1 < args.Length) { outputFile = args[i + 1]; } break; case "e": showEquation = true; break; case "m": showBenchmark = true; break; case "g": generateInput = true; break; case "b": if (i + 1 < args.Length && int.TryParse(args[i + 1], out benchmarkSize)) { benchmarkMode = true; i++; } ; break; case "t": if (i + 1 < args.Length && int.TryParse(args[i + 1], out benchmarkTime)) { benchmarkMode = true; i++; } ; break; } } i++; } // get input(s) List <Matrix> As = new List <Matrix>(), bs = new List <Matrix>(), sols = new List <Matrix>(), xs = new List <Matrix>(); if (benchmarkMode) { // generate input for (int j = 0; j < benchmarkTime; j++) { As.Add(Matrix.generateDiagonallyDominantMatrix(benchmarkSize, true, -100, 100)); bs.Add(Matrix.random(benchmarkSize, 1, -100, 100, true)); } Console.WriteLine("Generated " + benchmarkTime.ToString() + " random system(s) to solve."); } else if (inputFile.Length > 0 && File.Exists(inputFile)) { // parse input string inputArray = File.ReadAllText(inputFile); Utils.parseInput(inputArray, out As, out bs, out sols); Console.WriteLine("Got " + As.Count.ToString() + " system(s) from input file."); } else { // yell at user Console.WriteLine("Give me some inputs!"); Console.WriteLine("Exiting..."); MPI.Environment.Abort(1); } // do the calculation List <bool> converges = new List <bool>(); List <int> loopses = new List <int>(); List <Matrix> errs = new List <Matrix>(); int equCounts = As.Count; benchmark bm = new benchmark(); string bmResult = ""; Console.WriteLine("Now working with " + (comm.Size).ToString() + " process(es)...\n"); Gauss_Seidel_Parallel.showBenchmark = showBenchmark; bm.start(); for (int j = 0; j < equCounts; j++) { Console.Write("Solving system #" + (j + 1).ToString() + "... "); Matrix x, err; int loops = 0; for (int r = 1; r < comm.Size; r++) { comm.Send("start", r, 0); } bool converge = Gauss_Seidel_Parallel.solve(As[j], bs[j], out x, out err, out loops, comm); xs.Add(x); loopses.Add(loops); converges.Add(converge); errs.Add(err); Console.WriteLine("Done."); } bmResult = bm.getResult(); // write output if (!generateInput) { // show the result as usual if (outputFile.Length > 0) { writeOutput(outputFile, "\n"); } for (int j = 0; j < equCounts; j++) { Matrix x = xs[j], err = errs[j]; int loops = loopses[j]; bool converge = converges[j]; string strResult = ""; if (showEquation) { strResult += "\nEquation:\n" + Utils.writeEquation(As[j], bs[j]); } strResult += "\nNo. equations: " + x.Height.ToString(); strResult += "\nSolution: " + Matrix.Transpose(x).ToString(1e-14); strResult += "\nErrors: " + Matrix.Transpose(err).ToString(1e-14); strResult += "\nMean absolute error: " + string.Format("{0:0.##############}", Matrix.Abs(err).avgValue); strResult += "\nConverged: " + converge.ToString(); strResult += "\nLoops: " + loops.ToString(); writeOutput(outputFile, strResult); } writeOutput(outputFile, "\nElapsed time: " + bmResult + " (" + string.Format("{0:0.###}", bm.getElapsedSeconds() / equCounts) + " sec / equation)."); writeOutput(outputFile, ""); } else { // create a valid input file for (int j = 0; j < equCounts; j++) { Matrix x = xs[j], err = errs[j]; int loops = loopses[j]; bool converge = converges[j]; string strResult = "\n-----------\n"; strResult += x.Height.ToString(); strResult += "\n"; strResult += As[j].ToString(); strResult += "\n"; strResult += Matrix.Transpose(bs[j]).ToString(); strResult += "\n"; strResult += Matrix.Transpose(x).ToString(1e-14); strResult += "\n"; writeOutput(outputFile, strResult); } writeOutput("", "\nElapsed time: " + bmResult + " (" + string.Format("{0:0.###}", bm.getElapsedSeconds() / equCounts) + " sec / equation)."); writeOutput("", ""); } Console.WriteLine("Done. Exiting..."); // tell other ranks to exit for (int r = 1; r < comm.Size; r++) { comm.Send("exit", r, 0); } } else { // program for all other ranks // wait for command (start (solveSub), exit) string command = null; do { command = comm.Receive <string>(0, 0); // receive command from rank 0 if (command == "start") { Matrix A = null, b = null, x, err; int loops; Gauss_Seidel_Parallel.solve(A, b, out x, out err, out loops, comm); } } while (command != "exit"); } } }
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; }
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); } } } }
static void Main(String[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = MPI.Communicator.world; int p = comm.Size; int rank = comm.Rank; int range = 0, rem = 0, tag = 0; int N = 0; // the number of subparts of an image int noOfComponent = 0; int noOfPersons = 0; // the no of persons in the training data (here it's 5) string minLabel = ""; double minDistance = 0; //this is used to get the distance of the training data and the predicted image EuclideanDistance ed = new EuclideanDistance(); //this list will containt the parts of image after deviding it to N parts List <double[][]> testSubImgs = new List <double[][]>(); //this will contain the weighs of each persono (N parts for each person) List <double[][]> weights = new List <double[][]>(); //the label associated with each weight List <string> labels = new List <string>(); if (rank == 0) // It's the root { //create an object of the algorithm ModularFaceRecognitionAlgorithms mpca = new ModularFaceRecognitionAlgorithms(); //load the training data from file mpca.loadTrainingData("C:/train.txt"); //prepare the image for testing // u can change s1 to s2,s3,s4 ... s5 and watch out the result String filePath = "C:/test/s4/10.bmp"; Matrix test = FileManager.GetBitMapColorMatrix(filePath); //divide the image into N parts testSubImgs = testSubImgs = mpca.devideImageToN(test, mpca.N); //prepare local variables noOfPersons = mpca.weights.Count / mpca.N; N = mpca.N; noOfComponent = mpca.numOfComponents; weights = mpca.weights; labels = mpca.labels; if (p > 1) //this cond. to handle the exception of a single master process { //compute the no. of persons checked per process //each process will be resposible for a nubmber of persons //the process returns the dist. and label of the min distance of its persons range = noOfPersons / (p - 1); rem = noOfPersons % (p - 1); if (range == 0) // in case for ex. we have 5 persons and 6 slaves { range = 1; rem = 0; } } else { Console.WriteLine("There's only a master process"); } //broadcast the needed variables comm.Broadcast(ref N, 0); comm.Broadcast(ref noOfComponent, 0); comm.Broadcast(ref range, 0); comm.Broadcast(ref rem, 0); comm.Broadcast(ref testSubImgs, 0); comm.Broadcast(ref weights, 0); comm.Broadcast(ref labels, 0); comm.Broadcast(ref noOfPersons, 0); string resLabel = ""; //the final resulted label double resDistance = 0; // the final resulted distance minLabel = ""; //used to receive the min label of each slave minDistance = 0; //used to reciec the min distance of each slave //in the following for loop we are receiving the min distance and label //resulted from each slave and then get the min of them all // the resulted resLabel and resDistance is the final result //these line is used to handle if we have processes more than the noOfpersons int endLoop = p - 1; if (noOfPersons < (p - 1)) { endLoop = noOfPersons; } for (int src = 1; src <= endLoop; src++) { comm.Receive(src, tag, out minDistance); comm.Receive(src, tag, out minLabel); if (src == 1 || minDistance < resDistance) { resLabel = minLabel; resDistance = minDistance; } } Console.WriteLine("resLabel = " + resLabel); Console.WriteLine("resDistance = " + resDistance); } else { comm.Broadcast(ref N, 0); comm.Broadcast(ref noOfComponent, 0); comm.Broadcast(ref range, 0); comm.Broadcast(ref rem, 0); comm.Broadcast(ref testSubImgs, 0); comm.Broadcast(ref weights, 0); comm.Broadcast(ref labels, 0); comm.Broadcast(ref noOfPersons, 0); if (rank <= noOfPersons) //other wise do nothing { if (rank <= rem) { range++; } int start = 0; if (rank <= rem) { start = (rank - 1) * N + (rank - 1) * N; } else { start = (rank - 1) * N + rem * N; } //As we mentioned before the range is the number of personse per process // so in this for loop we are calculating the distance of each person // and eventually send the min distance and lable to the master process for (int i = 0; i < range; i++) { double dpj = 0; int begin = i * N + start; for (int j = begin, m = 0; m < N; j++, m++) { double dist = ed.getDistance(weights[j], testSubImgs[m]); dpj += ((double)1 / noOfComponent) * dist; } double dp = ((double)1 / N) * dpj; if (i == 0 || dp < minDistance) { minLabel = labels[begin]; minDistance = dp; } } comm.Send(minDistance, 0, 0); comm.Send(minLabel, 0, 0); } } } }
static void Main(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; int Id = comm.Rank; Connect4 game = new Connect4(comm, comm.Size, Id); if (Id == 0) { Board board = new Board(); //game.CalculateNextMove(board); Stopwatch timer = new Stopwatch(); timer.Start(); Console.WriteLine("Igra krece!"); while (true) { board.Draw(); bool kraj = false; while (true) { Console.WriteLine("Daj potez:"); try { int column = Int32.Parse(Console.ReadLine()); if (board.Put(column, 1)) { kraj = true; } break; } catch (Exception) { } } if (kraj) { Console.WriteLine("Pobijedio je igrac!"); break; } timer.Reset(); timer.Start(); int nextMove = game.CalculateNextMove(board.Duplicate()); Console.WriteLine("Potrebno vrijeme za izračun: " + timer.ElapsedMilliseconds); Console.WriteLine("Računalo igra potez " + nextMove); if (board.Put(nextMove, 2)) { Console.WriteLine("Pobijedilo je računalo!"); break; } } board.Draw(); Message exitMsg = new Message(0, EXIT); comm.Broadcast <Message>(ref exitMsg, 0); } else { while (true) { Message msg = null; comm.Broadcast <Message>(ref msg, 0); if (msg.MessageType == EXIT) { break; } comm.Send <Message>(new Message(Id, NEXT_TASK), 0, 0); while (true) { msg = comm.Receive <Message>(0, 0); if (msg.MessageType == STOP) { break; } else if (msg.MessageType == TASK) { Task task = msg.task; task.value = game.CalculateStateValue(task.b, game.Reverse(task.nextPlayer), -1, 0); Message answer = new Message(Id, RESULT); answer.task = task; comm.Send <Message>(answer, 0, 0); } } } } } }