samedi 22 février 2020

multprocessing for a stochastic process with multiple arguments

I want to solve a stochastic differential equation using multiprocessing. A simplified not-parallel code is like:

import numpy as np

x       = np.zeros((2, 3, 4))                     #matrix
z       = np.random.normal(0, 1, (2,3,4))         #noise
z_array = z
for i in range(2):
    for j in range(3):
        x[i,j,0] = i
        for k in range(3):
            x[i,j,k+1] = x[i,j,k]*z_array[i,j,k]

The outcomes are the noisez_array and the corresponding matrix x. I want to use multiprocessing for the second loop. The problem is that I don't know how to incorporate the noise z in the parallel code. A naive implementation is like

import os
import numpy     as np
import functools as ft
from multiprocess import Pool 

def fun(i, k):
    x = np.zeros(4)
    x[0] = i
    for k in range(2):
        z = np.random.normal(0, 1)
        x[k+1] = x[k]*z
    return x

if __name__=='__main__':
    pool  = Pool(os.cpu_count()-1)
    x   = np.zeros((2, 3, 4))
    for i in range(2):
        result = np.array(pool.map(ft.partial(fun, i), range(3)))
        x[i] = result           
    pool.close()
    pool.join()

Since the code involves random numbers, I am not sure whether parallel code is correct or not and I don't know how to get the noises z. Any ideas?




Aucun commentaire:

Enregistrer un commentaire