Skip to content

Commit 7d305ef

Browse files
committed
pushing some final changes to allow new runs'
1 parent 46a4a03 commit 7d305ef

File tree

16 files changed

+1101
-76
lines changed

16 files changed

+1101
-76
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,12 @@
2020
- [ ] add study rule ->
2121
- if sub already in obs -> move to int
2222
- all need to be after start date
23+
24+
### adding sleep logs
25+
- [x] need to return the sleep files from `/sleep` inside the accel folder in RDSS
26+
- [x] modify `code/utils/comparison_utils` to also add the sleep logs to the linkage, storing the correct study inside
27+
- [ ] need to split running by session and split sleep logs by session
28+
29+
30+
31+
- [ ] create a new util that transforms the current logs into the GGIR available one

app/.gitkeeper

Whitespace-only changes.

code/core/acc.R

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
#!/usr/bin/env Rscript
2+
3+
library(tidyr)
4+
library(plyr)
5+
library(optparse)
6+
library(GGIR)
7+
8+
main <- function() {
9+
# Define the option list
10+
option_list <- list(
11+
make_option(c("-p", "--project_dir"), type="character",
12+
default="/mnt/nfs/lss/vosslabhpc/Projects/BOOST/InterventionStudy/3-Experiment/data/act-int-test/",
13+
help="Path to the project directory", metavar="character"),
14+
make_option(c("-d", "--deriv_dir"), type="character",
15+
default="/derivatives/GGIR-2.8.2-test2/",
16+
help="Path to the derivatives directory", metavar="character")
17+
)
18+
19+
# Parse the options
20+
opt_parser <- OptionParser(option_list=option_list)
21+
opt <- parse_args(opt_parser)
22+
23+
# Assign variables
24+
ProjectDir <- opt$project_dir
25+
ProjectDerivDir <- opt$deriv_dir
26+
27+
# Print values to verify
28+
print(paste("Project Directory:", ProjectDir))
29+
print(paste("Derivatives Directory:", ProjectDerivDir))
30+
31+
# Helper functions
32+
SubjectGGIRDeriv <- function(x) {
33+
a <- dirname(x)
34+
paste0(ProjectDir, ProjectDerivDir, a)
35+
}
36+
37+
datadirname <- function(x) {
38+
b <- dirname(x)
39+
paste0(ProjectDir, b)
40+
}
41+
42+
# Gather subject directories
43+
directories <- list.dirs(ProjectDir, recursive = FALSE)
44+
subdirs <- directories[grepl("sub-*", directories)]
45+
print(paste("subdirs: ", subdirs))
46+
47+
# Create project-specific derivatives GGIR folder if it doesn't already exist
48+
if (!dir.exists(paste0(ProjectDir, ProjectDerivDir))) {
49+
dir.create(paste0(ProjectDir, ProjectDerivDir))
50+
}
51+
52+
# List accel.csv files within subject-specific folders
53+
filepattern <- "*accel.csv"
54+
GGIRfiles <- list.files(subdirs, pattern = filepattern, recursive = TRUE,
55+
include.dirs = TRUE, full.names = TRUE, no.. = TRUE)
56+
print(paste("GGIR Files before splitting: ", GGIRfiles))
57+
58+
# Split files at the "//" so we only have paths from sub-XXX/ses-.....
59+
GGIRfiles <- sapply(strsplit(GGIRfiles, "//", fixed = TRUE), function(x) paste(x[2]))
60+
61+
print(paste("GGIR Files after splitting: ", GGIRfiles))
62+
63+
64+
# Ensure directory structure exists for GGIR processing
65+
for (i in GGIRfiles) {
66+
if (!dir.exists(SubjectGGIRDeriv(i))) {
67+
dir.create(SubjectGGIRDeriv(i), recursive = TRUE)
68+
}
69+
}
70+
71+
72+
# Run GGIR loop
73+
for (r in GGIRfiles) {
74+
if (dir.exists(paste0(SubjectGGIRDeriv(r), "/output_beh"))) {
75+
next
76+
} else {
77+
datadir <- paste0(normalize(path(datadirname(r)))
78+
outputdir <- paste0(SubjectGGIRDeriv(r))
79+
print(paste("datadir: ", datadir))
80+
print(paste("outputdir: ", outputdir))
81+
if (!dir.exists(datadir)) {
82+
stop(paste("Error: datadir does not exist ->", datadir))
83+
}
84+
# Force evaluation before calling GGIR
85+
assign("datadir", datadir, envir = .GlobalEnv)
86+
assign("outputdir", outputdir, envir = .GlobalEnv)
87+
88+
try(g.shell.GGIR(
89+
mode = 1:5,
90+
datadir = get("datadir", envir = .GlobalEnv),
91+
outputdir = get("outputdir", envir = .GlobalEnv),
92+
overwrite = FALSE,
93+
print.filename = TRUE,
94+
storefolderstructure = FALSE,
95+
windowsizes = c(5, 900, 3600),
96+
desiredtz = "America/Chicago",
97+
do.enmo = TRUE, do.anglez = TRUE,
98+
dayborder = 0,
99+
strategy = 1, hrs.del.start = 0, hrs.del.end = 0,
100+
maxdur = 0, includedaycrit = 0,
101+
idloc = 1,
102+
dynrange = 8,
103+
chunksize = 1,
104+
do.cal = TRUE,
105+
use.temp = FALSE,
106+
spherecrit = 0.3,
107+
minloadcrit = 72,
108+
printsummary = TRUE,
109+
do.imp = TRUE,
110+
epochvalues2csv = TRUE,
111+
L5M5window = c(0,24),
112+
M5L5res = 10,
113+
winhr = c(5,10),
114+
qlevels = c(960/1440, 1320/1440, 1380/1440, 1410/1440, 1430/1440, 1435/1440, 1438/1440),
115+
ilevels = seq(0,600, by = 25),
116+
iglevels = c(seq(0,4000, by = 25), 8000),
117+
bout.metric = 4,
118+
do.visual = TRUE,
119+
excludefirstlast = FALSE,
120+
includenightcrit = 0,
121+
anglethreshold = 5,
122+
timethreshold = 5,
123+
ignorenonwear = TRUE,
124+
acc.metric = "ENMO",
125+
do.part3.pdf = TRUE,
126+
outliers.only = FALSE,
127+
def.noc.sleep = 1,
128+
excludefirstlast.part5 = FALSE,
129+
maxdur = 0,
130+
threshold.lig = c(45),
131+
threshold.mod = c(100),
132+
threshold.vig = c(430),
133+
boutdur.mvpa = c(1,5,10),
134+
boutdur.in = c(10,20,30),
135+
boutdur.lig = c(1,5,10),
136+
boutcriter.mvpa = 0.8,
137+
boutcriter.in = 0.9,
138+
boutcriter.lig = 0.8,
139+
timewindow = c("MM", "WW"),
140+
acc.metric = "ENMO",
141+
do.report = c(2,4,5),
142+
visualreport = TRUE,
143+
do.parallel = TRUE
144+
))
145+
}
146+
}
147+
}
148+
149+
# Run main if executed as a script
150+
if (!interactive()) {
151+
main()
152+
}

code/core/gg.py

Lines changed: 42 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,49 @@
1-
import os
21
import subprocess
3-
import sys
42

53
class GG:
4+
"""
5+
Class to execute GGIR processing for matched subject records.
6+
"""
7+
68
def __init__(self, matched, intdir, obsdir):
9+
"""
10+
Initialize the GG instance.
11+
12+
Args:
13+
matched (dict): Mapping of subject IDs to their records.
14+
intdir (str): Path to the internal directory.
15+
obsdir (str): Path to the observational directory.
16+
"""
717
self.matched = matched
8-
self.INTDIR = intdir
9-
self.OBSDIR = obsdir
18+
self.INTDIR = intdir+'/'
19+
self.OBSDIR = obsdir+'/'
20+
self.DERIVATIVES = "/derivatives/GGIR-3.1.4" # Defined within the class
1021

1122
def run_gg(self):
12-
for subject_id, records in self.matched.items():
13-
for record in records:
14-
study = record.get('study')
15-
file_path = record.get('file_path')
16-
session = record.get('run')
17-
18-
if not file_path or not os.path.exists(file_path):
19-
print(f"Invalid or missing file path for subject {subject_id}")
20-
continue
21-
22-
# Build the output directory based on study type.
23-
if study.lower() == 'obs':
24-
outdir = os.path.join(self.OBSDIR, 'derivatives', 'GGIR-3.1.4',
25-
f"sub-{subject_id}", "ses-{session}")
26-
else:
27-
outdir = os.path.join(self.INTDIR, 'derivatives', 'GGIR-3.1.4',
28-
f"sub-{subject_id}", "ses-{session}")
29-
30-
try:
31-
# Create the derivative subdirectory within outdir.
32-
deriv_dir = os.path.join(outdir, 'derivatives')
33-
34-
# Construct the Rscript command.
35-
command = (
36-
f"""
37-
Rscript core/basic_accel.R --input_file {file_path} --output_location {outdir} --verbose
38-
"""
39-
)
40-
41-
# Run the command in a new subprocess.
42-
print(f"running GGIR for {file_path}")
43-
result = subprocess.run(
44-
command,
45-
check=True,
46-
stdout=sys.stdout,
47-
stderr=sys.stderr
48-
)
49-
# Decode and print the output.
50-
print(f"Command output: {result.stdout.decode().strip()}")
51-
except subprocess.CalledProcessError as e:
52-
print(f"Command failed for subject {subject_id} with exit status: {e.returncode}")
53-
print(f"Error output: {e.stderr.decode().strip()}")
54-
23+
"""
24+
Run GGIR for both the internal and observational project directories.
25+
"""
26+
for project_dir in [self.INTDIR, self.OBSDIR]:
27+
command = f"Rscript core/acc.R --project_dir {project_dir} --deriv_dir {self.DERIVATIVES}"
28+
29+
try:
30+
# Execute the command in a new subprocess
31+
print(f"Running GGIR for project directory {project_dir}")
32+
process = subprocess.Popen(
33+
command,
34+
shell=True,
35+
stdout=subprocess.PIPE,
36+
stderr=subprocess.STDOUT,
37+
bufsize=1,
38+
universal_newlines=True
39+
)
40+
41+
# Stream output line-by-line
42+
for line in process.stdout:
43+
print(line, end='') # already includes newline
44+
45+
process.stdout.close()
46+
process.wait()
47+
48+
if process.returncode != 0:
49+
raise subprocess.CalledProcessError(process.returncode, command)

0 commit comments

Comments
 (0)