1+ import pandas as pd
2+ import json
3+ from pyActigraphy .io .base import BaseRaw
4+ from datetime import datetime
5+ import uuid as uuid_lib
6+ import matplotlib .pyplot as plt
7+ import seaborn as sns
8+
9+ df = pd .read_csv ("accelerometer_results/processed_acc_data.csv.gz" , compression = 'gzip' )
10+
11+ df ['time' ] = df ['time' ].str .split (r' \[' ).str [0 ]
12+ df ['time' ] = df ['time' ].str .replace (r"\+0000" , "+00:00" , regex = True )
13+ df ['time' ] = pd .to_datetime (df ['time' ])
14+ df .set_index ('time' , inplace = True )
15+ df .index .freq = "30S"
16+
17+ with open ("accelerometer_results/processed_acc_data-summary.json" , "r" ) as f :
18+ meta = json .load (f )
19+
20+ name = meta ["file-name" ]
21+ uuid_val = uuid_lib .uuid4 ()
22+ fmt = "BBA"
23+ axial_mode = "uni"
24+ raw_time_str = meta ["file-startTime" ]
25+ cleaned_time_str = raw_time_str .split (' [' )[0 ]
26+
27+ period = df .index .max () - df .index .min () + pd .Timedelta (seconds = 30 )
28+ frequency = 1 / period .total_seconds ()
29+
30+ df = df .reset_index ()
31+
32+ df ['time' ] = pd .to_datetime (df ['time' ]).dt .floor ('30S' )
33+
34+ full_range = pd .date_range (start = df ['time' ].min ().floor ('30S' ),
35+ end = df ['time' ].max ().ceil ('30S' ),
36+ freq = '30S' ,
37+ tz = 'UTC' )
38+
39+ df = df .set_index ('time' ).reindex (full_range ).interpolate (method = 'time' )
40+
41+ start_time = df .index .min ()
42+ data = df ["acc" ]
43+ light = None
44+
45+ act = BaseRaw (
46+ name = name ,
47+ uuid = uuid_val ,
48+ format = fmt ,
49+ axial_mode = axial_mode ,
50+ start_time = start_time ,
51+ data = data ,
52+ light = light ,
53+ fpath = "accelerometer_results/acc_data.csv.gz" ,
54+ period = period ,
55+ frequency = frequency
56+ )
57+
58+ cut_points = [8 , 20 , 60 , 120 ]
59+ labels = ["Sedentary" , "Light" , "Moderate" , "Vigorous" , "Very Vigorous" ]
60+
61+ act .create_activity_report (
62+ cut_points = cut_points ,
63+ labels = labels ,
64+ threshold = 10 ,
65+ start_time = "06:00:00" ,
66+ stop_time = "22:00:00" ,
67+ oformat = "minute" ,
68+ verbose = True
69+ )
70+
71+ report = act .activity_report
72+ print ("Activity Report:" )
73+ print (report )
74+
75+ report .to_csv ("activity_report.csv" , index = False )
76+ print ("\n Activity report saved to 'activity_report.csv'" )
77+
78+ processed_data = pd .DataFrame ({
79+ 'timestamp' : act .data .index ,
80+ 'acceleration' : act .data .values
81+ })
82+ processed_data .to_csv ("processed_accelerometer_data.csv" , index = False )
83+ print ("Processed data saved to 'processed_accelerometer_data.csv'" )
84+
85+ def categorize_activity (value , cut_points , labels ):
86+ """Categorize activity level based on cut points"""
87+ if pd .isna (value ):
88+ return "Unknown"
89+ for i , cp in enumerate (cut_points ):
90+ if value <= cp :
91+ return labels [i ]
92+ return labels [- 1 ]
93+
94+ activity_data = processed_data .copy ()
95+ activity_data ['activity_level' ] = activity_data ['acceleration' ].apply (
96+ lambda x : categorize_activity (x , cut_points , labels )
97+ )
98+ activity_data ['hour' ] = activity_data ['timestamp' ].dt .hour
99+ activity_data ['date' ] = activity_data ['timestamp' ].dt .date
100+
101+ activity_data .to_csv ("categorized_activity_data.csv" , index = False )
102+ print ("Categorized data saved to 'categorized_activity_data.csv'" )
103+
104+ plt .figure (figsize = (14 , 8 ))
105+ colors = ['#ff9999' , '#66b3ff' , '#99ff99' , '#ffcc99' , '#ff99cc' ]
106+
107+ for level , color in zip (labels , colors ):
108+ level_data = activity_data [activity_data ['activity_level' ] == level ]
109+ if not level_data .empty :
110+ plt .scatter (level_data ['timestamp' ], level_data ['acceleration' ],
111+ c = color , label = level , alpha = 0.6 , s = 1 )
112+
113+ plt .title ('Activity Pattern Over Time' , fontsize = 14 , fontweight = 'bold' )
114+ plt .xlabel ('Time' )
115+ plt .ylabel ('Acceleration' )
116+ plt .legend (title = 'Activity Level' )
117+ plt .xticks (rotation = 45 )
118+ plt .grid (True , alpha = 0.3 )
119+ plt .tight_layout ()
120+ plt .savefig ('activity_pattern_over_time.png' , dpi = 300 , bbox_inches = 'tight' )
121+ plt .show ()
122+
123+ print ("\n " + "=" * 50 )
124+ print ("SUMMARY STATISTICS" )
125+ print ("=" * 50 )
126+ print (f"Total data points: { len (activity_data ):,} " )
127+ print (f"Time range: { activity_data ['timestamp' ].min ()} to { activity_data ['timestamp' ].max ()} " )
128+ print (f"Duration: { activity_data ['timestamp' ].max () - activity_data ['timestamp' ].min ()} " )
129+ print (f"\n Acceleration statistics:" )
130+ print (f" Mean: { activity_data ['acceleration' ].mean ():.2f} " )
131+ print (f" Median: { activity_data ['acceleration' ].median ():.2f} " )
132+ print (f" Std: { activity_data ['acceleration' ].std ():.2f} " )
133+ print (f" Min: { activity_data ['acceleration' ].min ():.2f} " )
134+ print (f" Max: { activity_data ['acceleration' ].max ():.2f} " )
135+
136+ print (f"\n Activity level breakdown:" )
137+ for level in labels :
138+ count = (activity_data ['activity_level' ] == level ).sum ()
139+ percentage = (count / len (activity_data )) * 100
140+ print (f" { level } : { count :,} ({ percentage :.1f} %)" )
141+
142+ print (f"\n Files saved:" )
143+ print (f" - activity_report.csv" )
144+ print (f" - processed_accelerometer_data.csv" )
145+ print (f" - categorized_activity_data.csv" )
146+ print (f" - activity_pattern_over_time.png" )
0 commit comments