Parallel Summation using MPI in Python with mpi4py

Parallel Summation using MPI in Python with mpi4py

Parallel summation involves distributing the task of summing a large set of numbers across multiple processors or computing nodes, enabling simultaneous computation and aggregation of partial results. Each processor handles a portion of the data, performs local summation, and then communicates its partial sum to a designated root processor. The root processor collects and combines these partial sums to compute the global sum, thereby leveraging parallelism to accelerate the computation process and efficiently handle large-scale data sets. In this tutorial, we explore the implementation of parallel summation using MPI in Python, demonstrating how MPI facilitates communication and coordination among processes to achieve efficient parallel computation. Visit the detailed tutorial on MPI in Python here.

Code Example

from mpi4py import MPI

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

# Define the total number of elements
N = 100

# Calculate the number of elements to be handled by each process
chunk_size = N // size
start = rank * chunk_size
end = start + chunk_size

# Perform local summation for each process
local_sum = sum(range(start + 1, end + 1))

print("The processor", rank, "local sum is:", local_sum)
# Gather all local sums to the root process (rank 0)
global_sum = comm.reduce(local_sum, op=MPI.SUM, root=0)

# Print the result at the root process
if rank == 0:
    print("Global sum:", global_sum)
Output of the program

Explanation

Import MPI Module and Initialize MPI Environment

from mpi4py import MPI

This line imports the MPI module from the mpi4py package, enabling the use of MPI functionalities.

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

These lines initialize the MPI environment. MPI.COMM_WORLD creates a communicator object representing all processes in the MPI world. comm.Get_size() returns the number of processes in the communicator, and comm.Get_rank() returns the rank of the current process in the communicator.

Define the Total Number of Elements

N = 100

This line defines the total number of elements to be processed.

Calculate Chunk Size and Local Range

chunk_size = N / size
start = rank * chunk_size
end = start + chunk_size

These lines calculate the number of elements to be handled by each process (chunk_size) and determine the start and end indices of the local range of elements to be processed by the current process.

Perform Local Summation

local_sum = sum(range(start + 1, end + 1))

This line performs the local summation of elements for each process. It creates a range of numbers starting from start + 1 (since we want to include start) to end, and then sums up these numbers using the sum function.

Gather Local Sums to Root Process

global_sum = comm.reduce(local_sum, op=MPI.SUM, root=0)

This line gathers all the local sums from each process and performs a reduction operation. The local sums are reduced using the MPI sum operation (MPI.SUM). The resulting global sum is stored in the variable global_sum and is only computed by the root process (rank 0).

Print Result at Root Process

if rank == 0:
    print("Global sum:", global_sum)

This conditional statement ensures that only the root process (rank 0) prints the final result. Other processes contribute their local sums but do not print the result.

Material

Download the programs (code), covering the MPI4Py.

305 thoughts on “Parallel Summation using MPI in Python with mpi4py

  1. indianpharmacy com [url=http://indiapharmast.com/#]india pharmacy mail order[/url] indian pharmacy

  2. online shopping pharmacy india [url=https://indiapharmast.com/#]Online medicine home delivery[/url] indian pharmacy

  3. mexican online pharmacies prescription drugs [url=http://foruspharma.com/#]mexico pharmacy[/url] п»їbest mexican online pharmacies

  4. mexico drug stores pharmacies [url=http://mexicandeliverypharma.com/#]best online pharmacies in mexico[/url] medicine in mexico pharmacies

  5. mexico pharmacies prescription drugs [url=https://mexicandeliverypharma.com/#]reputable mexican pharmacies online[/url] mexico pharmacies prescription drugs

  6. mexican online pharmacies prescription drugs [url=https://mexicandeliverypharma.online/#]п»їbest mexican online pharmacies[/url] best online pharmacies in mexico

  7. mexican pharmaceuticals online [url=https://mexicandeliverypharma.com/#]buying prescription drugs in mexico[/url] buying prescription drugs in mexico online

  8. mexican border pharmacies shipping to usa [url=https://mexicandeliverypharma.com/#]medication from mexico pharmacy[/url] mexico drug stores pharmacies

  9. mexican pharmaceuticals online [url=http://mexicandeliverypharma.com/#]mexican pharmaceuticals online[/url] mexican mail order pharmacies

  10. best online pharmacies in mexico [url=http://mexicandeliverypharma.com/#]mexican drugstore online[/url] purple pharmacy mexico price list

  11. reputable mexican pharmacies online [url=https://mexicandeliverypharma.com/#]best online pharmacies in mexico[/url] mexican rx online

  12. mexican pharmaceuticals online [url=https://mexicandeliverypharma.com/#]mexico drug stores pharmacies[/url] mexico drug stores pharmacies

  13. п»їbest mexican online pharmacies [url=https://mexicandeliverypharma.online/#]mexican pharmaceuticals online[/url] mexico pharmacy

  14. mexican mail order pharmacies [url=https://mexicandeliverypharma.com/#]best online pharmacies in mexico[/url] best online pharmacies in mexico

  15. best online pharmacies in mexico [url=https://mexicandeliverypharma.com/#]buying prescription drugs in mexico online[/url] buying prescription drugs in mexico online

  16. El bitcoin es la primera y mayor criptomoneda del mundo por capitalización de mercado. Se trata de una moneda virtual basada en la tecnología blockchain, creada en 2009. A la hora de convertir criptomonedas en Changelly, puede ver dos tipos de tarifas: una tarifa de red y una tarifa de intercambio. Changelly cobra una tarifa de intercambio del 0,25% por cada transacción. Los intercambios retienen la tarifa de red para procesar sus fondos en el blockchain. El monto de esta tarifa varía según la moneda, las condiciones del mercado y otros factores. Limitaciones territoriales: los servicios de StormGain no están destinados a su utilización dentro de la Unión Europea. Los servicios de StormGain tampoco se encuentran disponibles en países que el Grupo de Acción Financiera Internacional (FATF) considera ser de alto riesgo ni en territorios no cooperativos que hayan incurrido en irregularidades estratégicas según la AML CFT, así como en países que se encuentren bajo sanciones internacionales.
    https://www.bandsworksconcerts.info/index.php?voyjudgsubbau1971
    Tras el misterioso envío a la dirección de la billetera Génesis, que en 2019 tenía los primeros 50 BTC minados por el propio Nakamoto y los envíos registrados en el blockchain de unas 6.637 microtransacciones a lo largo de estos años, ahora el saldo es de 99.68891510 BTC, que suman un total de 4.671.023,81 dólares aproximadamente, al momento de redactar esta nota. Actualizado : 11:52 Me temo que la clave privada de una cuenta de bitcoin no se puede cambiar. Nosotros no tenemos el servicio de recuperación de claves. Nuestra calculadora usa datos de Bitcoinity para obtener el tiempo promedio por bloque de los últimos 6 meses. Luego usa este tiempo por bloque (actualmente 9,69166666667 minutos entre bloque y bloque) para pronosticar la fecha del halving. The Data controller of your personal data is a company operating under the name OANDA TMS Brokers S.A. with its registered office in Warsaw, address: Warsaw UNIT, Daszyńskiego 1, 00-843 Warsaw, entered into the register of entrepreneurs under number 0000204776.

  17. “Iwish more singles would apply themselves to both their local congregations andthe church of Christ as a whole.” SELFIE VERIFICATION IS HERE! Connect with people and feel confident that they say who they say they are. Making Orthodox Christian dating a little less weird Therefore, not all dating sites labeled “Christian dating sites” actually work. And by work, I mean helping Christians meet fellow Christians and explore love together. “Iwish more singles would apply themselves to both their local congregations andthe church of Christ as a whole.” Be smart and do your research. It’s really easy with Google and social media, and it may save you time and heartache. One guy I connected with said he thought it was stupid for people to Google their matches. So I googled him and found a kind of paparazzi shot of him walking out of a courthouse in a high-profile criminal trial.
    http://evemall.co.kr/bbs/board.php?bo_table=free&wr_id=22806
    Katie O’Malley is the Site Director on ELLE UK. On a daily basis you’ll find Katie managing all digital workflow, editing site, video and newsletter content, liaising with commercial and sales teams on new partnerships and deals (eg Nike, Tiffany & Co., Cartier etc), implementing new digital strategies and compiling in-depth data traffic, SEO and ecomm reports. In addition to appearing on the radio and on TV, as well as interviewing everyone from Oprah Winfrey to Rishi Sunak PM, Katie enjoys writing about lifestyle, culture, wellness, fitness, fashion, and more.  Quickly gaining traction for its unique approach to matchmaking, Mind Body Green commends the platform for its inclusivity and diversity, offering a wide range of gender and sexuality options and catering to non-monogamous individuals. The platform also boasts keyword search functions, detailed profiles, and personality quizzes, shifting the focus from quick swipes to deeper connections.

  18. lipitor 20 mg generic [url=https://lipitor.guru/#]best price for lipitor[/url] lipitor prescription

  19. cheap lipitor generic [url=https://lipitor.guru/#]cheapest ace inhibitor[/url] lipitor tablets 10mg price

  20. online pharmacy india [url=https://indianpharmacy.company/#]top online pharmacy india[/url] world pharmacy india

  21. top 10 pharmacies in india [url=http://indianpharmacy.company/#]buy medicines online in india[/url] india pharmacy mail order

  22. best online pharmacy to buy cialis [url=http://pharmbig24.com/#]cialis online pharmacy us[/url] non prescription cialis online pharmacy

  23. top 10 online pharmacy in india [url=http://indianpharmacy.company/#]mail order pharmacy india[/url] world pharmacy india

  24. Lotrisone [url=http://pharmbig24.com/#]compounding pharmacy effexor[/url] how much is adipex at the pharmacy

  25. medicine in mexico pharmacies [url=https://mexicopharmacy.cheap/#]mexican online pharmacies prescription drugs[/url] buying from online mexican pharmacy

  26. best online pharmacies in mexico [url=https://mexicopharmacy.cheap/#]medicine in mexico pharmacies[/url] buying prescription drugs in mexico online

  27. finasteride online pharmacy india [url=http://pharmbig24.com/#]best online pharmacy generic viagra[/url] good online pharmacy

  28. online pharmacy tamoxifen [url=http://pharmbig24.com/#]global pharmacy bupropion[/url] mckesson pharmacy rx

  29. Online medicine order [url=http://indianpharmacy.company/#]reputable indian pharmacies[/url] top 10 online pharmacy in india

  30. reputable mexican pharmacies online [url=http://mexicopharmacy.cheap/#]п»їbest mexican online pharmacies[/url] mexican online pharmacies prescription drugs

  31. best india pharmacy [url=http://indianpharmacy.company/#]cheapest online pharmacy india[/url] top 10 pharmacies in india

  32. pharmacy online store malaysia [url=https://pharmbig24.com/#]online pharmacy baclofen[/url] xenical singapore pharmacy

  33. I’ve tried many online games, but Big Bass Bonanza stands out with its rewarding gameplay. I’ve managed to snag some impressive wins, and the bonus features keep me coming back for more. Highly recommend giving it a try! Café Casino has quickly become a popular choice for US players wishing to experience the best of online gambling. With an extensive selection of online slots and table games, as well as live dealer games, Café Casino offers something for all real money players. Finally, to make it onto our list of best paying online slot machines, a game needs to be available at one of our top-rated UK online casinos. There’s no use in finding a great game with a high RTP, that isn’t available at a reputable online casino. If you’re seeking to play PayPal slots at a real money casino online, then you’re in the right place. Not only can you find them here at Wizard Slots, but you can also play PayPal slots for real money here.
    https://www.pr6-articles.com/Articles-of-2024/write
    Size isn’t just about square footage. The amenities offered by a casino also contribute to its stature and popularity with guests. Casino resorts often include restaurants, theaters, shopping centers, spas, and pools. The MGM Grand, for instance, is renowned for its entertainment options, from concerts to famous bouts. We then quickly go over winners and losers so far, as once any one player gets up $25K for the day, I need to text our boss and let him know. Other than Harlan, I have two other players up close to $18K, which means I’ll need to let my staff know, so that if they get up another seven or eight thousand, they’ll call me so I can send the texts.  Meanwhile, Prime Sports, which operates in Ohio and New Jersey, paid out both U.S. and China as winners.  This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

  34. gates of olympus giris [url=http://gatesofolympusoyna.online/#]Gates of Olympus[/url] gates of olympus oyna

  35. farmacia online piГ№ conveniente [url=http://farmaciait.men/#]Farmacia online piГ№ conveniente[/url] Farmacia online miglior prezzo

  36. farmacie online autorizzate elenco [url=https://tadalafilit.com/#]Cialis generico farmacia[/url] farmacia online senza ricetta

  37. Farmacie on line spedizione gratuita [url=https://tadalafilit.com/#]Cialis generico controindicazioni[/url] farmacie online sicure

  38. comprare farmaci online con ricetta [url=http://farmaciait.men/#]Farmacie on line spedizione gratuita[/url] comprare farmaci online all’estero

  39. acquisto farmaci con ricetta [url=https://tadalafilit.com/#]Cialis generico farmacia[/url] Farmacia online miglior prezzo

  40. Farmacia online piГ№ conveniente [url=https://brufen.pro/#]Ibuprofene 600 generico prezzo[/url] acquisto farmaci con ricetta

  41. alternativa al viagra senza ricetta in farmacia [url=https://sildenafilit.pro/#]viagra senza ricetta[/url] esiste il viagra generico in farmacia

  42. pillole per erezioni fortissime [url=http://sildenafilit.pro/#]viagra farmacia[/url] viagra online consegna rapida

  43. viagra online spedizione gratuita [url=https://sildenafilit.pro/#]viagra[/url] viagra generico in farmacia costo

  44. comprare farmaci online all’estero [url=https://tadalafilit.com/#]Farmacie che vendono Cialis senza ricetta[/url] farmacia online

  45. pharmacie en ligne sans ordonnance [url=https://pharmaciepascher.pro/#]Medicaments en ligne livres en 24h[/url] pharmacies en ligne certifiГ©es

  46. SildГ©nafil Teva 100 mg acheter [url=http://vgrsansordonnance.com/#]Viagra generique en pharmacie[/url] Viagra femme sans ordonnance 24h

  47. pharmacie en ligne france fiable [url=https://clssansordonnance.icu/#]Cialis sans ordonnance pas cher[/url] acheter mГ©dicament en ligne sans ordonnance

  48. п»їViagra sans ordonnance 24h [url=http://vgrsansordonnance.com/#]viagra en ligne[/url] SildГ©nafil Teva 100 mg acheter

  49. An illustrative historical instance occurred during the Weimar Republic in Germany, where the exchange rate plummeted from 4.2 marks per dollar before World War I to an astonishing 4.2 trillion marks per dollar in November 1923. The pip value reduced drastically to a point where the currency could not be traded. Telephone calls and online chat conversations may be recorded and monitored. Apple, iPad, and iPhone are trademarks of Apple Inc., registered in the U.S. and other countries. App Store is a service mark of Apple Inc. Android is a trademark of Google Inc. This website uses cookies to obtain information about your general internet usage. Removal of cookies may affect the operation of certain parts of this website. Learn about cookies and how to remove them. Portions of this page are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
    https://wiki-view.win/index.php?title=What_is_the_most_reliable_forex_trading_platform
    From basic trading terms to trading jargon, you can find the explanation for a long list of trading terms here. Comment * Leverage in forex trading means the money you can borrow from a broker to trade currency derivatives. While there’s no direct interest charged, you will have to pay a brokerage fee for buying and selling currency derivatives on leverage.  Another prerequisite to becoming a successful forex trader is to find the best forex partner. Samco, with its high leverage-low margin mantra and best forex trading platform in India, is your perfect match. In leveraged forex trading, margin is one of the most important concepts to understand. Margin is essentially the amount of money that a trader needs to put forward in order to place a trade and maintain the position. Margin is not a transaction cost, but rather a security deposit that the broker holds while a forex trade is open.

  50. Be it alone or with your partner. Share all your secret thoughts with me. Dirty fantasies cam models are welcome with me! Here you get uninhibited dirty talk from me, dirty and secret dreams are lived and come true. I show you horny and want to see it from you! I look forward to seeing you on cam!

  51. That’s why it’s all the more important to us that you are well informed! But Cam2Cam is not everything and you should also take a closer look at the other free adult webcams. For example, you can record the camsex shows with the sexcam recorder and even control a dildo live in the chat with the cam girl!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this:
Verified by MonsterInsights