{"id":3483,"date":"2024-05-23T10:16:55","date_gmt":"2024-05-23T05:16:55","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=3483"},"modified":"2024-05-23T10:19:14","modified_gmt":"2024-05-23T05:19:14","slug":"monte-carlo-simulation-mpi4py","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/05\/23\/monte-carlo-simulation-mpi4py\/","title":{"rendered":"Monte Carlo Simulation: MPI4Py"},"content":{"rendered":"\n<p>Monte Carlo simulations are a statistical technique that allows for solving problems through random sampling. They are widely used in various fields such as physics, finance, and engineering to understand the impact of risk and uncertainty in prediction and forecasting models. The core idea is to use randomness to solve problems that might be deterministic in nature. <a href=\"https:\/\/afzalbadshah.com\/index.php\/mpi-with-python\/\" target=\"_blank\" rel=\"noopener\" title=\"\">You can visit the detailed tutorial here. <\/a><\/p>\n\n\n\n<p>For example, to estimate the value of Pi ((\\pi)), we can use the Monte Carlo method. We generate random points in a unit square and count how many fall within a quarter-circle inscribed within the square. The ratio of the points inside the quarter-circle to the total number of points approximates (\\pi\/4).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Detailed Program<\/h3>\n\n\n\n<p>Below is a Python program used <code>mpi4py<\/code> for parallel processing in a Monte Carlo simulation to estimate the value of Pi.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from mpi4py import MPI\nimport numpy as np\nimport random\n\ndef monte_carlo_pi(num_samples):\n    count = 0\n    for _ in range(num_samples):\n        x, y = random.random(), random.random()\n        if x**2 + y**2 &lt;= 1:\n            count += 1\n    return count\n\ndef main():\n    comm = MPI.COMM_WORLD\n    rank = comm.Get_rank()\n    size = comm.Get_size()\n\n    num_samples_per_proc = 1000000  # Adjust as needed\n    total_samples = num_samples_per_proc * size\n\n    # Each process runs its own Monte Carlo simulation\n    local_count = monte_carlo_pi(num_samples_per_proc)\n\n    # Gather all local counts to the root process\n    total_count = comm.reduce(local_count, op=MPI.SUM, root=0)\n\n    if rank == 0:\n        # Root process calculates the final estimate of Pi\n        pi_estimate = (4.0 * total_count) \/ total_samples\n        print(f\"Estimated Pi: {pi_estimate}\")\n\nif __name__ == \"__main__\":\n    main()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Line-by-Line Explanation<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>from mpi4py import MPI<\/code><\/pre>\n\n\n\n<p>This line imports the <code>MPI<\/code> module from the <code>mpi4py<\/code> package, which provides support for parallel processing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import numpy as np\nimport random<\/code><\/pre>\n\n\n\n<p>These lines import the <code>numpy<\/code> and <code>random<\/code> modules. <code>numpy<\/code> is a powerful library for numerical computations, although it&#8217;s not explicitly used in this example, and <code>random<\/code> provides functions for generating random numbers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def monte_carlo_pi(num_samples):<\/code><\/pre>\n\n\n\n<p>This line defines a function named <code>monte_carlo_pi<\/code> that takes one parameter <code>num_samples<\/code>, representing the number of random points to generate.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    count = 0<\/code><\/pre>\n\n\n\n<p>Initializes a counter <code>count<\/code> to zero. This will be used to count the number of points that fall inside the quarter-circle.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    for _ in range(num_samples):<\/code><\/pre>\n\n\n\n<p>Starts a loop that iterates <code>num_samples<\/code> times to generate random points.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        x, y = random.random(), random.random()<\/code><\/pre>\n\n\n\n<p>Generates two random floating-point numbers <code>x<\/code> and <code>y<\/code> between 0 and 1, representing the coordinates of a point.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        if x**2 + y**2 &lt;= 1:<\/code><\/pre>\n\n\n\n<p>Checks if the point (x, y) lies inside the quarter-circle by verifying if the sum of the squares of <code>x<\/code> and <code>y<\/code> is less than or equal to 1.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>            count += 1<\/code><\/pre>\n\n\n\n<p>If the point lies inside the quarter-circle, increments the counter <code>count<\/code> by 1.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    return count<\/code><\/pre>\n\n\n\n<p>Returns the total count of points that lie inside the quarter-circle.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def main():<\/code><\/pre>\n\n\n\n<p>Defines the main function which will be executed when the script is run.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    comm = MPI.COMM_WORLD<\/code><\/pre>\n\n\n\n<p>Initializes the MPI communication world, allowing communication between different processes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    rank = comm.Get_rank()<\/code><\/pre>\n\n\n\n<p>Gets the rank (ID) of the current process. The rank is used to identify each process uniquely.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    size = comm.Get_size()<\/code><\/pre>\n\n\n\n<p>Gets the total number of processes running in the MPI world.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    num_samples_per_proc = 1000000  # Adjust as needed<\/code><\/pre>\n\n\n\n<p>Defines the number of samples each process will generate. This can be adjusted based on the desired accuracy and computational resources.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    total_samples = num_samples_per_proc * size<\/code><\/pre>\n\n\n\n<p>Calculates the total number of samples by multiplying the number of samples per process by the total number of processes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    local_count = monte_carlo_pi(num_samples_per_proc)<\/code><\/pre>\n\n\n\n<p>Each process runs the <code>monte_carlo_pi<\/code> function independently to simulate its portion of the samples and stores the result in <code>local_count<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    total_count = comm.reduce(local_count, op=MPI.SUM, root=0)<\/code><\/pre>\n\n\n\n<p>Gathers all local counts to the root process (rank 0) and sums them up using the reduce operation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    if rank == 0:<\/code><\/pre>\n\n\n\n<p>Checks if the current process is the root process.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        pi_estimate = (4.0 * total_count) \/ total_samples<\/code><\/pre>\n\n\n\n<p>The root process calculates the final estimate of Pi using the total count of points inside the quarter-circle and the total number of samples.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        print(f\"Estimated Pi: {pi_estimate}\")<\/code><\/pre>\n\n\n\n<p>Prints the estimated value of Pi.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if __name__ == \"__main__\":\n    main()<\/code><\/pre>\n\n\n\n<p>Checks if the script is being run directly and, if so, calls the <code>main<\/code> function to start the program.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Running the Program<\/h3>\n\n\n\n<p>To run this program with MPI, use the following command, specifying the number of processes you want to use (e.g., 4):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mpiexec -n 4 python your_script_name.py<\/code><\/pre>\n\n\n\n<p>This command will start the script with 4 parallel processes, each performing part of the Monte Carlo simulation and collaborating to estimate the value of Pi.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"MPI (MPI4PY) on Jupyter Tutorial\" width=\"640\" height=\"360\" src=\"https:\/\/www.youtube.com\/embed\/videoseries?list=PLGiqyN7d0mypGRrq2Bv9mXLGoeZPXTcZA\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Monte Carlo simulations are a statistical technique that allows for solving problems through random sampling. They are widely used in various fields such as physics, finance, and engineering to understand the impact of risk and uncertainty in prediction and forecasting models. The core idea is to use randomness to solve problems that might be deterministic in nature. You can visit the detailed tutorial here. For example, to estimate the value of Pi ((\\pi)), we can use the Monte Carlo method&#8230;.<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/05\/23\/monte-carlo-simulation-mpi4py\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":3485,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[506],"tags":[540,543,567],"class_list":["post-3483","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mpi-with-python","tag-mpi","tag-mpi4py","tag-parallel-processing"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/05\/MPI-Python-6-jpg.webp?fit=1280%2C720&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-Ub","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3483","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=3483"}],"version-history":[{"count":3,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3483\/revisions"}],"predecessor-version":[{"id":3488,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3483\/revisions\/3488"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/3485"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=3483"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=3483"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=3483"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}