#!/usr/bin/env python

usage="""\
To use, enable FE_SPA_ENABLE in firmware. The code is a tweaked and 
simplified version of plot_spa.py. This code simply sums the time 
in each task between the start/stop times and converts this to a
percent for each CPU core. It prints a simple data table the columns:

- Task ID
- Priority
- Core
- Percent in this task

Examples:
 ./sum_spa.py file.T04 3200 3200.2 

 Copyright Trimble Inc 2023
"""

import numpy as np
import mutils as m
import argparse

def main():
    parser = argparse.ArgumentParser(description=usage,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("filename", help="File with rec35:271 data")
    parser.add_argument("start_secs", help="Start time [GPS secs]",type=float)
    parser.add_argument("end_secs", help="End time [GPS secs]",type=float)
    args = parser.parse_args()

    filename = args.filename
    t0 = args.start_secs
    t1 = args.end_secs

    tsk = load_spa( filename, t0, t1)

    do_sum( tsk )

def load_spa(filename, t0, t1):
    """Load data from T04 file.
       filename = T04 filename with SPA data
       t0 = start GPS seconds
       t1 = end GPS seconds. Make t1-t0 very short, or it takes a long time.
    """
    tsk=m.vd2cls(filename,'-d35:271 -s%d -e%d'%((int(t0-1),int(t1+2))))
    tsk=tsk[(tsk.MICROSECONDS>=t0*1e6)&(tsk.MICROSECONDS<=t1*1e6)]
    return tsk

def do_sum( tsk ):
    """Sum data from load_spa()
       tsk = task switch data
    """

    # Compute the percent for each task / each core over the processing 
    # window
    for curr_core in np.unique(tsk.CORE_NUM):
        print("Processing Core: %d" % curr_core)
        
        tska = tsk[tsk.CORE_NUM==curr_core]
        x = tska.MICROSECONDS*1e-6
        y = tska.TASK_ID
        pri = tska.PRI
        
        maxID = int(np.max(y)) + 1
        taskSum = np.zeros(maxID)
        taskPri = np.zeros(maxID)

        for idx in range(len(y) - 1):
          thisID = int(y[idx])
          delta = x[idx+1] - x[idx]
          taskSum[thisID] += delta
          # Wasteful as we only need this once per element
          taskPri[thisID]  = int(pri[idx])

        total = 0.0
        for idx in range(maxID):
          total += taskSum[idx]

        for idx in range(maxID):
          if(taskSum[idx] != 0.0):
            print("%3d %3d %d %7.4f%%" % (idx,taskPri[idx],curr_core,100.0 * taskSum[idx]/total) )

        print("\n");

if __name__ == '__main__':
     main()


