<commit_before>/*
 * ParticleTracker.java
 *
 * Created on 30. april 2007, 16:18
 *
 */

package ch.unizh.ini.caviar.eventprocessing.tracking;
//import ch.unizh.ini.caviar.aemonitor.AEConstants;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.event.*;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.graphics.*;
import com.sun.opengl.util.*;
import java.awt.*;
//import ch.unizh.ini.caviar.util.PreferencesEditor;
import java.awt.geom.*;
import java.io.*;
import java.util.*;
import java.util.prefs.*;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;


/**
 *
 * @author Philipp <<EMAIL>>
 */
public class ParticleTracker extends EventFilter2D implements FrameAnnotater, Observer{

    private static Preferences prefs=Preferences.userNodeForPackage(ParticleTracker.class);
    
    private java.util.List<Cluster> clusters=new LinkedList<Cluster>();
    protected AEChip chip;
    private AEChipRenderer renderer;
    private int[][] lastCluster= new int[128][128];
    private int[][] lastEvent= new int[128][128];
    private int next_cluster_id=1;
    protected Random random=new Random();
    private PrintStream logStream=null;
    
    //Variables that will be set by the tracker parameter pop-up window: 
    //------------------------------------------------------------------
    //private final int CLUSTER_UNSUPPORTED_LIFETIME=50000;
    int clusterUnsupportedLifetime= prefs.getInt("ParticleTracker.clusterUnsupportedLifetime",50000);
    //private final int CLUSTER_MINLIFEFORCE_4_DISPLAY=10;
    float clusterMinMass4Display= prefs.getFloat("ParticleTracker.clusterMinMass4Display",10);
    boolean OnPolarityOnly=prefs.getBoolean("ParticleTracker.OnPolarityOnly",false);
    float displayVelocityScaling=prefs.getFloat("ParticleTracker.DisplayVelocityScaling",5000.0f);
    int logFrameLength=prefs.getInt("Particletracker.LogFrameLength",0);
    int logFrameNumber=0;


   
    /** Creates a new instance of ParticleTracker */
    public ParticleTracker(AEChip chip) {
        super(chip);
        this.chip=chip;
        renderer=(AEChipRenderer)chip.getRenderer();
        chip.getRenderer().addAnnotator(this); // to draw the clusters
        chip.getCanvas().addAnnotator(this);
        chip.addObserver(this);
//        prefs.addPreferenceChangeListener(this);
//        Cluster newCluster=new Cluster(40,60,-1,-1);
//        clusters.add(newCluster);
        initFilter();
    }
    
// All callback functions for the tracker parameter pop-up:
// -----------------------------------------------------------
    public void setDisplayVelocityScaling(float x){
        this.displayVelocityScaling=x;
        prefs.putFloat("ParticleTracker.displayVelocityScaling", displayVelocityScaling);
    }
    public final float getDisplayVelocityScaling(){
        return(displayVelocityScaling);
    }
    public void setLogFrameLength(int x){
        if(x>0){
           //log.warning("I think I am opening a file here *************************");
            openLog();
        }else{
            closeLog();
        }
        this.logFrameLength=x;
        prefs.putInt("ParticleTracker.logFrameLength", logFrameLength);
    }
    public final int getLogFrameLength(){
        return(logFrameLength);
    }
    public void setClusterUnsupportedLifetime(int x){
        this.clusterUnsupportedLifetime=x;
        prefs.putInt("ParticleTracker.clusterUnsupportedLifetime", clusterUnsupportedLifetime);
    }
    public final int getClusterUnsupportedLifetime(){
        return(clusterUnsupportedLifetime);
    }
    public void setOnPolarityOnly(boolean b){
        this.OnPolarityOnly=b;
        prefs.putBoolean("ParticleTracker.OnPolarityOnly", OnPolarityOnly);
    }
    public final boolean getOnPolarityOnly(){
        return(OnPolarityOnly);
    }
    public void setClusterMinMass4Display(float x){
        this.clusterMinMass4Display=x;
        prefs.putFloat("ParticleTracker.clusterMinMass4Display", clusterMinMass4Display);
    }
    public final float getClusterMinMass4Display(){
        return(clusterMinMass4Display);
    }
    synchronized public void setFilterEnabled(boolean enabled) {
        super.setFilterEnabled(enabled);
        initFilter();
        if (!enabled){
            closeLog();
        }
    } 
// all default values for the tracker parameter pop-up
    private void initDefaults(){
        initDefault("ParticleTracker.clusterUnsupportedLifetime","50000");
        initDefault("ParticleTracker.ParticleTracker.clusterMinMass4Display","10");
        initDefault("ParticleTracker.displayVelocityScaling","5000.0f");
        initDefault("ParticleTracker.OnPolarityOnly","false");
        initDefault("ParticleTracker.LogFrameRate","0");
        
//        initDefault("ClassTracker.","");
    }
    
    private void initDefault(String key, String value){
        if(prefs.get(key,null)==null) prefs.put(key,value);
    }
    
    private void closeLog(){
        if(logStream!=null){
           //log.warning("I think I am closing a file here *************************");
                logStream.flush();
                logStream.close();
                logStream=null;
        }
    }
    
    private void openLog(){
            if(logStream==null){
                try{
                    logStream=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("ParticleTrackerLog.m"))));
                    logStream.println("function [m]=ParticleTrackerLog(time_shift,xshift,yshift,xscaling,yscaling,xlim,ylim)");
                    logStream.println("% lasttimestamp x y u v");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }        
    }
    
    private void printClusterLog(PrintStream log, LinkedList<Cluster> cl, int frameNumber, int now){

       ListIterator listScanner=cl.listIterator();
       Cluster c=null;
       int time_limit;
       
       time_limit=now-clusterUnsupportedLifetime;
       logStream.println(String.format("frameN=%d-time_shift", frameNumber));
       logStream.println(String.format("frame=["));
       while (listScanner.hasNext()){ 
           c=(Cluster)listScanner.next();
           if ((c.last < time_limit)||(c.last > now)){ //check if cluster is dead or if time has moved backwards
                listScanner.remove();
           }
           if (c.mass>clusterMinMass4Display){
               logStream.println(String.format("%d %e %e %e %e", c.last,c.location.x,c.location.y,c.velocity.x,c.velocity.y));
           }
       }
       logStream.println("];");
       //logStream.println("hold off");
       logStream.println("if (~isempty(frame))");
       logStream.println("plot(xscaling*frame(:,2)-xshift,yscaling*frame(:,3)-yshift,'o')");
       //logStream.println("hold on");
       logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
       logStream.println("m(frameN)=getframe;");
       logStream.println("end; %if");
    }

    // the method that actually does the tracking
    synchronized private void track(EventPacket<BasicEvent> ae){
        int n=ae.getSize();
        if(n==0) return;
        int l,k,i,ir,il,j,jr,jl;
        //int most_recent;
        //LinkedList<Cluster> pruneList=new LinkedList<Cluster>();
        int[] cluster_ids=new int[9];
        Cluster thisCluster=null;
        int[] merged_ids=null;
        float thisClusterWeight;
        float thatClusterWeight;
        ListIterator listScanner;
        Cluster c=null;
        //int maxNumClusters=getMaxNumClusters();
        
        // for each event, see which cluster it is closest to and add it to this cluster.
        // if its too far from any cluster, make a new cluster if we can
//        for(int i=0;i<n;i++){
        for(BasicEvent ev:ae){
            // check for if off-polarity is to be ignored
            if(  !( OnPolarityOnly && (ev instanceof TypedEvent)&&(((TypedEvent)ev).type==0) )  ){
// *****************
                if(logFrameLength>0){
                    if ((ev.timestamp/logFrameLength)>logFrameNumber){
                        logFrameNumber=ev.timestamp/logFrameLength;
                        printClusterLog(logStream, (LinkedList<Cluster>)clusters, logFrameNumber, ev.timestamp);<commit_msg>changed the matlab function format of the log-output of the ParticleTracker to one large switch statement. The resulting function often takes ages to load into matlab though. I'll have to look into this some more.<commit_after>/*
 * ParticleTracker.java
 *
 * Created on 30. april 2007, 16:18
 *
 */

package ch.unizh.ini.caviar.eventprocessing.tracking;
//import ch.unizh.ini.caviar.aemonitor.AEConstants;
import ch.unizh.ini.caviar.chip.*;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.event.*;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.graphics.*;
import com.sun.opengl.util.*;
import java.awt.*;
//import ch.unizh.ini.caviar.util.PreferencesEditor;
import java.awt.geom.*;
import java.io.*;
import java.util.*;
import java.util.prefs.*;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;


/**
 *
 * @author Philipp <<EMAIL>>
 */
public class ParticleTracker extends EventFilter2D implements FrameAnnotater, Observer{

    private static Preferences prefs=Preferences.userNodeForPackage(ParticleTracker.class);
    
    private java.util.List<Cluster> clusters=new LinkedList<Cluster>();
    protected AEChip chip;
    private AEChipRenderer renderer;
    private int[][] lastCluster= new int[128][128];
    private int[][] lastEvent= new int[128][128];
    private int next_cluster_id=1;
    protected Random random=new Random();
    private PrintStream logStream=null;
    
    //Variables that will be set by the tracker parameter pop-up window: 
    //------------------------------------------------------------------
    //private final int CLUSTER_UNSUPPORTED_LIFETIME=50000;
    int clusterUnsupportedLifetime= prefs.getInt("ParticleTracker.clusterUnsupportedLifetime",50000);
    //private final int CLUSTER_MINLIFEFORCE_4_DISPLAY=10;
    float clusterMinMass4Display= prefs.getFloat("ParticleTracker.clusterMinMass4Display",10);
    boolean OnPolarityOnly=prefs.getBoolean("ParticleTracker.OnPolarityOnly",false);
    float displayVelocityScaling=prefs.getFloat("ParticleTracker.DisplayVelocityScaling",5000.0f);
    int logFrameLength=prefs.getInt("Particletracker.LogFrameLength",0);
    int logFrameNumber=0;


   
    /** Creates a new instance of ParticleTracker */
    public ParticleTracker(AEChip chip) {
        super(chip);
        this.chip=chip;
        renderer=(AEChipRenderer)chip.getRenderer();
        chip.getRenderer().addAnnotator(this); // to draw the clusters
        chip.getCanvas().addAnnotator(this);
        chip.addObserver(this);
//        prefs.addPreferenceChangeListener(this);
//        Cluster newCluster=new Cluster(40,60,-1,-1);
//        clusters.add(newCluster);
        initFilter();
    }
    
// All callback functions for the tracker parameter pop-up:
// -----------------------------------------------------------
    public void setDisplayVelocityScaling(float x){
        this.displayVelocityScaling=x;
        prefs.putFloat("ParticleTracker.displayVelocityScaling", displayVelocityScaling);
    }
    public final float getDisplayVelocityScaling(){
        return(displayVelocityScaling);
    }
    public void setLogFrameLength(int x){
        if(x>0){
           //log.warning("I think I am opening a file here *************************");
            openLog();
        }else{
            closeLog();
        }
        this.logFrameLength=x;
        prefs.putInt("ParticleTracker.logFrameLength", logFrameLength);
    }
    public final int getLogFrameLength(){
        return(logFrameLength);
    }
    public void setClusterUnsupportedLifetime(int x){
        this.clusterUnsupportedLifetime=x;
        prefs.putInt("ParticleTracker.clusterUnsupportedLifetime", clusterUnsupportedLifetime);
    }
    public final int getClusterUnsupportedLifetime(){
        return(clusterUnsupportedLifetime);
    }
    public void setOnPolarityOnly(boolean b){
        this.OnPolarityOnly=b;
        prefs.putBoolean("ParticleTracker.OnPolarityOnly", OnPolarityOnly);
    }
    public final boolean getOnPolarityOnly(){
        return(OnPolarityOnly);
    }
    public void setClusterMinMass4Display(float x){
        this.clusterMinMass4Display=x;
        prefs.putFloat("ParticleTracker.clusterMinMass4Display", clusterMinMass4Display);
    }
    public final float getClusterMinMass4Display(){
        return(clusterMinMass4Display);
    }
    synchronized public void setFilterEnabled(boolean enabled) {
        super.setFilterEnabled(enabled);
        initFilter();
        if (!enabled){
            closeLog();
        }
    } 
// all default values for the tracker parameter pop-up
    private void initDefaults(){
        initDefault("ParticleTracker.clusterUnsupportedLifetime","50000");
        initDefault("ParticleTracker.ParticleTracker.clusterMinMass4Display","10");
        initDefault("ParticleTracker.displayVelocityScaling","5000.0f");
        initDefault("ParticleTracker.OnPolarityOnly","false");
        initDefault("ParticleTracker.LogFrameRate","0");
        
//        initDefault("ClassTracker.","");
    }
    
    private void initDefault(String key, String value){
        if(prefs.get(key,null)==null) prefs.put(key,value);
    }
    
    private void closeLog(){
        if(logStream!=null){
           //log.warning("I think I am closing a file here *************************");
                logStream.println("otherwise");
                logStream.println("particles=[];");
                logStream.println("cla;");
                logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
                logStream.println("end; %switch");
                logStream.flush();
                logStream.close();
                logStream=null;
        }
    }
    
    private void openLog(){
            if(logStream==null){
                try{
                    logStream=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("ParticleTrackerLog.m"))));
                    logStream.println("function [particles]=ParticleTrackerLog(frameN,time_shift,xshift,yshift,xscaling,yscaling,xlim,ylim)");
                    logStream.println("% lasttimestamp x y u v");
                    logStream.println("switch (frameN+time_shift)");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }        
    }
    
    private void printClusterLog(PrintStream log, LinkedList<Cluster> cl, int frameNumber, int now){

       ListIterator listScanner=cl.listIterator();
       Cluster c=null;
       int time_limit;
       
       time_limit=now-clusterUnsupportedLifetime;
       logStream.println(String.format("case %d", frameNumber));
       logStream.println(String.format("particles=["));
       while (listScanner.hasNext()){ 
           c=(Cluster)listScanner.next();
           if ((c.last < time_limit)||(c.last > now)){ //check if cluster is dead or if time has moved backwards
                listScanner.remove();
           }
           if (c.mass>clusterMinMass4Display){
               logStream.println(String.format("%d %e %e %e %e", c.last,c.location.x,c.location.y,c.velocity.x,c.velocity.y));
           }
       }
       logStream.println("];");
       //logStream.println("hold off");
       logStream.println("if (~isempty(particles))");
       logStream.println("plot(xscaling*particles(:,2)-xshift,yscaling*particles(:,3)-yshift,'o')");
       //logStream.println("hold on");
       logStream.println("set(gca,'xlim',xlim,'ylim',ylim)");
       //logStream.println("m(frameN)=getframe;");
       logStream.println("end; %if");
    }

    // the method that actually does the tracking
    synchronized private void track(EventPacket<BasicEvent> ae){
        int n=ae.getSize();
        if(n==0) return;
        int l,k,i,ir,il,j,jr,jl;
        //int most_recent;
        //LinkedList<Cluster> pruneList=new LinkedList<Cluster>();
        int[] cluster_ids=new int[9];
        Cluster thisCluster=null;
        int[] merged_ids=null;
        float thisClusterWeight;
        float thatClusterWeight;
        ListIterator listScanner;
        Cluster c=null;
        //int maxNumClusters=getMaxNumClusters();
        
        // for each event, see which cluster it is closest to and add it to this cluster.
        // if its too far from any cluster, make a new cluster if we can
//        for(int i=0;i<n;i++){
        for(BasicEvent ev:ae){
            // check for if off-polarity is to be ignored
            if(  !( OnPolarityOnly && (ev instanceof TypedEvent)&&(((TypedEvent)ev).type==0) )  ){
// *****************
                if(logFrameLength>0){
                    if ((ev.timestamp/logFrameLength)>logFrameNumber){
                        logFrameNumber=ev.timestamp/logFrameLength;
                        printClusterLog(logStream, (LinkedList<Cluster>)clusters, logFrameNumber, ev.timestamp);
{'fraction_non_alphanumeric': 0.13767441860465116, 'fraction_numerical': 0.009767441860465116, 'mean_word_length': 2.7630715379566833, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4045603', 'n_tokens_mistral': 5002, 'n_tokens_neox': 4879, 'n_words': 938}