2

I'm trying to simulate Python (I'm a Physics student and programming is not my strongest skill) and I am running short of RAM. I have 4Gb only.

This is my python program:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 21:10:00 2021

@author: samuel
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from funciones import *
from ctes import *

gif_1d = True
gif_2d = True

agents = [w]*N

path_graf='/home/samuel/Documents/FISICA/20-21/Física de los sistemas complejos/Proyecto/Programas/imagenes/grafico/'
path_map = '/home/samuel/Documents/FISICA/20-21/Física de los sistemas complejos/Proyecto/Programas/imagenes/mapa/'


#Dimension del mapa 2d
dim = int(np.sqrt(N))

for i in range(iterations):
    #tomar dos al azar
    ag1, ag2 = eleccion_agentes()
    
    #se realiza la transaccion
    agents[ag1],agents[ag2] = transaccion(agents[ag1],agents[ag2])
    
    #cada 100 iteraciones se guarda una imagen para el gif
    if i%5000==0:
        if gif_1d:
             fig,ax = plt.subplots(figsize=(15,10))
             ax.bar(range(1,N+1),agents)
             ax.set_ylabel('Riqueza')
             ax.set_title('Iteracion:' + str(i))
             frame = f'{i}.png'    
             plt.savefig(path_graf + frame)
             plt.close()
             
        if gif_2d:
            fig,ax = plt.subplots(figsize=(15,10))
            mapa= np.reshape(np.array(agents),(dim,dim))
            ax.imshow(mapa, cmap='viridis', interpolation='nearest')
            ax.set_title('Iteracion:' + str(i))
            frame = f'{i}.png'    
            plt.savefig(path_map + frame)
            plt.close()

The modules funciones.py and ctes.py are, respectively

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 19:56:51 2021

@author: samuel
"""
from ctes import *
import random

def eleccion_agentes():
    iguales=True
    while iguales:
        x1=random.randint(0,N-1)
        x2=random.randint(0,N-1)
        if x1!=x2:
            iguales=False
    return x1, x2

#función que dados dos agentes, hace la transaccion y devuelve las nuevas riquezas
#de los mismos
def transaccion(w1,w2):
    delta=random.uniform(0.0,alfa)*min(w1,w2)
    if random.random() <= 0.5:
        w1=w1+delta
        w2=w2-delta
    else:
        w1=w1-delta
        w2=w2+delta
    
    return w1,w2

and

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 19:57:28 2021

@author: samuel
"""

iterations = int(5e7)    #iterations for the simulation (number of transactions)


N=10000      #total number of agents (but we can work with the normalized distrib: N=1 and W=1)
            #DEBE SER NUMERO CON RAIZ, PARA QUE EL GIF 2D SALGA BIEN.
            
w = 100         #units of initial wealth for each agent.
W = w*N         #total wealth

alfa = 0.25     #

As said, the problem is that I run out of RAM. Before, when I tried to create the gif in the same problem, the images were being saved on a list as they were created (every 5000 iterations) but now I'm just saving them in some directory to make the animation after. I thought this would improve the use of RAM since there is no big variable increasing with each iteration. But I still fill my memory.

What could I do for this not to happen?

PD: I'm using the Spyder environment if that's of any use.

Chinez
  • 551
  • 2
  • 6
  • 29
  • In these cases, it's very useful to use a memory profiler, this lets you diagnose what and where in your code is consuming this memory. A quick "python memory profiler" search should lead you to another question here on Stack Overflow that shows some examples on how to use them (I'm on mobile so it's annoying to link things). – ihavenoidea Jun 06 '21 at 12:11
  • Spyder uses a lot RAM in my opinion so you can maybe try lauching your python code from the command line that way you have less things opened on your computer (to do that simply write "path to your python application" "path to your code" on the same line) – user14518362 Jun 06 '21 at 12:30
  • [This answer](https://stackoverflow.com/a/33343289/13145954) regarding pyplot memory usage might help – Seon Jun 06 '21 at 12:32

0 Answers0