def ecrireXml(visu, p):
    for plate in visu:
        for well in visu[plate]:
            if p==None:
                fichier = open("PL"+plate+"___P"+well+"___T00000.xml", 'w')
            else:
                fichier = open(str(p)+"PL"+plate+"___P"+well+"___T00000.xml", 'w')
                
            fichier.write(fHacktrack2.initXml())
            compteur=1
            for index in visu[plate][well]:
                for c in visu[plate][well][index]:
                    result = "\n      <Marker_Type>\n        <Type>{0}</Type>".format(compteur)
                    numFramePourXml = index+1
                    result+="\n        <Marker>\n          <MarkerX>{1}</MarkerX>\n          <MarkerY>{2}</MarkerY>\n          <MarkerZ>{0}</MarkerZ>\n        </Marker>".format(numFramePourXml, c[0], c[1])
                    result+="\n      </Marker_Type>"
                    fichier.write(result)
            fichier.write(fHacktrack2.finirXml())
    return
def trajPreparation(dicT, training):
    r={}; coord={}; nuCount=[0 for x in range(len(moments))]
    for plate in dicT:
        if plate not in r:
            r[plate]={}
            coord[plate]={}
        for well in dicT[plate]:
            if well not in r[plate]:
                r[plate][well]=[]
                coord[plate][well]=[]
            print plate, well
            dicC = dicT[plate][well]
            fichier=open("PL{0}___P{1}___T00000.xml{2}".format(plate, well, training), 'w'); fichier.write(fHacktrack2.initXml())

            tracklets=[]
            compteur = 1
            #signature de featuredTraj.__init__ : (self, ide, labelsSequence, beginning, end, num, features, to=None, fr=None):
            #going into all trajectories to get small tracklets
            #AND keeping in memory which tracklet they're related to
            
            #once we have all tracklets we can do the findCorresp
            
            #FINALLY we can recoller les morceaux and get model accuracy/trajectory instead of /movement from t to t+1
            print 'Pass of all tracks'
            for traj in dicC.lstTraj:                
                t=traj.lstPoints.keys(); t.sort(); 
                
#                if traj.numCellule ==36:
#                    fichier.write(fHacktrack2.ecrireXml(36, traj))
                    
                print "une trajectoire", traj.numCellule
                print "merge :", traj.fusion
                print "split :", traj.mitose
                print 'debut de la trajectoire :', min(t), "fin ", max(t)
#CHECK qu'est-ce que min(t), max(t)
#PLUS compute to and from for all tracklets
                #Here we don't want to delete all that happens after a merge
                #we want to cut the trajectory into pieces between all split and merge
                events = list(traj.fusion); events.extend(traj.mitose); events.sort(reverse=True)
                events = filter(lambda x: x>min(t)[0] and x<max(t)[0], events)[0]
#                if traj.fusion !=-1:
#                    if min(traj.fusion)<min(t):
#                        continue
#                    traj=traj.copyBefore(min(traj.fusion))
#                    t=sorted(traj.lstPoints.keys())
#                        
#                print 'apres le check merge, plus de merge normalement : ', traj.fusion , 'et que des splits avant : ', traj.mitose
                print "evenements de la trajectoire ", events
                if events !=[]:
                    end = max(t)[0]
                    for event in events:
                    #    if end-mit>9:
                        print "event ", event
                        track = traj.copyBetween(event, end)
                        r[plate][well].append(trajFeatures.featuredTraj(compteur, labelsSeq(track), track.numCellule, None, to, fr))
                        compteur +=1
                        #tracklets.append()
                        end = event
                    
                    track= traj.copyBefore(end)
                    r[plate][well].append(trajFeatures.featuredTraj(compteur, labelsSeq(track), track.numCellule, None, to, fr))
                    compteur +=1
                    #tracklets.append()
                else:#if end-t[0][0]>9:
                    track = traj
                    r[plate][well].append(trajFeatures.featuredTraj(compteur, labelsSeq(track), track.numCellule, None, to, fr))
                    compteur +=1
                    #tracklets.append(traj)    
                        

#ATTENTION here we throw away tracklets whose length is smaller than 10 (otherwise we don't have diffusion info because
#I use delta t in range (1, len(track)/3 +1) ie (1,2,3) if len(track)>9, and then do regression on it,
#so if we have less than three points to do linear regression it seems a bit dubious to me)    
#            if not len(tracklets)==len(filter(lambda x: len(x.lstPoints)>9 ,tracklets)):
#                raise             
            print 'Second pass of all tracks to extract features of tracks longer than 9 frames'
            #euh no here we're not doing this
#            pbl=dict(zip(moments, [[] for x in range(len(moments))]))
#            for track in filter(lambda x: len(x.lstPoints)>9 ,tracklets):
#                t=track.lstPoints.keys(); t.sort(); 
#                labelsSequence = [k[1] for k in t]
#                x= [track.lstPoints[k][0] for k in t]
#                y =[track.lstPoints[k][1] for k in t]
#                #pdb.set_trace()
#                coord[plate][well].append([x, y])
#                print "debut de l'extrait de trajectoire", min(t)[0], "fin ", max(t)[0]
#                
#    #Pour l'instant on ne normalise pas par rapport au deplacement moyen sur toute l'image car on ne considere qu'une partie de l'image
#                f=computingFeatures(track, movie_length[plate][well], np.mean(average, 0))
#                if 'pbl' in f:
#                    nu=f['pbl']
#                    #nuCount[nu].append(len(track.lstPoints))
#                    pbl[nu].append(track)
#                    fichier.write(fHacktrack2.ecrireXml(nu, track))
#                r[plate][well].append(featuredTraj(compteur, labelsSequence, min(t)[0], max(t)[0], track.numCellule, f))
#                if track.numCellule ==12:
#                    fichier.write(fHacktrack2.ecrireXml(12, traj))    
#                compteur +=1
##            
#            fichier.write(fHacktrack2.finirXml()); fichier.close()  
#    f=open('pblCoeffCorr{0}.pkl'.format(training), 'w')
#    pickle.dump(pbl, f); f.close() 
    return r, coord