Partage
  • Partager sur Facebook
  • Partager sur Twitter

Problème de boucle for infaisable

boucle for bloque le programme qui fonctionne

    18 juillet 2022 à 15:39:40

    Bonjour à toutes et à tous, 

    Je viens pour un problème que je n'arrive pas à résoudre et pour lequel je n'ai pas vraiment d'idée. Je fais du traitement d'image et du tracking de particule avec le module python 'Trackpy'. 

    Je fais ce tracking sur plusieurs positions, donc sur plusieurs séquences d'image. J'effectue donc une boucle "for" sur chacune de mes positions. 

    Seulement voilà ..  le programme ne tourne pas et se bloque au batching lorsque je mets une boucle. En revanche, si je fais ligne par ligne, le programme fonctionne très bien. 

    Avez vous une idée de ce qui peut causer cela? 

    Merci beaucoup et très bonne journée, 

    Alexandre

    # -*- coding: utf-8 -*-
    """
    Created on Mon Jul 18 15:36:21 2022
    
    @author: Labo-Gallet
    """
    #Simple tracking
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import os
    # import matplotlib as mpl
    # os.environ['SDL-AUDIODRIVER']='dsp'
    #import pygame
    #import sys
    import matplotlib.pyplot as plt
    # mpl.use("Agg")
    #import math
    # Optionally, tweak styles.
    # mpl.rc('figure',  figsize=(10, 6))
    # mpl.rc('image', cmap='gray')
    #import numpy as np
    #import pandas as pd
    #from pandas import DataFrame, Series  # for convenience
    #import imageio
    #import datetime
    #import moviepy
    import pims
    import trackpy as tp
    #from PIL import Image
    #from pillow import image
    #import Image
    #import query
    #from scipy import stats
    #from numba import jit
    #from numba import njit
    #from numba import types
    
    import multiprocessing
    #import warnings
    # msd.dropna(how = 'all', axis = 1 , inplace = True)
    # warnings.filterwarnings("ignore")
    # # warnings.filterwarnings("SubnetOversizeException")
    multiprocessing.set_start_method('spawn', True)
    # multiprocessing.get_start_method()
    
        #%%
    
    
    #############################################################################
    #                 PICTURE ANALYSIS                                          #
    #############################################################################
    #############################################################################
    ############################################################################
    #                           Read frames                                    #
    ############################################################################
    def readPictureToAnalyze(path):
        frames = pims.ImageSequence(path)#, as_grey=True) 
        return frames
    ##############################################################################
    #                            DATA TRAJECTORY Pos                              #
    ##############################################################################
    def outputDataTraj(TrajIndex, pathDataTraj,Index_i,Index_j):
        auxtmIndexExcel = pathDataTraj + '\\Traj\\tmindex'+str(Index_i).zfill(3)+'_'+str(Index_j).zfill(3)+'.xlsx'
        tmIndexExcel = TrajIndex.to_excel(auxtmIndexExcel)
        auxtmIndexCsv = pathDataTraj + '\\Traj\\tmindex'+str(Index_i).zfill(3)+'_'+str(Index_j).zfill(3)+'.csv'
        tmIndexCsv = tmindex.to_csv(auxtmIndexCsv)
        return tmIndexExcel,tmIndexCsv
    
    def outputTrajRescale(Traj,pathDataTraj,Index_i,Index_j):
        Xzero = {k:df['x'].values[0] for k,df in Traj.groupby('particle')}
        Yzero = {k:df['y'].values[0] for k,df in Traj.groupby('particle')}
        Traj['X0'] = [Xzero[Objet] for Objet in Traj['particle']]
        Traj['Y0'] = [Yzero[Objet] for Objet in Traj['particle']]
        Traj['X-X0']=Traj['x']-Traj['X0']
        Traj['Y-Y0']=Traj['y']-Traj['Y0']
        Traj_Rescale = Traj.copy()
        Traj_Rescale['x'] = Traj['X-X0']
        Traj_Rescale['y'] = Traj['Y-Y0']
        auxtmRescale = pathDataTraj + '\\Traj\\tmrescale'+str(Index_i).zfill(3)+'_'+str(Index_j).zfill(3)+'.csv'
        Traj_Rescale_csv = Traj_Rescale.to_csv(auxtmRescale)
        return Traj_Rescale,Traj_Rescale_csv
    
    
    ###############################################################################
    #                         FIG TRAJ POS                                        #
    ###############################################################################
    def outputFigTraj(traj,out,pathpicture,Index_i,Index_j,labelCells):
        plt.figure()
        ax = tp.plot_traj(traj,label=labelCells)
        auxFigTraj = pathpicture + '\\out_image\\Traj\\'+str(out)+str(Index_i).zfill(3)+'_'+str(Index_j).zfill(3)+'.pdf'
        SaveTraj = plt.savefig(auxFigTraj, format="pdf")
        plt.close()
        return ax,SaveTraj
    
    #%%
    global size1,size2,minmassPart,maxdisplacement,memoryframe,picturepath
    global filtertrajectories,size,mass,ecc,imin,imax,inum,jmin,jmax,jnum,stp
    
    
    manip = 4
    path = 'C:\\Users\\Labo-Gallet\\Desktop\\_4'
    os.mkdir(path + '\\Traj')
    os.mkdir(path + '\\out_image')
    os.mkdir(path + '\\out_image\\Traj')
    
    
    time_frame = 30
    noise_s =  0.5
    size1 = 9
    size2 = 9
    maxdisplacement = 5
    memoryframe = 2
    minmassPart = 25000
    filtertrajectories = 100
    size = 2.2
    mass = 200000
    ecc = 0.9
    imin = 0
    imax = 6
    inum = imax+1
    jmin = 0
    jmax = 6
    jnum = jmax+1
    stp = 1
    out_image = 'image'
    out_movie = 'none'
    Numero_Pos = 4
    nombre_de_paritcules_totale = 0
    i_Index_list = [0,1,2,3]
    
    j_Index_list = [0,1,2]
    
    #%%
    for i in i_Index_list : 
        for j in j_Index_list : 
            path_picturesRead = path+'/{}-Pos_00{}_00{}/*.tif'.format(Numero_Pos,i,j)
            print('path_picture == ',path_picturesRead)
            frames=readPictureToAnalyze(path_picturesRead)
            print('FRAME==========================',frames[0])
            print('SIZE 1 ========================',size1)
            print('minmassPart==================',minmassPart)
            print('maxdisplacment===============',maxdisplacement)
            print('size2======================',size2)
            print(frames)
            print('frames Nb=',len(frames))
            
            
            
            f = tp.locate(frames[0], size2,noise_size=noise_s, invert=True, minmass=minmassPart)
            print ("Localisation de ", len(f), " particules")
            f = tp.batch(frames[:],size2, invert=True);#round(f['mass'].min()),noise_size=noise_s,
            t = tp.link_df(f, maxdisplacement, memory=memoryframe)
            t1 = tp.filter_stubs(t, filtertrajectories)
            #%%
            # Compare the number of particles in the unfiltered and filtered data.
            print('Before:', t['particle'].nunique())
            print('After:', t1['particle'].nunique())
            condition = lambda x: ((x['mass'].mean() < mass) & (x['size'].mean() < size) & (x['ecc'].mean() < 0.9))
            t2 = tp.filter(t1, condition)  # a wrapper for pandas' filter that works around a bug in v 0.12
            number_of_traj= t2['particle'].nunique()
            # file = open(path+"/Traj/nbTraj"+str(iIndex).zfill(3)+"_"+str(jIndex).zfill(3)+".txt", "a")
            # file.write(str(number_of_traj))
            # file.close()
            
            tmindex=t2.reset_index(drop=True)
            auxtmIndex_Excel,auxtmIndex_Csv = outputDataTraj(tmindex,path,i,j)
            xtmIndex_Csv = outputDataTraj(tmindex,path,i,j)
            tmindex.to_excel(path+'\\Traj\\tmindex'+str(i).zfill(3)+'_'+str(j).zfill(3)+'.xlsx')
            tmindex.to_csv(path+'\\Traj\\tmindex'+str(i).zfill(3)+'_'+str(j).zfill(3)+'.csv')
            ax,SaveTraj = outputFigTraj(tmindex,'traj',path,i,j,True)
            Traj_Rescale,Traj_Rescale_csv = outputTrajRescale(tmindex,path,i,j)
            ax,SaveTraj = outputFigTraj(Traj_Rescale,'rescale',path,i,j,False)
            nombre_de_paritcules_totale +=number_of_traj



    • Partager sur Facebook
    • Partager sur Twitter
      18 juillet 2022 à 17:15:16

      Si la boucle for n'avance pas, c'est qu'une instruction bloque...

      Pour la trouver, il faut pouvoir faire tourner le code et pour le confirmer supprimer tout ce qui est sans rapport avec cette (ou ces) instruction(s). Tout ça pour arriver a une description plus concise du problème et chercher (sur Internet) les solutions mise en oeuvre par ceux qui ont eu des problèmes similaires.

      Au delà de ces remarques générales, je ne suis pas sûr qu'on puisse faire plus

      • Partager sur Facebook
      • Partager sur Twitter

      Problème de boucle for infaisable

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown