static void Main(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator world = Communicator.world; if (world.Rank == 0) { Polynomial polyA = new Polynomial(4); polyA.GeneratePolynomial(); Polynomial polyB = new Polynomial(8); polyB.GeneratePolynomial(); Console.WriteLine("A: " + polyA.ToString()); Console.WriteLine("B: " + polyB.ToString()); //world.Send("trimit la alt proces", 1, 0); //string message = world.Receive<string>(Communicator.anySource, 0); Console.WriteLine("Rank: " + world.Rank); //Console.WriteLine("PolyMULCheck: " + Util.Multiplication(polyA,polyB).ToString()); Console.WriteLine("PolyKaraCheck: " + Util.Karatsuba(polyA, polyB).ToString()); //MpiParent(polyA, polyB); MpiKaratsubaParent(polyA, polyB); } else { //string message = world.Receive<string>(world.Rank - 1, 0); //Console.WriteLine("Rank: " + world.Rank + " received message: \"" + message + "\" "); //world.Send(message + "," + world.Rank, (world.Rank + 1) % world.Size, 0); Console.WriteLine("Rank: " + world.Rank); //MpiChild(); MpiKaratsubaChild(); } } }
public override void synchronize() { Intracommunicator localComm = mpi.localComm(this); int root = mpi.ranksOf(this, "distribute")[0]; double[,] a_local = localComm.Scatter <double[, ]>(root); double[,] b_local = localComm.Scatter <double[, ]>(root); int number_of_jobs = a_local.GetLength(0); int dim_num = a_local.GetLength(1); for (int i = 0; i < number_of_jobs; i++) { IIntegralCase <F> ic = (IIntegralCase <F>)data.createElement(); ic.dim_num = dim_num; for (int j = 0; j < dim_num; j++) { ic.a[j] = a_local[i, j]; ic.b[j] = b_local[i, j]; } } // data.a = limits[0]; // data.b = limits[1]; } // end activate method
override public void initialize() { nx = Blocks.nx; ny = Blocks.ny; ipt = Blocks.ipt; jpt = Blocks.jpt; isiz3 = Instance.isiz3; isiz1 = Problem.isiz1; isiz2 = Problem.isiz2; u = Problem.Field_u; ii1 = Constants.ii1; ii2 = Constants.ii2; ji1 = Constants.ji1; ji2 = Constants.ji2; ki1 = Constants.ki1; ki2 = Constants.ki2; c2 = Constants.c2; dxi = Constants.dxi; deta = Constants.deta; dzeta = Constants.dzeta; worldcomm = this.WorldComm; // Mpi.worldComm(); }
public static void matrixMultiply(int[,] a, int[,] b, int[,] c, Intracommunicator comm) { int i; int[] d = new int[16]; for (i = 0; i < 16; i++) { d[i] = 0; Console.WriteLine(d[k]); } size = n / numberOfProcesses; start = processID * size; finish = (processID + 1) * size; Console.WriteLine("Proc with rank: " + processID + " is getting from: " + start + " to: " + finish); for (i = start; i <= finish; ++i) { for (j = 0; j < n; ++j) { for (k = 0; k < n; ++k) { c[i, j] += a[i, k] * b[k, j]; } } } comm.Allgather <int>(c[i, j], ref d); for (k = 0; k < n; k++) { Console.WriteLine("d[ " + k + "] = " + d[k]); } }
static void Main(string[] args) { k = 0; using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; procid = Communicator.world.Rank; numproc = Communicator.world.Size; FloydWarshall(graph, 4, procid, numproc, comm); /* for (k = 0; k < 4; k++) * { * Console.WriteLine("heeeeeeeeereeee\n hereeeeee " + k); * * * } * for (j = procid; j <= procid+1; j++) * { * * Console.WriteLine("procid :" + procid); * }*/ } }
public static int[] SimpleParallel(Intracommunicator communicator, int[] p1, int[] p2) { var perProcess = p1.Length / communicator.Size; var start = communicator.Rank * perProcess; if (communicator.Rank == communicator.Size - 1) { perProcess += p1.Length % communicator.Size; } var result = new int[p1.Length + p2.Length - 1]; for (var offset = 0; offset < perProcess; offset++) { var i = start + offset; for (var j = 0; j < p2.Length; j++) { result[i + j] += p1[i] * p2[j]; } } var results = communicator.Gather(result, 0); if (communicator.Rank == 0) { return(results.Aggregate(new int[p1.Length + p2.Length - 1], Add).ToArray()); } return(null); }
public MPIGreedyCD(Intracommunicator comm, Rectangle totalSize, Rectangle imageSection, float[,] psf) { this.comm = comm; this.imageSection = imageSection; psf2 = PSF.CalcPSFSquared(psf); aMap = PSF.CalcAMap(psf, totalSize, imageSection); }
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"); } } }
public static LocalDataset SplitDataAmongNodes(Intracommunicator comm, LocalDataset data) { var nrBaselines = data.UVW.GetLength(0) / comm.Size; var nrFrequencies = data.Frequencies.Length; var uvwSplit = new double[nrBaselines, data.UVW.GetLength(1), 3]; var visSplit = new Complex[nrBaselines, data.UVW.GetLength(1), nrFrequencies]; var flagsSplit = new bool[nrBaselines, data.UVW.GetLength(1), nrFrequencies]; var blOffset = data.UVW.GetLength(0) / comm.Size * comm.Rank; for (int i = 0; i < nrBaselines; i++) { for (int j = 0; j < data.UVW.GetLength(1); j++) { for (int k = 0; k < nrFrequencies; k++) { visSplit[i, j, k] = data.Visibilities[blOffset + i, j, k]; flagsSplit[i, j, k] = data.Flags[blOffset + i, j, k]; } uvwSplit[i, j, 0] = data.UVW[blOffset + i, j, 0]; uvwSplit[i, j, 1] = data.UVW[blOffset + i, j, 1]; uvwSplit[i, j, 2] = data.UVW[blOffset + i, j, 2]; } } return(new LocalDataset(data.Frequencies, uvwSplit, flagsSplit, visSplit)); }
/// <summary> /// Creates a <see cref="CartesianCommunicator"/>. /// </summary> /// <param name="oldComm"> /// An existing Intracommunicator from which to create the new communicator (e.g. <see cref="MPI.Communicator.world"/>). /// </param> /// <param name="ndims"> /// The number of dimensions for the Cartesian grid. /// </param> /// <param name="dims"> /// An array of length <paramref name="ndims"/> indicating the size of the grid in each dimension. /// </param> /// <param name="periods"> /// A logical array of length <paramref name="ndims"/> indicating whether the grid is periodic in any given dimension. /// </param> /// <param name="reorder"> /// Logical indicating whether ranks may be reordered or not. /// </param> public CartesianCommunicator(Intracommunicator oldComm, int ndims, int[] dims, bool[] periods, bool reorder) { int reorder_int = Convert.ToInt32(reorder); int[] periods_int = BoolToInt(periods); unsafe { fixed(int *dimsPtr = dims, periodsPtr = periods_int) fixed(MPI_Comm * commPtr = &(this.comm)) { int errorCode = Unsafe.MPI_Cart_create(oldComm.comm, ndims, dimsPtr, periodsPtr, reorder_int, commPtr); if (errorCode != Unsafe.MPI_SUCCESS) { throw Environment.TranslateErrorIntoException(errorCode); } } } NDims = ndims; Dims = dims; Periods = periods; Coords = GetCartesianCoordinates(Rank); AttachToComm(); }
static void Main(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; int root = 0; string[] nums = new string[5]; if (comm.Rank == root) { nums[1] = "Chapter 1: MPI"; nums[2] = "Chapter 2: BitCoins"; nums[3] = "Chapter 3: MongoDB"; nums[4] = "Chapter 4: How to Make a Sandwich"; comm.Scatter(nums, root); } else { string value = comm.Scatter(nums, root); Console.WriteLine(comm.Rank + " was assigned " + value); } } }
public MapManager(Intracommunicator comm, string mapFilePath, ActorsDivider divider) { moveCount = 0; this.comm = comm; if (!File.Exists(mapFilePath)) { throw new FileNotFoundException("The map file was not found."); } map = LoadMapFromFile(mapFilePath); if (map.Rats.Count != divider.NumberOfRats || map.Cats.Count != divider.NumberOfCats) { throw new Exception("Rat or cat counts does not match with map loaded."); } InitActorProcesses(); // Logger logger = new Logger(divider.GetProcesTypeByRank); // Initialize the message listener task messageListenerTask = new Task(ReceiveMessages); logger.LogMap(map.ToString()); }
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); } }
static void Main(string[] args) { using (new MPI.Environment(ref args)) { string path; path = "..\\..\\SpawnChild\\bin\\"; #if DEBUG path += "Debug\\"; #else path += "Release\\"; #endif path += "SpawnChild.exe"; Intracommunicator comm = MPI.Communicator.world; Intercommunicator inter_comm; string[] argv = new string[0]; int maxprocs = 4; int[] error_codes = new int[maxprocs]; //inter_comm = comm.Spawn(path, argv, maxprocs, 0, out error_codes); inter_comm = comm.Spawn(path, argv, maxprocs, 0); //for (int i = 0; i < error_codes.Length; i++) // System.Console.WriteLine("error[" + i + "] = " + error_codes[i]); inter_comm.Barrier(); inter_comm.Dispose(); } }
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 static DirtyImage ForwardCalculateB(Intracommunicator comm, GriddingConstants c, List <List <Subgrid> > metadata, Complex[,,] visibilities, double[,,] uvw, double[] frequencies, Complex[,] PsfCorrelation, float[,] psfCut, float maxSidelobe, Stopwatch watchIdg) { Stopwatch another = new Stopwatch(); comm.Barrier(); if (comm.Rank == 0) { watchIdg.Start(); } var localGrid = IDG.Grid(c, metadata, visibilities, uvw, frequencies); float[,] image = null; float maxSideLobeLevel = 0.0f; var grid_total = comm.Reduce <Complex[, ]>(localGrid, SequentialSum, 0); if (comm.Rank == 0) { var dirtyImage = FFT.BackwardFloat(grid_total, c.VisibilitiesCount); FFT.Shift(dirtyImage); if (comm.Rank == 0) { FitsIO.Write(dirtyImage, "dirtyImage.fits"); } maxSideLobeLevel = maxSidelobe * Residuals.GetMax(dirtyImage); //remove spheroidal image = Residuals.CalcGradientMap(dirtyImage, PsfCorrelation, new Rectangle(0, 0, psfCut.GetLength(0), psfCut.GetLength(1))); watchIdg.Stop(); } comm.Broadcast(ref maxSideLobeLevel, 0); comm.Broadcast(ref image, 0); return(new DirtyImage(image, maxSideLobeLevel)); }
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
public void enviroment(string[] args) { mpi = new MPI.Environment(ref args); worldcomm = Communicator.world; Size = worldcomm.Size; Rank = worldcomm.Rank; }
static void Main(string[] args) { using (new MPI.Environment(ref args)) { procid = Communicator.world.Rank; numproc = Communicator.world.Size; //Communicator.world.Barrier(); Intracommunicator comm = Communicator.world; /* if (procid == 0) * { * Console.WriteLine("How many vertices?\n"); * n = Convert.ToInt32(Console.ReadLine()); * } * Communicator.world.Broadcast<int>(ref n, procid);*/ /*if (procid == 0) Console.WriteLine("Enter the local_matrix\n"); * Read_matrix(local_mat, n, procid, numproc, comm); */ Console.WriteLine("Matrix :\n"); Print_matrix(local_mat, n, procid, numproc, comm); /*if (procid == 0) Console.WriteLine("\n"); * Floyd(local_mat, n, procid, numproc, comm); * * if (procid == 0) Console.WriteLine("The solution is:\n"); * Print_matrix(local_mat, n, procid, numproc, comm);*/ } }
public static void Floyd(int[] local_mat, int n, int procid, int numproc, Intracommunicator comm) { int global_k, local_i, global_j, temp; int root; int[] row_k = new int[40]; for (global_k = 0; global_k < n; global_k++) { root = global_k / (n / numproc); //root = Owner(global_k, numproc, n); if (procid == root) { Copy_row(local_mat, n, numproc, row_k, global_k); } comm.Broadcast <int>(ref row_k, root); for (local_i = 0; local_i < n / numproc; local_i++) { for (global_j = 0; global_j < n; global_j++) { temp = local_mat[local_i * n + global_k] + row_k[global_j]; if (temp < local_mat[local_i * n + global_j]) { local_mat[local_i * n + global_j] = temp; } } } } }
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 Intracommunicator localComm(IUnit caller) { Intracommunicator _localComm = null; //_localComm = (Intracommunicator)Communicator.world.Create(Communicator.world.Group.IncludeOnly(caller.Ranks)); // _localComm = (Intracommunicator)this.WorldComm.Create(this.WorldComm.Group.IncludeOnly(caller.Ranks)); return(_localComm); }
private void SendMatrixToWorkers(Intracommunicator communicator) { using (var perfCounter = new PerformanceCounter("Master. Broadcasting Jacoby: ")) { var jacoby = this; communicator.Broadcast <Jacoby>(ref jacoby, 0); } }
static void Main(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; NodeStarter.Run(comm); } }
public MPIWorkOrchestrator(Options options, IMessageHub messageHub, IMessageSink messageSink, IWorkerNodesLifecycleManager nodesManager) : base(options, messageHub, messageSink, nodesManager) { communicator = Communicator.world; this.nodesManager = nodesManager; }
// just use this when u don't care about convergence and loop public static Matrix solve(Matrix A, Matrix b, Intracommunicator comm) { Matrix x; int loops; solve(A, b, out x, out loops, comm); return(x); }
private static void BasicMonitorTest(string[] args) { using (new MPI.Environment(ref args)) { Intracommunicator comm = Communicator.world; TestMonitor monitor = new TestMonitor(new MpiHandler(comm)); monitor.SetRank(); } }
//protected Thread master = null; private void setup_mpi() { int nc, color; string[] args = System.Environment.GetCommandLineArgs(); mpi = new MPI.Environment(ref args); worldcomm = Communicator.world; total_nodes = worldcomm.Size; node = worldcomm.Rank; //--------------------------------------------------------------------- // compute square root; add small number to allow for roundoff //--------------------------------------------------------------------- nc = Convert.ToInt32(Math.Sqrt(total_nodes) + 0.00001d); maxcells = Convert.ToInt32(Math.Sqrt(total_nodes)); //--------------------------------------------------------------------- // We handle a non-square number of nodes by making the excess nodes // inactive. However, we can never handle more cells than were compiled // in. //--------------------------------------------------------------------- if (nc > maxcells) { nc = maxcells; } if (node >= nc * nc) { active = false; color = 1; } else { active = true; color = 0; } comm_setup = (Intracommunicator)worldcomm.Split(color, node); if (!active) { return; } no_nodes = comm_setup.Size; comm_solve = (Intracommunicator)comm_setup.Clone(); comm_rhs = (Intracommunicator)comm_setup.Clone(); //--------------------------------------------------------------------- // let node 0 be the root for the group (there is only one) //--------------------------------------------------------------------- root = 0; }
public GeneticWorldMPI(int individuosCount, int geneCount, int maxGenerations) : base(individuosCount, geneCount, maxGenerations) { migratedIn = new Individuo[individuosCount / 2]; migratedOut = new Individuo[individuosCount / 2]; comm = Communicator.world; processTo = (comm.Rank + 1) % comm.Size; processFrom = (comm.Rank + comm.Size - 1) % comm.Size; }
static void Main(string[] args) { using (MPI.Environment environment = new MPI.Environment(ref args)) { if (args[4].Equals("*")) { args[4] = "0"; } SectorInfo sectorinfo = new SectorInfo() { RealMinimum = Convert.ToDouble(args[0]), ImgMinimum = Convert.ToDouble(args[1]), Delta = Convert.ToDouble(args[2]), FromX = Convert.ToInt32(args[3]), FromY = Convert.ToInt32(args[4]), Width = Convert.ToInt32(args[5]), Height = Convert.ToInt32(args[6]), MaxIterations = Convert.ToInt32(args[7]), MaxValue = Convert.ToInt32(args[8]) }; Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { SectorInfo[] sectors = new SectorInfo[comm.Size]; for (int k = 0; k < sectors.Length; k++) { SectorInfo newsector = new SectorInfo() { RealMinimum = sectorinfo.RealMinimum, ImgMinimum = sectorinfo.ImgMinimum, Delta = sectorinfo.Delta, FromX = sectorinfo.FromX, FromY = sectorinfo.FromY + k * (sectorinfo.Height / comm.Size), Width = sectorinfo.Width, Height = sectorinfo.Height / comm.Size, MaxIterations = sectorinfo.MaxIterations, MaxValue = sectorinfo.MaxValue }; sectors[k] = newsector; } SectorInfo si = comm.Scatter(sectors); CalculateSector(args, si); } else { SectorInfo si = comm.Scatter <SectorInfo>(0); CalculateSector(args, si); } } }
internal static void Run(Intracommunicator comm) { var info = new JobInfo { //hack, let every node init their own job data Settings = new Settings(), //should be shared and sent to all workers later SourceImage = GetSourceImage() //should also be sent to all workers later }; info.Settings.PolygonsMax = 50/comm.Size; var instance = new WorkerInstance(comm.Rank*10, info); instance.WorkLoop(comm); }
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 TestRequests(Intracommunicator comm, RequestList requestList) { int datum = comm.Rank; int expectedDatum = (comm.Rank + comm.Size - 1) % comm.Size; int[] intArraySendBuffer = new int[comm.Rank + 1]; string[] strArraySendBuffer = new string[comm.Rank + 1]; for (int i = 0; i <= comm.Rank; ++i) { intArraySendBuffer[i] = i; strArraySendBuffer[i] = i.ToString(); } int[] intArrayRecvBuffer = new int[expectedDatum + 1]; string[] strArrayRecvBuffer = new string[expectedDatum + 1]; Request[] requests = new Request[8]; requests[0] = comm.ImmediateReceive<int>(Communicator.anySource, 0); requests[1] = comm.ImmediateReceive<string>(Communicator.anySource, 1); requests[2] = comm.ImmediateReceive(Communicator.anySource, 2, intArrayRecvBuffer); requests[3] = comm.ImmediateReceive(Communicator.anySource, 3, strArrayRecvBuffer); requests[4] = comm.ImmediateSend(datum, (comm.Rank + 1) % comm.Size, 0); requests[5] = comm.ImmediateSend(datum.ToString(), (comm.Rank + 1) % comm.Size, 1); requests[6] = comm.ImmediateSend(intArraySendBuffer, (comm.Rank + 1) % comm.Size, 2); requests[7] = comm.ImmediateSend(strArraySendBuffer, (comm.Rank + 1) % comm.Size, 3); if (requestList == null) { // Complete all communications manually bool allDone = false; while (!allDone) { allDone = true; for (int i = 0; i < requests.Length; ++i) allDone = allDone && requests[i].Test() != null; } } else { // Use the request list to complete all communications for (int i = 0; i < requests.Length; ++i) requestList.Add(requests[i]); requestList.WaitAll(); } ReceiveRequest intRecv = (ReceiveRequest)requests[0]; CompletedStatus intStatus = intRecv.Wait(); if ((int)intRecv.GetValue() != expectedDatum || intStatus.Source != expectedDatum || intStatus.Tag != 0) { System.Console.Error.WriteLine("error in non-blocking receive of integer: got " + (int)intRecv.GetValue() + " from " + intStatus.Source + " on tag " + intStatus.Tag + ", expected " + expectedDatum); MPI.Environment.Abort(-1); } ReceiveRequest strRecv = (ReceiveRequest)requests[1]; CompletedStatus strStatus = strRecv.Wait(); if ((string)strRecv.GetValue() != expectedDatum.ToString() || strStatus.Source != expectedDatum || strStatus.Tag != 1) { System.Console.Error.WriteLine("error in non-blocking receive of string: got " + strRecv.GetValue() + " from " + strStatus.Source + " on tag " + strStatus.Tag + ", expected " + expectedDatum); MPI.Environment.Abort(-1); } ReceiveRequest intArrayRecv = (ReceiveRequest)requests[2]; CompletedStatus intArrayStatus = intArrayRecv.Wait(); if (intArrayRecv.GetValue() != intArrayRecvBuffer || intArrayStatus.Source != expectedDatum || intArrayStatus.Tag != 2 ) { System.Console.WriteLine("error: received into the wrong integer array"); MPI.Environment.Abort(-1); } for (int i = 0; i <= expectedDatum; ++i) { if (intArrayRecvBuffer[i] != i) { System.Console.WriteLine("error: intArrayRecv[" + i + "] is " + intArrayRecvBuffer[i] + ", expected " + i); MPI.Environment.Abort(-1); } } ReceiveRequest strArrayRecv = (ReceiveRequest)requests[3]; CompletedStatus strArrayStatus = strArrayRecv.Wait(); if (strArrayRecv.GetValue() != strArrayRecvBuffer || strArrayStatus.Source != expectedDatum || strArrayStatus.Tag != 3) { System.Console.WriteLine("error: received into the wrong string array"); MPI.Environment.Abort(-1); } for (int i = 0; i <= expectedDatum; ++i) { if (strArrayRecvBuffer[i] != i.ToString()) { System.Console.WriteLine("error: strArrayRecv[" + i + "] is " + strArrayRecvBuffer[i] + ", expected " + i.ToString()); MPI.Environment.Abort(-1); } } }
public override void initialize() { comm = this.WorldComm; // Mpi.localComm(this); }
/// <summary> /// Returns a recommended configuration for a new Cartesian grid. /// </summary> /// <param name="oldcomm"> /// The existing communicator. /// </param> /// <param name="ndims"> /// The number of dimensions for the Cartesian grid. /// </param> /// <param name="dims"> /// An array of length <paramref name="ndims"/> indicating the size of the grid in each dimension. /// </param> /// <param name="periods"> /// A logical array of length <paramref name="ndims"/> indicating whether the grid is periodic in any given dimension. /// </param> /// <returns> /// The new rank of the calling process. /// </returns> public static int Map(Intracommunicator oldcomm, int ndims, int[] dims, bool[] periods) { int newrank; int[] periods_int = BoolToInt(periods); unsafe { fixed (int* dimsPtr = dims, periodsPtr = periods_int) { int errorCode =Unsafe.MPI_Cart_map(oldcomm.comm, ndims, dimsPtr, periodsPtr, out newrank); if (errorCode != Unsafe.MPI_SUCCESS) throw Environment.TranslateErrorIntoException(errorCode); } } return newrank; }
/// <summary> /// Creates a <see cref="CartesianCommunicator"/>. /// </summary> /// <param name="oldComm"> /// An existing Intracommunicator from which to create the new communicator (e.g. <see cref="MPI.Communicator.world"/>). /// </param> /// <param name="ndims"> /// The number of dimensions for the Cartesian grid. /// </param> /// <param name="dims"> /// An array of length <paramref name="ndims"/> indicating the size of the grid in each dimension. /// </param> /// <param name="periods"> /// A logical array of length <paramref name="ndims"/> indicating whether the grid is periodic in any given dimension. /// </param> /// <param name="reorder"> /// Logical indicating whether ranks may be reordered or not. /// </param> public CartesianCommunicator(Intracommunicator oldComm, int ndims, int[] dims, bool[] periods, bool reorder) { int reorder_int = Convert.ToInt32(reorder); int[] periods_int = BoolToInt(periods); unsafe { fixed (int* dimsPtr = dims, periodsPtr = periods_int) fixed (MPI_Comm* commPtr = &(this.comm)) { int errorCode = Unsafe.MPI_Cart_create(oldComm.comm, ndims, dimsPtr, periodsPtr, reorder_int, commPtr); if (errorCode != Unsafe.MPI_SUCCESS) throw Environment.TranslateErrorIntoException(errorCode); } } NDims = ndims; Dims = dims; Periods = periods; Coords = GetCartesianCoordinates(Rank); AttachToComm(); }
internal virtual void WorkLoop(Intracommunicator comm) { startTime = DateTime.Now; Console.WriteLine("Starting worker {0} ", comm.Rank); var timer = new Stopwatch(); int partitionHeight = info.SourceImage.Height / comm.Size; int partitionY = partitionHeight * comm.Rank; for (int i = 0; i < info.Settings.PolygonsMax; i++) { var polygon = new DnaPolygon(); parentDrawing.Polygons.Add(polygon); polygon.Init(parentDrawing, info); //foreach (DnaPoint p in polygon.Points) //{ // p.Y = partitionY + partitionHeight / 2; //} } int waitTimer = 0; while (true) { if (comm.Rank == 0) NotifyProgress(generation); timer.Reset(); timer.Start(); while (timer.ElapsedMilliseconds < waitTimer) { var currentDrawing = parentDrawing.GetMutatedChild(info); var currentErrorLevel = GetFitnessForDrawing(currentDrawing); if (currentErrorLevel < parentErrorLevel) { parentErrorLevel = currentErrorLevel; parentDrawing = currentDrawing; } } if (waitTimer < 6000) waitTimer += 500; timer.Stop(); generation++; var drawingInfo = new MpiWorkerDrawingInfo { Drawing = parentDrawing }; // Stopwatch swSync = new Stopwatch(); // swSync.Start(); MpiWorkerDrawingInfo[] allResults = comm.Allgather(drawingInfo); if (bgImage != null) bgImage.Dispose(); bgImage = new Bitmap(info.SourceImage.Width, info.SourceImage.Height, PixelFormat.Format32bppArgb); var bgGraphics = Graphics.FromImage(bgImage); bgGraphics.Clear(Color.Black); bgGraphics.SmoothingMode = SmoothingMode.HighQuality; for (int i = 0; i < comm.Rank; i++) { Renderer.Render(allResults[i].Drawing, bgGraphics, 1); } if (fgImage != null) fgImage.Dispose(); fgImage = new Bitmap(info.SourceImage.Width, info.SourceImage.Height, PixelFormat.Format32bppArgb); var fgGraphics = Graphics.FromImage(fgImage); fgGraphics.Clear(Color.Transparent); fgGraphics.SmoothingMode = SmoothingMode.HighQuality; for (int i = comm.Rank + 1; i < comm.Size; i++) { Renderer.Render(allResults[i].Drawing, fgGraphics, 1); } fgGraphics.Dispose(); bgGraphics.Dispose(); //recalc the new parent error level parentErrorLevel = GetFitnessForDrawing(parentDrawing); // swSync.Stop(); // Console.WriteLine("sync {0}", swSync.Elapsed); } }
static void Main(string[] args) { // By default, test with primitives types and the predefined MPI_SUM Test test = testPrimitiveAndPredefined; using (new MPI.Environment(ref args)) { if (args.Length > 0 && args[0] == "/direct") { test = testDirect; System.Console.WriteLine("Using direct MPI interface."); } else if (args.Length > 0 && args[0] == "/user") { test = testPrimitiveAndMethod; Operation<double>.UseGeneratedUserOps = true; System.Console.WriteLine("Using primitive type (double) with user-defined sum and run-time code generation"); } else if (args.Length > 0 && args[0] == "/marshaluser") { test = testPrimitiveAndMethod; Operation<double>.UseGeneratedUserOps = false; System.Console.WriteLine("Using primitive type (double) with user-defined sum and marshalling"); } else if (args.Length > 0 && args[0] == "/valuetype") { test = testValueType; System.Console.WriteLine("Using value types with user-defined sum"); } else if (args.Length > 0 && args[0] == "/reftype") { test = testReferenceType; System.Console.WriteLine("Using reference types with user-defined sum"); } else System.Console.WriteLine("Using MPI.NET interface."); comm = MPI.Communicator.world; self = comm.Rank; 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 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; if (self == 0) System.Console.Write("{0,3:D}: {1,9:D} doubles {2,7:D} times ---> ", n, bufflen, nRepeat); GC.Collect(); test(bufflen, n, nRepeat, ref tlast); if (self == 0) System.Console.WriteLine("{0,9:F2} Mbps in {1:F9} sec", bwstats[n].bps, tlast); } } } }
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); } } } }