def export_trajectories(self, trajectories, filename, movement_type_index=None):
     filename = os.path.join(self.settings.out_folder, '%s.pkl' % filename)
     plate="PL0"; well="W0" if movement_type_index == None else "W{}".format(movement_type_index)
     dict_={plate:{well:ensTraj()}}
     cour = dict_[plate][well]
     num=0
     longueurFilm=0
     for movement_type in trajectories:
         print movement_type
         for i in range(len(trajectories[movement_type])):
             print i,
             traj=trajectoire(num, id=0)
             frame=0
             for x,y in trajectories[movement_type][i]:
                 traj.ajoutPoint(x,y, frame, 0)
                 frame+=1
             traj.density=[4 for k in range(frame)]
             cour.add(traj)
             num+=1
             longueurFilm=max(longueurFilm, frame)
     movie_length={plate:{well:longueurFilm}}
     connexions= {plate: {well: {}}}
     if not os.path.isdir(self.settings.out_folder):
         os.mkdir(self.settings.out_folder)
     
     fp = open(filename, 'w')
     pickle.dump(dict(zip(['tracklets dictionary', 'connexions between tracklets', 'movie_length'], [dict_, connexions, movie_length])), fp)
     fp.close()
     return
def trackletBuilder(new_sol, centresFolder, training=False):
    '''
    J'ajoute un compteur HoleError dans le cas ou Cplex ne respecte pas les contraintes : des cellules ne sont pas atteintes
    et par consequent elles ont l'air de surgir de nulle part sans etre apparues via l'algorithme. Je considere que dix erreurs de ce type sont acceptables
    par movie
    
    '''
    nb_voisins_max=10
    #distance_densi=40
    stories = ordonnancement(new_sol); res = {}
    global movie_length
    connexions = {}
    for plate in stories:
        res.update({plate : {}})
        connexions.update({plate : {}})
        movie_length.update({plate : {}})
        
        for well in stories[plate]:
            
            count_HoleError=0
            
            print plate, well
            ensembleTraj = fHacktrack2.ensTraj()
            res[plate].update({well:ensembleTraj})
            connexions[plate].update({well:{}})
            num = 0; l=[0]; trajC=None
            idd=0; firstIndex=min(stories[plate][well].keys()); 

            movie_length[plate].update({well : max(stories[plate][well].keys())-firstIndex+2})
            #+2 because there are no tracking in the last frame but it exists
            f=open(os.path.join(centresFolder, 'centers_P{}_w{}.pkl'.format(plate, well)), 'r')
            lCentersDict=pickle.load(f); f.close()
            
            for index in stories[plate][well]:
                print " -----INDEX ", index,
                dC={}
                lCenters =lCentersDict[index]
                nlCenters =lCentersDict[index+1]
                treeC = cKDTree(lCenters, leafsize = 10)      
                nTree = cKDTree(nlCenters, leafsize = 10)          
                
                connexions[plate][well].update({index:dC})
                solC = stories[plate][well][index]
                if type(solC.truth)==str:
                    l.append(index+1)
                    continue
                singlets = solC.singlets
                nextSinglets = solC.nextSinglets
                try:
                    result =solC.result
                except AttributeError:
                    result = filter(lambda x: x[1]==1, zip(solC.hypotheses, solC.truth))
                
                for hyp in result:
                    s, t = hyp[0]; source = [] ; target = []; 
                    #print hyp
                    if type(s) in [np.int32, np.uint16] and s!=-1:
                        source.append(filter(lambda x: x.label == s, singlets)[0])
                    elif type(s)==tuple:        
                        for c in s:
                            source.append(filter(lambda x: x.label == c, singlets)[0])
                    if type(t) in [np.int32, np.uint16] and t!=-1:
                        target.append(filter(lambda x: x.label == t, nextSinglets)[0])
                    elif type(t)==tuple:        
                        for c in t:
                            target.append(filter(lambda x: x.label == c, nextSinglets)[0])  
                    
                    incoming = len(source) ; outcoming= len(target)
                    mit = (outcoming>1) 
                    mer = (incoming>1)
#                    if mit or mer:
#                        print'#####', hyp
                    if incoming == 0:
                        #print "APPEAR"
                        for c in target:
                            newTraj= fHacktrack2.trajectoire(num, c.center[0], c.center[1], index+1, c.label, idd)
                            newTraj.addDensity(c.center, nTree, nb_voisins_max, densities)
                            #print num, idd
                            ensembleTraj.add(newTraj)
                            num+=1; idd+=1
                            
                        continue
                    elif outcoming ==0:
#                        print "DISAPPEAR"
                        if index in l:
                            #pdb.set_trace()#en fait ce sont au moins les trajectoires qui commencent en 0 et finissent en 0 ie les apparitions disparitions en 0
                            for c in source:
                                newTraj = fHacktrack2.trajectoire(num, c.center[0], c.center[1], index, c.label, idd)
                                #ici c'est une disparititon de trajectoire qui dure une image donc inutile d'ajouter la densite
                                ensembleTraj.add(newTraj)
                                num+=1; idd+=1
                        continue
                    elif incoming == 1: 
                #FROM ONE
                        c = source[0]
                        incomingTraj = ensembleTraj.findLabelFrame(c.label, index)
                        if incomingTraj==[]:
                            #It can happen only at the first frame : trajectories have not been initiated yet
                            #otherwise I raise HoleError if it has been observed more than 10 times
                            if index>firstIndex and training==False: 
                                count_HoleError+=1
                                if count_HoleError>=10:
                                    raise HoleError(plate, well, index)
                                
                            if not mit:
                                t=target[0]
                                newTraj = fHacktrack2.trajectoire(num, c.center[0], c.center[1], index, c.label, idd)
                                newTraj.addDensity(c.center, treeC, nb_voisins_max, densities)
                                newTraj.ajoutPoint(t.center[0], t.center[1], index+1, t.label)
                                newTraj.addDensity(t.center, nTree, nb_voisins_max, densities)
                                ensembleTraj.add(newTraj)
                                #print num, idd
                                num+=1; idd+=1
                                continue
                            elif mit:
                                newTraj = fHacktrack2.trajectoire(num, c.center[0], c.center[1], index, c.label, idd)
                                newTraj.addDensity(c.center, treeC, nb_voisins_max, densities)
                                idSource=(idd,)
                                ensembleTraj.add(newTraj)
                                num+=1; numC=num; idd+=1; targetCourantes=[]; 
                                for t in target:
                                    newTraj = fHacktrack2.trajectoire(numC, t.center[0], t.center[1], index+1, t.label, idd)
                                    newTraj.addDensity(t.center, nTree, nb_voisins_max,densities)
                                    targetCourantes.append(idd)
                                    #print numC, idd
                                    idd+=1
                                    ensembleTraj.add(newTraj)
                                dC[idSource]=tuple(targetCourantes)

                        elif not mit:
                            first = True
                            traj=incomingTraj[0]
                            t = target.pop()
                            traj.ajoutPoint(t.center[0], t.center[1], index+1, t.label)
                            traj.addDensity(t.center, nTree, nb_voisins_max, densities)
                            #print traj.numCellule, traj.id
                        elif mit:
#                            print 'mit'
                            first = True; fusion=False; idCourantes=[]; targetCourantes=[]
                            for i, traj in enumerate(incomingTraj):
                                idCourantes.append(traj.id)
                                if first: 
                                    numC = incomingTraj[i].numCellule
                                first=False
                                fusion=fusion or traj.fusion
                                incomingTraj[i].numCellule = numC
                                
                            for t in target:
                                newTraj = fHacktrack2.trajectoire(numC, t.center[0], t.center[1], index+1, t.label, idd)
                                newTraj.addDensity(t.center, nTree, nb_voisins_max, densities)
                                newTraj.fusion = fusion
                                ensembleTraj.add(newTraj)
                                targetCourantes.append(idd)
                                #print numC, idd
                                idd+=1
                            dC[tuple(idCourantes)]=tuple(targetCourantes)
    
                    elif mer:
                        if mit:
                            raise
#                        print "FROM MORE THAN ONE"
                        t = target[0]
                        trajC = fHacktrack2.trajectoire(num, t.center[0], t.center[1], index+1, t.label, idd)
                        trajC.addDensity(t.center, nTree, nb_voisins_max, densities)
                        trajC.fusion=True
                        idTarget=(idd,)
                        #print num, idd
                        idd+=1; num+=1; ensembleTraj.add(trajC)

                        idSource=[]#; tt=[]
                        for c in source:
                            incomingTraj = ensembleTraj.findLabelFrame(c.label, index)
                            try:
                                #tt.append(incomingTraj[0])
                                idSource.append(incomingTraj[0].id)
#                                print incomingTraj[0].numCellule, incomingTraj[0].id
                            except IndexError:
                                #donc il faut creer des nouvelles trajectoires
                                if index>firstIndex and training==False: 
                                    count_HoleError+=1
                                    if count_HoleError>=10:
                                        raise HoleError(plate, well, index)
                                    
                                trajC = fHacktrack2.trajectoire(num, c.center[0], c.center[1], index, c.label, idd)
                                trajC.addDensity(c.center, treeC, nb_voisins_max, densities)
                                idSource.append(idd)
                                idd+=1; num+=1
                                ensembleTraj.add(trajC)
                                #pdb.set_trace()#dans quel cas peut-on bien tomber ici ??
                                #on tombe ici a t=0 mais est-ce qu'on y tombe apres ? oui si on calcule les trajectoires du training
                                #set pcq il y a des evenements elimines par defaut (mvt a quatre)
                        dC[tuple(idSource)]=idTarget
#                print dC

    return res, connexions, movie_length
            filename = os.path.join(outputFolder, fi); print filename
            f=open(filename, 'r')
            dataDict = pickle.load(f)
            f.close()
        except:
            sys.stderr.write('Folder {} does not contain densities trajectories file.'.format(outputFolder))
            sys.exit()
                    
        else:
            if not options.simulated:
                d,c, movie_length = dataDict['tracklets dictionary'], dataDict['connexions between tracklets'], dataDict['movie_length']
                res = histogramPreparationFromTracklets(d, c, outputFolder, False, verbose, movie_length, name=fi_trajfeatures,
                                                        filtering_fusion=settings.filtering_fusion,
                                                        time_window=time_window) 
            else:
                d=ensTraj()
                for traj in dataDict:
                    t = trajectoire(1, xi=None, yi=None, frame=None, idC=None, id=1)
                    t.lstPoints = traj
                    d.lstTraj.append(t)
                res=histogramPreparationFromTracklets({options.plate : {options.well : d}}, None, 
                                                      outputFolder,training =True, verbose=verbose, movie_length={options.plate : {options.well :99}}, 
                                                      name=fi_trajfeatures)  #(d,c, outputFolder, False, verbose, tab=True, length=movie_length)
    
    final = time.clock() - initTime
    print "##################TEMPS FINAL {}".format(final)