diff --git a/.DS_Store b/.DS_Store index bb7a34e..9c22936 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/3d_files/.DS_Store b/3d_files/.DS_Store index b08f0dd..4a1e463 100644 Binary files a/3d_files/.DS_Store and b/3d_files/.DS_Store differ diff --git a/3d_files/Miniscope_Enclosure/.DS_Store b/3d_files/Miniscope_Enclosure/.DS_Store index 8c0ea94..94b5988 100644 Binary files a/3d_files/Miniscope_Enclosure/.DS_Store and b/3d_files/Miniscope_Enclosure/.DS_Store differ diff --git a/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.skp b/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.skp new file mode 100644 index 0000000..fad0ba3 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.skp differ diff --git a/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.stl b/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.stl new file mode 100644 index 0000000..e38e43e Binary files /dev/null and b/3d_files/Miniscope_Enclosure/archive/ScopeCover_flight_thinned_tall.stl differ diff --git a/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.skp b/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.skp new file mode 100644 index 0000000..b786101 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.skp differ diff --git a/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.stl b/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.stl new file mode 100644 index 0000000..b77cc21 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/archive/ScopeCover_housing_thinned_tall.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/.DS_Store b/3d_files/Miniscope_Enclosure/working/.DS_Store new file mode 100644 index 0000000..3a2156e Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/.DS_Store differ diff --git a/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.skp b/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.skp index fad0ba3..4279045 100644 Binary files a/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.skp and b/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.stl b/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.stl index e38e43e..a2a6061 100644 Binary files a/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.stl and b/3d_files/Miniscope_Enclosure/working/ScopeCover_flight_thinned_tall.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.skp b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.skp index b786101..be09512 100644 Binary files a/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.skp and b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.stl b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.stl index b77cc21..a465310 100644 Binary files a/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.stl and b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall~.skp b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall~.skp new file mode 100644 index 0000000..2e1ecde Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/ScopeCover_housing_thinned_tall~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/scopeCover_flight_snap_wider9.stl b/3d_files/Miniscope_Enclosure/working/scopeCover_flight_snap_wider9.stl new file mode 100644 index 0000000..b45a572 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/scopeCover_flight_snap_wider9.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/.DS_Store b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/.DS_Store differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap.stl new file mode 100644 index 0000000..095219f Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2.skp new file mode 100644 index 0000000..b93f72f Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2~.skp new file mode 100644 index 0000000..91ddf13 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider2~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.skp new file mode 100644 index 0000000..ad18048 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.stl new file mode 100644 index 0000000..8c20bef Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3~.skp new file mode 100644 index 0000000..245f421 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider3~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider4.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider4.stl new file mode 100644 index 0000000..79b9f57 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider4.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.skp new file mode 100644 index 0000000..ef7a372 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.stl new file mode 100644 index 0000000..0b79714 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5~.skp new file mode 100644 index 0000000..12cd62a Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider5~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.skp new file mode 100644 index 0000000..697038c Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.stl new file mode 100644 index 0000000..c3dc3bb Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider6.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.skp new file mode 100644 index 0000000..953919c Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.stl new file mode 100644 index 0000000..0572c97 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7~.skp new file mode 100644 index 0000000..1692047 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider7~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.skp new file mode 100644 index 0000000..6174c26 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.stl new file mode 100644 index 0000000..f65ac67 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8~.skp new file mode 100644 index 0000000..f2291f1 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider8~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.skp new file mode 100644 index 0000000..6546cfc Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.stl new file mode 100644 index 0000000..b45a572 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9~.skp new file mode 100644 index 0000000..bb13b34 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_flight_snap_wider9~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_housing_snap_wider8.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_housing_snap_wider8.stl new file mode 100644 index 0000000..d21890c Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_housing_snap_wider8.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.skp new file mode 100644 index 0000000..a51f9cd Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.stl new file mode 100644 index 0000000..f5ad91a Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2.skp new file mode 100644 index 0000000..c8b3d0b Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2~.skp new file mode 100644 index 0000000..e60b55e Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap2~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.skp new file mode 100644 index 0000000..fcc07c0 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.stl new file mode 100644 index 0000000..39903c5 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3~.skp new file mode 100644 index 0000000..0480c52 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap3~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap4.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap4.skp new file mode 100644 index 0000000..2116a59 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap4.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap6.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap6.skp new file mode 100644 index 0000000..f3a3696 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap6.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.skp new file mode 100644 index 0000000..9628b09 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.stl new file mode 100644 index 0000000..e76f8da Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap7.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.skp new file mode 100644 index 0000000..2219290 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.stl new file mode 100644 index 0000000..a8bef6f Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8~.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8~.skp new file mode 100644 index 0000000..fe6d66b Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap8~.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.skp b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.skp new file mode 100644 index 0000000..0bf501c Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.skp differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.stl new file mode 100644 index 0000000..b7ff5fe Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap9.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider2.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider2.stl new file mode 100644 index 0000000..f83ba63 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider2.stl differ diff --git a/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider_reversed.stl b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider_reversed.stl new file mode 100644 index 0000000..44fbb18 Binary files /dev/null and b/3d_files/Miniscope_Enclosure/working/snap_lock_cap/scopeCover_middleConector_snap_wider_reversed.stl differ diff --git a/ImBat_BatchExtract.m b/ImBat_BatchExtract.m index 463131b..af7cba2 100644 --- a/ImBat_BatchExtract.m +++ b/ImBat_BatchExtract.m @@ -31,31 +31,31 @@ disp('.mov files already extracted...'); else % extract .mov files: - % FS_AV_Parse_batch(pwd,'mat_dir','/extracted') - % extract c3d files: -% processed_dir = [pwd,'/extracted/']; -% -% c3dList = dir([pwd filesep '*.c3d']); -% -% %run through list of c3d files in that directory, convert to mat, and save -% %to processed directory -% for i = 1:length(c3dList) -% fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat -% %fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat -% dateSesh = datestr(datetime(c3dList(i).date),'yymmdd'); -% batName = extractBefore(fileName,['_' dateSesh]); -% %sessionNum = fileName(end); -% -% -% [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError]=readC3D_analog([cd filesep c3dList(i).name]); %convert file -% %plot ttl impulses to check they are linear and not missing ttl -% event_ttls = AnalogSignals(:,2); -% [R,LT,UT,LL,UL] = risetime(event_ttls,VideoFrameRate); -% -% %save new mat file in both original directory and copied directory for processing -% save([processed_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); -% %save([copy_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); -% end + FS_AV_Parse_batch(pwd,'mat_dir','/extracted') + %extract c3d files: + processed_dir = [pwd,'/extracted/']; + + c3dList = dir([pwd filesep '*.c3d']); + + %run through list of c3d files in that directory, convert to mat, and save + %to processed directory + for i = 1:length(c3dList) + fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat + %fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat + dateSesh = datestr(datetime(c3dList(i).date),'yymmdd'); + batName = extractBefore(fileName,['_' dateSesh]); + %sessionNum = fileName(end); + + + [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError]=readC3D_analog([cd filesep c3dList(i).name]); %convert file + %plot ttl impulses to check they are linear and not missing ttl + event_ttls = AnalogSignals(:,2); + [R,LT,UT,LL,UL] = risetime(event_ttls,VideoFrameRate); + + %save new mat file in both original directory and copied directory for processing + save([processed_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); + %save([copy_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); + end % Run extraction close all; diff --git a/ImBat_MultiDayAnalysis.m b/ImBat_MultiDayAnalysis.m index 600c85c..e10712d 100644 --- a/ImBat_MultiDayAnalysis.m +++ b/ImBat_MultiDayAnalysis.m @@ -12,11 +12,27 @@ ST3_2 = 1; % Place Cell Overlay ST3_3 = 1; % ST3_5 = 1; +saveFlag = 1; % local Directory: -LD = 'D:\Bat_Data2\Zack\Processed\' +LD = 'Z:\users\tobias\flight\data_processed\topQualityData\analysis_done\za\'; +%LD = 'D:\Bat_Data2\Zack\Processed\' %LD = '/Users/ARGO/Documents/DATA/Bat_Data_ZuZu'; +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + %saveDir1 = '/Users/periscope/Desktop/analysis/flight/plots/'; + %saveDir1 = 'C:\Users\tobias\Desktop\analysis\plots\'; + if ~exist([saveDir1 datestr(now,'yymmdd') ]) + mkdir([saveDir1 datestr(now,'yymmdd')]); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep]; +end +if ~exist(LD) mkdir(LD); +end % Cell array containing strings of the days you want to look at ( MANUAL) % days = {'190528','190529','190530'}; @@ -54,17 +70,17 @@ % create index into correct subfolder ( get biggest flight and rest % Flight Flder - cd(days{i}); + cd([days{i} filesep 'extracted']); out = ImBat_GetBiggestFolder('fly'); - - - folder = [out,'/processed']; + cd(out); + processedDir = dir('processed_*'); + folder = [processedDir(end).name]; ROI_Data{i}.folder = folder; % save this for indexing later... disp(['entering into folder for day: ', days{i}]); cd(folder) % index into folder Alignment = load('Alignment.mat'); % get alignment data - ROIs = load('Motion_corrected_Data_DS_results.mat'); % Get ROI data + ROIs = load('results.mat'); % Get ROI data % Consolidate ROI and Flight data ROI_Data{i}.Alignment = Alignment; @@ -84,11 +100,16 @@ try - cd(days{i}); - out = ImBat_GetBiggestFolder('rest1'); - folder_rest = [out,'/processed']; - - cd(DIR); cd(folder_rest); + %cd(days{i}); + cd ..; + cd ..; + out = ImBat_GetBiggestFolder('rest1'); +cd(out); + processedDir = dir('processed_*'); + folder_rest = [processedDir(end).name]; + + %cd(DIR); + cd(folder_rest); load('Motion_corrected_Data_DS', 'Y','Ysiz'); disp( 'Getting Max Projection for rest...'); [MaxProj_rest, ~] = ImBat_Dff(Y); @@ -103,7 +124,7 @@ end % Save data locally somewhere... -cd(LD); +cd(saveDir); for i = 1:size(ROI_Data,2); if i ==1; filename = ['ROI_Data_',days{1}] @@ -111,9 +132,10 @@ filename = [filename,'_',days{i}]; end end - -save([filename,'.mat'],'ROI_Data') +save([filename, '.mat'],'ROI_Data') +%save([filename,'.mat'],'ROI_Data') +cd(LD) end %% Cell Sort to get 'similar ROIs' diff --git a/ImBat_plotFlights.asv b/ImBat_plotFlights.asv new file mode 100644 index 0000000..bc0a595 --- /dev/null +++ b/ImBat_plotFlights.asv @@ -0,0 +1,313 @@ +function [flightPaths] = ImBat_plotFlights(trackData,varargin) + +nclusters = 6; %nIumber of clusters for kmeans clustering of flight trajectories +ntrajectories = 12; %number of output trajectories from kmeans that you want to look at +clusterInd = 12; %number of different cluster indices to initiate + +batName = []; +dateSesh = []; +sessionType = []; +saveFlag = 0; +loadFlag = 0; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + end +end + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + date = strcat(lower(batName(1:2)),dateSesh); + label = [batName '_' dateSesh '_' sessionType]; + folderName = extractBefore(pwd,batName); + %trackData = load([folderName label '_track.mat']); +end +%find ttl pulses for synching +%event_ttls = trackData.AnalogSignals(:,2); %from motion data +%[R,LT,UT,LL,UL] = risetime(event_ttls,trackData.VideoFrameRate); %find times of ttl pulses in SECONDS + +%might want to use raw c3d to keep track of each marker (this could be +%useful for when not all 3 markers are present, which is often the case +%when the animal is at a wall) +idx = trackData.Markers == 0; +trackData.Markers(idx) = NaN; +avgMarker = squeeze(nanmean(trackData.Markers,2)); +mx=avgMarker(:,1); +my=avgMarker(:,2); +mz=avgMarker(:,3); + +%mx = trackData.Markers(:,1,1);%trackData.Markers(1:length(trackData.Markers(:,1,1))/2,1,1);%trackData.Markers(length(trackData.Markers(:,1,1))/2+1:length(trackData.Markers(:,1,1)),1,1); +%my = trackData.Markers(:,1,2);%trackData.Markers(1:length(trackData.Markers(:,1,1))/2,1,2);%trackData.Markers(length(trackData.Markers(:,1,1))/2+1:length(trackData.Markers(:,1,1)),1,2); +%mz = trackData.Markers(:,1,3);%trackData.Markers(1:length(trackData.Markers(:,1,1))/2,1,3);%trackData.Markers(length(trackData.Markers(:,1,1))/2+1:length(trackData.Markers(:,1,1)),1,3); + +%set zeros to nan +mx(find(mx == 0)) = nan; +my(find(my == 0)) = nan; +mz(find(mz == 0)) = nan; + +trajPartial(1,:) = mx'; +trajPartial(2,:) = my'; +trajPartial(3,:) = mz'; + +%mxNan = find(mx == nan); +mxNan = find(isnan(mx)); + +mxFull = fillmissing(mx,'nearest'); +myFull = fillmissing(my,'nearest'); +mzFull = fillmissing(mz,'nearest'); + +trajectories_continuous(1,:) = mxFull'; +trajectories_continuous(2,:) = myFull'; +trajectories_continuous(3,:) = mzFull'; + +%plot all flights in black +plotFlightPathsAll = figure(); +%plot3(mxFull,myFull,mzFull,'LineWidth',2,'Color','k') +scatter3(mxFull,myFull,mzFull,'.','k') +hold on + +% col = jet(100); +% for i = 2:length(trackData.Markers(:,1,:)) +% %plot3(mxFull(i), myFull(i), mzFull(i), 'color',col(vecnorm([mxFull(i),myFull(i),mzFull(i) - mxFull(i-1),myFull(i-1),mzFull(i-1)], 2, 2))) +% hold on +% end +% % modify labels for tick marks +% xticks = get(gca,'xtick'); +% yticks = get(gca,'ytick'); +% zticks = get(gca,'ztick'); +% scaling = 0.1; %1.1um per pixel +% newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); +% newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); +% newlabelsZ = arrayfun(@(az) sprintf('%g', scaling * az), zticks, 'un', 0); +% set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY,'zticklabel',newlabelsZ); +title(['All flights: ' batName ' ' dateSesh ' ' sessionType]); +xlabel('mm'); ylabel('mm'); zlabel('mm'); +view(0,90) +hold off + +%threshold based on speed +Vx = gradient(mxFull, 1/trackData.VideoFrameRate); +Vy = gradient(myFull, 1/trackData.VideoFrameRate); +Vz = gradient(mzFull, 1/trackData.VideoFrameRate); +batSpeed = sqrt(Vx.^2 + Vy.^2 + Vz.^2)/1000; %in m/s + +nonflying = find(batSpeed < 1.5); +toofast = find(batSpeed > 35); + +%set low speed points to zero +%mx([nonflying]) = nan;%mx(nonflying) = nan; %mx([nonflying; toofast]) = nan; +%my([nonflying]) = nan;%my(nonflying) = nan;%my([nonflying; toofast]) = nan; +%mz([nonflying]) = nan;%mz(nonflying) = nan;%mz([nonflying; toofast]) = nan; + +%splice out individual flights +% nonflying = downsample(nonflying,5); +% nonflying = round(nonflying/5); +% nonflyTemp = find(nonflying==0); +% nonflying(nonflyTemp) = 1; +%toofast = round(toofast/5); +batspeed = batSpeed; +batspeed(nonflying) = nan; +%batspeed(toofast) = nan; + +bflying=~isnan(batspeed); + +%for each data point, sum up the next 1s of data +allsums = []; +for bf = 1 : size(bflying,1)-trackData.VideoFrameRate + allsums(bf) = sum(bflying(bf:bf+trackData.VideoFrameRate/2)); +end + +[R,rLT,rUT,rLL,rUL] = risetime(allsums); +[F,fLT,fUT,fLL,fUL] = falltime(allsums); +flight_starts = round(rLT); +flight_ends = round(fLT); + +%cut out flights and save +plotFlightPathsStartStop = figure(); +if size(R,2) > 0 + CM = jet(size(R,2)); + for nf = 1 : size(R,2) + hold on + plot3(mxFull(flight_starts(nf):flight_ends(nf)),myFull(flight_starts(nf):flight_ends(nf)),mzFull(flight_starts(nf):flight_ends(nf)),'LineWidth',1,'Color',CM(nf,:)) + hold on + + fstartxyz(nf,1) = round(nanmean(mxFull(flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + fstartxyz(nf,2) = round(nanmean(myFull(flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + fstartxyz(nf,3) = round(nanmean(mzFull(flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + + fendxyz(nf,1) = round(nanmean(mxFull(flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + fendxyz(nf,2) = round(nanmean(myFull(flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + fendxyz(nf,3) = round(nanmean(mzFull(flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + + %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),75,'r','filled') + hold on + scatter3(fendxyz(nf,1),fendxyz(nf,2),fendxyz(nf,3),50,'k','filled') + %pause + end +else + fstartxyz(1,1) = (0); + fstartxyz(1,2) = (0); + fstartxyz(1,3) = (0); + + fendxyz(1,1) = (0); + fendxyz(1,2) = (0); + fendxyz(1,3) = (0); +end +title(['All flights start(r)/stop(b): ' batName ' ' dateSesh ' ' sessionType]); +xlabel('mm'); ylabel('mm'); zlabel('mm'); +hold off +%try +%k means cluster of flight trajectories into nclusters +%find pairs of start and endpoints with a high number of flights +rng(2) %control random number generation +try + kstart = kmeans(fstartxyz,nclusters); +catch + %kstart = kmeans(fstartxyz,nclusters/2); +end +rng(2) +try + kend = kmeans(fendxyz,nclusters); +catch + %kend = kmeans(fendxyz,nclusters/2); +end +nflights = []; +allflights = []; +npair = []; +ncounter = 0; +for ks = 1 : nclusters + for ke = 1 : nclusters + ncounter = ncounter + 1; + npair(ncounter,:) = [ks ke]; + nflights(ncounter) = size(intersect(find(kstart == ks),find(kend == ke)),1); + allflights{ncounter} = intersect(find(kstart == ks),find(kend == ke))'; + end +end + +[~, ssf] = sort(nflights,'descend'); %sort clustered flights +%plot clustered flights +plotFlightPathsClusterEach = figure(); +jj = jet(1500); +for traj = 1 : clusterInd + try + if traj + end + end + + function cb_new(AN, h, event) + if length(AN.plot_annotations) ~= size(AN.annotations, 1) + error('Annotion list out of sync. Try reopening annotator.'); + end + + % get annotation + h = AN.drawAnnotation(); + if ~isvalid(h) + return; + end + + % mark as unsaved + AN.saved = false; + + % add to list + AN.plot_annotations{end + 1} = h; + AN.annotations = [AN.annotations; h.getPosition()]; + end + + function cb_load(AN, h, event) + [filename, pathname] = uigetfile({'*.mat', 'MATLAB File (*.mat)'; '*.*', 'All Files'}, 'Load annotations'); + + % was anceled? + if isequal(filename, 0) || isequal(pathname, 0) + return; + end + + % load file + AN.loadAnnotations(fullfile(pathname, filename)); + end + + function cb_save(AN, h, event) + % figure out default name + if isempty(AN.annot_file) + [path, nm, ~] = fileparts(AN.file); + def_name = [path filesep nm '.mat']; + else + def_name = AN.annot_file; + end + + % show save window + [filename, pathname] = uiputfile({'*.mat', 'MATLAB File (*.mat)'; '*.*', 'All Files'}, 'Save annotations', def_name); + + % was anceled? + if isequal(filename, 0) || isequal(pathname, 0) + return; + end + + % save + AN.saveAnnotations(fullfile(pathname, filename)); + end + + function cb_beforeCloseWindow(AN, h, event) + % clean annotations + AN.cleanAnnotations(); + + % cache masks + AN.cached_masks = AN.getMasks(); + + % is unsaved? + if ~AN.saved + % prompt to save + response = questdlg('Do you want to save changes before closing?', 'Save Changes', 'Cancel', 'No', 'Yes', 'Yes'); + switch response + case 'Yes' + AN.cb_save(h, event); + case 'Cancel' + return + end + end + + % clear image + delete(gcf); + end + + function cb_closeWindow(AN, h, event) + % clear image + clear AN.image; + end + + function loadAnnotations(AN, fl) + % load file + d = load(fl); + + % check file + if ~isfield(d, 'annotations') + warning('Invalid annotations file.'); + return + end + + if d.width ~= AN.width && d.height ~= AN.height + error('The annotation file has different dimensions.'); + end + + if ~strcmp(d.file, AN.file) + warning('Annotations were potentially for a different image.'); + end + + % store file name + AN.annot_file = fl; + + % copy data + AN.annotations = d.annotations; + + % redraw + AN.redrawAnnotations(); + + % mark saved + AN.saved = true; + end + + function saveAnnotations(AN, fl) + % clean annotations + AN.cleanAnnotations(); + + % extract variables + name = AN.name; %#ok + file = AN.file; %#ok + %image = AN.image; %#ok + annotations = AN.annotations; %#ok + width = AN.width; %#ok + height = AN.height; %#ok + %masks = AN.cached_masks; %#ok + % do save + save(fl, '-v7.3', 'name', 'file', 'annotations', 'width', 'height'); + + % store file name + AN.annot_file = fl; + + % mark saved + AN.saved = true; + end + + function results = wait(AN) + % block + uiwait(AN.win); + results = AN.annotations; + end + + function results = getAnnotations(AN) + AN.cleanAnnotations(); + results = AN.annotations; + end + + function masks = getMasks(AN) + if ~isvalid(AN.win) + masks = AN.cached_masks; + return; + end + + AN.cleanAnnotations(); + + ret = {}; + for i = 1:length(AN.plot_annotations) + h = AN.plot_annotations{i}; + if ~isvalid(h) + continue; + end + + ret{end + 1} = h.createMask(); + end + masks = cat(3, ret{:}); + end + end + + methods (Access=protected) + function h = drawAnnotation(AN, position) + if ~exist('position', 'var') || isempty(position) + h = imellipse(AN.axes); + if ~isvalid(h) + return; + end + else + h = imellipse(AN.axes, position); + end + addNewPositionCallback(h, @(p) AN.annotationPositionUpdate(h, p)); + end + + function annotationPositionUpdate(AN, h, position) + for i = 1:length(AN.plot_annotations) + if AN.plot_annotations{i} == h + AN.annotations(i, :) = position; + AN.saved = false; + break; + end + end + end + + function redrawAnnotations(AN) + % hold axes + hold(AN.axes, 'on'); + + % remove existing plot + if ~isempty(AN.plot_annotations) + for i = 1:length(AN.plot_annotations) + h = AN.plot_annotations{i}; + delete(h); + end + AN.plot_annotations = {}; + end + + % add new plot + if ~isempty(AN.annotations) + for i = 1:size(AN.annotations, 1) + % draw new annotation + h = AN.drawAnnotation(AN.annotations(i, :)); + AN.plot_annotations{i} = h; + end + end + + % unhold axes + hold(AN.axes, 'off'); + end + + function cleanAnnotations(AN) + % only if window is still valid + if ~isvalid(AN.win) + return; + end + + new_annotations = []; + new_plot_annotations = {}; + for i = 1:length(AN.plot_annotations) + % not valid + if ~isvalid(AN.plot_annotations{i}) + continue; + end + + % add annotations + new_annotations = [new_annotations; AN.annotations(i, :)]; + new_plot_annotations{end + 1} = AN.plot_annotations{i}; + end + AN.annotations = new_annotations; + AN.plot_annotations = new_plot_annotations; + end + end +end diff --git a/ROI/CaBMI_XMASS.m b/ROI/CaBMI_XMASS.m index f9dbccb..038b510 100644 --- a/ROI/CaBMI_XMASS.m +++ b/ROI/CaBMI_XMASS.m @@ -1,11 +1,9 @@ function [RGB1 RGB2] = CaBMI_XMASS(GG1,GG2,GG3,varargin); - -% Make sure you take the median for the input matrixes.. - - +days = 3; -HL = [0.20 .80]; +% Make sure you take the median for the input matrixes.. +HL = [0.05 0.6];%[0.05 .4]; T = 1:size(GG1,2); F = 1:size(GG1,1); movie = 0; @@ -31,12 +29,16 @@ % im1(:,:,:,2)= (GG2 - min(GG2(:))) / (max(GG2(:)) - min(GG2(:))); % im1(:,:,:,3)= (GG3 - min(GG3(:))) / (max(GG3(:)) - min(GG3(:))); -im1(:,:,:,1)= mat2gray(GG1); -im1(:,:,:,2)= mat2gray(GG2); -im1(:,:,:,3)= mat2gray(GG3); +im1(:,:,:,1)= GG1;%mat2gray(GG1); +im1(:,:,:,2)= GG2;%mat2gray(GG2); +if isempty(GG3) + im1(:,:,:,3)= GG2;%mat2gray(GG2); +else + im1(:,:,:,3)= GG3;%mat2gray(GG3); +end % Mean subtracted/Normalized -for ii = 1:3 +for ii = 1:days M = squeeze(im1(:,:,:,ii)); imT = (M./(median(M,3)+.01)); im2(:,:,:,ii) = imT- median(imT,3); @@ -44,7 +46,7 @@ %im2 = im2 - mean(im2(:,:,:,:),3); %im2 = mat2gray(im2); -for ii = 1:3; % normalize each channel... +for ii = 1:days % normalize each channel... M = squeeze(im2(:,:,:,ii)); im2(:,:,:,ii) = mat2gray(M);%(M - min(M(:))) / (max(M(:)) - min(M(:))); end @@ -52,9 +54,8 @@ rsjp = imadjust(im1(:),[Llim ; Hlim]); rsjp2 = imadjust(im2(:),[Llim ; Hlim]); - -RGB1 = reshape(rsjp,[size(im1,1),size(im1,2),size(im1,3),3]); -RGB2 = reshape(rsjp2,[size(im2,1),size(im2,2),size(im2,3),3]); + RGB1 = reshape(rsjp,[size(im1,1),size(im1,2),size(im1,3),3]); + RGB2 = reshape(rsjp2,[size(im2,1),size(im2,2),size(im2,3),3]); %F = flip(F,1); %RGB1 = RGB1(size(RGB1,1):-1:1,:,:); @@ -118,7 +119,9 @@ hold on plot(zscore(squeeze(mean(mean(GG1,1),2))),'r'); plot(zscore(squeeze(mean(mean(GG2,1),2))),'g'); - plot(zscore(squeeze(mean(mean(GG3,1),2))),'b'); + if ~isempty(GG3) + plot(zscore(squeeze(mean(mean(GG3,1),2))),'b'); + end end if size(RGB1,3) ==1; diff --git a/ROI/FS_annotate_image.m b/ROI/FS_annotate_image.m new file mode 100644 index 0000000..1960ca5 --- /dev/null +++ b/ROI/FS_annotate_image.m @@ -0,0 +1,28 @@ +function ROI = FS_annotate_image(im) +an = Annotator(im); +an.wait(); +masks = an.getMasks(); + + +for i = 1: size(masks,3) + + [col,row] = find(masks(:,:,i)== 1); + + ROI.coordinates{1,i} = [row col]; + ROI.stats(i).Centroid=mean(ROI.coordinates{i}); + ROI.stats(i).Diameter=max(pdist(ROI.coordinates{i},'euclidean')); + k=convhull(ROI.coordinates{i}(:,1),ROI.coordinates{i}(:,2)); + ROI.stats(i).ConvexHull=ROI.coordinates{i}(k,:); + +end + +ROI.type = 'Image'; +im2 = imread(im); +ROI.reference_image = im2; +b = im(1:end-4); +b = strcat(b,'_ROI_DATA.mat'); +save(b,'ROI') +end + + + diff --git a/ROI/ImBat_Dff.m b/ROI/ImBat_Dff.m index a79894f..578fd9e 100644 --- a/ROI/ImBat_Dff.m +++ b/ROI/ImBat_Dff.m @@ -4,6 +4,14 @@ dateSesh = []; sessionType = []; loadFlag = 0; +% ImBat_Dff +scaling = 10; +minLimMult = 0; %0 5 min limit multiplier for max projections +maxLimMult = 0.45; %32 20 max limit multiplier for max projections +%filt_rad = 10; +%filt_alpha = 2; + gSig = 1; + gSiz = 4.5*gSig; % User inputs overrides nparams=length(varargin); @@ -15,46 +23,60 @@ dateSesh = varargin{i+1}; case 'sessiontype' sessionType = varargin{i+1}; - case 'loadflag' + case 'loadflag' loadFlag = varargin{i+1}; + case 'filt_rad' + filt_rad = varargin{i+1}; + filt_alpha = filt_rad; end end -% ImBat_Dff -scaling = 8; + + %labels for loading and saving data if running independent fromImBat_analyze if loadFlag == 1 date = strcat(lower(batName(1:2)),dateSesh); label = [batName '_' dateSesh '_' sessionType]; - load([pwd '/processed/Motion_corrected_Data_DS.mat']); + processedFolders = dir('processed*'); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + load([pwd processed_Newest '/Motion_corrected_Data_DS.mat']); end % Make df/f image - +% Take min of movie +Y_min = min(Y,3); +% Subtract min +Y = Y-Y_min; % Filter movie - -Y = (convn(Y, single(reshape([1 1 1] /10, 1, 1, [])), 'same')); - -% Take median of movie -Y_med = median(Y,3); - -% Subtract median -Y = Y-Y_med; +Y = medfilt3(Y); %filter temporally +% filtering +% h=fspecial('gaussian',filt_rad,filt_alpha); +% Y=imfilter(Y,h,'circular'); +% Y = (convn(Y, single(reshape([1 1 1] /10, 1, 1, [])), 'same')); + %make gaussian filter based on normcorre function + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + Y = imfilter(Y,psf,'symmetric'); % take max Ymax = max(Y,[],3); -Ymax = imresize(Ymax,scaling); +Ymax = imresize(Ymax,scaling); %resize maxFig = figure(); colormap(gray); -imagesc(Ymax); +%imagesc(Ymax,[0 10]); +imagesc(Ymax,[abs(min(min(Ymax)))*minLimMult max(max(Ymax))*maxLimMult]);% max(max(Ymax))*maxLimMult]); +set(gca,'YDir','normal'); hold on; -xticks = get(gca,'xtick'); -yticks = get(gca,'ytick'); -scaling = 1.1; %1.1um per pixel -newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); -newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); -set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +%xticks = get(gca,'xtick'); +%yticks = get(gca,'ytick'); +%scaling_pixel = 1.1; %1.1um per pixel +%newlabelsX = arrayfun(@(ax) sprintf('%g', scaling_pixel * ax), xticks, 'un', 0); +%newlabelsY = arrayfun(@(ay) sprintf('%g', scaling_pixel * ay), yticks, 'un', 0); +%set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); title(['Max Projection dFF: ' batName ' ' dateSesh ' ' sessionType]); xlabel('um'); ylabel('um'); diff --git a/ROI/ImBat_RGB_flightAlign.m b/ROI/ImBat_RGB_flightAlign.m new file mode 100644 index 0000000..500f397 --- /dev/null +++ b/ROI/ImBat_RGB_flightAlign.m @@ -0,0 +1,840 @@ +function ImBat_RGB_flightAlign(batId,fullSeshTag,day1,day2,day3) +%batId = 'Gal'; +%fullSeshTag = 1, chooses to look at whole session for 3 day comparison +clustNum = 2; +saveFlag = 1; +rigidFlag = 1; +rest1Flag = 1; +hFilt1 = 35; %this is for smoothing the image to determine background for dividing it out to normalize the pixel intensities on all layers +hFilt2 = 25; %this is for smoothing the actual image before the exponential to show the layers, use 25 for rgb overlay and 50 for the difference heat plots +clipRangeShow = [-0.45 0.45]; % [-0.4 0.4] clipping HL to use for the heat map plots +clipRangeOverlap = [0 0.25];%[0.40 0.8]; %clipping HL to use for the RGB overlay +saveTag = ['rest']; +dirAllTrials = pwd; +h1 = fspecial('disk',hFilt1); %normalize background smoothing +h2 = fspecial('disk',hFilt2); %smooth presentation image + +%load first day placeCellStableROI data +if strcmp(batId,'Gal') + %cd([dirTop(day1).folder filesep 'plots\200911-preDurPost cells across days']); + load('Gal_200227to200404_YmaxFull_test.mat'); + activity_allTrials = YmaxFullAllDays; + %load('Gal_200311to200324_activity_allTrials_allClusts_allTrials_sMat_newDff_newOrder.mat'); %load activity for pre,dur,post +elseif strcmp(batId,'Gen') + load('Gen_200305to200311_YmaxFull_Ymed.mat'); + %load('Gen_200319to200324_YmaxFull_test.mat'); + activity_allTrials = YmaxFullAllDays; + %load('Gen_200319to200324_activity_allTrials_allClusts_sMat_newDff_newOrder.mat'); %load activity for pre,dur,post +elseif strcmp(batId,'Z2') + %load('Z2_190701to190822_activity_allTrials_allClusts_sMat_newDff_newOrder.mat'); + load('Z2_190701to190822_YmaxFull_Ymed.mat'); + activity_allTrials = YmaxFullAllDays; +elseif strcmp(batId,'Zu') + load('Zu_190704to190820_YmaxFull_test.mat'); + activity_allTrials = YmaxFullAllDays; +elseif strcmp(batId,'Za') + %load('Za_190524to190530_activity_allTrials_allClusts_sMat_newDff_newOrder.mat'); + load('Za_190524to190530_YmaxFull_rest.mat'); + activity_allTrials = YmaxFullAllDays; +end + +%make saving directory +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + %saveDir1 = '/Users/periscope/Desktop/analysis/flight/plots/'; + %saveDir1 = 'C:\Users\tobias\Desktop\analysis\plots\'; + if ~exist([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']) + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign' filesep]; +end +%% pull out the correct data into the raw image variables +if fullSeshTag == 0 %comparing flight aligned max proj + if isempty(day3) + if day1 == day2 %if looking at the cluster flight aligned vs full session + %set raw to the flight aligned frames and full session + if rest1Flag == 1 + IM1_raw = activity_allTrials.YmaxRest{day1}; + else + IM1_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day1}; + end + IM2_raw = activity_allTrials.YmaxFull{day1}; + IM3_raw = activity_allTrials.YmaxFull{day1}; %duplicate for now + plotTitle = [saveTag ' ' batId ' clust ' num2str(clustNum) ': Day ' num2str(day1) ' (r) v full session (c)']; + else %if looking at 1 day vs another day only + %set raw to the flight aligned frames, + IM1_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day1}; + IM2_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day2}; + IM3_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day2}; %duplicate for now + plotTitle = [saveTag ' ' batId ' clust ' num2str(clustNum) ': Day ' num2str(day1) ' (r) v Day ' num2str(day2) ' (c)'] + end + else %if looking at comparing 3 days + IM1_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day1}; + IM2_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day2}; + IM3_raw = activity_allTrials.maxMeanFrames_dur{clustNum}{day3}; + plotTitle = [saveTag ' ' batId ' clust ' num2str(clustNum) ': Day ' num2str(day1) ' (r) v Day ' num2str(day2) ' (g) v Day ' num2str(day3) ' (b)']; + end +else %comparing the full session + if isempty(day3) %comparing 1 day vs another + IM1_raw = activity_allTrials.YmaxFull{day1}; + IM2_raw = activity_allTrials.YmaxFull{day2}; + IM3_raw = activity_allTrials.YmaxFull{day2}; %duplicate for now + plotTitle = [saveTag ' ' batId ' clust ' num2str(clustNum) ' Full Sesh: Day ' num2str(day1) ' (r) v Day ' num2str(day2) ' (c)']; + else %comparing 3 days full + if rest1Flag == 1 + IM1_raw = activity_allTrials.YmaxRest{day1}; + IM2_raw = activity_allTrials.YmaxRest{day2}; + IM3_raw = activity_allTrials.YmaxRest{day3}; + else + IM1_raw = activity_allTrials.YmaxFull{day1}; + IM2_raw = activity_allTrials.YmaxFull{day2}; + IM3_raw = activity_allTrials.YmaxFull{day3}; + end + plotTitle = [saveTag ' ' batId ' Full Sesh: Day ' num2str(day1) ' (r) v Day ' num2str(day2) ' (g) v Day ' num2str(day3) ' (b)']; + end +end + +% IM_rawall = cell(3,1); +% for day_i = 1:3 +% IM_rawall{day_i} = zeros(size(YmaxFull{day_i},1),size(YmaxFull{day_i},2),3); +% for part_i = 1:3 +% IM_rawall{day_i}(:,:,part_i) = YmaxFull{part_i+(day_i-1)*3}; +% end +% end +% IM1_raw = mean(IM_rawall{1},3); +% IM2_raw = mean(IM_rawall{2},3); +% IM3_raw = mean(IM_rawall{3},3); +% IM1_raw = IM_rawall{3}(:,:,1); +% IM2_raw = IM_rawall{3}(:,:,2); +% IM3_raw = IM_rawall{3}(:,:,3); + +%filter, and divide background to make the pixels all the same brightness +%resize and subtract background +IM1doub = imresize(double(IM1_raw),2); +IM2doub = imresize(double(IM2_raw),2); +IM3doub = imresize(double(IM3_raw),2); +% IM1_filt = IM1doub; +% IM2_filt = IM2doub; +% IM3_filt = IM3doub; + +bground1=imfilter(IM1doub,h1,'replicate');%smoothdata(IM1doub,'gaussian',2);% +bground2=imfilter(IM2doub,h1,'replicate');%smoothdata(IM2doub,'gaussian',2);% +bground3=imfilter(IM3doub,h1,'replicate');%smoothdata(IM3doub,'gaussian',2);% +IM1_filt=IM1doub./(bground1+5); +IM2_filt=IM2doub./(bground2+5); +IM3_filt=IM3doub./(bground3+5); + +%concatenate to make into grayscale and then break apart into correct sizes +IMcat = [IM1_filt IM2_filt IM3_filt]; IMcat_gray = mat2gray(IMcat); +IM1 = IMcat_gray(:,1:size(IMcat_gray,2)/3); +IM2 = IMcat_gray(:,(size(IMcat_gray,2)/3)+1:2*size(IMcat_gray,2)/3); +IM3 = IMcat_gray(:,(2*size(IMcat_gray,2)/3)+1:end); +%make sure all images are same size if overlapping later +minRow = min([size(IM1,1),size(IM2,1),size(IM3,1)]); +minCol = min([size(IM1,2),size(IM2,2),size(IM3,2)]); + +%make copy of the image to heavily filter for image registration +image1 = IM1; +image2 = IM2; +image3 = IM3; +% imfilt1 = imfilter(image1,h,'replicate'); +% imfilt2 = imfilter(image2,h,'replicate'); +% imfilt3 = imfilter(image3,h,'replicate'); +% image1 = imfilt1.^2; +% image2 = imfilt2.^2; +% image3 = imfilt3.^2; +% Clip image ( binarize) above 25 percentile +image1(image1<0.25) =0; +image2(image2<0.25) =0; +image3(image3<0.25) =0; +% Clip image ( binarize) above 25 percentile +image1(image1>=0.75) =1; +image2(image2>=0.75) =1; +image3(image3>=0.75) =1; +% remove edges ( in case these are producing artifacts) +edgeCutoff = 70; +image1(1:edgeCutoff,:) = 0; +image1(:,1:edgeCutoff) = 0; +image1(end-edgeCutoff:end,:) = 0; +image1(:,end-edgeCutoff:end) = 0; +image2(1:edgeCutoff,:) = 0; +image2(:,1:edgeCutoff) = 0; +image2(end-edgeCutoff:end,:) = 0; +image2(:,end-edgeCutoff:end) = 0; +image3(1:edgeCutoff,:) = 0; +image3(:,1:edgeCutoff) = 0; +image3(end-edgeCutoff:end,:) = 0; +image3(:,end-edgeCutoff:end) = 0; + +if isempty(day3) + IM3 = []; + image3 = []; +end +if rigidFlag == 1 %use the rigid alignment with affine + try + [imagesAligned] = ImBat_imageAlign(image1,image2,image3,IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3(1:minRow,1:minCol)); + catch + [imagesAligned] = ImBat_imageAlign(image1,image2,image3,IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3); + end +else %use nonrigid with demon flow + [figNonrigid,imagesAligned] = ImBat_imageAlign_nonrigid(image1,image2,image3,IM1,IM2,IM3); +end +IM1_aligned = imagesAligned.IM1_aligned; +IM2_aligned = imagesAligned.IM2_aligned; +IM3_aligned = imagesAligned.IM3_aligned; + +% IM1doub = imresize(double(IM1_aligned),2); +% IM2doub = imresize(double(IM2_aligned),2); +% IM3doub = imresize(double(IM3_aligned),2); +% bground1=imfilter(IM1doub,h,'replicate');%smoothdata(IM1doub,'gaussian',2);% +% bground2=imfilter(IM2doub,h,'replicate');%smoothdata(IM2doub,'gaussian',2);% +% bground3=imfilter(IM3doub,h,'replicate');%smoothdata(IM3doub,'gaussian',2);% +% IM1_bfilt=imresize(double(IM1_aligned),2)./(bground1+5); +% IM2_bfilt=imresize(double(IM2_aligned),2)./(bground2+5); +% IM3_bfilt=imresize(double(IM3_aligned),2)./(bground3+5); + +%filter, then average the images and subtract each from that average to show difference +IM1_aligned_filt = imfilter(IM1_aligned,h2,'replicate');%(IM1_aligned,hFilt,'replicate'); +IM2_aligned_filt = imfilter(IM2_aligned,h2,'replicate');%(IM2_aligned,hFilt,'replicate'); +IM3_aligned_filt = imfilter(IM3_aligned,h2,'replicate');%(IM3_aligned,hFilt,'replicate'); +IM1_aligned_filt = IM1_aligned_filt.^3; +IM2_aligned_filt = IM2_aligned_filt.^3; +IM3_aligned_filt = IM3_aligned_filt.^3; + +%RGB the images +[aOverlap,bOverlap] = CaBMI_XMASS(IM1_aligned_filt,IM2_aligned_filt,IM3_aligned_filt,'hl',clipRangeOverlap); +%rgb the original unaligned for comparison +[aUnaligned,bUnaligned] = CaBMI_XMASS(IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3); + +%quantify quartiles of overlap to see how good the days overlap +sizeIm = size(IM1_aligned_filt)/2; +quartRange(1,:) = [1,sizeIm(1),1,sizeIm(2)]; +quartRange(2,:) = [1,sizeIm(1),sizeIm(2)+1,sizeIm(2)*2]; +quartRange(3,:) = [sizeIm(1)+1,sizeIm(1)*2,1,sizeIm(2)]; +quartRange(4,:) = [sizeIm(1)+1,sizeIm(1)*2,sizeIm(2)+1,sizeIm(2)*2]; + +for quart_i = 1:4 + %quartRange = [1+sizeIm(1)*(quart_i-1),quart_i*sizeIm(1),1+sizeIm(2)*(quart_i-1),quart_i*sizeIm(2)]; +overlapQuart(quart_i,1) = sum(sum(abs(IM1_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM2_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +overlapQuart(quart_i,2) = sum(sum(abs(IM2_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM3_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +%overlapQuart(quart_i,3) = sum(sum(abs(IM1_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM3_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +medOverlapQuart(quart_i) = median(overlapQuart(quart_i,:)); +end +medOverlapAll = round(median(overlapQuart,'all')); + +%use the larger filter of 50 to smooth the images for subtraction/comparisons +IM1_aligned_filt_comp = imfilter(IM1_aligned,h1,'replicate');%(IM1_aligned,hFilt,'replicate'); +IM2_aligned_filt_comp = imfilter(IM2_aligned,h1,'replicate');%(IM2_aligned,hFilt,'replicate'); +IM3_aligned_filt_comp = imfilter(IM3_aligned,h1,'replicate');%(IM3_aligned,hFilt,'replicate'); +IM1_aligned_filt_comp = IM1_aligned_filt_comp.^3; +IM2_aligned_filt_comp = IM2_aligned_filt_comp.^3; +IM3_aligned_filt_comp = IM3_aligned_filt_comp.^3; +IM_sum = IM1_aligned_filt_comp + IM2_aligned_filt_comp + IM3_aligned_filt_comp; +IM_mean = IM_sum/3; +IM1_diff = IM1_aligned_filt_comp - IM_mean; +IM2_diff = IM2_aligned_filt_comp - IM_mean; +IM3_diff = IM3_aligned_filt_comp - IM_mean; +IM_1diff2 = IM2_aligned_filt_comp - IM1_aligned_filt_comp; +%IM_1diff2 = IM_1diff2.^5; +IM_2diff3 = IM3_aligned_filt_comp - IM2_aligned_filt_comp; +%IM_2diff3 = IM_2diff3.*5; +IM_1diff3 = IM3_aligned_filt_comp - IM1_aligned_filt_comp; +%IM_1diff3 = IM_1diff3.*5; +%concatenate to take min/max and subtract from that +IM_combined(:,:,1) = IM1_aligned_filt_comp; +IM_combined(:,:,2) = IM2_aligned_filt_comp; +IM_combined(:,:,3) = IM3_aligned_filt_comp; +IM_combined_max = max(IM_combined,[],3); +IM_combined_min = min(IM_combined,[],3); +IM1_maxDiff = IM1_aligned_filt_comp - IM_combined_max; +IM2_maxDiff = IM2_aligned_filt_comp - IM_combined_max; +IM3_maxDiff = IM3_aligned_filt_comp - IM_combined_max; +IM1_minDiff = IM1_aligned_filt_comp - IM_combined_min; +IM2_minDiff = IM2_aligned_filt_comp - IM_combined_min; +IM3_minDiff = IM3_aligned_filt_comp - IM_combined_min; + +%% load masks and warp to match registered max projection for each day +if rigidFlag == 1 %only if have the rigid twarp output + maskDir1 = ['\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\Za']; + %maskDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done'; + days = [day1 day2 day3]; + ROI2plot = cell(length(days),1); + ROI_coords = cell(length(days),1); + centroid = cell(length(days),1); + col = cell(length(days)); + for day_i = 1:length(days) + %cd([maskDir1 batId]); + cd([maskDir1]); + dayDir = dir([batId(1:2) '*']); + cd([dayDir(days(day_i)).name filesep 'extracted']); + if rest1Flag == 1 && day_i == 1 + rest1Dir = dir('*rest1*extraction'); + cd(rest1Dir(end).name); + elseif rest1Flag == 1 && fullSeshTag == 1 + rest1Dir = dir('*rest1*extraction'); + cd(rest1Dir(end).name); + else + flyDir = dir('*fly-*extraction'); + cd(flyDir(end).name); + end + processedDir = dir('processed*'); + load([processedDir(end).name filesep 'results.mat']); + Atemp = full(results.A); + resultsA{day_i} = Atemp; + resultsCn{day_i} = results.Cn; + resultsCraw{day_i} = results.C_raw; + + % Plot binary mask of all neurons in the A matrix + %convert A matrix into full matrix + Ysiz = size(resultsCn{day_i}); + nRois = size(resultsA{day_i},2); + scaling = 10; %depends on size of frame and downsampling from extraction step + %ROI2plot = (:,:,zeros(length(Atemp(1,:))); + % get ROI centroids for top 30%; + %ROI2plot{day_i} = zeros(Ysiz(1),Ysiz(2),nRois); + %centroid{day_i} = zeros(nRois,2); + col{day_i} = zeros(nRois,3); + for roi_i = 1:nRois + %create 3d matrix with all ROI heat maps + ROI2plot{day_i}(:,:,roi_i) = mat2gray(reshape(Atemp(:,roi_i),Ysiz(1),Ysiz(2))); + ROI2plot_scaled{day_i}(:,:,roi_i) = imresize(ROI2plot{day_i}(:,:,roi_i),scaling); + end + cd(dirAllTrials); %go back to home activitity all_trials directory + end + %register day ROIs 1 to day 2 alignment + for day_i = 1:length(days) + for roi_i = 1:size(resultsA{day_i},2) + if day_i == 1 + ROI2plot_aligned{1}(:,:,roi_i) = imwarp(ROI2plot_scaled{1}(:,:,roi_i),imagesAligned.IM1_tform,'OutputView',imref2d(size(IM2))); + elseif day_i == 2 + ROI2plot_aligned{2}(:,:,roi_i) = ROI2plot_scaled{2}(:,:,roi_i); + elseif day_i == 3 + ROI2plot_aligned{3}(:,:,roi_i) = imwarp(ROI2plot_scaled{3}(:,:,roi_i),imagesAligned.IM3_tform,'OutputView',imref2d(size(IM2))); + end + binaryImage = imbinarize(ROI2plot_aligned{day_i}(:,:,roi_i)); + [y,x]=find(binaryImage); + %get ROI coordinates + ROI_coords{day_i}(roi_i,1) = {x}; + ROI_coords{day_i}(roi_i,2) = {y}; + %calculate centroids + centroid{day_i}(roi_i,1) = mean(cell2mat(ROI_coords{day_i}(roi_i,1)));%*scaling; + centroid{day_i}(roi_i,2) = mean(cell2mat(ROI_coords{day_i}(roi_i,2)));%*scaling;%get the centroid of mask + %subplot(2,1,1); + %imshow(ROI2plot_aligned{1}(:,:,roi_i)); + %subplot(2,1,2); + %p = plot(ROI_coords{1}{roi_i,1},ROI_coords{1}{roi_i,2},'LineWidth',4); + %clf; + end + col{day_i} = jet(size(resultsA{day_i},2)); + end + %ROI_coords = smoothdata(ROI_coords,'gaussian',3); %filter the ROI coordinate mask so it is not so jagged +end + + + + + + +%% plots +%plot the unaligned vs aligned for comparison +plotDay123_unaligned = figure(); +sgtitle(plotTitle); +subplot(1,2,1); +image((aUnaligned(:,:,:))); +title('un-aligned'); +set(gca,'xticklabel',[],'yticklabel',[]); +subplot(1,2,2); +image((aOverlap(:,:,:))); +title('aligned'); +set(gca,'xticklabel',[],'yticklabel',[]); + +%plot just the aligned figure with all 3rgb overlapping +plotDay123_aligned = figure(); +image(aOverlap(:,:,:)); +title([plotTitle ' medDiff ' num2str(medOverlapAll)]); +set(gca,'xticklabel',[],'yticklabel',[]); +%set(gca,'YDir','normal'); + +%plot aligned RGB figure and each day with centroids on top +plotDay123_centroids = figure('units','normalized','outerposition',[0 0 1 0.6]); +sgtitle([plotTitle ' and daily centroids']); +ha = tight_subplot(1,4,[.02 .01],[.01 .08],[.01 .01]); +set(0,'CurrentFigure',plotDay123_centroids); +axes(ha(1)); imshow((aOverlap(:,:,:)),[]); title('RGB Overlap'); +axes(ha(2)); imshow(IM1_aligned_filt,[0 0.5]); +colormap(ha(2),gray); +hold on; +for roi_i = 1:size(ROI2plot_aligned{1},3) + plot(ROI_coords{1}{roi_i,1},ROI_coords{1}{roi_i,2},'LineWidth',4,'Color',[col{1}(roi_i,:) 0.01]); + p = text(centroid{1}(roi_i,1),centroid{1}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{1}(size(ROI2plot_aligned{1},3) + 1 - roi_i,:); +end +title('Day 1 ROIs'); +hold off +axes(ha(3)); imshow(IM2_aligned_filt,[0 0.5]); +colormap(ha(3),gray); +hold on; +for roi_i = 1:size(ROI2plot_aligned{2},3) + plot(ROI_coords{2}{roi_i,1},ROI_coords{2}{roi_i,2},'LineWidth',4,'Color',[col{2}(roi_i,:) 0.01]); + p = text(centroid{2}(roi_i,1),centroid{2}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{2}(size(ROI2plot_aligned{2},3) + 1 - roi_i,:); +end +title('Day 2 ROIs'); +hold off +axes(ha(4)); imshow(IM3_aligned_filt,[0 0.5]); +colormap(ha(4),gray); +hold on; +try +for roi_i = 1:size(ROI2plot_aligned{3},3) + plot(ROI_coords{3}{roi_i,1},ROI_coords{3}{roi_i,2},'LineWidth',4,'Color',[col{3}(roi_i,:) 0.01]); + p = text(centroid{3}(roi_i,1),centroid{3}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{3}(size(ROI2plot_aligned{3},3) + 1 - roi_i,:); +end +catch +end +title('Day 3 ROIs'); +hold off + +%plot the rgb, mean, and each difference +plotDay123_diffs = figure('units','normalized','outerposition',[0 0 1 0.6]); +sgtitle([plotTitle ' and daily differences from mean']); +ha = tight_subplot(1,5,[.02 .01],[.01 .08],[.01 .01]); +set(0,'CurrentFigure',plotDay123_diffs); +axes(ha(1)); imshow(aOverlap(:,:,:),[]); title('RGB Overlap'); +%colorbar('southoutside'); +axes(ha(2)); imshow(IM_mean,[]); title('Mean Day 1, 2, 3'); +colormap(ha(2),gray); +colorbar('southoutside'); +axes(ha(3)); imshow(IM1_diff,clipRangeShow); title('Diff Day 1'); +colormap(ha(3),fireice); +colorbar('southoutside'); +axes(ha(4)); imshow(IM2_diff,clipRangeShow); title('Diff Day 2'); +colormap(ha(4),fireice); +colorbar('southoutside'); +axes(ha(5)); imshow(IM3_diff,clipRangeShow); title('Diff Day 3'); +colormap(ha(5),fireice); +colorbar('southoutside'); + +%plot rgb and each progression of differences from 1 day to next +plotDay123_progression = figure('units','normalized','outerposition',[0 0 1 0.6]); +sgtitle([plotTitle ' and day to day progression']); +ha = tight_subplot(1,5,[.02 .01],[.01 .08],[.01 .01]); +set(0,'CurrentFigure',plotDay123_progression); +axes(ha(1)); imshow(aOverlap(:,:,:),[]); title('RGB Overlap'); +%colorbar('southoutside'); +axes(ha(2)); imshow(IM1_aligned_filt,[0 0.5]); title('Day 1'); +colormap(ha(2),gray); +colorbar('southoutside'); +axes(ha(3)); imshow(IM_1diff2,clipRangeShow); title('Day 2 - Day 1'); +colormap(ha(3),fireice); +colorbar('southoutside'); +axes(ha(4)); imshow(IM_2diff3,clipRangeShow); title('Day 3 - Day 2'); +colormap(ha(4),fireice); +colorbar('southoutside'); +axes(ha(5)); imshow(IM_1diff3,clipRangeShow); title('Day 3 - Day 1'); +colorbar('southoutside'); +colormap(ha(5),fireice); + +%% plot rgb and each progression of differences from 1 day to next +plotDay123_all = figure('units','normalized','outerposition',[0 0 1 1]); +sgtitle([plotTitle ' medDiff ' num2str(medOverlapAll)]); +ha = tight_subplot(4,5,[.02 .01],[.01 .08],[.01 .01]); +set(0,'CurrentFigure',plotDay123_all); +axes(ha(1)); imshow(aOverlap(:,:,:),[]); title('RGB Overlap'); +%colorbar('southoutside'); +axes(ha(2)); imshow(IM1_aligned_filt,[0 0.5]); title('Day 1'); +%colorbar('southoutside'); +axes(ha(3)); imshow(IM_1diff2,clipRangeShow); title('Day 2 - Day 1'); +%colorbar('southoutside'); +axes(ha(4)); imshow(IM_2diff3,clipRangeShow); title('Day 3 - Day 2'); +%colorbar('southoutside'); +axes(ha(5)); imshow(IM_1diff3,clipRangeShow); title('Day 3 - Day 1'); +%colorbar('southoutside'); +colormap(ha(3),fireice); +colormap(ha(4),fireice); +colormap(ha(5),fireice); +axes(ha(6)); imshow(IM1_aligned_filt,[0 0.5]); +colormap(ha(6),gray); +hold on; +for roi_i = 1:size(ROI2plot_aligned{1},3) + plot(ROI_coords{1}{roi_i,1},ROI_coords{1}{roi_i,2},'LineWidth',4,'Color',[col{1}(roi_i,:) 0.01]); + p = text(centroid{1}(roi_i,1),centroid{1}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{1}(size(ROI2plot_aligned{1},3) + 1 - roi_i,:); +end +title('Day 1 ROIs'); +hold off +axes(ha(7)); imshow(IM_mean,[]); title('Mean Day 1, 2, 3'); +%colorbar('southoutside'); +axes(ha(8)); imshow(IM1_diff,clipRangeShow); title('Day 1 - mean'); +%colorbar('southoutside'); +axes(ha(9)); imshow(IM2_diff,clipRangeShow); title('Day 2 - mean'); +%colorbar('southoutside'); +axes(ha(10)); imshow(IM3_diff,clipRangeShow); title('Day 3 - mean'); +colormap(ha(8),fireice); +colormap(ha(9),fireice); +colormap(ha(10),fireice);%colorbar('southoutside'); +axes(ha(11)); imshow(IM2_aligned_filt,[0 0.5]); +colormap(ha(11),gray); +hold on; +for roi_i = 1:size(ROI2plot_aligned{2},3) + plot(ROI_coords{2}{roi_i,1},ROI_coords{2}{roi_i,2},'LineWidth',4,'Color',[col{2}(roi_i,:) 0.01]); + p = text(centroid{2}(roi_i,1),centroid{2}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{2}(size(ROI2plot_aligned{2},3) + 1 - roi_i,:); +end +title('Day 2 ROIs'); +hold off +axes(ha(12)); imshow(IM_combined_max,[]); title('Max Day 1, 2, 3'); +%colorbar('southoutside'); +axes(ha(13)); imshow(IM1_maxDiff,clipRangeShow); title('Day 1 - max'); +%colorbar('southoutside'); +axes(ha(14)); imshow(IM2_maxDiff,clipRangeShow); title('Day 2 - max'); +%colorbar('southoutside'); +axes(ha(15)); imshow(IM3_maxDiff,clipRangeShow); title('Day 3 - max'); +colormap(ha(13),fireice); +colormap(ha(14),fireice); +colormap(ha(15),fireice);%colorbar('southoutside'); +axes(ha(16)); imshow(IM3_aligned_filt,[0 0.5]); +colormap(ha(16),gray); +hold on; +try +for roi_i = 1:size(ROI2plot_aligned{3},3) + plot(ROI_coords{3}{roi_i,1},ROI_coords{3}{roi_i,2},'LineWidth',4,'Color',[col{3}(roi_i,:) 0.01]); + p = text(centroid{3}(roi_i,1),centroid{3}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{3}(size(ROI2plot_aligned{3},3) + 1 - roi_i,:); +end +catch +end +title('Day 3 ROIs'); +hold off +axes(ha(17)); imshow(IM_combined_min,[]); title('Min Day 1, 2, 3'); +%colorbar('southoutside'); +axes(ha(18)); imshow(IM1_minDiff,clipRangeShow); title('Day 1 - min'); +%colorbar('southoutside'); +axes(ha(19)); imshow(IM2_minDiff,clipRangeShow); title('Day 2 - min'); +%colorbar('southoutside'); +axes(ha(20)); imshow(IM3_minDiff,clipRangeShow); title('Day 3 - min'); +colormap(ha(18),fireice); +colormap(ha(19),fireice); +colormap(ha(20),fireice);%colorbar('southoutside'); + +%% plot the cnmfe time series only for the 3 days +plotCnmfeSeries = figure('units','normalized','outerposition',[0 0 1 1]); +sgtitle(plotTitle); +% subplot(4,4,1); +% image(aOverlap(:,:,:)); +% title([plotTitle ' medDiff ' num2str(medOverlapAll)]); +% set(gca,'xticklabel',[],'yticklabel',[]); + +for day_i = 1:length(resultsCraw) + subplot(3,1,day_i); +for roi_i = 1:size(resultsCraw{day_i},1); + plot(1:size(resultsCraw{day_i},2),zscore(smoothdata(resultsCraw{day_i}(roi_i,:),'movmedian',30))+roi_i*6); + hold on; +end +dataTicks = [6:6:size(resultsCraw{day_i},1)*6]; +set(gca,'YTick',dataTicks,'YTickLabel',[1:length(dataTicks)],'xlim',[0 size(resultsCraw{day_i},2)]); +xt = get(gca,'xtick'); +set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); +title(['Day ' num2str(day_i)]); +ylabel([num2str(size(resultsCraw{day_i},1)) ' ROIs']); +if day_i == 3 + xlabel('Time (m)'); +end +end + +%% plot the time series from cnmfe next to RGB and daily overlap to check that cells are selected properly +%plot rgb overlap +plotOverlapTimeSeries = figure('units','normalized','outerposition',[0 0 1 1]); +sgtitle([plotTitle ' medDiff ' num2str(medOverlapAll)]); +%ha = tight_subplot(4,4,[.02 .01],[.01 .08],[.01 .01]); +set(0,'CurrentFigure',plotOverlapTimeSeries); +ax1 = subplot(4,4,1); imagesc(aOverlap(:,:,:)); title('RGB Overlap'); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +%colorbar('southoutside'); +ax2 = subplot(4,4,2); imagesc(IM_1diff2,clipRangeShow); title('Day 2 - Day 1'); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +%colorbar('southoutside'); +ax3 = subplot(4,4,3); imagesc(IM_2diff3,clipRangeShow); title('Day 3 - Day 2'); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +%colorbar('southoutside'); +ax4 = subplot(4,4,4); imagesc(IM_1diff3,clipRangeShow); title('Day 3 - Day 1'); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +colormap(ax2,fireice); +colormap(ax3,fireice); +colormap(ax4,fireice); +ax5 = subplot(4,4,5); imagesc(IM1_aligned_filt); +colormap(ax5,gray); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +hold on; +for roi_i = 1:size(ROI2plot_aligned{1},3) + plot(ROI_coords{1}{roi_i,1},ROI_coords{1}{roi_i,2},'LineWidth',4,'Color',[col{1}(roi_i,:) 0.01]); + p = text(centroid{1}(roi_i,1),centroid{1}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{1}(size(ROI2plot_aligned{1},3) + 1 - roi_i,:); +end +title('Day 1 ROIs'); +hold off +subplot(4,4,6:8); +for roi_i = 1:size(resultsCraw{1},1); + plot(1:size(resultsCraw{1},2),zscore(smoothdata(resultsCraw{1}(roi_i,:),'movmedian',30))+roi_i*6); + hold on; +end +dataTicks = [6:6:size(resultsCraw{1},1)*6]; +set(gca,'YTick',dataTicks,'YTickLabel',[1:length(dataTicks)],'xlim',[0 size(resultsCraw{1},2)]); +xt = get(gca,'xtick'); +set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); +title(['Day 1']); +ylabel([num2str(size(resultsCraw{1},1)) ' ROIs']); +hold off +ax9 = subplot(4,4,9); imagesc(IM2_aligned_filt); +colormap(ax9,gray); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +hold on; +for roi_i = 1:size(ROI2plot_aligned{2},3) + plot(ROI_coords{2}{roi_i,1},ROI_coords{2}{roi_i,2},'LineWidth',4,'Color',[col{2}(roi_i,:) 0.01]); + p = text(centroid{2}(roi_i,1),centroid{2}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{2}(size(ROI2plot_aligned{2},3) + 1 - roi_i,:); +end +title('Day 2 ROIs'); +hold off +subplot(4,4,10:12); +for roi_i = 1:size(resultsCraw{2},1); + plot(1:size(resultsCraw{2},2),zscore(smoothdata(resultsCraw{2}(roi_i,:),'movmedian',30))+roi_i*6); + hold on; +end +dataTicks = [6:6:size(resultsCraw{2},1)*6]; +set(gca,'YTick',dataTicks,'YTickLabel',[1:length(dataTicks)],'xlim',[0 size(resultsCraw{2},2)]); +xt = get(gca,'xtick'); +set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); +title(['Day 2']); +ylabel([num2str(size(resultsCraw{2},1)) ' ROIs']); +hold off +ax13 = subplot(4,4,13); imagesc(IM3_aligned_filt); +colormap(ax13,gray); +set(gca,'XTick',[],'YTick',[],'XTickLabel',[],'YTickLabel',[]); +hold on; +try +for roi_i = 1:size(ROI2plot_aligned{3},3) + plot(ROI_coords{3}{roi_i,1},ROI_coords{3}{roi_i,2},'LineWidth',4,'Color',[col{3}(roi_i,:) 0.01]); + p = text(centroid{3}(roi_i,1),centroid{3}(roi_i,2),num2str(roi_i)); + p.Color(1:3) = col{3}(size(ROI2plot_aligned{3},3) + 1 - roi_i,:); +end +catch +end +title('Day 3 ROIs'); +hold off +subplot(4,4,14:16); +try +for roi_i = 1:size(resultsCraw{3},1); + plot(1:size(resultsCraw{3},2),zscore(smoothdata(resultsCraw{3}(roi_i,:),'movmedian',30))+roi_i*6); + hold on; +end +dataTicks = [6:6:size(resultsCraw{3},1)*6]; +set(gca,'YTick',dataTicks,'YTickLabel',[1:length(dataTicks)],'xlim',[0 size(resultsCraw{3},2)]); +xt = get(gca,'xtick'); +set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); +title(['Day 3']); +ylabel([num2str(size(resultsCraw{3},1)) ' ROIs']); +catch +end +hold off +%% ask which cells and days times series to compare +inputGo = []; +inputGo = input('Go?'); +while isempty(inputGo) + inputDay = input('What days would you like to compare?'); +inputROI = input('What ROIs would you like to compare?'); +Ysiz = size(resultsCn{1}); %size of the image frame +Rtime = []; +Rmask = []; +timeseries = []; +binaryMask = []; +binaryMaskAlign = []; +%find duration of each day and concatenate the day/roi numbers for titles +for comp_i = 1:length(inputDay) + dur(comp_i) = length(resultsCraw{inputDay(comp_i)}); + dayROI{comp_i} = [num2str(inputDay(comp_i)) '.' num2str(inputROI(comp_i))]; +end +minDurDay = min(dur); %find min duration of the days to limit the time series +%extract the time series and binary mask of each Day/ROI combo +for comp_i = 1:length(inputDay) + timeseries(:,comp_i) = zscore(smoothdata(resultsCraw{inputDay(comp_i)}(inputROI(comp_i),1:minDurDay),2,'movmedian',30))'; + + roiMask = imresize(mat2gray(reshape(resultsA{inputDay(comp_i)}(:,inputROI(comp_i)),Ysiz(1),Ysiz(2))),10); + binaryMask(:,:,comp_i) = imbinarize(roiMask);%mat2gray(reshape(resultsA{inputDay(comp_i)}(:,inputROI(comp_i)),Ysiz(1),Ysiz(2)))); + + %warp the binary mask according to the twarps from the image alignment + if inputDay(comp_i) == 1 + binaryMaskAlign(:,:,comp_i) = imwarp(binaryMask(:,:,comp_i),imagesAligned.IM1_tform,'OutputView',imref2d(size(IM2))); + elseif inputDay(comp_i) == 2 + binaryMaskAlign(:,:,comp_i) = binaryMask(:,:,comp_i); + elseif inputDay(comp_i) == 3 + binaryMaskAlign(:,:,comp_i) = imwarp(binaryMask(:,:,comp_i),imagesAligned.IM3_tform,'OutputView',imref2d(size(IM2))); + end +end +%find correlation coefficients and pvalues for timeseries +[Rtime,Ptime] = corrcoef(timeseries); +%find correlation coefficients for 2d spatial masks +for corr_i = 1:length(inputDay) + for corr_ii = corr_i:length(inputDay) + Rmask(corr_i,corr_ii) = corr2(binaryMaskAlign(:,:,corr_i),binaryMaskAlign(:,:,corr_ii)); + Rmask(corr_ii,corr_i) = corr2(binaryMaskAlign(:,:,corr_ii),binaryMaskAlign(:,:,corr_i)); + end +end +%overlay the RGB +if length(inputDay) < 3 + [aMask,bMask] = CaBMI_XMASS(binaryMaskAlign(:,:,1),binaryMaskAlign(:,:,2),binaryMaskAlign(:,:,2)); + titleMask = ['RGB overlap ' dayROI{1} '(r) ' dayROI{2} '(c)']; +elseif length(inputDay) >= 3 + [aMask,bMask] = CaBMI_XMASS(binaryMaskAlign(:,:,1),binaryMaskAlign(:,:,2),binaryMaskAlign(:,:,3)); + titleMask = ['RGB overlap ' dayROI{1} '(r) ' dayROI{2} '(g) ' dayROI{3} '(b)']; +end +%plot the similarity matrix of time series, mask, and the time series +plotCompareTimeSeries = figure('units','normalized','outerposition',[0 0 1 0.5]); +sgtitle([batId ' Comparing ROIs']); +subplot(1,7,1); +imagesc(Rtime,[0 1]); %plot similarity matrix of time series +set(gca,'XTick',[1:length(inputDay)],'XTickLabel',dayROI,'YTick',[1:length(inputDay)],'YTickLabel',dayROI); +xlabel('Day.ROI'); +ylabel('Day.ROI'); +title('Correlation of Time series'); +colorbar('southoutside'); + +subplot(1,7,2:4); %plot time series of selected ROIS +for plot_i = 1:length(inputDay) + plot(1:minDurDay,timeseries(:,plot_i)+plot_i*6); + hold on; +end +dataTicks = [6:6:length(inputDay)*6]; +set(gca,'YTick',dataTicks,'YTickLabel',dayROI,'xlim',[0 minDurDay]); +xt = get(gca,'xtick'); +set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); +title(['ROI Time Series']); +%ylabel('ROIs (Day.ROI)'); +xlabel('Time (m)'); +hold off +subplot(1,7,5); +imagesc(Rmask,[0 1]); %plot similarity matrix of masks +set(gca,'XTick',[1:length(inputDay)],'XTickLabel',dayROI,'YTick',[1:length(inputDay)],'YTickLabel',dayROI); +xlabel('Day.ROI'); +ylabel('Day.ROI'); +title('Correlation of ROI masks'); +colorbar('southoutside'); +subplot(1,7,6:7); +imshow(aMask); +set(gca,'xtick',[],'ytick',[]); +title(titleMask); +%concatenate the day/rois into 1 title so it can be used for saving title +dayROITitle = []; +for i = 1:length(dayROI); + dayROITitle = [dayROITitle '_' dayROI{i}]; +end +if saveFlag == 1 + saveas(plotCompareTimeSeries,[saveDir filesep batId '_corrROIS_days' dayROITitle '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotCompareTimeSeries,[saveDir filesep batId '_corrROIS_days' dayROITitle '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); +end +inputGo = input('Go?'); +end +%compData1 = ; + +%% +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(plotDay123_unaligned,[saveDir filesep 'Gal_200227and200404_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_unaligned,[saveDir filesep 'Gal_200227and200404_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_aligned,[saveDir filesep 'Gal_200227and200404_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_aligned,[saveDir filesep 'Gal_200227and200404_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_diffs,[saveDir filesep 'Gal_200227and200404_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_diffs,[saveDir filesep 'Gal_200227and200404_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_progression,[saveDir filesep 'Gal_200227and200404_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_progression,[saveDir filesep 'Gal_200227and200404_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_centroids,[saveDir filesep 'Gal_200227and200404_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_centroids,[saveDir filesep 'Gal_200227and200404_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_all,[saveDir filesep 'Gal_200227and200404_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_all,[saveDir filesep 'Gal_200227and200404_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotOverlapTimeSeries,[saveDir filesep 'Gal_200227and200404_timeSeriesOverlap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotOverlapTimeSeries,[saveDir filesep 'Gal_200227and200404_timeSeriesOverlap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotCnmfeSeries,[saveDir filesep 'Gal_200227and200404_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotCnmfeSeries,[saveDir filesep 'Gal_200227and200404_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + if rigidFlag == 0 + saveas(figNonrigid,[saveDir filesep 'Gal_200227and200404_nonrigidAlign_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(figNonrigid,[saveDir filesep 'Gal_200227and200404_nonrigidAlign_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + end + elseif strcmp(batId,'Gen') + %saveas(plotDay123_unaligned,[saveDir filesep 'Gen_200305and200311_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotDay123_unaligned,[saveDir filesep 'Gen_200305and200311_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_aligned,[saveDir filesep 'Gen_200305and200311_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_aligned,[saveDir filesep 'Gen_200305and200311_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotDay123_diffs,[saveDir filesep 'Gen_200305and200311_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_diffs,[saveDir filesep 'Gen_200305and200311_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_progression,[saveDir filesep 'Gen_200305and200311_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_progression,[saveDir filesep 'Gen_200305and200311_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_all,[saveDir filesep 'Gen_200305and200311_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_all,[saveDir filesep 'Gen_200305and200311_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_centroids,[saveDir filesep 'Gen_200305and200311_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_centroids,[saveDir filesep 'Gen_200305and200311_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotOverlapTimeSeries,[saveDir filesep 'Gen_200305and200311_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotOverlapTimeSeries,[saveDir filesep 'Gen_200305and200311_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotCnmfeSeries,[saveDir filesep 'Gen_200305and200311_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotCnmfeSeries,[saveDir filesep 'Gen_200305and200311_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Z2') + %saveas(plotDay123_unaligned,[saveDir filesep 'Zo2_200701and822_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotDay123_unaligned,[saveDir filesep 'Zo2_200701and822_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_aligned,[saveDir filesep 'Zo2_200701and822_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_aligned,[saveDir filesep 'Zo2_200701and822_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotDay123_diffs,[saveDir filesep 'Zo2_200701and822_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_diffs,[saveDir filesep 'Zo2_200701and822_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_progression,[saveDir filesep 'Zo2_200701and822_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_progression,[saveDir filesep 'Zo2_200701and822_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_all,[saveDir filesep 'Zo2_200701and822_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_all,[saveDir filesep 'Zo2_200701and822_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_centroids,[saveDir filesep 'Zo2_200701and822_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_centroids,[saveDir filesep 'Zo2_200701and822_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotOverlapTimeSeries,[saveDir filesep 'Zo2_200701and822_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotOverlapTimeSeries,[saveDir filesep 'Zo2_200701and822_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotCnmfeSeries,[saveDir filesep 'Zo2_200701and822_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotCnmfeSeries,[saveDir filesep 'Zo2_200701and822_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Zu') + %saveas(plotDay123_unaligned,[saveDir filesep 'Zu_200704and820_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotDay123_unaligned,[saveDir filesep 'Zu_200704and820_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_aligned,[saveDir filesep 'Zu_200704and820_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_aligned,[saveDir filesep 'Zu_200704and820_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotDay123_diffs,[saveDir filesep 'Zu_200704and820_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_diffs,[saveDir filesep 'Zu_200704and820_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_progression,[saveDir filesep 'Zu_200704and820_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_progression,[saveDir filesep 'Zu_200704and820_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_all,[saveDir filesep 'Zu_200704and820_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_all,[saveDir filesep 'Zu_200704and820_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_centroids,[saveDir filesep 'Zu_200704and820_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_centroids,[saveDir filesep 'Zu_200704and820_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotOverlapTimeSeries,[saveDir filesep 'Zu_200704and820_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotOverlapTimeSeries,[saveDir filesep 'Zu_200704and820_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotCnmfeSeries,[saveDir filesep 'Zu_200704and820_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotCnmfeSeries,[saveDir filesep 'Zu_200704and820_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Za') + %saveas(plotDay123_unaligned,[saveDir filesep 'Za_200524and530_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotDay123_unaligned,[saveDir filesep 'Za_200524and530_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_aligned,[saveDir filesep 'Za_200524and530_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_aligned,[saveDir filesep 'Za_200524and530_overLap_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotDay123_diffs,[saveDir filesep 'Za_200524and530_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_diffs,[saveDir filesep 'Za_200524and530_diffs_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_progression,[saveDir filesep 'Za_200524and530_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_progression,[saveDir filesep 'Za_200524and530_progression_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_all,[saveDir filesep 'Za_200524and530_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_all,[saveDir filesep 'Za_200524and530_allPlots_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + saveas(plotDay123_centroids,[saveDir filesep 'Za_200524and530_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotDay123_centroids,[saveDir filesep 'Za_200524and530_centroids_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotOverlapTimeSeries,[saveDir filesep 'Za_200524and530_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(plotOverlapTimeSeries,[saveDir filesep 'Za_200524and530_overlapTimeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(plotCnmfeSeries,[saveDir filesep 'Za_200524and530_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + %savefig(plotCnmfeSeries,[saveDir filesep 'Za_200524and530_timeSeries_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + if rigidFlag == 0 + saveas(figNonrigid,[saveDir filesep 'Gen_200305and200311_nonrigidAlign_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); + savefig(figNonrigid,[saveDir filesep 'Gen_200305and200311_nonrigidAlign_day' num2str(day1) '_day' num2str(day2) '_day' num2str(day3) '_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + end + end +end + + diff --git a/ROI/ImBat_RGBroi.m b/ROI/ImBat_RGBroi.m new file mode 100644 index 0000000..e71c139 --- /dev/null +++ b/ROI/ImBat_RGBroi.m @@ -0,0 +1,54 @@ +function ImBat_RGBroi + +% Load in Data: +mat1 = imresize(results10.results.Cn,4); +mat2 = imresize(results12.results.Cn,4); +mat3 = imresize(results13.results.Cn,4); +IM1 = mat2gray(mat1); +IM2 = mat2gray(mat2); +IM3 = mat2gray(mat3); + +minRow = min([size(IM1,1),size(IM2,1),size(IM3,1)]); +minCol = min([size(IM1,2),size(IM2,2),size(IM3,2)]); + +% Alignment script +[IM1_aligned,IM2_aligned,IM3_aligned] = ImBat_imageAlign(IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3(1:minRow,1:minCol)); + + +% Will RGB script +[a1,b1] = CaBMI_XMASS(IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3(1:minRow,1:minCol)); +[a2,b2] = CaBMI_XMASS(IM1_aligned,IM2_aligned,IM3_aligned); + +figure(); +subplot(121) +image((a1(:,:,:))) +title('un-aligned') +subplot(122) +image((a2(:,:,:))) +title('aligned') + +figure() +image((a2(:,:,:))) +title('Galileo: 3/10 (R), 3/12 (G), 3/15 (B)') +set(gca,'YDir','normal'); + +%% +imagesc(imresize(results10.results.Cn,4)); colormap(gray); +imagesc(imresize(results12.results.Cn,4)); colormap(gray); +imagesc(imresize(results15.results.Cn,4)); colormap(gray); + +figure(); +[imRGB] = cat(3,results10.results.Cn(1:112,1:153),results12.results.Cn(1:112,1:153),results15.results.Cn(1:112,1:153)); + +C = imfuse(results10.results.Cn(1:112,1:153),results12.results.Cn(1:112,1:153),'falsecolor','Scaling','joint','ColorChannels',[1 2 0]); + +a = imresize(results10.results.Cn,4); +b = imresize(results12.results.Cn,4); +c = imresize(results15.results.Cn,4); +agray = mat2gray(a); +bgray = mat2gray(b); +cgray = mat2gray(c); +abcRGB = cat(3,agray(1:448,1:612),bgray(1:448,1:612),cgray(1:448,1:612)); +imagesc(abcRGB); + + diff --git a/ROI/ImBat_ROI_plotAll.m b/ROI/ImBat_ROI_plotAll.m new file mode 100644 index 0000000..433a08d --- /dev/null +++ b/ROI/ImBat_ROI_plotAll.m @@ -0,0 +1,81 @@ +function ImBat_ROI_plotAll +close all; +batId = 'Z'; +saveFlag = 1; +%make saving directory +if saveFlag == 1 + saveTag = ''; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + %saveDir1 = '/Users/periscope/Desktop/analysis/flight/plots/'; + %saveDir1 = 'C:\Users\tobias\Desktop\analysis\plots\'; + if ~exist([saveDir1 datestr(now,'yymmdd') filesep 'maxProj_allDays']) + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'maxProj_allDays']); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'maxProj_allDays' filesep]; +end + + +dirTop = dir([batId '*']); +for bn_i = 1:length(dirTop) + batInit(bn_i,1:2) = dirTop(bn_i).name(1:2); +end +uniqueInit = unique(batInit); + +for bat_i = 1:length(uniqueInit)-1 + close all; + dirBat = dir([batId uniqueInit(bat_i) '*']);%uniqueInit(bat_i+1) '*']); + plotAllROI = figure('units','normalized','outerposition',[0 0 1 1]); + sgtitle([dirBat(1).name ': Max Projections Full Session']); + %ha = tight_subplot(ceil(length(dirBat)/5),5,[.02 .01],[.01 .08],[.01 .01]); + for day_i = 1:length(dirBat); + cd(dirBat(day_i).name); + dirFly = dir('*fly*extraction'); + try + try + cd(dirFly(end).name); + catch + try + cd('extracted'); + dirFly = dir('*fly*extraction'); + cd(dirFly(end).name); + catch + dirExtraction = dir('*extraction'); + cd(dirExtraction(1).name); + end + end + dirAnal = dir('analysis*'); + try + maxFig = openfig([dirAnal(end).folder filesep dirAnal(end).name filesep 'ROI' filesep dirFly(end).name(1:17) 'maxProject.fig']); + catch + try + maxFig = openfig([dirAnal(end).folder filesep dirAnal(end).name filesep 'ROI' filesep dirFly(end).name(1:18) 'maxProject.fig']); + catch + maxFig = openfig([dirAnal(end).folder filesep dirAnal(end).name filesep 'ROI' filesep dirFly(end).name(1:19) 'maxProject.fig']); + end + end + drawnow; + ax1 = gca; + set(0,'CurrentFigure',plotAllROI); + s1 = subplot(ceil(length(dirBat)/7),7,day_i); + fig1 = get(ax1(1),'children'); + copyobj(fig1,s1); + hold on; + colormap('gray'); + xlim([0 640]); + ylim([0 480]); + set(gca,'CLim',[0 max(max(fig1.CData))/2],'XTick',[],'XTickLabel',[],'YTick',[],'YTickLabel',[]); + %title(dirBat(day_i).name); + drawnow; + cd(dirTop(bat_i).folder); + close Figure 2; + catch + cd(dirTop(bat_i).folder); + end + end + if saveFlag == 1 + saveas(plotAllROI,[saveDir dirBat(bat_i).name(1:2) '_maxProjAllROI_allDays_' saveTag '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(plotAllROI,[saveDir dirBat(bat_i).name(1:2) '_maxProjAllROI_allDays_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + end +end diff --git a/ROI/ImBat_ROIoverlay.m b/ROI/ImBat_ROIoverlay.m index 954de89..e0f674a 100644 --- a/ROI/ImBat_ROIoverlay.m +++ b/ROI/ImBat_ROIoverlay.m @@ -1,13 +1,13 @@ -function [ROIoverlay,goodCellIndex,badCellIndex] = ImBat_ROIoverlay(results,varargin) +function [ROIoverlay,correlationImage,centroidMax] = ImBat_ROIoverlay(results,varargin) global topROI %manual inputs -centroidFlag = 0; +centroidFlag = 1; binaryMaskFlag = 1; roiHeatFlag = 1; roiHeatFlagIndiv = 0; -scaling = 8; %depends on size of frame and downsizing from extraction step +scaling = 5; %depends on size of frame and downsampling from extraction step topROILocal = topROI * 0.01; %look at first x% of ROIs batName = []; @@ -21,19 +21,19 @@ end for i=1:2:nparams switch lower(varargin{i}) - case 'batName' + case 'batname' batName=varargin{i+1}; - case 'dateSesh' + case 'datesesh' dateSesh = varargin{i+1}; - case 'sessionType' + case 'sessiontype' sessionType = varargin{i+1}; case 'roiheatflagindiv' roiHeatFlagIndiv = varargin{i+1}; case 'centroid' centroidFlag = varargin{i+1}; - case 'binaryMask' + case 'binarymask' binaryMaskFlag = varargin{i+1}; - case 'roiHeat' + case 'roiheat' roiHeatFlag = varargin{i+1}; end end @@ -61,51 +61,64 @@ %ROI_coords = smoothdata(ROI_coords,'gaussian',3); %filter the ROI coordinate mask so it is not so jagged hold on % modify labels for tick marks -xticks = get(gca,'xtick'); -yticks = get(gca,'ytick'); -scaling = 1.1; %1.1um per pixel -newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); -newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); -set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +%xticks = get(gca,'xtick'); +%yticks = get(gca,'ytick'); +%scaling_pixel = 1.1; %1.1um per pixel +%newlabelsX = arrayfun(@(ax) sprintf('%g', scaling_pixel * ax), xticks, 'un', 0); +%newlabelsY = arrayfun(@(ay) sprintf('%g', scaling_pixel * ay), yticks, 'un', 0); +%set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); title(['Max Projection: ' batName ' ' dateSesh ' ' sessionType]); xlabel('um'); ylabel('um'); col = jet(length(ROI_coords)); +%plot correlation image +correlationImage = figure(); +hold on; +imagesc(imresize(results.Cn,scaling)); colormap(gray); +title(['Correlation image: ' batName ' ' dateSesh ' ' sessionType]); +xlabel('um'); ylabel('um'); +axis 'tight' 'equal' +hold off; -%plot centroid over top of max projection +%plot centroid over top of correlation image if centroidFlag == 1 - figure(); + centroidMax = figure(); hold on; - imagesc(imresize(results.Cn,8)); colormap(gray); + imagesc(imresize(results.Cn,scaling)); colormap(gray); for i = 1:length(ROI_coords) try - p = plot(centroid(i,1),centroid(i,2),'o'); - p.Color(1:3) = col(i,:); + %p = plot(centroid(i,1),centroid(i,2),'o'); + p = text(centroid(i,1),centroid(i,2),num2str(i)); + p.Color(1:3) = col(i,:); catch end end end axis 'tight' 'equal' +title(['ROI Centroids: ' batName ' ' dateSesh ' ' sessionType]); + %plot binary mask over top of max projection if binaryMaskFlag == 1 - figure(); + ROIoverlay = figure(); + sgtitle([batName ' ' dateSesh ' ' sessionType ': ' num2str(length(results.A(1,:))) ' ROI']) subplot(2,2,1) - imagesc(imresize(results.Cn,8)); colormap(gray); + imagesc(imresize(results.Cn,scaling)); colormap(gray); + set(gca,'YDir','normal'); axis 'tight' 'equal' title('Correlation Image'); - subplot(2,2,2) - imagesc(imresize(results.Cn,8)); colormap(gray); - + imagesc(imresize(results.Cn,scaling)); colormap(gray); + set(gca,'YDir','normal'); + hold on for i = 1:length(ROI_coords) try - p = plot(ROI_coords{i,1},ROI_coords{i,2},'LineWidth',8); - p.Color(4) = 0.4; + p = plot(ROI_coords{i,1},ROI_coords{i,2},'LineWidth',4); + p.Color(4) = 0.2; catch end end @@ -160,6 +173,7 @@ subplot(2,2,3); imagesc(RGBim2) +set(gca,'YDir','normal'); title('ROI Watershed'); A = RGBim2; @@ -171,8 +185,10 @@ C = A + B; subplot(2,2,4); imagesc(C); -title('ROI Watershed overlain on Correlation Image'); +set(gca,'YDir','normal'); +title('ROI Watershed on Correlation Image'); set(gcf, 'Position', get(0, 'Screensize')/1.5); +xlabel('um'); ylabel('um'); @@ -186,14 +202,15 @@ roiHeatMax = imresize(roiHeatMax, scaling); ROIoverlay = figure(); imagesc(roiHeatMax); + set(gca,'YDir','normal'); hold on %set(gca,'YDir','normal'); - xticks = get(gca,'xtick'); - yticks = get(gca,'ytick'); - scaling = 1.1; %1.1um per pixel - newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); - newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); - set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); + %xticks = get(gca,'xtick'); + %yticks = get(gca,'ytick'); + %scaling = 1.1; %1.1um per pixel + %newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); + %newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); + %set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); title(['Max Projection ROI ' cell_i ': ' batName ' ' dateSesh ' ' sessionType]); xlabel('um'); ylabel('um'); diff --git a/ROI/ImBat_annotateRoi_manual.m b/ROI/ImBat_annotateRoi_manual.m new file mode 100644 index 0000000..5259f5c --- /dev/null +++ b/ROI/ImBat_annotateRoi_manual.m @@ -0,0 +1,80 @@ +saveFlag = 1; %do you want to save the figures and output structure? +reexportFlag = 0; %do you want to reproduce the dff and corr images in new folder +saveTag = 'allTrials_sMat_large_1to4'; +if saveFlag == 1 +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections'])>0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections' '\']; +end + +%run export function to produce all the maxProj files in the output folder +if reexportFlag == 1 +ImBat_exportProjections(saveFlag) +end + +cd(saveDir); %go to new folder with the maxcorr images +tifDir = dir('*_maxCorrProject.tif'); +ROI = struct; +for i = 1:length(tifDir) + ROI(i).batName = tifDir(i).name(1:3); + ROI(i).dateSesh = tifDir(i).name(5:10); + ROI(i).sessionType = tifDir(i).name(12:16); + ROI(i).fileName = tifDir(i).name; + ROI(i).folder = tifDir(i).folder; + ROI(i).data = FS_annotate_image(tifDir(i).name); +end + +for ii = length(tifDir):-1:1 + ROI(ii).data = FS_annotate_image(tifDir(ii).name); +end + +save([ROI(1).batName '_ROI_' datestr(now,'YYmmDD_hhMM') '.mat'],'ROI'); + +%% +trackableROI = figure(); +sgtitle([ROI(1).batName ': stable cells across ' num2str(length(ROI)) ' days']); +for iii = 1:length(ROI) + subplot(4,3,iii);%,length(ROI.coordinates),iii); + hold on; + for p = 1:length(ROI(iii).data.coordinates) + plot(ROI(iii).data.coordinates{p}(:,1),ROI(iii).data.coordinates{p}(:,2)); + txt = text(ROI(iii).data.coordinates{p}(ceil(end/2),1),ROI(iii).data.coordinates{p}(1,2),num2str(p)); + end + set(gca, 'YDir','reverse') + title([ROI(iii).batName ' ' ROI(iii).dateSesh]); + xticklabels([]); + yticklabels([]); + +end + +savefig(trackableROI,['plot_' ROI(1).batName '_ROI_' datestr(now,'YYmmDD_hhMM') '.fig']); +saveas(trackableROI,['plot_' ROI(1).batName '_ROI_' datestr(now,'YYmmDD_hhMM') '.tif']); + +%% + +% dirTop = dir('Ga*'); +% for day_i = 1:length(nDays) %for each day +% %load results data +% try %extract metadata names and enter processed folder +% cd([dirTop(nDays(day_i)).name filesep 'extracted']) +% flyFolders = dir('*fly*extraction'); +% batName{day_i} = flyFolders(end).name(1:3); +% dateSesh{day_i} = flyFolders(end).name(5:10); +% sessionType{day_i} = flyFolders(end).name(12:16); +% +% cd(flyFolders(end).name); +% %copy _maxCorrProject files to working dir +% dirAnalysis = dir('analysis_*'); +% cd([dirAnalysis(end).name filesep 'ROI']); +% maxCorrDir = dir('*_maxCorrProject.tif'); +% +% fp = dir('*flightPaths.mat'); +% load(fp(end).name); %load flightPaths +% sd = dir('*snakePlotData.mat'); +% load(sd(end).name); + diff --git a/ROI/ImBat_correlation_image.m b/ROI/ImBat_correlation_image.m new file mode 100644 index 0000000..cd86956 --- /dev/null +++ b/ROI/ImBat_correlation_image.m @@ -0,0 +1,109 @@ +function [Cn, PNR, PNR_mov] = ImBat_correlation_image(Y,metadata) + + +try +options = metadata.options; +catch + options.metadata = metadata; + options.center_psf = 1; +end +%% compute correlation image of endoscopic data. it has to spatially filter the data first +%% Input: +% Y: d X T matrx, imaging data +% options: struct data of paramters/options +% d1: number of rows +% d2: number of columns +% gSiz: maximum size of a neuron +% nb: number of background +% min_corr: minimum threshold of correlation for segementing neurons +% K: scalar, the rank of the random matrix for projection + +%% Output: +% Cn: d1*d2, correlation image +% PNR: d1*d2, peak to noise ratio +%% Author: Pengcheng Zhou, Carnegie Mellon University. zhoupc1988@gmail.com + +%% use correlation to initialize NMF +%% parameters +[d1 d2 ~] = size(Y); +% d1 = options.d1; % image height +% d2 = options.d2; % image width +% gSig = options.gSig; % width of the gaussian kernel approximating one neuron +% gSiz = options.gSiz; % average size of neurons +gSig = options.metadata.cnmfe.gSig; +gSiz = options.metadata.cnmfe.gSiz; +sig = 3; % thresholding noise by sig*std() + +if ismatrix(Y); Y = reshape(Y, d1, d2, []); end; % convert the 3D movie to a matrix +Y(isnan(Y)) = 0; % remove nan values +Y = double(Y); +T = size(Y, 3); + +if ~exist('K', 'var') + K = []; +end +%% preprocessing data +% create a spatial filter for removing background +if gSig>0 + if options.center_psf + psf = fspecial('gaussian', ceil(gSig*4+1), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; + else + psf = fspecial('gaussian', round(gSiz), gSig); + end +else + psf = []; +end + +% divide data into multiple patches +if numel(Y) < 500^3 + patch_sz = [1, 1]; +else + x = sqrt(500^3/T); + patch_sz = ceil([d1/x, d2/x]); +end +r0_patch = round(linspace(1, d1, 1+patch_sz(1))); +c0_patch = round(linspace(1, d2, 1+patch_sz(2))); +nr_patch = length(r0_patch)-1; +nc_patch = length(c0_patch)-1; +Cn = zeros(d1, d2); +PNR = zeros(d1,d2); + +% compute correlation_image patch by patch +bd = round(gSiz); +for mr = 1:nr_patch + r0 = max(1, r0_patch(mr)-bd); % minimum row index of the patch + r1 = min(d1, r0_patch(mr+1)+bd-1); % maximum row index of the patch + for mc = 1:nc_patch + c0 = max(1, c0_patch(mc)-bd); % minimum column index of the patch + c1 = min(d2, c0_patch(mc+1)+bd-1); % maximum column index of the patch + + % take the patch from the raw data + nrows = (r1-r0+1); % number of rows in the patch + ncols = (c1-c0+1); %number of columns in the patch + Ypatch = double(Y(r0:r1, c0:c1, :)); + + % spatially filter the data + if ~isempty(psf) + HY = imfilter(Ypatch, psf, 'replicate'); + else + HY = Ypatch; + end + % copute signal to noise ratio + PNR_mov = HY-median(HY,3); + HY = reshape(HY, [], T); + HY = bsxfun(@minus, HY, median(HY, 2)); + HY_max = max(HY, [], 2); + Ysig = GetSn(HY); + tmp_PNR = reshape(HY_max./Ysig, nrows, ncols); + PNR(r0:r1, c0:c1) = max(PNR(r0:r1, c0:c1), tmp_PNR); + + + % compute loal correlation + HY(bsxfun(@lt, HY, Ysig*sig)) = 0; + tmp_Cn = correlation_image(HY, [1,2], nrows, ncols, [], K); + Cn(r0:r1, c0:c1) = max(Cn(r0:r1, c0:c1), tmp_Cn); + end +end \ No newline at end of file diff --git a/ROI/ImBat_defaults.m b/ROI/ImBat_defaults.m new file mode 100644 index 0000000..5ad873f --- /dev/null +++ b/ROI/ImBat_defaults.m @@ -0,0 +1,25 @@ +function [metadata] = ImBat_defaults; +% creates 'default' metadata file for troubleshooting pipelines: + + +% Default Movie Paramaters: +metadata.temporal_downsample = 5; % temporal downsampleing +metadata.spatial_downsample = 0.4; % spatial downsampling +metadata.median_filter_kernal = 3; % median filtering +metadata.artifact_reject = 1; % median filtering +metadata.initial_median_filter_kernal = 11; +% Default CNMFe Paramaters: +metadata.cnmfe.min_corr = 0.9; % minimum local correlation for a seeding pixel +metadata.cnmfe.min_pnr = 50; % minimum peak-to-noise ratio for a seeding pixel +metadata.cnmfe.gSig = 4; % pixel, gaussian width of a gaussian kernel for filtering the data. 0 means no filtering +metadata.cnmfe.gSiz = 4*metadata.cnmfe.gSig+1; % pixel, approximate neuron diameter +metadata.cnmfe.ssub = 1; % +center_psf = 1; % set the value as true when the background fluctuation is large (usually 1p data) + + +%defualt alignment params: +metadata.moco.itter = 5; +metadata.moco.bin_width = 200; + +metadata.processed_FN = 'temp'; +mkdir(metadata.processed_FN); \ No newline at end of file diff --git a/ROI/ImBat_exportProjections.m b/ROI/ImBat_exportProjections.m new file mode 100644 index 0000000..c37655d --- /dev/null +++ b/ROI/ImBat_exportProjections.m @@ -0,0 +1,109 @@ +function ImBat_exportProjections(saveFlag) +centroidFlag = 1; %plot centroid ROI# on each cell +binaryMaskFlag = 1; %plot masks on top of max projection +roiHeatFlag = 1; %plot maks on correlation image with/without mask +%macDesk = '/Users/periscope/Desktop/analysis/flight/ROI_manual_selections/'; %local directory to save +%saveFlag = 1; %do you want to save the figures and output structure? +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'manualROI_selections' '\']; +end + +g = dir('G*'); %find all g bats +z = dir('Z*'); %find all z bats +dirTop = vertcat(g,z); %find all folders in top quality directory + +%ROI_duplicate = cell(length(dirTop),1); %make cell for indices of duplicated ROIS + +%plot_ROI_refined = figure('units','normalized','outerposition',[0 0 0.9 0.9]); +for day_i = 1:length(dirTop) + + try %extract metadata names and enter processed folder + cd([dirTop(day_i).name filesep 'extracted']); + flyFolders = dir('*fly*extraction'); + if strcmp(flyFolders(end).name(1),'G') + batName = flyFolders(end).name(1:3); + dateSesh = flyFolders(end).name(5:10); + sessionType = flyFolders(end).name(12:16); + elseif strcmp(flyFolders(end).name(1:2),'Zo') + batName = flyFolders(end).name(1:5); + dateSesh = flyFolders(end).name(7:12); + sessionType = flyFolders(end).name(14:18); + else + batName = flyFolders(end).name(1:4); + dateSesh = flyFolders(end).name(6:11); + sessionType = flyFolders(end).name(13:17); + end + + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + catch + cd(dirTop(day_i).name); + flyFolders = dir('*fly*extraction'); + if strcmp(flyFolders(end).name(1:2),'Zo') + batName = flyFolders(end).name(1:5); + dateSesh = flyFolders(end).name(7:12); + sessionType = flyFolders(end).name(14:18); + else + batName = flyFolders(end).name(1:4); + dateSesh = flyFolders(end).name(6:11); + sessionType = flyFolders(end).name(13:17); + end + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + end + + cellData = load('results.mat'); + videoData = load('Motion_corrected_Data_DS.mat'); + + %make max projection from video + [Ymax, Y, maxFig] = ImBat_Dff(videoData.Y,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + hold on + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + %savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProject.fig']); + %saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProject.tif']); + if saveFlag == 1 + savefig(maxFig,[saveDir batName '_' dateSesh '_' sessionType '_maxProject.fig']); + saveas(maxFig,[saveDir batName '_' dateSesh '_' sessionType '_maxProject.tif']); + end + %make correlation image and max projection with ROI overlays + [ROIoverlay,correlationImage,centroidMax] = ImBat_ROIoverlay(cellData.results,'centroid',centroidFlag,'binarymask',binaryMaskFlag,'roiheat',roiHeatFlag,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + %savefig(correlationImage,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_correlationImage.fig']); + %saveas(correlationImage, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_correlationImage.tif']); + if saveFlag == 1 + savefig(correlationImage,[saveDir batName '_' dateSesh '_' sessionType '_correlationImage.fig']); + saveas(correlationImage,[saveDir batName '_' dateSesh '_' sessionType '_correlationImage.tif']); + savefig(ROIoverlay,[saveDir batName '_' dateSesh '_' sessionType '_ROIoverlay.fig']); + saveas(ROIoverlay,[saveDir batName '_' dateSesh '_' sessionType '_ROIoverlay.tif']); + savefig(centroidMax,[saveDir batName '_' dateSesh '_' sessionType '_ROIcentroid.fig']); + saveas(centroidMax,[saveDir batName '_' dateSesh '_' sessionType '_ROIcentroid.tif']); + end + + maxName = [saveDir batName '_' dateSesh '_' sessionType '_maxProject.tif']; + corrName = [saveDir batName '_' dateSesh '_' sessionType '_correlationImage.tif']; + combName = {maxName corrName}; + combName = string(combName); + combFigure = figure('units','normalized','outerposition',[0 0 1 1]); + montage(combName); + set(gcf,'units','normalized','outerposition',[0 0 1 1]) + if saveFlag == 1 + savefig(combFigure,[saveDir batName '_' dateSesh '_' sessionType '_maxCorrProject.fig']); + saveas(combFigure,[saveDir batName '_' dateSesh '_' sessionType '_maxCorrProject.tif']); + end + close all; + cd(dirTop(day_i).folder); + +end \ No newline at end of file diff --git a/ROI/ImBat_imageAlign.m b/ROI/ImBat_imageAlign.m index 358b9a5..b17dd88 100644 --- a/ROI/ImBat_imageAlign.m +++ b/ROI/ImBat_imageAlign.m @@ -1,16 +1,41 @@ -function [IM1_aligned,IM2_aligned,IM3_aligned] = ImBat_imageAlign(IM1,IM2,IM3) +function [imagesAligned] = ImBat_imageAlign(image1,image2,image3,IM1,IM2,IM3) %IM1 = GG1; %IM2 = GG2; %IM3 = GG3; -[optimizer, metric] = imregconfig('multimodal') +[optimizer, metric] = imregconfig('multimodal'); optimizer.InitialRadius = 0.005; optimizer.Epsilon = 1.5e-4; optimizer.GrowthFactor = 1.01; optimizer.MaximumIterations = 500; +transformType = 'affine'; -IM3_aligned = IM3; -IM1_aligned = imregister(IM1, IM3, 'affine', optimizer, metric); -IM2_aligned = imregister(IM2, IM3, 'affine', optimizer, metric); \ No newline at end of file + +IM2_aligned = IM2; +IM1_tform = imregtform(image1,image2,transformType,optimizer,metric); +IM1_aligned = imwarp(IM1,IM1_tform,'OutputView',imref2d(size(IM2))); +if ~isempty(IM3) + %IM1_aligned = imregister(IM1, IM3, transformType, optimizer, metric); + %IM2_aligned = imregister(IM2, IM3, transformType, optimizer, metric); + IM3_tform = imregtform(image3,image2,transformType,optimizer,metric); + IM3_aligned = imwarp(IM3,IM3_tform,'OutputView',imref2d(size(IM2))); +else + IM3_tform = []; + IM3_aligned = IM2; +end + +imagesAligned.image1 = image1; +imagesAligned.image2 = image2; +imagesAligned.image3 = image3; +imagesAligned.IM1 = IM1; +imagesAligned.IM2 = IM2; +imagesAligned.IM3 = IM3; +imagesAligned.IM1_aligned = IM1_aligned; +imagesAligned.IM2_aligned = IM2_aligned; +imagesAligned.IM3_aligned = IM3_aligned; +imagesAligned.IM1_tform = IM1_tform; +imagesAligned.IM3_tform = IM3_tform; +imagesAligned.transformType = transformType; +imagesAligned.optimizer = optimizer; \ No newline at end of file diff --git a/ROI/ImBat_imageAlign_kernalsPlot.m b/ROI/ImBat_imageAlign_kernalsPlot.m new file mode 100644 index 0000000..11cc1e4 --- /dev/null +++ b/ROI/ImBat_imageAlign_kernalsPlot.m @@ -0,0 +1,44 @@ +figure('units','normalized','outerposition',[0 0 1 0.7]); +sgtitle('gaussfilt 70cutoff nofilt noexp b4 filt exp3 after'); +filtKernal = [1 5 15 25 35 45 50]; + +IM1_aligned = imagesAligned.IM1_aligned; +IM2_aligned = imagesAligned.IM2_aligned; +IM3_aligned = imagesAligned.IM3_aligned; + +for filt_i = 1:length(filtKernal) +hFilt = fspecial('disk',filtKernal(filt_i)); +IM1_aligned_filt = imfilter(IM1_aligned,hFilt,'replicate'); +IM2_aligned_filt = imfilter(IM2_aligned,hFilt,'replicate'); +IM3_aligned_filt = imfilter(IM3_aligned,hFilt,'replicate'); +IM1_aligned_filt = IM1_aligned_filt.^3; +IM2_aligned_filt = IM2_aligned_filt.^3; +IM3_aligned_filt = IM3_aligned_filt.^3; + + +%RGB the images +[aOverlap,bOverlap] = CaBMI_XMASS(IM1_aligned_filt,IM2_aligned_filt,IM3_aligned_filt,'hl',[.05 .3]); +%rgb the original unaligned for comparison +[aUnaligned,bUnaligned] = CaBMI_XMASS(IM1(1:minRow,1:minCol),IM2(1:minRow,1:minCol),IM3); + +%quantify quartiles of overlap to see how good the days overlap +sizeIm = size(IM1_aligned_filt)/2; +quartRange(1,:) = [1,sizeIm(1),1,sizeIm(2)]; +quartRange(2,:) = [1,sizeIm(1),sizeIm(2)+1,sizeIm(2)*2]; +quartRange(3,:) = [sizeIm(1)+1,sizeIm(1)*2,1,sizeIm(2)]; +quartRange(4,:) = [sizeIm(1)+1,sizeIm(1)*2,sizeIm(2)+1,sizeIm(2)*2]; + +for quart_i = 1:4 + %quartRange = [1+sizeIm(1)*(quart_i-1),quart_i*sizeIm(1),1+sizeIm(2)*(quart_i-1),quart_i*sizeIm(2)]; +overlapQuart(quart_i,1) = sum(sum(abs(IM1_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM2_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +overlapQuart(quart_i,2) = sum(sum(abs(IM2_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM3_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +%overlapQuart(quart_i,3) = sum(sum(abs(IM1_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))-IM3_aligned_filt(quartRange(quart_i,1):quartRange(quart_i,2),quartRange(quart_i,3):quartRange(quart_i,4))))); +medOverlapQuart(quart_i) = median(overlapQuart(quart_i,:)); +end +medOverlapAll = median(overlapQuart,'all'); + +subplot(2,4,filt_i); +image(aOverlap); +set(gca,'xticklabel',[],'yticklabel',[]); +title(['rad ' num2str(filtKernal(filt_i)) ':' num2str(medOverlapAll)]); +end \ No newline at end of file diff --git a/ROI/ImBat_imageAlign_nonrigid.m b/ROI/ImBat_imageAlign_nonrigid.m new file mode 100644 index 0000000..6f424c2 --- /dev/null +++ b/ROI/ImBat_imageAlign_nonrigid.m @@ -0,0 +1,167 @@ +function [figNonrigid,imagesAligned] = ImBat_imageAlign_nonrigid(image1,image2,image3,IM1,IM2,IM3); % Basic demon registration code. (To easy understand the algorithm) + +saveFlag = 1; +% Alpha (noise) constant +alpha=2; + +%if you need to compile the c_files +%curDir = pwd; +%cd('C:\Users\tobias\Documents\MATLAB\demon_registration_version_8f\'); +% Clean +%clc; clear all; close all; +% Compile the mex files +%compile_c_files + +%make saving directory +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + %saveDir1 = '/Users/periscope/Desktop/analysis/flight/plots/'; + %saveDir1 = 'C:\Users\tobias\Desktop\analysis\plots\'; + if ~exist([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']) + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign' filesep]; +end + +% Read two images +%I1=im2double(imread('images/lenag1.png')); +%I2=im2double(imread('images/lenag2.png')); + +% Set static and moving image to align image 1 to image 2 +S=image2; M1=image1; + +% Velocity field smoothing kernel +Hsmooth=fspecial('gaussian',[60 60],10); +% The transformation fields +Tx1=zeros(size(M1)); Ty1=zeros(size(M1)); +[Sy,Sx] = gradient(S); +for itt=1:200 + % Difference image between moving and static image + Idiff=M1-S; + % Default demon force, (Thirion 1998) + %Ux = -(Idiff.*Sx)./((Sx.^2+Sy.^2)+Idiff.^2); + %Uy = -(Idiff.*Sy)./((Sx.^2+Sy.^2)+Idiff.^2); + % Extended demon force. With forces from the gradients from both + % moving as static image. (Cachier 1999, He Wang 2005) + [My,Mx] = gradient(M1); + Ux = -Idiff.* ((Sx./((Sx.^2+Sy.^2)+alpha^2*Idiff.^2))+(Mx./((Mx.^2+My.^2)+alpha^2*Idiff.^2))); + Uy = -Idiff.* ((Sy./((Sx.^2+Sy.^2)+alpha^2*Idiff.^2))+(My./((Mx.^2+My.^2)+alpha^2*Idiff.^2))); + + % When divided by zero + Ux(isnan(Ux))=0; Uy(isnan(Uy))=0; + % Smooth the transformation field + Uxs=3*imfilter(Ux,Hsmooth); + Uys=3*imfilter(Uy,Hsmooth); + % Add the new transformation field to the total transformation field. + Tx1=Tx1+Uxs; + Ty1=Ty1+Uys; + M1=movepixels(IM1,Tx1,Ty1); %make transformation on the original image +end +figNonrigid = figure('units','normalized','outerposition',[0 0 1 0.6]); +sgtitle(['Gal 123 Nonrigid alignment: alpha ' num2str(alpha)]); +ha = tight_subplot(2,7,[.02 .01],[.01 .08],[.01 .01]); + set(0,'CurrentFigure',figNonrigid); + axes(ha(1)); imshow(IM1,[]); title('Day 1'); + axes(ha(2)); imshow(image1,[]); title('Day 1 filt'); + axes(ha(3)); imshow(IM2,[]); title('Day 2'); + axes(ha(4)); imshow(image2,[]); title('Day 2 filt'); + axes(ha(5)); imshow(Tx1,[]); title('Transformation Field x'); + axes(ha(6)); imshow(Ty1,[]); title('Transformation Field y'); + axes(ha(7)); imshow(M1,[]); title('Registered Day 1'); + +% subplot(2,5,1), imshow(IM1,[]); title('Day 1'); +% subplot(2,5,2), imshow(IM2,[]); title('Day 2'); +% subplot(2,5,3), imshow(M1,[]); title('Registered Day 1'); +% subplot(2,5,4), imshow(Tx,[]); title('Transformation Field x'); +% subplot(2,5,5), imshow(Ty,[]); title('Transformation Field y'); + +%% align image 3 to image 2 +if ~isempty(image3) +% Set static and moving image +S=image2; M3=image3; %use the filtered images + +% Velocity field smoothing kernel +Hsmooth=fspecial('gaussian',[60 60],10); +% The transformation fields +Tx3=zeros(size(M3)); Ty3=zeros(size(M3)); +[Sy,Sx] = gradient(S); +for itt=1:200 + % Difference image between moving and static image + Idiff=M3-S; + % Default demon force, (Thirion 1998) + %Ux = -(Idiff.*Sx)./((Sx.^2+Sy.^2)+Idiff.^2); + %Uy = -(Idiff.*Sy)./((Sx.^2+Sy.^2)+Idiff.^2); + % Extended demon force. With forces from the gradients from both + % moving as static image. (Cachier 1999, He Wang 2005) + [My,Mx] = gradient(M3); + Ux = -Idiff.* ((Sx./((Sx.^2+Sy.^2)+alpha^2*Idiff.^2))+(Mx./((Mx.^2+My.^2)+alpha^2*Idiff.^2))); + Uy = -Idiff.* ((Sy./((Sx.^2+Sy.^2)+alpha^2*Idiff.^2))+(My./((Mx.^2+My.^2)+alpha^2*Idiff.^2))); + + % When divided by zero + Ux(isnan(Ux))=0; Uy(isnan(Uy))=0; + % Smooth the transformation field + Uxs=3*imfilter(Ux,Hsmooth); + Uys=3*imfilter(Uy,Hsmooth); + % Add the new transformation field to the total transformation field. + Tx3=Tx3+Uxs; + Ty3=Ty3+Uys; + M3=movepixels(IM3,Tx3,Ty3); %make transformation on the original image +end + + set(0,'CurrentFigure',figNonrigid); + axes(ha(8)); imshow(IM2,[]); title('Day 2'); + axes(ha(9)); imshow(image2,[]); title('Day 2 filt'); + axes(ha(10)); imshow(IM3,[]); title('Day 3'); + axes(ha(11)); imshow(image3,[]); title('Day 3 filt'); + axes(ha(12)); imshow(Tx3,[]); title('Transformation Field x'); + axes(ha(13)); imshow(Ty3,[]); title('Transformation Field y'); + axes(ha(14)); imshow(M3,[]); title('Registered Day 3'); + +% subplot(2,5,6), imshow(IM2,[]); title('Day 2'); +% subplot(2,5,7), imshow(IM3,[]); title('Day 3'); +% subplot(2,5,8), imshow(M3,[]); title('Registered day 3'); +% subplot(2,5,9), imshow(Tx,[]); title('Transformation x'); +% subplot(2,5,10), imshow(Ty,[]); title('Transformation y'); +else + M3 = []; + Tx3 = []; + Ty3 = []; +end + +if saveFlag == 1 + saveas(figNonrigid,[saveDir filesep 'Gal_200311and20_day1_day2_day3_' datestr(now,'yymmdd-HHMM') 'alignment_nonrigid_alpha' num2str(alpha) '.tif']); + savefig(figNonrigid,[saveDir filesep 'Gal_200311and20_day1_day2_day3_' datestr(now,'yymmdd-HHMM') 'alignment_nonrigid_alpha' num2str(alpha) '.fig']); +end +%go back to original folder precompiling +%cd(curDir); + +imagesAligned.alpha = alpha; +imagesAligned.IM1 = IM1; +imagesAligned.IM2 = IM2; +imagesAligned.IM3 = IM3; +imagesAligned.image1 = image1; +imagesAligned.image2 = image2; +imagesAligned.image3 = image3; +imagesAligned.IM1_aligned = M1; +imagesAligned.IM2_aligned = IM2; +imagesAligned.IM3_aligned = M3; +imagesAligned.Tx1 = Tx1; +imagesAligned.Ty1 = Ty1; +imagesAligned.Tx3 = Tx3; +imagesAligned.Ty3 = Ty3; + +%% run rgb overlay, plot, and save +% [a2,b2] = CaBMI_XMASS(IM1,M1,M3); +% plotTitle = ['nonrigid alpha' num2str(alpha) ': Gal Full Sesh: Day 1 (r) v 2 (g) v 3 (b)']; +% +% plotDay123_aligned = figure(); +% image((a2(:,:,:))) +% title(plotTitle); +% set(gca,'xticklabel',[],'yticklabel',[]); +% +% if saveFlag == 1 +% saveas(plotDay123_aligned,[saveDir filesep 'Gal_200311and20_day1_day2_day3_full' datestr(now,'yymmdd-HHMM') 'nonrigid_alpha' num2str(alpha) '.tif']); +% savefig(plotDay123_aligned,[saveDir filesep 'Gal_200311and20_day1_day2_day3_full' datestr(now,'yymmdd-HHMM') 'nonrigid_alpha' num2str(alpha) '.fig']); +% end \ No newline at end of file diff --git a/ROI/ImBat_maxProfDff_wrapperUpdate.m b/ROI/ImBat_maxProfDff_wrapperUpdate.m new file mode 100644 index 0000000..76878fb --- /dev/null +++ b/ROI/ImBat_maxProfDff_wrapperUpdate.m @@ -0,0 +1,85 @@ +function ImBat_maxProfDff_wrapperUpdate +close all; +saveFlag = 1; %save data? +flyFlag = 0; %0 = fly, 1 = rest1, 2 = rest2 + +if saveFlag == 1 +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'maxProjAll'])>0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'maxProjAll']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'maxProjAll' '\']; +end + +g = dir('Ge*'); +z = dir('Zp*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +figAllDff = figure('units','normalized','outerposition',[0 0.1 0.4 0.8]); +sgtitle(['Max Projection Across Days ' dirTop(1).name(1:2)]); +figAllA = figure('units','normalized','outerposition',[0 0.1 0.4 0.8]); +sgtitle(['Corr Image Across Days ' dirTop(1).name(1:2)]); +%for each bat/session +for sesh_i = 1:length(dirTop) + + %get meta info for each bat/day + cd([dirTop(sesh_i).name filesep 'extracted']); + if flyFlag == 0 + dirFly = dir('*fly*extraction*'); + elseif flyFlag == 1 + dirFly = dir('*rest1*extraction'); + elseif flyFlag == 2 + dirFly = dir('*rest2*extraction'); + end + batName = dirFly(1).name(1:3); + dateSesh = dirFly(1).name(5:10); + sessionType = dirFly(1).name(12:16); + fileName = [batName '_' dateSesh '_' sessionType]; + %load cellData, flightpaths,alignment files + cd(dirFly(1).name); + dirAnal = dir('analysis*'); + + dirDff = dir([dirAnal(end).folder filesep dirAnal(end).name filesep 'ROI' filesep '*maxProject.fig']); %find the max projection image + figDff = openfig([dirDff.folder filesep dirDff.name],'reuse'); + axDff = gca; + figure(1) + s1 = subplot(ceil(length(dirTop)/3),3,sesh_i); + fig1 = get(axDff,'children'); + copyobj(fig1,s1); + axis image; + hold on; + colormap(gray); + set(gca,'xticklabel',[],'yticklabel',[]); + title([batName ' ' dateSesh ' ' sessionType]); + drawnow + close Figure 3 + + dirA = dir([dirAnal(end).folder filesep dirAnal(end).name filesep 'ROI' filesep '*maxProjectROI.fig']); + figA = openfig([dirA.folder filesep dirA.name],'reuse'); + axA = gca; + figure(2) + s2 = subplot(ceil(length(dirTop)/3),3,sesh_i); + fig2 = get(axA,'children'); + copyobj(fig2,s2); + axis image; + colormap(gray); + hold on; + set(gca,'xticklabel',[],'yticklabel',[]); + title([batName ' ' dateSesh ' ' sessionType]); + drawnow + close Figure 3 + + cd(dirTop(sesh_i).folder); +end + +if saveFlag == 1 + saveas(figAllDff,[saveDir filesep batName '_' dateSesh '_' sessionType '_maxProjAllDays_' datestr(now,'yymmdd_HHMM') '.tif']); + savefig(figAllDff,[saveDir filesep batName '_' dateSesh '_' sessionType '_maxProjAllDays_' datestr(now,'yymmdd_HHMM') '.fig']); + saveas(figAllA,[saveDir filesep batName '_' dateSesh '_' sessionType '_corrImAllDays_' datestr(now,'yymmdd_HHMM') '.tif']); + savefig(figAllA,[saveDir filesep batName '_' dateSesh '_' sessionType '_corrImAllDays_' datestr(now,'yymmdd_HHMM') '.fig']); +end + + diff --git a/ROI/ImBat_roi3day.m b/ROI/ImBat_roi3day.m new file mode 100644 index 0000000..ceb4e42 --- /dev/null +++ b/ROI/ImBat_roi3day.m @@ -0,0 +1,189 @@ +function [framesData] = ImBat_roi3day(days1to3,varargin) +%% +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + end +end + +for i = 1:length(days1to3) + datadir = dir([days1to3{i} '\extracted\' '*fly*']); + dirFlags = [datadir.isdir]; + % Extract only those that are directories. + flyFolders{i} = datadir(dirFlags); + %enter newest processed folder + processedFolders = dir([flyFolders{i}.folder,'/',flyFolders{i}.name,'/','processed*']); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + analysisFolders = dir([flyFolders{i}.folder,'/',flyFolders{i}.name,'/','analysis*']); + analysisNewest = sort({analysisFolders(end).name}); + analysisNewest = char(analysisNewest); + %load data + trackDir = dir([flyFolders{i}.folder filesep flyFolders{i}.name filesep analysisNewest filesep '*_flightPaths.mat']); + batName{i} = trackDir.name(1:3); + seshTemp = extractAfter(trackDir.name,[batName{i} '_' days1to3{i} '_']); + sessionType{i} = extractBefore(seshTemp,'_flightPaths.mat'); + results(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep processedNewest filesep 'results.mat']); + track(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep analysisNewest filesep trackDir.name]); + video(i) = load([pwd filesep days1to3{i} filesep 'Motion_corrected_Data.mat']); + alignment(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep processedNewest filesep 'Alignment.mat']); + close all; +end +%% +figure(); +sgtitle([batName{1} ': cluster 2']); +scaling = 4; %scaling for resizing the pixel/frame +%initialize frame vectors for video chunks +frames = cell(length(track),1); +framesCat = cell(length(track),1); +framesCat4 = cell(length(track),1); +framesLength =[]; +minValueStart = []; +minValueEnd = []; +closestIndexStart = []; +closestIndexEnd = []; +randInd = cell(length(track),1); +flightNums = cell(length(track),1); +%find min number of flights in each day to subsample later +for i = 1:length(track) + flightNums{i} = track(i).flightPaths.clusterIndex{2}'; %get the indices for the flights in the cluster + flightNumsLength(i) = length(flightNums{i}); %number of flights on each day +end +minFlightNums = min(flightNumsLength); %least number of flights across the 3 days +for i = 1:length(track) + randInd{i} = randperm(flightNumsLength(i),minFlightNums); %generate random list with minlength of flights for random selection %flightNumsLength(i)); + for p = 1:minFlightNums %for each flight within cluster #2 %length(randInd) + %get imaging times of start and stop index converting from tracking to video times + [minValueStart{i}(p),closestIndexStart{i}(p)] = min(abs(alignment(i).video_timesDS-alignment(i).out.Location_time(track(i).flightPaths.flight_starts_idx(track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))))); + [minValueEnd{i}(p),closestIndexEnd{i}(p)] = min(abs(alignment(i).video_timesDS-alignment(i).out.Location_time(track(i).flightPaths.flight_ends_idx(track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))))); + framesLength{i}(p) = closestIndexEnd{i}(p) - closestIndexStart{i}(p); + end + framesMax(i) = max(framesLength{i}); %find max # frames across all flights +end + framesMaxAll = max(framesMax); +for i = 1:length(track) + frames{i} = cell(length(track(i).flightPaths.clusterIndex{2}),1); + for p = 1:minFlightNums %length(randInd) + framesDiff{i}(p) = framesMaxAll - framesLength{i}(p); + %add to frames vector and concatenate + frames{i}{p} = video(i).Y(:,:,closestIndexStart{i}(p):(closestIndexEnd{i}(p)+framesDiff{i}(p))); + framesCat{i} = cat(3,framesCat{i},frames{i}{p}); + framesCat4{i} = cat(4,framesCat4{i},frames{i}{p}); + subplot(4,3,i); + plot3(track(i).flightPaths.pos(1,:,track(i).flightPaths.clusterIndex{2}(randInd{i}(p))),track(i).flightPaths.pos(2,:,track(i).flightPaths.clusterIndex{2}(randInd{i}(p))),track(i).flightPaths.pos(3,:,track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))); + hold on; + end + framesCat4_mean{i} = mean(framesCat4{i},4); + %make gaussian filter based on normcorre function + gSig = 2; + gSiz = 5*gSig; + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + % Filter movie for max projection + framesCat_conv{i} = imfilter(framesCat{i},psf,'symmetric'); + framesCat4_conv{i} = imfilter(framesCat4_mean{i},psf,'symmetric'); + +% framesCat_conv{i} = (convn(framesCat{i}, single(reshape([1 1 1] /10, 1, 1, [])), 'same')); + % Take median of movie + framesCat_min{i} = median(framesCat_conv{i},3); + framesCat4_min{i} = median(framesCat4_conv{i},3); + % Subtract median + framesCat_medNorm{i} = framesCat_conv{i}-framesCat_min{i}; + framesCat4_medNorm{i} = framesCat4_conv{i}-framesCat4_min{i}; + % take max + Ymax{i} = max(framesCat_medNorm{i},[],3); + Ymax{i} = imresize(Ymax{i},scaling); + framesCat4_Ymax{i} = max(framesCat4_medNorm{i},[],3); + framesCat4_Ymax{i} = imresize(framesCat4_Ymax{i},scaling); + + subplot(4,3,3+i) + imagesc(Ymax{i}); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title([batName{i} ' ' days1to3{i} ' ' sessionType{i}]); + + %filter movie for PNR + [metadata] = ImBat_defaults; + [Cn{i}, PNR{i}, PNR_mov{i}] = ImBat_correlation_image(framesCat_medNorm{i},metadata); + [Cn4{i}, PNR4{i}, PNR_mov4{i}] = ImBat_correlation_image(framesCat4_mean{i},metadata); + subplot(4,3,i+6) + imagesc(framesCat4_Ymax{i}); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title(['PNR ' batName{i} ' ' days1to3{i} ' ' sessionType{i}]); + +end +%% align and overlay +%align all 3 days +[Ymax_aligned{1},Ymax_aligned{2},Ymax_aligned{3}] = ImBat_imageAlign(Ymax{1},Ymax{2},Ymax{3}); +[PNR_aligned{1},PNR_aligned{2},PNR_aligned{3}] = ImBat_imageAlign(PNR{1},PNR{2},PNR{3}); + + +%change into RGB and overlay colors +[RGB1,RGB2] = CaBMI_XMASS(Ymax{1},Ymax{2},Ymax{3}); +[RGB3,RGB4] = CaBMI_XMASS(Ymax_aligned{1},Ymax_aligned{2},Ymax_aligned{3}); +[RGB_PNR1,RGB_PNR2] = CaBMI_XMASS(PNR_aligned{1},PNR_aligned{2},PNR_aligned{3}); + +subplot(4,3,10) +image((RGB1(:,:,:))); +set(gca,'YDir','normal'); +title([batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); + +subplot(4,3,11) +image((RGB3(:,:,:))); +set(gca,'YDir','normal'); +title(['Aligned ' batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); + +subplot(4,3,12) +image((RGB_PNR1(:,:,:))); +set(gca,'YDir','normal'); +title(['Aligned PNR ' batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); + +%% add to final data structure + +framesData.framesLength = framesLength; +framesData.framesMax = framesMax; +framesData.frames = frames; +framesData.framesCat = framesCat; +framesData.framesCat4 = framesCat4; +framesData.Ymax = Ymax; +framesData.framesCat4_Ymax = framesCat4_Ymax; +framesData.randInd = randInd; +framesData.flightNums = flightNums; +framesData.Ymax_aligned = Ymax_aligned; +framesData.PNR_aligned = PNR_aligned; +framesData.RGB1 = RGB1; +framesData.RGB3 = RGB3; +framesData.RGB_PNR1 = RGB_PNR1; +framesData.Cn = Cn; +framesData.PNR = PNR; +framesData.PNR_mov = PNR_mov; +framesData.Cn4 = Cn4; +framesData.PNR4 = PNR4; +framesData.PNR_mov4 = PNR_mov4; + + + + + + diff --git a/ROI/ImBat_roi3day_2.m b/ROI/ImBat_roi3day_2.m new file mode 100644 index 0000000..fc7ce3e --- /dev/null +++ b/ROI/ImBat_roi3day_2.m @@ -0,0 +1,256 @@ +function [framesData] = ImBat_roi3day_2(days1to3,data_3day,varargin) +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; +minLimMult = 3; %min limit multiplier for max projections +maxLimMult = 0.6; %max limit multiplier for max projections +scaling = 4; %scaling for resizing the pixel/frame + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + end +end + +%% concatenate, filter, max project, and mean +figure('units','normalized','outerposition',[0 0 0.85 0.85]); +sgtitle([data_3day.batName{1} ': cluster 2']); +scaling = 4; %scaling for resizing the pixel/frame +%initialize frame vectors for video chunks +frames = cell(length(data_3day.track),1); +framesCat = cell(length(data_3day.track),1); +framesCat4 = cell(length(data_3day.track),1); +framesCat4_conv = cell(length(data_3day.track),1); +framesCat4_minNorm = cell(length(data_3day.track),1); +framesCat4_min = cell(length(data_3day.track),1); +Ymax = cell(length(data_3day.track),1); +framesLength =[]; +minValueStart = []; +minValueEnd = []; +closestIndexStart = []; +closestIndexEnd = []; +randInd = cell(length(data_3day.track),1); +flightNums = cell(length(data_3day.track),1); + +%find min number of flights in each day to subsample later +for i = 1:length(data_3day.track) + flightNums{i} = data_3day.track(i).flightPaths.clusterIndex{2}'; %get the indices for the flights in the cluster + flightNumsLength(i) = length(flightNums{i}); %number of flights on each day +end +minFlightNums = min(flightNumsLength); %least number of flights across the 3 days +for i = 1:length(data_3day.track) + randInd{i} = randperm(flightNumsLength(i),minFlightNums); %generate random list with minlength of flights for random selection %flightNumsLength(i)); + for p = 1:minFlightNums %for each flight within cluster #2 %length(randInd) + %get imaging times of start and stop index converting from tracking to video times + [minValueStart{i}(p),closestIndexStart{i}(p)] = min(abs(data_3day.alignment(i).video_timesDS-data_3day.alignment(i).out.Location_time(data_3day.track(i).flightPaths.flight_starts_idx(data_3day.track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))))); + [minValueEnd{i}(p),closestIndexEnd{i}(p)] = min(abs(data_3day.alignment(i).video_timesDS-data_3day.alignment(i).out.Location_time(data_3day.track(i).flightPaths.flight_ends_idx(data_3day.track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))))); + framesLength{i}(p) = closestIndexEnd{i}(p) - closestIndexStart{i}(p); + end + framesMax(i) = max(framesLength{i}); %find max # frames across all flights +end + %max number of frames across all flights and days + framesMaxAll = max(framesMax); + %make gaussian filter based on normcorre function + gSig = 2; + gSiz = 5*gSig; + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + %filt_rad = 20; + %filt_alpha = 2; + %h=fspecial('gaussian',filt_rad,filt_alpha); +for i = 1:length(data_3day.track) + %filter whole day for full day stability max projection + movFull_conv{i} = imfilter(data_3day.video(i).Y,psf,'symmetric'); %filter + movFull_min{i} = min(movFull_conv{i},[],3); %take min + movFull_minNorm{i} = movFull_conv{i} - movFull_min{i}; %normalize by subtracting min + movFull_Ymax{i} = max(movFull_minNorm{i},[],3); %take max + movFull_Ymax{i} = imresize(movFull_Ymax{i},scaling); %resize the max + + for p = 1:minFlightNums %length(randInd) + framesDiff{i}(p) = framesMaxAll - framesLength{i}(p); + %add to frames vector and concatenate + frames{i}(:,:,:,p) = data_3day.video(i).Y(:,:,closestIndexStart{i}(p):(closestIndexEnd{i}(p)+framesDiff{i}(p))); + %max(max) concatenate all frames together in 1 long vector + framesCat{i} = cat(3,framesCat{i},frames{i}(:,:,:,p)); + %max(mean) + framesCat4{i} = frames{i}; %cat(4,framesCat4{i},frames{i}{p}); ) + % Filter movie for max projection + framesCat4_conv{i}(:,:,:,p) = imfilter(framesCat4{i}(:,:,:,p),psf,'symmetric'); + %framesCat4_conv{i}(:,:,:,p)=imfilter(framesCat4{i}(:,:,:,p),h,'circular'); + % Take median of movie + framesCat4_min{i}(:,:,:,p) = min(framesCat4_conv{i}(:,:,:,p),[],3); + % Subtract median + framesCat4_minNorm{i}(:,:,:,p) = framesCat4_conv{i}(:,:,:,p)-framesCat4_min{i}(:,:,:,p); + % take max of 1 trial + Ymax_temp{i}(:,:,p) = max(framesCat4_minNorm{i}(:,:,:,p),[],3); + Ymax{i}(:,:,p) = imresize(Ymax_temp{i}(:,:,p),scaling); + + %make pnr + [metadata] = ImBat_defaults; + [Cn4{i}(:,:,p), PNR4{i}(:,:,p), PNR_mov4{i}(:,:,:,p)] = ImBat_correlation_image(framesCat4{i}(:,:,:,p),metadata); + + % plot flights + subplot(6,5,i); + plot3(data_3day.track(i).flightPaths.pos(1,:,data_3day.track(i).flightPaths.clusterIndex{2}(randInd{i}(p))),data_3day.track(i).flightPaths.pos(2,:,data_3day.track(i).flightPaths.clusterIndex{2}(randInd{i}(p))),data_3day.track(i).flightPaths.pos(3,:,data_3day.track(i).flightPaths.clusterIndex{2}(randInd{i}(p)))); + hold on; + end + %take average across all trials + framesCat4_mean{i} = mean(framesCat4_minNorm{i},4); %mean filtered video of all trials for each day + Ymax_mean{i} = mean(Ymax{i},3); %mean of all the max projections for each trial + PNR_mean{i} = mean(PNR4{i},3); + + % Filter movie for max projection with all trials concatenated + % together, then filtered and averaged (max(max)) + framesCat3_conv{i} = imfilter(framesCat{i},psf,'symmetric'); + % Take median of movie + framesCat3_med{i} = min(framesCat3_conv{i},[],3); + % Subtract median + framesCat3_medNorm{i} = framesCat3_conv{i}-framesCat3_med{i}; + % take max across the whole trial + Ymax3{i} = max(framesCat3_medNorm{i},[],3); %max(max) + Ymax3_resize{i} = imresize(Ymax3{i},scaling); +%% time plots + filt2use = 5; + exp2use = 2; + [im1_rgb{i} norm_max_proj{i},I{i},idx_img{i}] = CABMI_allpxs(framesCat4_mean{i},'filt_rad',filt2use,'exp',exp2use); + subplot(6,5,25+i) + imagesc(I{i}); + set(gca,'YDir','normal'); + %colorbar; + title(['Across time ' data_3day.batName{i} ' ' days1to3{i} ' ' data_3day.sessionType{1}]); + +%% max projection plots + %full day max projection + subplot(6,5,5+i) + imagesc(movFull_Ymax{i},[min(min(movFull_Ymax{1}))*minLimMult max(max(movFull_Ymax{i}))*maxLimMult]); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title(['Max Full Day ' data_3day.batName{i} ' ' days1to3{i} ' ' data_3day.sessionType{i}]); + %colorbar; + + %max projection with data concat>filter>maxProject max(max) + subplot(6,5,10+i) + %imagesc(framesCat4_Ymax{i}); + imagesc(Ymax3_resize{i},[min(min(Ymax3_resize{1}))*minLimMult max(max(Ymax3_resize{1}))*maxLimMult]); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title(['Max(max) ' data_3day.batName{i} ' ' days1to3{i} ' ' data_3day.sessionType{i}]); + %colorbar; + hold off; + + %max projection with data filter>max project>mean max(mean) + subplot(6,5,15+i) + imagesc(Ymax_mean{i},[min(min(Ymax_mean{1}))*minLimMult max(max(Ymax_mean{1}))*maxLimMult]);%[0.75 1.9]); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title(['Max(mean) ' data_3day.batName{i} ' ' days1to3{i} ' ' data_3day.sessionType{i}]); + %colorbar; + + %PNR data PNR>mean + subplot(6,5,20+i) + %imagesc(framesCat4_Ymax{i}); + imagesc(PNR_mean{i},[min(min(PNR_mean{1}))*minLimMult max(max(PNR_mean{1}))*maxLimMult]); + colormap('gray'); + set(gca,'YDir','normal'); + hold on; + title(['PNR ' data_3day.batName{i} ' ' days1to3{i} ' ' data_3day.sessionType{1}]); + %colorbar; + +end +%% align and overlay 3 days +%align all 3 days +[Ymax_aligned{1},Ymax_aligned{2},Ymax_aligned{3}] = ImBat_imageAlign(Ymax3_resize{1},Ymax3_resize{2},Ymax3_resize{3}); %max(max) +[PNR_aligned{1},PNR_aligned{2},PNR_aligned{3}] = ImBat_imageAlign(PNR_mean{1},PNR_mean{2},PNR_mean{3}); %max(PNR) +[YmaxFull_aligned{1},YmaxFull_aligned{2},YmaxFull_aligned{3}] = ImBat_imageAlign(movFull_Ymax{1},movFull_Ymax{2},movFull_Ymax{3}); %max(max) +%change into RGB and overlay colors +[RGB_Ymax1,RGB_Ymax2] = CaBMI_XMASS(Ymax3_resize{1},Ymax3_resize{2},Ymax3_resize{3},'normalize',2,'hl',[0.05,0.6]); +[RGB_YmaxAligned1,RGB_YmaxAligned2] = CaBMI_XMASS(Ymax_aligned{1},Ymax_aligned{2},Ymax_aligned{3},'normalize',2,'hl',[0.05,0.6]); +[RGB_PNR1,RGB_PNR2] = CaBMI_XMASS(PNR_mean{1},PNR_mean{2},PNR_mean{3},'normalize',2,'hl',[0.05,0.6]); +[RGB_PNRAligned1,RGB_PNRAligned2] = CaBMI_XMASS(PNR_aligned{1},PNR_aligned{2},PNR_aligned{3},'normalize',2,'hl',[0.05,0.6]); +[RGB_full1,RGB_full2] = CaBMI_XMASS(movFull_Ymax{1},movFull_Ymax{2},movFull_Ymax{3},'normalize',2,'hl',[0.05,0.6]); +[RGB_fullAlign1,RGB_fullAlign2] = CaBMI_XMASS(YmaxFull_aligned{1},YmaxFull_aligned{2},YmaxFull_aligned{3},'normalize',2,'hl',[0.05,0.6]); + +%RGB of full video max projection +subplot(6,5,9) +image((RGB_full1(:,:,:))); +set(gca,'YDir','normal'); +title(['Full max(max) ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); +%colorbar; +%RGB of full video max projection aligned +subplot(6,5,10) +image((RGB_fullAlign1(:,:,:))); +set(gca,'YDir','normal'); +title(['Full aligned ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); +%colorbar; + +%RGB of nonaligned max projections +subplot(6,5,14) +image((RGB_Ymax1(:,:,:))); +set(gca,'YDir','normal'); +title(['Max(max) ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); +%colorbar; +%RGB of aligned max projections +subplot(6,5,15) +image((RGB_YmaxAligned1(:,:,:))); +set(gca,'YDir','normal'); +title(['Aligned Max(max) ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); + +%RGB of nonaligned PNR +subplot(6,5,24) +image((RGB_PNRAligned1(:,:,:))); +set(gca,'YDir','normal'); +title(['Aligned PNR ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); +%colorbar; +%RGB of aligned PNR +subplot(6,5,25) +image((RGB_PNRAligned1(:,:,:))); +set(gca,'YDir','normal'); +title(['Aligned PNR ' data_3day.batName{1} ': ' days1to3{1} ' ' days1to3{2} ' ' days1to3{3}]); +%colorbar; + + +%% add to final data structure + +framesData.framesLength = framesLength; +framesData.framesMax = framesMax; +framesData.frames = frames; +framesData.framesCat = framesCat; +framesData.framesCat4 = framesCat4; +framesData.Ymax_temp = Ymax_temp; +framesData.Ymax = Ymax; +framesData.randInd = randInd; +framesData.flightNums = flightNums; +framesData.Ymax_aligned = Ymax_aligned; +framesData.PNR_aligned = PNR_aligned; +framesData.RGB1 = RGB_Ymax1; +framesData.RGB3 = RGB_YmaxAligned1; +framesData.RGB_PNR1 = RGB_PNRAligned1; +%framesData.Cn = Cn; +%framesData.PNR = PNR; +%framesData.PNR_mov = PNR_mov; +framesData.Cn4 = Cn4; +framesData.PNR4 = PNR4; +framesData.PNR_mov4 = PNR_mov4; + + + + + + diff --git a/ROI/ImBat_roi3day_loadData.m b/ROI/ImBat_roi3day_loadData.m new file mode 100644 index 0000000..3b96183 --- /dev/null +++ b/ROI/ImBat_roi3day_loadData.m @@ -0,0 +1,54 @@ +function [data_3day] = ImBat_roi3day_loadData(days1to3,varargin) +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + end +end +%% load data for each of the days +for i = 1:length(days1to3) + datadir = dir([days1to3{i} '\extracted\' '*fly*']); + dirFlags = [datadir.isdir]; + % Extract only those that are directories. + flyFolders{i} = datadir(dirFlags); + %enter newest processed folder + processedFolders = dir([flyFolders{i}.folder,'/',flyFolders{i}.name,'/','processed*']); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + analysisFolders = dir([flyFolders{i}.folder,'/',flyFolders{i}.name,'/','analysis*']); + analysisNewest = sort({analysisFolders(end).name}); + analysisNewest = char(analysisNewest); + %load data + trackDir = dir([flyFolders{i}.folder filesep flyFolders{i}.name filesep analysisNewest filesep '*_flightPaths.mat']); + batName{i} = trackDir.name(1:3); + seshTemp = extractAfter(trackDir.name,[batName{i} '_' days1to3{i} '_']); + sessionType{i} = extractBefore(seshTemp,'_flightPaths.mat'); + results(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep processedNewest filesep 'results.mat']); + track(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep analysisNewest filesep trackDir.name]); + video(i) = load([pwd filesep days1to3{i} filesep 'Motion_corrected_Data.mat']); + alignment(i) = load([flyFolders{i}.folder filesep flyFolders{i}.name filesep processedNewest filesep 'Alignment.mat']); + close all; +end + +data_3day.batName = batName; +data_3day.sessionType = sessionType; +data_3day.results = results; +data_3day.track = track; +data_3day.video = video; +data_3day.alignment = alignment; + diff --git a/ROI/ImBat_scatterCorrVDist.m b/ROI/ImBat_scatterCorrVDist.m new file mode 100644 index 0000000..a5d01fd --- /dev/null +++ b/ROI/ImBat_scatterCorrVDist.m @@ -0,0 +1,43 @@ +ROI_refined = ROI_refined;% ROI_refined_Gal_11to20_c65; +saveFlag = 1; %do you want to save the figures and output structure? +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'ROI_covar_scatter'])>0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'ROI_covar_scatter']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'ROI_covar_scatter' '\']; + +scatterCorrDist = figure('units','normalized','outerposition',[0 0.5 1 0.5]); +for i = 1:length(ROI_refined.batName) + subplot(2,length(ROI_refined.batName),i) + scatter(ROI_refined.timeCorrS{i}(ROI_refined.corrIndAllS{i}),ROI_refined.distance{i}(ROI_refined.corrIndAll{i})) + hold on; + sgtitle('Gal Smatrix: Pairwise ROI distance (um) vs corr coeff (R)') + title(['Day # ' num2str(i)]); + if i == 1 + xlabel('CorrCoef'); + ylabel('Distance (um)'); + end +end + +for i = 1:length(ROI_refined.batName) + subplot(2,length(ROI_refined.batName),length(ROI_refined.batName)+i) + scatter(ROI_refined.timeCorrCloseS{i}(ROI_refined.corrIndCloseS{i}),ROI_refined.distance{i}(ROI_refined.corrIndClose{i}),'r') + hold on; + %sgtitle('SMatrix: Pairwise close ROI distance (um) vs corr coeff (R)') + %title(['Gal Day# ' num2str(i)]); + if i == 1 + xlabel('CorrCoef'); + ylabel('Subthresh: Distance (um)'); + end +end + +if saveFlag == 1 + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(scatterCorrDist,[saveDir 'scatterCorrDist_' ROI_refined.batName{1} '_19to24_' datestr(now,'yymmdd-hhMMss') '.fig']); + saveas(scatterCorrDist, [saveDir 'scatterCorrDist_' ROI_refined.batName{1} '_19to24_' datestr(now,'yymmdd-hhMMss') '.tif']); + %saveas(scatterCorrDist, [saveDir 'scatterCorrDist' ROI_refined.batName{1} ROI_refined.dateSesh{1} ROI_refined.sessionType{1} '_' datestr(now,'yymmdd-hhMMss') '.svg']); +end \ No newline at end of file diff --git a/ROI/annotate_image.m b/ROI/annotate_image.m new file mode 100644 index 0000000..43398b5 --- /dev/null +++ b/ROI/annotate_image.m @@ -0,0 +1,26 @@ +function ROI = annotate_image(im) +an = Annotator(im); +an.wait(); +masks = an.getMasks(); + + +for i = 1: size(masks,3) + + [row,col] = find(masks(:,:,i)== 1); + + ROI.coordinates{1,i} = [col row]; + ROI.stats(i).Centroid=mean(ROI.coordinates{i}); + ROI.stats(i).Diameter=max(pdist(ROI.coordinates{i},'euclidean')); + k=convhull(ROI.coordinates{i}(:,1),ROI.coordinates{i}(:,2)); + ROI.stats(i).ConvexHull=ROI.coordinates{i}(k,:); + +end + +ROI.type = 'Image'; +im2 = imread(im); +ROI.reference_image = im2; +b = im(1:end-4); +b = strcat(b,'_ROI_DATA.mat'); +save(b,'ROI') +end + diff --git a/analysis_tobias/Angelo2Will_format.m b/analysis_tobias/Angelo2Will_format.m new file mode 100644 index 0000000..5bee612 --- /dev/null +++ b/analysis_tobias/Angelo2Will_format.m @@ -0,0 +1,42 @@ +function Angelo2Will_format +% Wrapper to convert to the old format... + +dateDir = dir('20*'); +for i = 1:length(dateDir) + cd(dateDir(i).name); + +%make new folders +processed_FN = ['processed_',datestr(now,'yyyy_mm_dd__hhMM')]; +trackDir = dir('*track.mat'); +fileName = extractBefore(trackDir.name,'_track.mat'); +extractFolder = [fileName '_extraction']; +mkdir(['extracted' filesep extractFolder filesep processed_FN]); + + +% copy over tracking file +disp('Copying Track File') +copyfile(trackDir.name, 'extracted'); + +% copy over alignment file +disp('Copying Alignment File') +copyfile('Alignment.mat', ['extracted' filesep extractFolder filesep processed_FN]); + +% convert ROI data +disp('Converting ROI data...'); +S = dir(fullfile(pwd,'*.mat')); +N = {S.name}; +X = contains(N,'CNMFe'); +out = load(N{X}, 'neuron_1'); +results = struct(out.neuron_1); +save(['extracted' filesep extractFolder filesep processed_FN filesep 'results'],'results'); + +% save tif to mat +disp('Loading video...'); +Y = read_file('DSampled.tif'); +Ysiz = size(Y); +disp('Saving video...'); +save(['extracted' filesep extractFolder filesep processed_FN filesep 'Motion_corrected_Data_DS.mat'],'Y','Ysiz') +clear Y Ysiz % clear data for memory resons + +cd(dateDir(i).folder); +end diff --git a/analysis_tobias/ImBat_Analyze.m b/analysis_tobias/ImBat_Analyze.m index 83cb82e..03ee6f4 100644 --- a/analysis_tobias/ImBat_Analyze.m +++ b/analysis_tobias/ImBat_Analyze.m @@ -14,25 +14,37 @@ % TAS % d07/24/2019 +% d04/19/2020 %topROI is top% of cells you want to look at topROI = 60; % Manual inputs analysisFlag = 1; reAnalyze = 1; +flightFixedFlag = 0; %roi plot flags plotROIFlag = 1; centroidFlag = 1; roiHeatFlag = 1; binaryMaskFlag = 1; %flight plot flags -plotFlightsFlag = 1; -flightPathsAllFlag = 1; -flightPathsFeederFlag = 1; +plotFlightsFlag = 0; +flightPathsAllFlag = 0; +clustManualFlag = 0; +flightPathsFeederFlag = 0; +plotFlightvsCellsFlag = 0; %place cells plot flags -plotPlaceCellsFlag = 1; +plotPlaceCellsFlag = 0; +plotPlaceCellsAng = 0; %snake/schnitz plot flags -plotSnakesFlag = 1; +plotSnakesFlag = 0; +plotSnakesManualFlag = 0; +plotPsthFlag = 0; +plotPSTHstableFlag = 0; +batId = 'Gen'; +galDate = 0; +%align max projections of specific flights across trajectories +plotROI3dayFlag = 0; % Get all folders in directory files = dir(pwd); @@ -48,24 +60,62 @@ end %% Perform analysis on each folder -for i = 1:length(subFolders) +for i = 1:2%length(subFolders)%[51,52,67,68,77,78]%[2,3,27,28,33,34]% disp(['entering folder ', char(subFolders(i).name)]) cd([subFolders(i).folder,'/',subFolders(i).name]); + % if AngeloData == 1 + % trackFiles = dir('*track.mat'); + % cnmfeFiles = dir('CNMFe*'); + % % load tracking and cell data + % if analysisFlag == 1 + % trackData = load([trackFiles(1).folder,'/',trackFiles(1).name]); + % cellData = load([cnmfeFiles(1).folder,'/',cnmfeFiles(1).name]); + % videoData = load('Motion_corrected_Data.mat'); + % alignment = load('Alignment.mat'); + % alignment.out.video_timesDS = alignment.out.video_times(1:5:end); + % fileName = extractBefore(trackFiles(1).name,'_track'); %get filename for titles + % dateSesh = trackFiles(1).name(5:10); + % batName = trackFiles(1).name(1:3); + % sessionType = extractAfter(fileName,[dateSesh '_']); + % % make new analysis directory for .fig and .jpg files + % cd([imageFolders(kk).folder,'/',imageFolders(kk).name]); + % mkdir('analysis'); + % disp('Analyzing!!'); + % end + % else + extractedFolderFlag = 0; + % Check if this folder is in the newer extracted version with an extracted folder or older version of cnmfe/extraction + subFolderFiles = dir(pwd); + subFolderFiles(ismember( {subFolderFiles.name}, {'.', '..','.DS_Store','Thumbs.db'})) = []; %remove . and .. and DS_Store + % Get a logical vector that tells which is a directory. + subDirFlags = [subFolderFiles.isdir]; + % Extract only those that are directories. + subDirFolders = subFolderFiles(subDirFlags); + % Print folder names to command window. + for k = 1 : length(subDirFolders) + fprintf('Sub folder #%d = %s\n', k, subDirFolders(k).name); + if strcmp(subDirFolders(k).name,'extracted') == 1 + cd([subDirFolders(k).folder,'/',subDirFolders(k).name]); + extractedFolderFlag = 1; + break + end + end % index every subfolder... trackFiles = dir('*track.mat'); + trackFiles(ismember( {trackFiles.name}, {'_track.mat'})) = []; %'_track.mat' imageFolders = dir('*_extraction'); %print image data folder names for kk = 1 : length(imageFolders) fprintf('Image data folder #%d = %s\n', kk, imageFolders(kk).name); %check that track data matches image data - if strcmp(imageFolders(kk).name(1:end-10),trackFiles(kk).name(1:end-9)) == 0 - fprintf('Tracking and image data do not match'); - analysisFlag = 0; - end + % if strcmp(imageFolders(kk).name(1:end-10),trackFiles(kk).name(1:end-9)) == 0 + % fprintf('Tracking and image data do not match'); + % analysisFlag = 0; + % end % Check if folder exists - if exist([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis'])>0; + if exist([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis*'])>0; disp('Folder already analyzed..'); if reAnalyze ==1 disp('Re-Analyzing...'); @@ -75,161 +125,259 @@ end end + processedFolders = dir([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed*']); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + + + % load tracking and cell data if analysisFlag == 1 trackData = load([trackFiles(kk).folder,'/',trackFiles(kk).name]); - cellData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS_results.mat']); - videoData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS.mat']); - alignment = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Alignment.mat']); + alignment = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/',processedNewest,'/','Alignment.mat']); + if flightFixedFlag == 1 && numel(fieldnames(trackData)) < 5 + load('\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\210113\2ROI_Data_za190524_za190527_za190528_za190529_za190530.mat'); + %trackData.AnalogFrameRate = 120; + %trackData.AnalogySignals = ROI_Data{kk}.Alignment.out.Flights_Repaired; + %trackData.VideoFrameFrate = 120; + trackData.Markers_Original = trackData.Markers; + trackData = rmfield(trackData,'Markers'); + marker_temp = ROI_Data{i}.Alignment.out.Flights_Repaired; + for dim_i = 1:3 + + trackData.Markers(:,1,dim_i) = marker_temp(:,dim_i); + + end + %trackData.Markers = ROI_Data{kk}.Alignment.out.Flights_Repaired; + %trackData.Markers = cat(3,trackData.Markers,zeros(size(ROI_Data{kk}.Alignment.out.Flights_Repaired))); + %trackData.Markers = cat(3,trackData.Markers,zeros(size(ROI_Data{kk}.Alignment.out.Flights_Repaired))); + + % for dim_i = 1:3 +% %trackData.Markers(:,dim_i) = ROI_Data{kk}.Alignment.out.Flights_Repaired(:,dim_i); +% trackData.Markers(:,dim_i,:) = cat(3,trackData.Markers,zeros(size(ROI_Data{kk}.Alignment.out.Flights_Repaired,1),3)); +% end + align_temp = ROI_Data{i}.Alignment; + alignment.out.Location_Original = alignment.out.Location; + alignment.out.Location = align_temp.out.Flights_Repaired; + save([trackFiles(kk).folder,'/',trackFiles(kk).name],'-struct','trackData'); + save([imageFolders(kk).folder,'/',imageFolders(kk).name,'/',processedNewest,'/','Alignment.mat'],'-struct','alignment'); + end + cellData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/',processedNewest,'/','results.mat']);%'Motion_corrected_Data_DS_results.mat']); + videoData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/',processedNewest,'/','Motion_corrected_Data_DS.mat']); + video_timesDS = alignment.out.video_times(1:5:end); + alignment.out.video_timesDS = video_timesDS; fileName = extractBefore(imageFolders(kk).name,'_extraction'); %get filename for titles - dateSesh = imageFolders(kk).folder(end-5:end); + if extractedFolderFlag == 1 + dateSesh = imageFolders(kk).folder(end-15:end-10); + else + dateSesh = imageFolders(kk).folder(end-5:end); + end batName = extractBefore(fileName,['_' dateSesh]); sessionType = extractAfter(fileName,[dateSesh '_']); - % make new analysis directory for .fig and .tif files + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' processedNewest '/Alignment.mat'],'video_timesDS','-append'); + % make new analysis directory for .fig and .jpg files cd([imageFolders(kk).folder,'/',imageFolders(kk).name]); - mkdir('analysis'); + analysis_Folder = ['analysis_',datestr(now,'yyyy_mm_dd__hhMM')]; + mkdir(analysis_Folder); disp('Analyzing!!'); end -% if strcmp(extractBefore(sessionType,'-'),'fly') -% plotFlightsFlag = 1; -% flightPathsAllFlag = 1; -% flightPathsFeederFlag = 1; -% plotPlaceCellsFlag = 1; -% else -% plotFlightsFlag = 0; -% flightPathsAllFlag = 0; -% flightPathsFeederFlag = 0; -% plotPlaceCellsFlag = 0; -% end + %end + % if strcmp(extractBefore(sessionType,'-'),'fly') + % plotFlightsFlag = 1; + % flightPathsAllFlag = 1; + % flightPathsFeederFlag = 1; + % plotPlaceCellsFlag = 1; + % else + % plotFlightsFlag = 0; + % flightPathsAllFlag = 0; + % flightPathsFeederFlag = 0; + % plotPlaceCellsFlag = 0; + % end %%perform basic sanity checks on imaging and flight data if plotROIFlag == 1 - mkdir('analysis/ROI'); + mkdir([analysis_Folder filesep 'ROI']); % max projection from each session without ROI overlay [Ymax, Y, maxFig] = ImBat_Dff(videoData.Y,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); hold on %save fig and tif of max projection - set(findall(maxFig,'-property','FontSize'),'FontSize',20); - savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.fig']); - saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.tif']); + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProject.fig']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProject.jpg']); % max projection with ROI overlay - [ROIoverlay] = ImBat_ROIoverlay(cellData.results,videoData.Ysiz,centroidFlag,binaryMaskFlag,roiHeatFlag,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + [ROIoverlay,correlationImage,centroidMax] = ImBat_ROIoverlay(cellData.results,'centroid',centroidFlag,'binarymask',binaryMaskFlag,'roiheat',roiHeatFlag,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(correlationImage,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_correlationImage.fig']); + saveas(correlationImage, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_correlationImage.jpg']); + if centroidFlag == 1 || binaryMaskFlag == 1 %save fig and tif of max projection - set(findall(maxFig,'-property','FontSize'),'FontSize',20); - savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.fig']); - saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.tif']); + %set(findall(centroidMax,'-property','FontSize'),'FontSize',20); + savefig(centroidMax,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProjectROI.fig']); + saveas(centroidMax, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProjectROI.jpg']); end if roiHeatFlag == 1 - set(findall(ROIoverlay,'-property','FontSize'),'FontSize',20); - savefig(ROIoverlay,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.fig']); - saveas(ROIoverlay, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.tif']); + %set(findall(ROIoverlay,'-property','FontSize'),'FontSize',20); + savefig(ROIoverlay,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProjectROIheatMap.fig']); + saveas(ROIoverlay, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/ROI/' fileName '_maxProjectROIheatMap.jpg']); end hold off end %plot flights in 3d and their clusters if plotFlightsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') - mkdir('analysis/flights') + mkdir([analysis_Folder filesep 'flights']) %plot all flights in 3D if flightPathsAllFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') - [flightPaths] = ImBat_plotFlights(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); - save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'flightPaths'); - set(findall(flightPaths.flightPathsAll,'-property','FontSize'),'FontSize',20); - savefig(flightPaths.flightPathsAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.fig']); - saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.tif']); - set(findall(flightPaths.flightPathsStartStop,'-property','FontSize'),'FontSize',20); - savefig(flightPaths.flightPathsStartStop,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.fig']); - saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.tif']); - set(findall(flightPaths.flightPathsClusterEach,'-property','FontSize'),'FontSize',20); - savefig(flightPaths.flightPathsClusterEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.fig']); - saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.tif']); - set(findall(flightPaths.flightPathsClusterAll,'-property','FontSize'),'FontSize',20); - savefig(flightPaths.flightPathsClusterAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.fig']); - saveas(flightPaths.flightPathsClusterAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.tif']); + %[flightPaths] = ImBat_plotFlights(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType,'clustmanualflag',clustManualFlag); + [flightPaths] = ImBat_flightsAng(trackData,alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType,'day_i',kk); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/' fileName '_flightPaths.mat'],'flightPaths'); + %set(findall(flightPaths.flightPathsAll,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAll.fig']); + saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAll.jpg']); + saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAll.svg']); + %set(findall(flightPaths.flightPathsStartStop,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsStartStop,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAllStartStop.fig']); + saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAllStartStop.jpg']); + saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsAllStartStop.svg']); + %set(findall(flightPaths.flightPathsClusterEach,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsClusterEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterEach.fig']); + saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterEach.jpg']); + saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterEach.svg']); + savefig(flightPaths.flightTimeline,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightTimeline.fig']); + saveas(flightPaths.flightTimeline, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightTimeline.jpg']); + saveas(flightPaths.flightTimeline, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightTimeline.svg']); + savefig(flightPaths.clusterDistance,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_clusterDistance.fig']); + saveas(flightPaths.clusterDistance, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_clusterDistance.jpg']); + saveas(flightPaths.clusterDistance, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_clusterDistance.svg']); + %set(findall(flightPaths.flightPathsClusterAll,'-property','FontSize'),'FontSize',20); + %savefig(flightPaths.flightPathsClusterAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterAll.fig']); + %saveas(flightPaths.flightPathsClusterAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterAll.jpg']); end %plot flights to/from feeder in 3D if flightPathsFeederFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') [flightPathsToFeeder, flightPathsFromFeeder,flightPathsClusterToFeederEach, flightPathsClusterToFeederAll, flightFeedersStartStop] = ImBat_plotFlightsToFeeder(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); - set(findall(flightPathsToFeeder,'-property','FontSize'),'FontSize',20); - savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); - saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); - set(findall(flightPathsFromFeeder,'-property','FontSize'),'FontSize',20); - savefig(flightPathsFromFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.fig']); - saveas(flightPathsFromFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.tif']); - set(findall(flightPathsClusterToFeederEach,'-property','FontSize'),'FontSize',20); - savefig(flightPathsClusterToFeederEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.fig']); - saveas(flightPathsClusterToFeederEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.tif']); - set(findall(flightPathsClusterToFeederAll,'-property','FontSize'),'FontSize',20); - savefig(flightPathsClusterToFeederAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.fig']); - saveas(flightPathsClusterToFeederAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.tif']); - save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightsToFromFeeders.mat'],... + %set(findall(flightPathsToFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsToFeeder.fig']); + saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsToFeeder.jpg']); + %set(findall(flightPathsFromFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsFromFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsFromFeeder.fig']); + saveas(flightPathsFromFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsFromFeeder.jpg']); + %set(findall(flightPathsClusterToFeederEach,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterToFeederEach.fig']); + saveas(flightPathsClusterToFeederEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterToFeederEach.jpg']); + %set(findall(flightPathsClusterToFeederAll,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterToFeederAll.fig']); + saveas(flightPathsClusterToFeederAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightPathsClusterToFeederAll.jpg']); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/' fileName '_flightsToFromFeeders.mat'],... 'flightFeedersStartStop'); end - %plot flights over traces - load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis','/',fileName '_flightPaths.mat']); - [flightVsVelocity,smoothAvgSpiking,smoothVelocity] = ImBat_plotFlightsVsCells(cellData,alignment,flightPaths,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); - save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'smoothVelocity','smoothAvgSpiking','-append'); - set(findall(flightVsVelocity,'-property','FontSize'),'FontSize',20); - savefig(flightVsVelocity,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.fig']); - saveas(flightVsVelocity, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.tif']); + % plot flights over traces + if plotFlightvsCellsFlag == 1 + %load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/',analysis_Folder,'/',fileName '_flightPaths.mat']); + [flightVsVelocity,smoothAvgSpiking,smoothVelocity] = ImBat_plotFlightsVsCells(cellData,alignment,flightPaths,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/' fileName '_flightPaths.mat'],'smoothVelocity','smoothAvgSpiking','-append'); + %set(findall(flightVsVelocity,'-property','FontSize'),'FontSize',20); + savefig(flightVsVelocity,[imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightVsVelocity.fig']); + saveas(flightVsVelocity, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/flights/' fileName '_flightVsVelocity.jpg']); + end end - - %number of total flights and rewarded flights - %numTotalFlights = length(flightPaths.flight_starts_idx); - %numRewardedFlights = length(flightFeedersStartStop.flightToFeederStart); - - %variability of flights - %covariance matrix - - %place cells - %spike activity over flight trajectories - if plotPlaceCellsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') - mkdir('analysis/placeCells') - cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/placeCells']) - ImBat_PlaceCells_Tobias(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) - savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); - saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); - - end - - %snake plots: raw fluorescent traces for each cell sorted by timing of - %peak activity for the smoothed zscored mean across all trials in a cluster - if plotSnakesFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') - cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis']) - mkdir('snakePlots') - cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/snakePlots']) - %load([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/',batName,'_',dateSesh,'_',sessionType,'_flightPaths.mat']); - [snakeTrace] = ImBat_snakeData(cellData,flightPaths,alignment) - [snakeTrace] = ImBat_plotSnake(snakeTrace) - saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clust.svg']); - saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.svg']); - saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.svg']); - saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); - saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); - saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustAll.tif']); - saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.tif']); - saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.tif']); - saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.tif']); - saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.tif']); - saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.tif']); - saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.svg']); - saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.tif']); - saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); - - save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakePlotData.mat'],'snakeTrace'); - savefig(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustAll.fig']); - savefig(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.fig']); - savefig(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.fig']); - savefig(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); - savefig(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.fig']); - savefig(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_prefAll.fig']); - savefig(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.fig']); - - end - - close all; + + %number of total flights and rewarded flights + %numTotalFlights = length(flightPaths.flight_starts_idx); + %numRewardedFlights = length(flightFeedersStartStop.flightToFeederStart); + + %variability of flights + %covariance matrix + + %place cells + %spike activity over flight trajectories + if plotPlaceCellsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/placeCells']); + cd([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/placeCells']); + ImBat_PlaceCells_Tobias(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + end + if plotPlaceCellsAng == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/placeCellsAng']); + cd([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/placeCellsAng']); + %ImBat_placeCells_Ang(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + ImBat_placeCells_Will(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + + end + + + %snake plots: raw fluorescent traces for each cell sorted by timing of + %peak activity for the smoothed zscored mean across all trials in a cluster + if plotSnakesFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + galDate = galDate + 1; + cd([imageFolders(kk).folder ,'/',imageFolders(kk).name,'/' analysis_Folder]) + mkdir('snakePlots') + cd([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/snakePlots']) + %load([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/' analysis_Folder '/',batName,'_',dateSesh,'_',sessionType,'_flightPaths.mat']); + if plotSnakesManualFlag == 1 + [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData_manualStable(cellData,flightPaths,alignment,'galdate',galDate); + else + [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData(cellData,flightPaths,alignment); + end + [snakeTrace_plots] = ImBat_plotSnake(snakeTrace_cRaw); + %add the 3 data sets to snakeTrace + snakeTrace.cRaw = snakeTrace_cRaw; + snakeTrace.c = snakeTrace_c; + snakeTrace.s = snakeTrace_s; + + saveas(snakeTrace_plots.snakePlot_clust, [imageFolders(kk).folder filesep imageFolders(kk).name filesep analysis_Folder filesep 'snakePlots' filesep fileName '_snakePlots_clust.svg']); + saveas(snakeTrace_plots.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustOddEven.svg']); + saveas(snakeTrace_plots.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustBy1.svg']); + saveas(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakeTrace_plots.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); + saveas(snakeTrace_plots.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustAll.jpg']); + saveas(snakeTrace_plots.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustOddEven.jpg']); + saveas(snakeTrace_plots.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustBy1.jpg']); + saveas(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.jpg']); + saveas(snakeTrace_plots.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.jpg']); + saveas(snakeTrace_plots.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefAll.jpg']); + saveas(snakeTrace_plots.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefAll.svg']); + saveas(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.jpg']); + saveas(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); + + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/' fileName '_snakePlotData.mat'],'snakeTrace'); + savefig(snakeTrace_plots.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustAll.fig']); + savefig(snakeTrace_plots.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustOddEven.fig']); + savefig(snakeTrace_plots.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_clustBy1.fig']); + savefig(snakeTrace_plots.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); + savefig(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.fig']); + savefig(snakeTrace_plots.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlots_prefAll.fig']); + savefig(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.fig']); + + %plot psth of each cell for every cluster on the same day + if plotPsthFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/psthPlots']); + cd([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/psthPlots']); + ImBat_psth_allClust(flightPaths, snakeTrace_cRaw,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + end + %plot psth of only the pre-defined stable ROIs including across + %all days overlaid + if plotPSTHstableFlag == 1 && strcmp(extractBefore(sessionType,'-'),'Gal_200320_fly') || plotPSTHstableFlag == 1 && strcmp(extractBefore(sessionType,'-'),'Gen_200324_fly') + [psth_stableROI] = ImBat_psth_stableROI('batid',batId,'saveflag',1,'plotpsthclustflag',1); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/' analysis_Folder '/' fileName '_psth_stableROIdata.mat'],'psth_stableROI'); + + end + end + + %snake plots: raw fluorescent traces for each cell sorted by timing of + %peak activity for the smoothed zscored mean across all trials in a cluster + if plotROI3dayFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + cd([imageFolders(kk).folder ,'/',imageFolders(kk).name,'/' analysis_Folder]) + mkdir('roi3day') + cd([imageFolders(kk).folder,'/',imageFolders(kk).name,'/' analysis_Folder '/roi3day']) + %load([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/' analysis_Folder '/',batName,'_',dateSesh,'_',sessionType,'_flightPaths.mat']); + [roi3day] = ImBat_roi3day(videoData,flightPaths,alignment) + + end + + close all; end -close all; + close all; end \ No newline at end of file diff --git a/analysis_tobias/ImBat_Analyze_edit.m b/analysis_tobias/ImBat_Analyze_edit.m new file mode 100644 index 0000000..6a1394c --- /dev/null +++ b/analysis_tobias/ImBat_Analyze_edit.m @@ -0,0 +1,254 @@ +function ImBat_Analyze_edit + +global topROI + +% Main wrapper for all analyzing bat calcium imaging and flight data. +% Goals: +% 1. Sanity checks: max projection w/ ROI overlay, flight + traces, flights in 3d +% 2. Quantify behavior: #total flights, #rewarded flights, variability of +% flights (covariance matrix), stability of flights over days (Karthik code) +% 3. Cells aligned to behavior: +% a. Place cell plots: heat maps, plot3, schnitzer plots +% b. Preflight activity: 2 sec, 20 sec before +% c. Postflight activity: 2 sec, 20 sec, rewarded vs nonrewarded + +% TAS +% d07/24/2019 + +%topROI is top% of cells you want to look at +topROI = 60; +% Manual inputs +analysisFlag = 1; +reAnalyze = 1; +%roi plot flags +plotROIFlag = 0; +centroidFlag = 0; +roiHeatFlag = 0; +binaryMaskFlag = 0; +%flight plot flags +plotFlightsFlag = 1; +flightPathsAllFlag = 1; +flightPathsFeederFlag = 1; +%place cells plot flags +plotPlaceCellsFlag = 0; +%snake/schnitz plot flags +plotSnakesFlag = 1; + +% Get all folders in directory +files = dir(pwd); +files(ismember( {files.name}, {'.', '..','.DS_Store','Thumbs.db'})) = []; %remove . and .. and DS_Store + +% Get a logical vector that tells which is a directory. +dirFlags = [files.isdir]; +% Extract only those that are directories. +subFolders = files(dirFlags); +% Print folder names to command window. +for k = 1 : length(subFolders) + fprintf('Date folder #%d = %s\n', k, subFolders(k).name); +end + +%% Perform analysis on each folder +for i = 1:length(subFolders) + disp(['entering folder ', char(subFolders(i).name)]) + cd([subFolders(i).folder,'/',subFolders(i).name]); + + % index every subfolder... + trackFiles = dir('*track.mat'); + imageFolders = dir('*_extraction'); + %print image data folder names + for kk = 1 : length(imageFolders) + fprintf('Image data folder #%d = %s\n', kk, imageFolders(kk).name); + %check that track data matches image data + if strcmp(imageFolders(kk).name(1:end-10),trackFiles(kk).name(1:end-9)) == 0 + fprintf('Tracking and image data do not match'); + analysisFlag = 0; + end + + % Check if folder exists + if exist([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis'])>0; + disp('Folder already analyzed..'); + if reAnalyze ==1 + disp('Re-Analyzing...'); + else + disp('Moving to the next folder...'); + analysisFlag = 0 ; + end + end + + % load tracking and cell data + if analysisFlag == 1 + trackData = load([trackFiles(kk).folder,'/',trackFiles(kk).name]); + cellDir = dir([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','CNMFe_*' '.mat']); + cellData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/',cellDir.name]); + cellData.results = cellData.neuron_1; + %cellData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS_results.mat']); + videoData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS.mat']); + alignment = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Alignment.mat']); + fileName = extractBefore(imageFolders(kk).name,'_extraction'); %get filename for titles + dateSesh = imageFolders(kk).folder(end-5:end); + batName = extractBefore(fileName,['_' dateSesh]); + sessionType = extractAfter(fileName,[dateSesh '_']); + % make new analysis directory for .fig and .tif files + cd([imageFolders(kk).folder,'/',imageFolders(kk).name]); + mkdir('analysis'); + disp('Analyzing!!'); + end +% if strcmp(extractBefore(sessionType,'-'),'fly') +% plotFlightsFlag = 1; +% flightPathsAllFlag = 1; +% flightPathsFeederFlag = 1; +% plotPlaceCellsFlag = 1; +% else +% plotFlightsFlag = 0; +% flightPathsAllFlag = 0; +% flightPathsFeederFlag = 0; +% plotPlaceCellsFlag = 0; +% end + %%perform basic sanity checks on imaging and flight data + if plotROIFlag == 1 + mkdir('analysis/ROI'); + % max projection from each session without ROI overlay + [Ymax, Y, maxFig] = ImBat_Dff(videoData.Y,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + hold on + %save fig and tif of max projection + set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.fig']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.tif']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.svg']); + % max projection with ROI overlay + [ROIoverlay] = ImBat_ROIoverlay(cellData.results,videoData.Ysiz,centroidFlag,binaryMaskFlag,roiHeatFlag,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + if centroidFlag == 1 || binaryMaskFlag == 1 + %save fig and tif of max projection + set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.fig']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.tif']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.svg']); + end + if roiHeatFlag == 1 + set(findall(ROIoverlay,'-property','FontSize'),'FontSize',20); + savefig(ROIoverlay,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.fig']); + saveas(ROIoverlay, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.tif']); + saveas(ROIoverlay, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.svg']); + end + hold off + end + + %plot flights in 3d and their clusters + if plotFlightsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir('analysis/flights') + %plot all flights in 3D + if flightPathsAllFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + [flightPaths] = ImBat_plotFlights(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'flightPaths'); + set(findall(flightPaths.flightPathsAll,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.fig']); + saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.tif']); + saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.svg']); + set(findall(flightPaths.flightPathsStartStop,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsStartStop,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.fig']); + saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.tif']); + saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.svg']); + set(findall(flightPaths.flightPathsClusterEach,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsClusterEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.fig']); + saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.tif']); + saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.svg']); + set(findall(flightPaths.flightPathsClusterAll,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsClusterAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.fig']); + saveas(flightPaths.flightPathsClusterAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.tif']); + saveas(flightPaths.flightPathsClusterAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.svg']); + end + %plot flights to/from feeder in 3D + if flightPathsFeederFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + [flightPathsToFeeder, flightPathsFromFeeder,flightPathsClusterToFeederEach, flightPathsClusterToFeederAll, flightFeedersStartStop] = ImBat_plotFlightsToFeeder(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + set(findall(flightPathsToFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); + saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); + saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.svg']); + set(findall(flightPathsFromFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsFromFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.fig']); + saveas(flightPathsFromFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.tif']); + saveas(flightPathsFromFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.svg']); + set(findall(flightPathsClusterToFeederEach,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.fig']); + saveas(flightPathsClusterToFeederEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.tif']); + saveas(flightPathsClusterToFeederEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.svg']); + set(findall(flightPathsClusterToFeederAll,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.fig']); + saveas(flightPathsClusterToFeederAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.tif']); + saveas(flightPathsClusterToFeederAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.svg']); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightsToFromFeeders.mat'],... + 'flightFeedersStartStop'); + end + %plot flights over traces + load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis','/',fileName '_flightPaths.mat']); + [flightVsVelocity,smoothAvgSpiking,smoothVelocity] = ImBat_plotFlightsVsCells(cellData,alignment,flightPaths,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'smoothVelocity','smoothAvgSpiking','-append'); + set(findall(flightVsVelocity,'-property','FontSize'),'FontSize',20); + savefig(flightVsVelocity,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.fig']); + saveas(flightVsVelocity, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.tif']); + saveas(flightVsVelocity, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.svg']); + end + + %number of total flights and rewarded flights + %numTotalFlights = length(flightPaths.flight_starts_idx); + %numRewardedFlights = length(flightFeedersStartStop.flightToFeederStart); + + %variability of flights + %covariance matrix + + %place cells + %spike activity over flight trajectories + if plotPlaceCellsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + load(['analysis/' batName '_' dateSesh '_' sessionType '_flightPaths.mat']); + load(['analysis/' batName '_' dateSesh '_' sessionType '_flightsToFromFeeders.mat']); + + mkdir('analysis/placeCells') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/placeCells']) + ImBat_PlaceCells_Tobias(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + %savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); + %saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); + %saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.svg']); + + end + + %snake plots: raw fluorescent traces for each cell sorted by timing of + %peak activity for the smoothed zscored mean across all trials in a cluster + if plotSnakesFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis']) + mkdir('snakePlots') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/snakePlots']) + %load([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/',batName,'_',dateSesh,'_',sessionType,'_flightPaths.mat']); + [snakeTrace] = ImBat_snakeData(cellData,flightPaths,alignment) + [snakeTrace] = ImBat_plotSnake(snakeTrace) + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clust.svg']); + saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.svg']); + saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.svg']); + saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustAll.tif']); + saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.tif']); + saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.tif']); + saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.tif']); + saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.tif']); + saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.tif']); + saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.svg']); + saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.tif']); + saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); + + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakePlotData.mat'],'snakeTrace'); + savefig(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustAll.fig']); + savefig(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.fig']); + savefig(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.fig']); + savefig(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); + savefig(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.fig']); + savefig(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_prefAll.fig']); + savefig(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.fig']); + + end + + close all; + end + + +close all; +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_Dff_forMY_200714.m b/analysis_tobias/ImBat_Dff_forMY_200714.m new file mode 100644 index 0000000..c188560 --- /dev/null +++ b/analysis_tobias/ImBat_Dff_forMY_200714.m @@ -0,0 +1,91 @@ +function [Ymax, Y, maxFig] = ImBat_Dff_forMY_200714(Y,varargin); + +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; +% ImBat_Dff +scaling = 10; +minLimMult = 0; %0 5 min limit multiplier for max projections +maxLimMult = 10; %28 20 max limit multiplier for max projections +%filt_rad = 10; +%filt_alpha = 2; + gSig = 1; + gSiz = 4.5*gSig; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'filt_rad' + filt_rad = varargin{i+1}; + filt_alpha = filt_rad; + end +end + + + + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + date = strcat(lower(batName(1:2)),dateSesh); + label = [batName '_' dateSesh '_' sessionType]; + processedFolders = dir('processed*'); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + load([pwd processed_Newest '/Motion_corrected_Data_DS.mat']); +end + +% Make df/f image + +% Filter movie +% filtering +% h=fspecial('gaussian',filt_rad,filt_alpha); +% Y=imfilter(Y,h,'circular'); +% Y = (convn(Y, single(reshape([1 1 1] /10, 1, 1, [])), 'same')); + %make gaussian filter based on normcorre function + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + Y = imfilter(Y,psf,'symmetric'); + +% Take median of movie +Y_med = median(Y,3); + +% Subtract median +Y = Y-Y_med; + +% take max +Ymax = max(Y,[],3); +Ymax = imresize(Ymax,scaling); +maxFig = figure(); +colormap(gray); +%imagesc(Ymax,[0 10]); +imagesc(Ymax,[abs(min(min(Ymax)))*minLimMult abs(min(min(Ymax)))*maxLimMult]);% max(max(Ymax))*maxLimMult]); +set(gca,'YDir','normal'); +hold on; +%xticks = get(gca,'xtick'); +%yticks = get(gca,'ytick'); +%scaling_pixel = 1.1; %1.1um per pixel +%newlabelsX = arrayfun(@(ax) sprintf('%g', scaling_pixel * ax), xticks, 'un', 0); +%newlabelsY = arrayfun(@(ay) sprintf('%g', scaling_pixel * ay), yticks, 'un', 0); +%set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +title(['Max Projection dFF: ' batName ' ' dateSesh ' ' sessionType]); +%xlabel('um'); ylabel('um'); +%axis off +colorbar%('southoutside') + + + + + + diff --git a/analysis_tobias/ImBat_PlaceCells_Tobias.m b/analysis_tobias/ImBat_PlaceCells_Tobias.m index a395f80..4c10610 100644 --- a/analysis_tobias/ImBat_PlaceCells_Tobias.m +++ b/analysis_tobias/ImBat_PlaceCells_Tobias.m @@ -1,9 +1,8 @@ function [plotFiringTrajectory] = ImBat_PlaceCells_Tobias(flightPaths, cellData, alignment,varargin) - -offset = 0.1; % account for slow calcium estimation ~move locations back 100ms in time... This is the knob to turn for 'prospective' coding... -spikeThresh = 0.1; %threshold for eliminating noise from the S matrix - +offset = 0; % account for slow calcium estimation ~move locations back 100ms in time... This is the knob to turn for 'prospective' coding... +spikeThreshMult = 5; %number of times to multiply std of s vector for determining spike threshold +speedThresh = 0.7; %threshold for when to eliminate nonflying moments batName = []; dateSesh = []; sessionType = []; @@ -21,6 +20,8 @@ sessionType = varargin{i+1}; case 'loadflag' loadFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; end end @@ -31,78 +32,145 @@ %label = [dateSesh '_' sessionType]; cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); alignment = load([pwd '/processed/Alignment.mat']); - load([pwd '/analysis/' label '_flightPaths.mat']); + load([pwd '/' analysis_Folder '/' label '_flightPaths.mat']); end % Remove that pesky first flight that starts at 0:0; -a = find(alignment.out.flights(:,1) == 0); -a2 = isnan(alignment.out.flights(a(1):end,1)); -a3 = find(a2>0); -alignment.out.flights(a(1):a(1)+a3(1),:) = NaN; -alignment.out.Location2 = alignment.out.flights; - -% Plot the location in space that each cell is active -plotFiringTrajectory = figure(); +try + a = find(alignment.out.flights(:,1) == 0); + a2 = isnan(alignment.out.flights(a(1):end,1)); + a3 = find(a2>0); + alignment.out.flights(a(1):a(1)+a3(1),:) = NaN; + alignment.out.Location2 = alignment.out.flights; +catch +end +% Plot the location in space that each cell is active in 1 figure +plotFiringTrajectory = figure('units','normalized','outerposition',[0 0 0.8 1]); +sgtitle([batName ' ' dateSesh ': Firing Fields']); +ha = tight_subplot(ceil(length(cellData.results.S(:,1))/5),5,[.02 .01],[.01 .08],[.01 .01]); for ii = 1:length(cellData.results.S(:,1)); % for each cell + set(0,'CurrentFigure',plotFiringTrajectory); + axes(ha(ii)); + %a1 = subplot(ceil(length(cellData.results.S(:,1))/5),5,ii); hold on; - %plot(alignment.out.flights(:,1),alignment.out.flights(:,2),'k','LineWidth',2);% plot the flight trajectory in space - plot3(alignment.out.flights(:,1),alignment.out.flights(:,2),alignment.out.flights(:,3),'k');%,'LineWidth',2);% plot the flight trajectory in space - - - [~,xy] = find(cellData.results.S(ii,:)>spikeThresh); % get time neuron is active - xy = xy(xyspikeThresh(ii)); % get time neuron is active + xy = xy(xy0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'ROI_covar_refined']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'ROI_covar_refined' filesep]; + + +distThresh = 10; %number of pixels to check if the cells are close enough to be considered same cell +corrThresh = 0.65; %max correlation of time series if cells are very close +scaling = 5; % 5x but depends on size of frame and downsampling from extraction step +minLim = 0.7; %limits for correlation imagesc +maxLim = 1; %limits for correlation imagesc +distThresh = distThresh * scaling; + +g = dir('Ga*'); +z = dir('Z1*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +ROI_duplicate = cell(length(dirTop),1); %make cell for indices of duplicated ROIS +ROI_unique = cell(length(dirTop),1); %make cell for unique indices +distance = cell(length(dirTop),1); %make cell for recording pairwise distances of ROIS +timeCorrClose = cell(length(dirTop),1);%make cell for recording correlation between time series of nearby ROIs +ROI_coords = cell(length(dirTop),1); +centroid = cell(length(dirTop),1); +timeCorrAll = cell(length(dirTop),1); %correlation coefficients between all ROIs pairwise +corrIndClose = cell(length(dirTop),1); %make cell for indices of correlations between close cells +corrIndAll = cell(length(dirTop),1); %make cell for indices of correlations across all pairwise cells +timeCorrS = cell(length(dirTop),1); %make cell for indices of correlations across all pairwise cells with S matrix +timeCorrCloseS = cell(length(dirTop),1); %make cell for indices of correlations across all close cells with S matrix +corrIndCloseS = cell(length(dirTop),1); %make cell for indices of correlations between close cells with S matrix +corrIndAllS = cell(length(dirTop),1); %make cell for indices of correlations across all pairwise cells with S matrix +spikeSmooth = cell(length(dirTop),1); %make cell for smoothed S matrix + +for d = 1:length(dirTop) + plot_ROI_refined = figure('units','normalized','outerposition',[0 0 0.9 0.9]); + try %extract metadata names and enter processed folder + cd([dirTop(d).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + batName{d} = flyFolders(end).name(1:3); + dateSesh{d} = flyFolders(end).name(5:10); + sessionType{d} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + if strcmp(batName{d}(1),'G') + cd(dirProcessed(end).name); + else + cd(dirProcessed(end).name); + end + catch + cd(dirTop(d).name); + flyFolders = dir('*fly*extraction'); + batName{d} = flyFolders(end).name(1:3); + dateSesh{d} = flyFolders(end).name(5:10); + sessionType{d} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + end + + load('results.mat'); + %convert A matrix into full matrix + Atemp = full(results.A); + Ysiz = size(results.Cn); + %make array for coordinates of each cell + ROI_coords{d} = cell(length(results.A(1,:)),2); + centroid{d} = zeros(length(results.A(1,:)),2); + + % get ROI centroids for each cell; + for i = 1:round(length(results.A(1,:))) + %create 3d matrix with all ROI heat maps + ROI2plot(:,:,i) = mat2gray(reshape(Atemp(:,i),Ysiz(1),Ysiz(2))); + %binarize the coordinates into mask + binaryImage = imbinarize(mat2gray(reshape(Atemp(:,i),Ysiz(1),Ysiz(2)))); + [y,x]=find(binaryImage); + %get ROI coordinates + ROI_coords{d}(i,1) = {x*scaling}; + ROI_coords{d}(i,2) = {y*scaling}; + %calculate centroids + centroid{d}(i,1) = mean(ROI_coords{d}{i,1});%*scaling; + centroid{d}(i,2) = mean(ROI_coords{d}{i,2});%*scaling;%get the centroid of mask + end + + %compare euclidian distance between centroids and the timeseries correlation between + %close ROIS + distance{d} = zeros(round(length(results.A(1,:)))); + timeCorrAll{d} = zeros(round(length(results.A(1,:)))); + timeCorrClose{d} = zeros(round(length(results.A(1,:)))); + for ii = 1:round(length(results.A(1,:))) + for iii = ii+1:round(length(results.A(1,:))) + distance{d}(ii,iii) = sqrt((centroid{d}(iii,1)-centroid{d}(ii,1))^2 + (centroid{d}(iii,2)-centroid{d}(ii,2))^2); %find distance between centroids + R1 = corrcoef(results.C_raw(ii,:),results.C_raw(iii,:)); %take correlation between two time series + timeCorrAll{d}(ii,iii) = R1(1,2); + + w = gausswin(10); %smooth the S matrix by gaussian window of 10 + spikeSmooth{d}(ii,:) = filter(w,1,full(results.S(ii,:))); + spikeSmooth{d}(iii,:) = filter(w,1,full(results.S(iii,:))); + RS = corrcoef(spikeSmooth{d}(ii,:),spikeSmooth{d}(iii,:)); %take correlation between two smooth close series + timeCorrS{d}(ii,iii) = RS(1,2); + if distance{d}(ii,iii) < distThresh %if closer than 10 pixels + %R = corrcoef(results.C_raw(ii,:),results.C_raw(iii,:)); %take correlation between two time series + timeCorrClose{d}(ii,iii) = R1(1,2); + %RSclose = corrcoef(spikeSmooth,spikeSmooth); %take correlation between two smooth close series + timeCorrCloseS{d}(ii,iii) = RS(1,2); + if timeCorrClose{d}(ii,iii) > corrThresh %if correlation is greater than 0.8 + if snr(zscore(smoothdata(results.C_raw(ii,:),'movmedian',3)),results.Fs) > snr(zscore(smoothdata(results.C_raw(iii,:),'movmedian',3)),results.Fs) %unique index is the time series with higher snr + ROI_duplicate{d} = [ROI_duplicate{d} iii]; %duplicated index is low snr signal + else + ROI_duplicate{d} = [ROI_duplicate{d} ii]; + end + end + end + end + end + %identify unique indices that were not duplicated + for u = 1:round(length(results.A(1,:))) + if ismember(u,ROI_duplicate{d}) == 0 + ROI_unique{d} = [ROI_unique{d} u]; + end + end +%% + %plot correlation image raw + sgtitle([num2str(distThresh/scaling) ' pixels :: ' num2str(corrThresh) ' corr']); + ax1 = subplot(length(results.C(:,1))+2,4,1:4:(length(results.C(:,1))*2)); + %subplot(length(results.C(:,1)),3,1:3:(length(results.C(:,1))*1.5)-2) + imagesc(imresize(results.Cn,scaling),[minLim maxLim]); + colormap(ax1,gray); + title([batName{d} ' ' dateSesh{d} ' ' sessionType{d} ': ' num2str(length(ROI_unique{d})) '/' num2str(length(results.A(1,:))) ' ROI']) + set(gca,'YDir','normal'); + axis 'off' + drawnow; + + %plot correlation image with unique cells in blue and replicates in red + remAdjust = rem(round(length(results.C(:,1))*2),8); + if remAdjust == 0; + adjust2 = 5; + adjust4 = 6; + elseif remAdjust == 6; + adjust2 = 7; + adjust4 = 8; + elseif remAdjust == 4; + adjust2 = 9; + adjust4 = 10; + elseif remAdjust == 2; + adjust2 = 11; + adjust4 = 12; + end + ax2 = subplot(length(results.C(:,1))+2,4,round(length(results.C(:,1))*2)+adjust2:4:length(results.C(:,1))*4); + %subplot(length(results.C(:,1)),3,round(length(results.C(:,1))*1.5)+2:3:length(results.C(:,1))*3) + imagesc(imresize(results.Cn,scaling),[minLim maxLim]); + colormap(ax2,gray); + %title([batName{d} ' ' dateSesh{d} ' ' sessionType{d} ': ' num2str(length(ROI_unique{d})) '/' num2str(length(results.A(1,:))) ' ROI']) + set(gca,'YDir','normal'); + axis 'off' %'tight' 'equal' + hold on + for i = 1:length(ROI_unique{d}) %plot unique ROIs in blue + try + p = plot(ROI_coords{d}{ROI_unique{d}(i),1},ROI_coords{d}{ROI_unique{d}(i),2},'b','LineWidth',4); + p.Color(4) = 0.1; + t = text(centroid{d}(ROI_unique{d}(i),1),centroid{d}(ROI_unique{d}(i),2),num2str(ROI_unique{d}(i))); + %t.Color(1:3) = col(i,:); + catch + end + end + for ii = 1:length(ROI_duplicate{d}) %plot duplicated ROIs in red + try + p = plot(ROI_coords{d}{ROI_duplicate{d}(ii),1},ROI_coords{d}{ROI_duplicate{d}(ii),2},'r','LineWidth',4); + p.Color(4) = 0.1; + t = text(centroid{d}(ROI_duplicate{d}(ii),1),centroid{d}(ROI_duplicate{d}(ii),2),num2str(ROI_duplicate{d}(ii))); + %t.Color(1:3) = col(ii,:); + catch + end + end + hold off + drawnow; + + %plot distance covariance matrix + distFull{d} = distance{d} + distance{d}.'; + ax3 = subplot(length(results.C(:,1))+2,4,2:4:round(length(results.C(:,1))*2)-8); + %subplot(length(results.C(:,1)),3,2:3:round(length(results.C(:,1))*1.5)-6) + imagesc(distFull{d}); + colormap(ax3,parula); + colorbar; + title('Distance between ROI pairs (um)'); + set(gca,'xtick',1:4:length(results.C(:,1)),'ytick',1:4:length(results.C(:,1))); + ylabel('ROI #'); + xlabel([]);%('ROI #'); + drawnow; + + %plot time correlation covariance matrix + timeCorrFull{d} = timeCorrClose{d} + timeCorrClose{d}.'; + ax4 = subplot(length(results.C(:,1))+2,4,round(length(results.C(:,1))*2)+adjust4:4:length(results.C(:,1))*4); + %subplot(length(results.C(:,1)),3,round(length(results.C(:,1))*1.5)+9:3:length(results.C(:,1))*3) + imagesc(timeCorrFull{d}); + colormap(ax4,parula); + colorbar; + title('Correlation coefficient of nearby ROI pairs'); + set(gca,'xtick',1:4:length(results.C(:,1)),'ytick',1:4:length(results.C(:,1))); + ylabel('ROI #'); + xlabel('ROI #'); + drawnow; + + %plot traces for each ROI + subArea1 = 3:4:4*length(results.C(:,1)); + subArea2 = 4:4:4*length(results.C(:,1)); + subAreaComb = [subArea1,subArea2]; + ax5 = subplot(length(results.C(:,1))+2,4,subAreaComb');%3:3:length(results.C(:,1))*3) + %subplot(length(results.C(:,1)),3,3:3:length(results.C(:,1))*3) + hold on + normSmoothData = zeros(length(results.C(:,1)),length(results.C(1,:))); + for i = 1:length(results.C(:,1)) %[9 31 16 27 26 29 41 46 54 61 68 98 86 87 151]% + normSmoothData(i,:) = zscore(smoothdata(results.C_raw(i,:),'movmedian',3)); %normalize each ROI trace + try + if sum(ismember(ROI_unique{d},i)) > 0 + plot(1:length(results.C_raw(1,:)),normSmoothData(i,:)+i*6,'b') %may have to tweak the +i*6 at the end + else + plot(1:length(results.C_raw(1,:)),normSmoothData(i,:)+i*6,'r') %may have to tweak the +i*6 at the end + end + catch + end + end + title(['ROI Activity: ' batName{d} ' ' dateSesh{d} ' ' sessionType{d}]) + ylabel(['z-score dff: ' num2str(length(results.C(:,1))) ' ROIs']) + %yticklabel(gca, + xlabel('Time (min)') + set(gca,'ytick',6:12:length(results.C(:,1))*6,'yticklabel',1:2:length(results.C(:,1))); + set(gca,'xtick',1:(5*60*results.Fs):length(results.C(1,:)),'xticklabel',1:5:round(length(results.C(1,:))/(60*results.Fs))) + xlim([1 length(results.C(1,:))]) + ylim([1 (length(results.C(:,1))+2)*results.Fs]) + axis 'tight' + hold off + drawnow; + + %find all correlation indices across all pairs and close pairs of cells + corrIndAll{d} = find(abs(timeCorrAll{d})>0); + corrIndClose{d} = find(abs(timeCorrClose{d})>0); + corrIndAllS{d} = find(abs(timeCorrS{d})>0); + corrIndCloseS{d} = find(abs(timeCorrCloseS{d})>0); + %plot distributions of correlation coeffiecients for all and close ROIs + plot_corrDist = figure(); + subplot(1,2,1); + histogram(timeCorrAll{d}(corrIndAll{d})); + hold on; + title(['Dist R ALL ROIs: ' batName{d} ' ' dateSesh{d} ' ' sessionType{d}]); + xlabel('Correlation coefficients'); + ylabel('# ROI pairs'); + subplot(1,2,2); + histogram(timeCorrClose{d}(corrIndClose{d}),8,'FaceColor','r'); + hold on; + title('Dist R CLOSE ROIs (cRaw matrix)'); + xlabel('Correlation coefficients'); + ylabel('# ROI pairs'); + hold off; + + %plot distributions of correlation coeffiecients for all and close ROIs + plot_corrDistS = figure(); + subplot(1,2,1); + histogram(timeCorrS{d}(corrIndAllS{d})); + hold on; + title(['Dist R ALL ROIs: ' batName{d} ' ' dateSesh{d} ' ' sessionType{d}]); + xlabel('Correlation coefficients'); + ylabel('# ROI pairs'); + subplot(1,2,2); + histogram(timeCorrCloseS{d}(corrIndCloseS{d}),8,'FaceColor','r'); + hold on; + title('Dist R CLOSE ROIs (S matrix)'); + xlabel('Correlation coefficients'); + ylabel('# ROI pairs'); + hold off; + + if saveFlag == 1 + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(plot_ROI_refined,[saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.fig']); + saveas(plot_ROI_refined, [saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.tif']); + saveas(plot_ROI_refined, [saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.svg']); + + %save fig and tif of correlation distributions + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(plot_corrDist,[saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.fig']); + saveas(plot_corrDist, [saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.tif']); + saveas(plot_corrDist, [saveDir 'plot_corrDist_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.svg']); + %save fig and tif of correlation distributions + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(plot_corrDistS,[saveDir 'plot_corrDistS_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.fig']); + saveas(plot_corrDistS, [saveDir 'plot_corrDistS_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.tif']); + saveas(plot_corrDistS, [saveDir 'plot_corrDistS_' batName{d} dateSesh{d} sessionType{d} '_' datestr(now,'yymmdd-hhMMss') '.svg']); + + end + close all; + cd(dirTop(d).folder); +end + +% for u = 1:round(length(results.A(1,:))) +% if ismember(u,ROI_duplicate) == 0 +% ROI_unique = [ROI_unique u]; +% end +% end +% +% figure(); +% imagesc(imresize(results.Cn,scaling)); colormap(gray); +% set(gca,'YDir','normal'); +% hold on +% for f = 1:length(ROI_unique) +% try +% p = plot(ROI_coords{ROI_unique(f),1},ROI_coords{ROI_unique(f),2},'b','LineWidth',4); +% p.Color(4) = 0.2; +% catch +% end +% end +% for p = 1:length(ROI_duplicate) +% try +% p = plot(ROI_coords{ROI_duplicate(p),1},ROI_coords{ROI_duplicate(p),2},'r','LineWidth',4); +% p.Color(4) = 0.2; +% catch +% end +% end +% hold off +% title([batName{d} ' ' dateSesh{d} ' ' sessionType{d} ': d(' num2str(distThresh) '), c(' num2str(corrThresh) ')']); +ROI_refined.batName = batName; +ROI_refined.dateSesh = dateSesh; +ROI_refined.sessionType = sessionType; +ROI_refined.ROI_duplicate = ROI_duplicate; +ROI_refined.ROI_unique = ROI_unique; +ROI_refined.distance = distance; +ROI_refined.distFull = distFull; +ROI_refined.timeCorrAll = timeCorrAll; +ROI_refined.timeCorrClose = timeCorrClose; +ROI_refined.timeCorrFull = timeCorrFull; +ROI_refined.timeCorrS = timeCorrS; +ROI_refined.timeCorrCloseS = timeCorrCloseS; +ROI_refined.corrIndAll = corrIndAll; +ROI_refined.corrIndClose = corrIndClose; +ROI_refined.corrIndAllS = corrIndAllS; +ROI_refined.corrIndCloseS = corrIndCloseS; +ROI_refined.distThresh = distThresh/scaling; %number of pixels to check if the cells are close enough to be considered same cell +ROI_refined.corrThresh = corrThresh; %max correlation of time series if cells are very close +ROI_refined.scaling = scaling; % 5x but depends on size of frame and downsampling from extraction step +ROI_refined.minLim = minLim; %limits for correlation imagesc +ROI_refined.maxLim = maxLim; +ROI_refined.ROI_coords = ROI_coords; +ROI_refined.centroid = centroid; + +%if saveFlag == 1 +save([saveDir 'ROI_refined_c05' num2str(distThresh/scaling) '_' num2str(corrThresh) '_' datestr(now,'yyMMdd-hhmmss') '.mat'],'ROI_refined'); +%save(['/Users/periscope/Desktop/analysis/ROI_refined/ROI_refined_' num2str(distThresh/scaling) '_' num2str(corrThresh) '_' datestr(now,'yyMMdd-hhmmss') '.mat'],'ROI_refined'); +%end \ No newline at end of file diff --git a/analysis_tobias/ImBat_catchTrials_vs_rewardTrials.m b/analysis_tobias/ImBat_catchTrials_vs_rewardTrials.m new file mode 100644 index 0000000..ff12aa9 --- /dev/null +++ b/analysis_tobias/ImBat_catchTrials_vs_rewardTrials.m @@ -0,0 +1,46 @@ + +fs = 120; +batName = 'Gen'; +dateSesh = '200530'; +sessionType = 'fly-1'; +[rewardR,rewardLT,rewardUT] = risetime(out.RewardVector); +rewardYes_idx = find(bhv_data.trials(:,9)==1); +rewardNo_idx = find(bhv_data.trials(:,9)==0); +rewardYes_times = rewardLT(rewardYes_idx); +rewardNo_times = rewardLT(rewardNo_idx); + +figure(); +subplot(1,2,1) +for t = 1:length(rewardYes_times) +[minEndYes(t),minEndYesIdx(t)] = min(abs(rewardYes_times(t)-flightPaths.flight_ends_idx)); +plot3(flightPaths.trajectoriesContinous(1,flightPaths.flight_starts_idx(minEndYesIdx(t)):flightPaths.flight_ends_idx(minEndYesIdx(t))),flightPaths.trajectoriesContinous(2,flightPaths.flight_starts_idx(minEndYesIdx(t)):flightPaths.flight_ends_idx(minEndYesIdx(t))),flightPaths.trajectoriesContinous(3,flightPaths.flight_starts_idx(minEndYesIdx(t)):flightPaths.flight_ends_idx(minEndYesIdx(t)))); +hold on; +%scatter3(flightPaths.flight_starts_xyz(1,1,t),flightPaths.flight_starts_xyz(2,1,t),flightPaths.flight_starts_xyz(3,1,t),50,'r','filled') +%scatter3(flightPaths.flight_ends_xyz(1,1,t),flightPaths.flight_ends_xyz(2,1,t),flightPaths.flight_ends_xyz(3,1,t),50,'r','filled') +end +xlim([-3 3]) +ylim([-3 3]) +view(0,90) +xlabel('m'); ylabel('m'); +title(['Rewarded flights: ' batName ' ' dateSesh ' ' sessionType]); + +subplot(1,2,2) +for t = 1:length(rewardNo_times) +[minEndNo(t),minEndNoIdx(t)] = min(abs(rewardNo_times(t)-flightPaths.flight_ends_idx)); +plot3(flightPaths.trajectoriesContinous(1,flightPaths.flight_starts_idx(minEndNoIdx(t)):flightPaths.flight_ends_idx(minEndNoIdx(t))),flightPaths.trajectoriesContinous(2,flightPaths.flight_starts_idx(minEndNoIdx(t)):flightPaths.flight_ends_idx(minEndNoIdx(t))),flightPaths.trajectoriesContinous(3,flightPaths.flight_starts_idx(minEndNoIdx(t)):flightPaths.flight_ends_idx(minEndNoIdx(t)))); +hold on; +end +xlim([-3 3]) +ylim([-3 3]) +view(0,90) +xlabel('m'); ylabel('m'); +title(['Catch trials: ' batName ' ' dateSesh ' ' sessionType]); + +for i = 1:length(flightPaths.clusterIndex{2}) +targetPos(i,:) = flightPaths.flight_ends_xyz(flightPaths.clusterIndex{2}(i),:); +targetTime(i) = flightPaths.flight_ends_idx(flightPaths.clusterIndex{2}(i)); +[minStart(i),minStartIdx(i)] = min(abs(rewardYes_times-targetTime(i))); +%flightPaths.pos(:,flightPaths.flight_ends_idx(i),i) +end +feeder2 = mean(targetPos); + diff --git a/analysis_tobias/ImBat_categoricalStability_barcode.m b/analysis_tobias/ImBat_categoricalStability_barcode.m new file mode 100644 index 0000000..2d3744f --- /dev/null +++ b/analysis_tobias/ImBat_categoricalStability_barcode.m @@ -0,0 +1,181 @@ +saveFlag = 1; +batId = 'Gal'; +if strcmp(batId,'Gal') + g = dir('Ga*'); +elseif strcmp(batId,'Gen') + g = dir('Ge*'); +end +z = dir('Z1*'); +dirTop = vertcat(g,z); %find all folders in top quality directory +nDays = length(dirTop); +%ROI_duplicate = cell(length(dirTop),1); %make cell for indices of duplicated ROIS + +clusP = cell(length(dirTop),1); +clusPre = cell(length(dirTop),1); +clusPost = cell(length(dirTop),1); +roiP = cell(length(dirTop),1); +roiPre = cell(length(dirTop),1); +roiPost = cell(length(dirTop),1); +ppCells = cell(length(dirTop),1); +ppreCells = cell(length(dirTop),1); +ppostCells = cell(length(dirTop),1); + + +for day_i = 1:nDays + %load results data + dirExtracted = dir([dirTop(day_i).name filesep '*Extracted*']); + load([dirTop(day_i).name filesep dirExtracted(end).name]); + + batName{day_i} = dirTop(day_i).name(1:3); + dateSesh{day_i} = dirTop(day_i).name(5:10); + + if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'categoricalStability'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'categoricalStability']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'categoricalStability' '\']; + end + + clusP{day_i} = placeCellsAngStable.clusP; + clusPre{day_i} = placeCellsAngStable.clusPre; + clusPost{day_i} = placeCellsAngStable.clusPost; + + ppCells{day_i} = placeCellsAngStable.pp_cells; + ppreCells{day_i} = placeCellsAngStable.ppre_cells; + ppostCells{day_i} = placeCellsAngStable.ppost_cells; + + roiP{day_i} = placeCellsAngStable.roiP; + roiPre{day_i} = placeCellsAngStable.roiPre; + roiPost{day_i} = placeCellsAngStable.roiPost; +end + +%% plot cluster 2 barcode of pre/dur/post cell classification +if strcmp(batId,'Gal') + clustList = [2 2 2 2 2 2 2 2 2; 3 5 3 3 3 3 3 3 5; 1 3 4 6 4 11 1 1 8]; %cluster conversion so all match for Gal +elseif strcmp(batId,'Gen') + clustList = [2 2 2 2 2; 3 3 3 3 3]; %cluster conversion so all match for Gen +end + +for clust_i = 1:size(clustList,1); + +categoricalStabilityBarcode = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +sgtitle([batId 'Pre (r)/Dur (g)/Post (b) Categorical Stability: Cluster ' num2str(clust_i+1)]); +nROI = size(ppCells{1},2); +ha = tight_subplot(nDays,nROI,[.01 .01],[.03 .1],[.02 .02]); +for day_ii = 1:nDays + hold on; + for roi_i = 1:nROI + if ppreCells{day_ii}(clustList(clust_i,day_ii),roi_i) == 1 + axes(ha((nROI*day_ii)-nROI+roi_i)); + x = [0 1 1 0]; + y = [0 0 1 1]; + plot(x,y,'r','LineWidth',2); + area(x,y,'FaceColor','red'); + hold on; + y = [1 2 2 2]; + plot(x,y,'r','LineWidth',2); + area(x,y,'FaceColor','red'); + axis([0 3 0 2]); + set(gca,'xticklabel',[],'yticklabel',[]); + end + if ppCells{day_ii}(clustList(clust_i,day_ii),roi_i) == 1 + axes(ha((nROI*day_ii)-nROI+roi_i)); + x = [1 2 2 1]; + y = [0 0 1 1]; + plot(x,y,'g','LineWidth',2); + hold on; + y = [1 2 2 2]; + plot(x,y,'g','LineWidth',2); + area(x,y,'FaceColor','green'); + axis([0 3 0 2]); + set(gca,'xticklabel',[],'yticklabel',[]); + end + if ppostCells{day_ii}(clustList(clust_i,day_ii),roi_i) == 1 + axes(ha((nROI*day_ii)-nROI+roi_i)); + x = [2 3 3 2]; + y = [0 0 1 1]; + plot(x,y,'b','LineWidth',2); + area(x,y,'FaceColor','blue'); + hold on; + y = [1 2 2 2]; + plot(x,y,'b','LineWidth',2); + area(x,y,'FaceColor','blue'); + axis([0 3 0 2]); + set(gca,'xticklabel',[],'yticklabel',[]); + end + axes(ha((nROI*day_ii)-nROI+roi_i)); + if roi_i == 1 + ylabel(['Day ' num2str(day_ii)]); + end + if day_ii == 1 + title(['ROI ' num2str(roi_i)]); + end + end + drawnow; +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(categoricalStabilityBarcode,[saveDir filesep 'Gal_200311to20_categoricalStabilityBarcode_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(categoricalStabilityBarcode,[saveDir filesep 'Gal_200311to20_categoricalStabilityBarcode_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + elseif strcmp(batId,'Gen') + saveas(categoricalStabilityBarcode,[saveDir filesep 'Gen_200319to24_categoricalStabilityBarcode_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(categoricalStabilityBarcode,[saveDir filesep 'Gen_200319to24_categoricalStabilityBarcode_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + end +end + +end + +% %% plot the functional stability of peak timings from beginning to end of recording session +% +% day1 = 1; +% dayEnd = nDays; +% +% day1Cells = cell(3,1); %3 cells for pre, dur, post +% day1Pks = cell(3,1); +% day1Locs = cell(3,1); +% day1Cells{1} = find(ppreCells{day1}(clust_i+1,:)); %preflight active cells +% day1Cells{2} = find(ppCells{day1}(clust_i+1,:)); %durflight active cells +% day1Cells{3} = find(ppostCells{day1}(clust_i+1,:)); %durflight active cells +% for p_i = 1:3 +% day1Pks{p_i} = zeros(length(day1Cells{p_i}),1); +% day1Locs{p_i} = zeros(length(day1Cells{p_i}),1); +% for roi_i = 1:length(day1Cells{p_i}) +% if p_i == 1 +% [day1Pks{p_i}(roi_i),day1Locs{p_i}(roi_i)] = findpeaks(placeCellsAngStable.ppre_cells_activity(roi_i,:)); +% elseif p_i == 2 +% [day1Pks{p_i}(roi_i),day1Locs{p_i}(roi_i)] = findpeaks(placeCellsAngStable.pp_cells_activity(roi_i,:)); +% elseif p_i == 3 +% [day1Pks{p_i}(roi_i),day1Locs{p_i}(roi_i)] = findpeaks(placeCellsAngStable.ppost_cells_activity(roi_i,:)); +% end +% end +% end +% + +% for clust_i = 1:size(clustList,1) +% day1Pre{clust_i} = find(ppreCells{day1}(clust_i+1,:)); +% for +% day1Dur{clust_i} = find(ppCells{day1}(clust_i+1,:)); +% day1Post{clust_i} = find(ppostCells{day1}(clust_i+1,:)); +% +% dayEndPre{clust_i} = find(ppreCells{dayEnd}(clust_i+1,:)); +% dayEndDur{clust_i} = find(ppCells{dayEnd}(clust_i+1,:)); +% dayEndPost{clust_i} = find(ppostCells{dayEnd}(clust_i+1,:)); +% +% +% end + + + + + + + + + + diff --git a/analysis_tobias/ImBat_checkRawCalcium_vs_spiking.m b/analysis_tobias/ImBat_checkRawCalcium_vs_spiking.m new file mode 100644 index 0000000..747c497 --- /dev/null +++ b/analysis_tobias/ImBat_checkRawCalcium_vs_spiking.m @@ -0,0 +1,30 @@ +close all; +batName = 'Gio'; +dateSesh = '200325'; +sessionType = 'raw vs deconvolved'; +timeZoom = 1400:1900;%1:size(results.S,2); +neuron = [6 10 19 22]; + +rawVsDecon = figure(); +sgtitle([batName ' ' dateSesh ' ' sessionType]); +for i = 1:length(neuron) +subplot(length(neuron),1,i) +plot(results.C_raw(neuron(i),timeZoom),'r') +hold on +plot(results.C(neuron(i),timeZoom),'g') +plot(results.S(neuron(i),timeZoom)*10,'b') +if i == 1 +text((timeZoom(end)-timeZoom(1)-100),max(results.C_raw(2,timeZoom))-1,['time ' num2str(timeZoom(1)) ':' num2str(timeZoom(end))]); +end +title(['Neuron ' num2str(neuron(i))]); +end + + +% subplot(3,1,2) +% plot(results.P.kernel_pars(:,1)) +% title('Rising kernel') +% subplot(3,1,3) +% plot(results.P.kernel_pars(:,2)) +% title('decaying kernel') + +saveas(rawVsDecon,['/Users/periscope/Desktop/rawVsDecon/' batName '_' dateSesh '_' sessionType '.tif']); \ No newline at end of file diff --git a/analysis_tobias/ImBat_checkRiseVsDecayTimeARModel.m b/analysis_tobias/ImBat_checkRiseVsDecayTimeARModel.m new file mode 100644 index 0000000..a8fb95c --- /dev/null +++ b/analysis_tobias/ImBat_checkRiseVsDecayTimeARModel.m @@ -0,0 +1,38 @@ +close all; +batName = 'Gen'; +dateSesh = '200520'; +sessionType = 'riseDecayKernal'; + +ROI.ker1 = results.P.kernel_pars(:,1); +ROI.ker2 = results.P.kernel_pars(:,2); + +%% Fit the average AR model +%Sort structure by Ker1 +[~,idx]=sort([ROI.ker1]); +%ROI=ROI(idx); +%Params +CNMF_Fs = 6; +g = [mean([ROI.ker1]) mean([ROI.ker2])]; +%AR(2) model definition +s = [0 0 1 0 0 0 0 zeros(1,100)]; %spikes +y = zeros(1,length(s)); %fluorescence +x = linspace(0, (length(y))/CNMF_Fs, length(y)); %time +for n = 3:length(y) + y(n) = g(1)*y(n-1)+g(2)*y(n-2)+s(n); +end +y = y./max(y); +%Fit with a double exponential +fo = fitoptions('Method','NonlinearLeastSquares','StartPoint', [3, 3, 0.5, 0.05],'Lower', [0.1, 0.5, 0.1, 0.001],'Upper', [10, 10, 2, 2]); +ft = fittype('A*(exp(-(x-x0)/td)-exp(-(x-x0)/tr))','options',fo); +f = fit(x',y',ft); +coeffvals= coeffvalues(f); +riseDecayPlot = figure(); +plot(x,y,'LineWidth',3,'color','k'); xlim([-2 Inf]); ylim([0 Inf]); +hold on; stem(x,s,'LineWidth',4, 'Marker','none','color','r'); +text(8,0.5,{['Rise: ' num2str(coeffvals(3)) ' s'],['Decay: ' num2str(coeffvals(2)) ' s']}); +xlabel('Time(s)'); ylabel('Fluorescence'); +title([batName ' ' dateSesh ' ' sessionType]); +figure(); +plot(f,x,y); + +saveas(riseDecayPlot,['/Users/periscope/Desktop/rawVsDecon/' batName '_' dateSesh '_' sessionType '.tif']); \ No newline at end of file diff --git a/analysis_tobias/ImBat_corrNeurBehavFootprint.m b/analysis_tobias/ImBat_corrNeurBehavFootprint.m new file mode 100644 index 0000000..e848951 --- /dev/null +++ b/analysis_tobias/ImBat_corrNeurBehavFootprint.m @@ -0,0 +1,105 @@ +batId = 'Gen'; +clustNum = 2; +saveFlag = 0; +saveTag = ['sMat']; +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays' '\']; +end + +nPhases = size(dataPreDurPost.findSelectiveCells,2); +nDays = size(dataPreDurPost.mean_act_aligned{1},1); +nRois = size(dataPreDurPost.mean_act_aligned{1},2); +lenTrialNeur = size(dataPreDurPost.mean_act_aligned{clustNum}{1,1},2); +lenTrialBehav = size(dataPreDurPost.mean_vel_dur{clustNum}{1,1},2); +%make matrix of correlations between each day +%neural data +%make matrix to hold 3d to get data out of cell +act_allRois = zeros(nDays,nRois,lenTrialNeur); +mean_act_allDay = zeros(nDays,lenTrialNeur); +mean_velXY_dur = zeros(nDays,3,lenTrialBehav); +for day_i = 1:nDays + for roi_i = 1:nRois + act_allRois(day_i,roi_i,:) = dataPreDurPost.mean_act_aligned{clustNum}{day_i,roi_i}; + end + mean_act_allDay(day_i,:) = mean(act_allRois(day_i,:,:)); + %build behavior matrix with velocity, X and Y from just flight times + mean_velXY_dur(day_i,1,:) = dataPreDurPost.mean_vel_dur{clustNum}{day_i}(1,:); %velocity + mean_velXY_dur(day_i,2,:) = dataPreDurPost.mean_XY_dur{clustNum}{day_i}(1,1,:); %x position + mean_velXY_dur(day_i,3,:) = dataPreDurPost.mean_XY_dur{clustNum}{day_i}(1,2,:); %y position +end + +%find correlations between average neural data mean across whole day +for day_i = 1:nDays-1 + for day_ii = 2:nDays + Rneural = corrcoef(mean_act_allDay(day_i,:),mean_act_allDay(day_ii,:)); + corrNeural(day_i,day_ii) = Rneural(1,2); + %Rbehav = corrcoef(dataPreDurPost.mean_vel_aligned{clustNum}{day_i}(1,:),datareDurPost.mean_vel_aligned{clustNum}{day_ii}(1,:)); + Rbehav = corrcoef(mean_velXY_dur(day_i,:,:),mean_velXY_dur(day_ii,:,:)); + corrBehav(day_i,day_ii) = Rbehav(1,2); + %also take correlation for each individual ROI of that day + for roi_i = 1:nRois + RneuralRoi(roi_i,:,:) = corrcoef(act_allRois(day_i,roi_i,:),act_allRois(day_ii,roi_i,:)); + corrNeuralRoi(roi_i,day_i,day_ii) = RneuralRoi(roi_i,1,2); + RBehavRoi(roi_i,:,:) = corrcoef(mean_velXY_dur(day_i,:,:),mean_velXY_dur(day_ii,:,:)); + corrBehavRoi(roi_i,day_i,day_ii) = RBehavRoi(roi_i,1,2); + end + end +end +%plot correlation matrix of neural data from pairwise days +figCorrNeuralBehaviorFootPrint = figure(); +sgtitle([batId ' Daily correlations of all mean activity, flights, footprints']); +hold on; +subplot(1,3,1); +imagesc(corrNeural); +title('Neural data'); +xlabel('Days'); +ylabel('Days'); +axis(gca,'equal') +colorbar('southoutside'); + +%plot correlation matrix of velocity/XY data from pairwise days +subplot(1,3,2); +imagesc(corrBehav); +title('Behavior data'); +xlabel('Days'); +ylabel('Days'); +axis(gca,'equal') +colorbar('southoutside'); + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(figCorrNeuralBehaviorFootPrint,[saveDir filesep 'Gal_200311to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clustNum) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(figCorrNeuralBehaviorFootPrint,[saveDir filesep 'Gal_200311to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clustNum) '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(figCorrNeuralBehaviorFootPrint,[saveDir filesep 'Gen_200319to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clustNum) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(figCorrNeuralBehaviorFootPrint,[saveDir filesep 'Gen_200319to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clustNum) '_' datestr(now,'yymmdd-HHMM') '.fig']); + + end +end + + + +%% make scatter plot of the correlations of behavior and neural data for each ROI +figScatterCorrNeurBehav = figure(); +scatter(corrBehavRoi(:,:,:),corrNeuralRoi(:,:,:)); +xlabel('XY+V R-val'); +ylabel('Dff R-val'); +title([batId ' Daily pairwise correlation values across all days & ROIs']); + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(figScatterCorrNeurBehav,[saveDir filesep 'Gal_200311to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(figScatterCorrNeurBehav,[saveDir filesep 'Gal_200311to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(figScatterCorrNeurBehav,[saveDir filesep 'Gen_200319to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(figScatterCorrNeurBehav,[saveDir filesep 'Gen_200319to24_corrNeurBehavFootprint_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + + end +end diff --git a/analysis_tobias/ImBat_evaluateImaging.m b/analysis_tobias/ImBat_evaluateImaging.m new file mode 100644 index 0000000..b3fa894 --- /dev/null +++ b/analysis_tobias/ImBat_evaluateImaging.m @@ -0,0 +1,50 @@ +dirBat = dir('G*'); +goodlist = strings(length(dirBat),5); +badlist = strings(length(dirBat),5); +badData = 0; + +for i = 1:length(dirBat) + cd(dirBat(i).name); + dirSession = dir('*fly-*extraction'); +% goodlist(i) = char.empty; +% badlist(i) = char.empty; + for ii = 1:length(dirSession) + cd(dirSession(ii).name); + try + dirAnalysis = dir('analysis*'); + analysisNewest = sort({dirAnalysis(end).name}); + analysisNewest = char(analysisNewest); + %cd(analysisNewest); + try + openfig([dirAnalysis(1).folder filesep analysisNewest{1} filesep 'flights' filesep '*_flightVsVelocity.fig']); + catch + disp(['No cell data ' dirBat(i).name]) + badData = 1; + badlist(i,ii) = dirSession(i).name; + end + try + openfig([dirAnalysis(1).folder filesep analysisNewest{1} filesep 'ROI' filesep '*_maxProjectROI.fig']); + catch + disp(['No ROI data' dirBat(i).name]) + badData = 1; + badlist(i,ii) = dirSession(i).name; + end + if badData == o + prompt = 'Is the imaging data good quality?'; + x = input(prompt) + if x == 1 + goodlist(i,ii) = dirSession(i).name; + %badlist(i,ii) = []; + else + badlist(i,ii) = dirSession(i).name; + %goodlist(i,ii) = []; + end + end + catch + end + close all; + cd('../'); + badData = 0; + end + cd('../'); +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_extract_YmaxFull_AllDays.m b/analysis_tobias/ImBat_extract_YmaxFull_AllDays.m new file mode 100644 index 0000000..ea514e9 --- /dev/null +++ b/analysis_tobias/ImBat_extract_YmaxFull_AllDays.m @@ -0,0 +1,147 @@ +function [YmaxFullAllDays] = ImBat_extract_YmaxFull_AllDays(batId) +saveFlag = 1; %do you want to save the figures and output structure? +rest1Flag = 1; %do you want to include the rest1 session too? + +saveTag = 'rest'; +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd')])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd')]) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep]; +end + +if strcmp(batId,'Gal') + nDays = [1:40]; %which days to look at + dirTop = dir('Ga*'); +elseif strcmp(batId,'Gen') + nDays = [1:100]; + dirTop = dir('Ge*'); +elseif strcmp(batId,'Z2') + nDays = [1:40]; %which days to look at + dirTop = dir('z2*'); +elseif strcmp(batId, 'Zu') + nDays = [1:40]; + dirTop = dir('zu*'); +elseif strcmp(batId,'Za') + nDays = [1:5]; + dirTop = dir('za*'); +end + + +for day_i = 1:length(nDays) %[50,51,66,67,76,77]%[2,3,27,28,33,34]%for each day + %load results data + try %extract metadata names and enter processed folder + cd([dirTop(nDays(day_i)).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + rest1Folders = dir('*rest1*extraction'); + batName{day_i} = flyFolders(end).name(1:4); + dateSesh{day_i} = flyFolders(end).name(6:11); + sessionType{day_i} = flyFolders(end).name(13:17); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); %can change this if need to look at earlier or later processed folders based on batname, date, etc + catch + cd(dirTop(nDays(day_i)).name); + flyFolders = dir('*fly*extraction'); + rest1Folders = dir('*rest1*extraction'); + batName{day_i} = flyFolders(end).name(1:3);%(1:3); + dateSesh{day_i} = flyFolders(end).name(5:10);%(5:10); + sessionType{day_i} = flyFolders(end).name(12:16); %(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + end + %load('results.mat'); %load cellData + vidData = load('Motion_corrected_Data_DS.mat'); %load video frame data + %make gaussian filter based on dff function for spatial filtering + gSig = 1; + gSiz = 4.5*gSig; + scaling = 10; %scale up the ymax to make less pixelated + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + % % Take median, filter, and max of full movie + Y_med = median(vidData.Y,3); + Y_min = min(vidData.Y,3); + Ydff = vidData.Y - Y_med; %subtract med + Ydff_tFilt = medfilt3(Ydff); %temporal filtering + Ydff_filt = imfilter(Ydff_tFilt,psf,'symmetric'); %spatial filtering + length_vector = 1:length(Ydff_filt); + rand_length_vector= randperm(length(length_vector)); + YmaxFull{15} = max(Ydff_filt(:,:,rand_length_vector(1:round(length(length_vector)/3))),[],3); + YmaxFull{16} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3):round(length(length_vector)/3)*2)),[],3); + YmaxFull{17} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3)*2:end)),[],3); + + YmaxFull{day_i} = max(Ydff_filt,[],3); %take max + YmaxFull{day_i} = imresize(YmaxFull{day_i},scaling); %resize to eliminate pixelation + %alignment = load('Alignment.mat'); + cd(dirProcessed(end).folder); + disp(num2str(day_i)) + clear vidData; + cd .. + if rest1Flag == 1 + cd(rest1Folders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); %can change this if need to look at earlier or later processed folders based on batname, date, etc + %load('results.mat'); %load cellData + vidData = load('Motion_corrected_Data_DS.mat'); %load video frame data + % % Take median, filter, and max of full movie + Y_med = median(vidData.Y,3); + Y_min = min(vidData.Y,3); + Ydff = vidData.Y - Y_med; %subtract med + Ydff_tFilt = medfilt3(Ydff); %temporal filtering + Ydff_filt = imfilter(Ydff_tFilt,psf,'symmetric'); %spatial filtering + length_vector = 1:length(Ydff_filt); + rand_length_vector= randperm(length(length_vector)); + YmaxRest{15} = max(Ydff_filt(:,:,rand_length_vector(1:round(length(length_vector)/3))),[],3); + YmaxRest{16} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3):round(length(length_vector)/3)*2)),[],3); + YmaxRest{17} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3)*2:end)),[],3); + + YmaxRest{day_i} = max(Ydff_filt,[],3); %take max + YmaxRest{day_i} = imresize(YmaxRest{day_i},scaling); %resize to eliminate pixelation + %alignment = load('Alignment.mat'); + cd(dirProcessed(end).folder); + disp(num2str(day_i)) + clear vidData; + + + end + + cd(dirTop(1).folder); + +end + +YmaxFullAllDays.batId = batId; +YmaxFullAllDays.batName = batName; +YmaxFullAllDays.sessionType = sessionType; +YmaxFullAllDays.dateSesh = dateSesh; +YmaxFullAllDays.YmaxFull = YmaxFull; +if rest1Flag == 1 + YmaxFullAllDays.YmaxRest = YmaxRest; +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + save([saveDir 'Gal_200227to200404_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + elseif strcmp(batId,'Gen') + save([saveDir 'Gen_200305to200311_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + %save([saveDir 'Gen_200424to200523_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + elseif strcmp(batId,'Z2') + save([saveDir 'Z2_190701to190822_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + elseif strcmp(batId,'Zu') + save([saveDir 'Zu_190704to190820_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + elseif strcmp(batId,'Za') + save([saveDir 'Za_190524to190530_YmaxFull_' saveTag '.mat'],'YmaxFullAllDays','-v7.3'); + end +end + + + diff --git a/analysis_tobias/ImBat_extract_activity_allTrials.m b/analysis_tobias/ImBat_extract_activity_allTrials.m new file mode 100644 index 0000000..514ef64 --- /dev/null +++ b/analysis_tobias/ImBat_extract_activity_allTrials.m @@ -0,0 +1,366 @@ +function [activity_allTrials,flightAligned_vidData] = ImBat_extract_activity_allTrials(batId) +plotFlag = 0; +saveFlag = 1; %do you want to save the figures and output structure? +cRaw = 0; + +saveTag = 'sMat_newDff_newOrder'; +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd')])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd')]) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep]; +end + +if strcmp(batId,'Gal') + nDays = [1:12]; %which days to look at + nRois = [1:15]; +elseif strcmp(batId,'Gen') + nDays = [1:5]; + nRois = [1:20];%size(ROIs_manual(day_i,:),2); %number of ROIs +elseif strcmp(batId,'Gi') + nDays = [1:10]; + nRois = [1:5];%size(ROIs_manual(day_i,:),2); %number of ROIs +elseif strcmp(batId,'Z2') + nDays = [1:10]; %which days to look at + nRois = [1:10]; +elseif strcmp(batId,'Za') + nDays = [1:5]; %which days to look at + nRois = [1:10]; +end +%dayCounter = 1; %start the +if strcmp(batId,'Gal') + % 15 stable manually selected ROIs across 9 days for Gal + ROIs_manual = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 25 6 30 27 3 1 2 9 8 37 NaN 15 31 24 36; + 8 12 35 20 1 10 2 39 9 30 3 14 31 24 11; + 10 7 39 35 3 31 8 22 9 37 5 11 39 17 2; + 9 27 25 45 1 7 8 46 11 33 23 6 42 3 2; + 20 34 29 51 7 10 6 40 16 45 5 8 42 26 43; + 8 2 25 38 16 44 20 7 14 26 3 35 37 24 41; + 1 7 28 NaN 6 17 2 35 16 33 12 11 27 30 34; + 19 4 16 NaN 27 21 3 24 2 29 14 8 26 32 33]; + dirTop = dir('Ga*'); +elseif strcmp(batId,'Gen') + % 20 stable manually selected ROIs across 5 days for Gen + ROIs_manual = [NaN NaN 10 3 16 12 17 18 27 29 8 9 NaN NaN 21 11 31 15 20 25; + 8 17 5 1 2 6 21 10 18 31 NaN 11 51 53 28 4 38 19 23 20; + 50 54 12 3 48 18 27 15 31 34 NaN NaN 28 NaN 29 25 24 22 38 14; + 9 NaN 7 31 2 22 NaN 20 40 25 13 NaN 34 NaN 26 NaN 45 3 24 21; + 10 36 3 11 2 NaN 21 18 20 9 33 NaN NaN NaN 17 NaN 22 7 30 26]; %14 NaN 3 28 2 6 33 26 18 45 NaN NaN 25 NaN 32 NaN 37 8 28 11 + dirTop = dir('Ge*'); +elseif strcmp(batId,'Z2') + % 15 stable manually selected ROIs across 9 days for Gal + ROIs_manual = [1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10]; + dirTop = dir('z2*'); +elseif strcmp(batId,'Za') + % 15 stable manually selected ROIs across 9 days for Gal + ROIs_manual = [1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10]; + dirTop = dir('za*'); +elseif strcmp(batId,'Gi') + % 15 stable manually selected ROIs across 9 days for Gal + ROIs_manual = [1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10; + 1 2 3 4 5 6 7 8 9 10]; + dirTop = dir('Gi*'); +end +if plotFlag == 1 + fig1 = figure(); set(gcf, 'units','normalized','outerposition',[0.2 0 0.5 1]); + sgtitle(['Gal Event Timing Across 3 Days for 3 ROIs: Cluster: 2']); + ha = tight_subplot(3,3,[.06 .03],[.02 .1],[.05 .02]); +end +%make the matrices to hold the neural data +act_pre = cell(1,length(nRois)); +act_dur = cell(1,length(nRois)); +act_post = cell(1,length(nRois)); +for clust_ii = 1:length(act_pre) + act_pre{clust_ii} = cell(length(nDays),length(nRois)); + act_post{clust_ii} = cell(length(nDays),length(nRois)); + act_dur{clust_ii} = cell(length(nDays),length(nRois)); +end + +for day_i = 1:length(nDays) %for each day + %load results data + try %extract metadata names and enter processed folder + cd([dirTop(nDays(day_i)).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + batName{day_i} = flyFolders(end).name(1:3); + dateSesh{day_i} = flyFolders(end).name(5:10); + sessionType{day_i} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); %can change this if need to look at earlier or later processed folders based on batname, date, etc + catch + cd(dirTop(nDays(day_i)).name); + flyFolders = dir('*fly*extraction'); + batName{day_i} = flyFolders(end).name(1:3); + dateSesh{day_i} = flyFolders(end).name(5:10); + sessionType{day_i} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + end + load('results.mat'); %load cellData + vidData = load('Motion_corrected_Data_DS.mat'); %load video frame data + %make gaussian filter based on dff function for spatial filtering + gSig = 1; + gSiz = 4.5*gSig; + scaling = 10; %scale up the ymax to make less pixelated + psf = fspecial('gaussian', round(2*gSiz), gSig); + ind_nonzero = (psf(:)>=max(psf(:,1))); + psf = psf-mean(psf(ind_nonzero)); + psf(~ind_nonzero) = 0; % only use pixels within the center disk + % % Take median, filter, and max of full movie + Y_med = median(vidData.Y,3); + Y_min = min(vidData.Y,3); + Ydff = vidData.Y - Y_med; %subtract med + Ydff_tFilt = medfilt3(Ydff); %temporal filtering + Ydff_filt = imfilter(Ydff_tFilt,psf,'symmetric'); %spatial filtering + length_vector = 1:length(Ydff_filt); + rand_length_vector= randperm(length(length_vector)); + YmaxFull{7} = max(Ydff_filt(:,:,rand_length_vector(1:round(length(length_vector)/3))),[],3); + YmaxFull{8} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3):round(length(length_vector)/3)*2)),[],3); + YmaxFull{9} = max(Ydff_filt(:,:,rand_length_vector(round(length(length_vector)/3)*2:end)),[],3); + + YmaxFull{day_i} = max(Ydff_filt,[],3); %take max + YmaxFull{day_i} = imresize(YmaxFull{day_i},scaling); %resize to eliminate pixelation + %alignment = load('Alignment.mat'); + cd(dirProcessed(end).folder); + + %load flightPaths and snakeTrace data + %extract metadata names and enter analysis folder + dirAnalysis = dir('analysis_*'); + cd(dirAnalysis(end).name); + fp = dir('*flightPaths.mat'); + load(fp(end).name); %load flightPaths + sd = dir('*snakePlotData.mat'); + load(sd(end).name); + + if plotFlag == 1 + figh = findall(0,'type','figure'); + other_figures = setdiff(figh, fig1) + delete(other_figures) + else + close all; + end + + if cRaw ==1 + sData = snakeTrace.cRaw; %select data from the s,cRaw, or c matrix + else + sData = snakeTrace.s; + end + nClusts = length(flightPaths.clusterIndex); %which clusters to look at + + nFlights = cell(nClusts,1); + lenFlight = cell(nClusts,1); + lenPre = cell(nClusts,1); + lenPost = cell(nClusts,1); + for clust_i = 1:length(act_pre) + for roi_i = 1:length(nRois) + act_pre{clust_i}{day_i,roi_i} = NaN(1,1500); + act_dur{clust_i}{day_i,roi_i} = NaN(1,1500); + act_post{clust_i}{day_i,roi_i} = NaN(1,1500); + vel_pre{clust_i}{day_i} = NaN(1,4000); + vel_dur{clust_i}{day_i} = NaN(1,4000); + vel_post{clust_i}{day_i} = NaN(1,4000); + XY_dur{clust_i}{day_i} = NaN(1,3,4000); + %framesRaw_pre{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + framesRaw_dur{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + %framesRaw_post{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + %framesFilt_pre{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + framesFilt_dur{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + %framesFilt_post{clust_i}{day_i} = NaN(1,vidData.Ysiz(1),vidData.Ysiz(2),1500); + end + end + %for each cluster in nClusts + for clust_i = 1:nClusts + nFlights{clust_i} = size(flightPaths.clusterIndex{clust_i},1); %find number of flights for that cluster + %find length of pre, dur, post trials for each cluster + lenPre{clust_i} = length(sData.normTraceRawPre{clust_i}(1,:,1)); + lenFlight{clust_i} = length(sData.normTraceRawFlight{clust_i}(1,:,1)); + lenPost{clust_i} = length(sData.normTraceRawPost{clust_i}(1,:,1)); + lenBehavPre{clust_i} = length(sData.smoothSpeedRawPre{clust_i}(1,:)); + lenBehavDur{clust_i} = length(sData.smoothSpeedRawFlight{clust_i}(1,:)); + lenBehavPost{clust_i} = length(sData.smoothSpeedRawPost{clust_i}(1,:)); + %initialize velocity matrices + vel_pre{clust_i}{day_i} = zeros(nFlights{clust_i},lenBehavPre{clust_i}); + vel_dur{clust_i}{day_i} = zeros(nFlights{clust_i},lenBehavDur{clust_i}); + vel_post{clust_i}{day_i} = zeros(nFlights{clust_i},lenBehavPost{clust_i}); + XY_dur{clust_i}{day_i} = zeros(nFlights{clust_i},3,lenBehavDur{clust_i}); + %framesRaw_pre{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenPre{clust_i}); + framesRaw_dur{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenFlight{clust_i}); + %framesRaw_post{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenPost{clust_i}); + %framesFilt_pre{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenPre{clust_i}); + framesFilt_dur{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenFlight{clust_i}); + %framesFilt_post{clust_i}{day_i} = zeros(nFlights{clust_i},vidData.Ysiz(1),vidData.Ysiz(2),lenPost{clust_i}); + %roiCounter = 1;r + for roi_i = 1:length(nRois) + %if nFlights{clust_i} > 0 + act_pre{clust_i}{day_i,roi_i} = zeros(nFlights{clust_i},lenPre{clust_i}); + act_dur{clust_i}{day_i,roi_i} = zeros(nFlights{clust_i},lenFlight{clust_i}); + act_post{clust_i}{day_i,roi_i} = zeros(nFlights{clust_i},lenPost{clust_i}); + %else + + %end + + for flight_i = 1:nFlights{clust_i} + if ~isnan(ROIs_manual(nDays(day_i),nRois(roi_i))) + act_pre{clust_i}{day_i,roi_i}(flight_i,:) = sData.normTraceRawPre{clust_i}(flight_i,:,ROIs_manual(nDays(day_i),nRois(roi_i))); + act_dur{clust_i}{day_i,roi_i}(flight_i,:) = sData.normTraceRawFlight{clust_i}(flight_i,:,ROIs_manual(nDays(day_i),nRois(roi_i))); + act_post{clust_i}{day_i,roi_i}(flight_i,:) = sData.normTraceRawPost{clust_i}(flight_i,:,ROIs_manual(nDays(day_i),nRois(roi_i))); + end + end + + if plotFlag == 1 + axList = [1 2 3; 4 5 6; 7 8 9]; + axes(ha(axList(day_i,roi_i))); imagesc(act_dur{clust_i}{day_i,roi_i}); %set(gca,'xtick',[]); + title(['Day ' num2str(nDays(day_i)) ' ROI ' num2str(nRois(roi_i))]); + xlim([200 300]); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1)); + if roi_i ~= 1 + set(gca,'YTickLabel',[]); + else + xlabel('Time (s)'); + ylabel('Flight #'); + end + hold on; + end + + end + Fs_cnmfe = 30; + prePad = 3*Fs_cnmfe; + postPad = 7 * Fs_cnmfe; + for flight_i = 1:nFlights{clust_i} + %build matrices with the imaging raw frames for flight-aligned max projections + %cut out raw data, subtract min, temporal and spatial filtering + %framesRaw_pre{clust_i}{day_i}(flight_i,:,:,:) = Ydff(:,:,sData.startIdxTrace{clust_i}(flight_i)-sData.preFlightPadCalcium:sData.startIdxTrace{clust_i}(flight_i)); + %Y_minPre = min(framesRaw_pre{clust_i}{day_i}(flight_i,:,:,:),4); + %framesDff_pre = framesRaw_pre{clust_i}{day_i}(flight_i,:,:,:);% - Y_minPre; + %framesDff_pre = squeeze(framesDff_pre); + %framesTFilt_pre = medfilt3(framesDff_pre); + %framesFilt_pre{clust_i}{day_i}(flight_i,:,:,:) = imfilter(framesTFilt_pre,psf,'symmetric'); + try + framesRaw_dur{clust_i}{day_i}(flight_i,:,:,:) = Ydff(:,:,sData.startIdxTrace{clust_i}(flight_i)-prePad:... + sData.endIdxTrace{clust_i}(flight_i) + (sData.medDur{clust_i}-sData.dur{clust_i}(flight_i))+ postPad); + %framesRaw_post{clust_i}{day_i}(flight_i,:,:,:) = Ydff(:,:,sData.endIdxTrace{clust_i}(flight_i):sData.endIdxTrace{clust_i}(flight_i)+sData.postFlightPadCalcium); + catch + framesRaw_dur{clust_i}{day_i}(flight_i,:,:,1:length(Ydff(:,:,sData.startIdxTrace{clust_i}(flight_i)-prePad:end)))... + = Ydff(:,:,sData.startIdxTrace{clust_i}(flight_i)-prePad:end); + %framesRaw_post{clust_i}{day_i}(flight_i,:,:,1:length(Ydff(:,:,sData.endIdxTrace{clust_i}(flight_i):end)))... + % = Ydff(:,:,sData.endIdxTrace{clust_i}(flight_i):end); + end + %cut out raw data, subtract min, temporal and spatial filtering + %Y_minDur = min(framesRaw_dur{clust_i}{day_i}(flight_i,:,:,:),3); + framesDff_dur = framesRaw_dur{clust_i}{day_i}(flight_i,:,:,:);% - Y_minDur; + framesDff_dur = squeeze(framesDff_dur); + framesTFilt_dur = medfilt3(squeeze(framesDff_dur)); + framesFilt_dur{clust_i}{day_i}(flight_i,:,:,:) = imfilter(framesTFilt_dur,psf,'symmetric'); + %Y_minPost = min(framesRaw_post{clust_i}{day_i}(flight_i,:,:,:),3); + %framesDff_post = framesRaw_post{clust_i}{day_i}(flight_i,:,:,:);% - Y_minPost; + %framesDff_post = squeeze(framesDff_post); + %framesTFilt_post = medfilt3(squeeze(framesDff_post)); + %framesFilt_post{clust_i}{day_i}(flight_i,:,:,:) = imfilter(framesTFilt_post,psf,'symmetric'); + + %add data to matrices for velocity of the active trials + if ~isnan(ROIs_manual(nDays(day_i),nRois(roi_i))) + vel_pre{clust_i}{day_i}(flight_i,:) = sData.smoothSpeedRawPre{clust_i}(flight_i,:); + vel_dur{clust_i}{day_i}(flight_i,:) = sData.smoothSpeedRawFlight{clust_i}(flight_i,:); + vel_post{clust_i}{day_i}(flight_i,:) = sData.smoothSpeedRawPost{clust_i}(flight_i,:); + XY_dur{clust_i}{day_i}(flight_i,1,:) = sData.posFlight{clust_i}(flight_i,1,:); %flightPaths.pos(1,:,flightPaths.clusterIndex{clust_i}(flight_i)); + XY_dur{clust_i}{day_i}(flight_i,2,:) = sData.posFlight{clust_i}(flight_i,2,:); %flightPaths.pos(2,:,flightPaths.clusterIndex{clust_i}(flight_i)); + XY_dur{clust_i}{day_i}(flight_i,3,:) = sData.posFlight{clust_i}(flight_i,3,:); + end + end + %take average across all trials to get 'average' flight activity + %meanFrames_pre{clust_i}{day_i} = squeeze(nanmean(framesFilt_pre{clust_i}{day_i},1)); + meanFrames_dur{clust_i}{day_i} = squeeze(nanmean(framesFilt_dur{clust_i}{day_i},1)); + %meanFrames_post{clust_i}{day_i} = squeeze(nanmean(framesFilt_post{clust_i}{day_i},1)); + %find max projection of this mean + %maxMeanFrames_pre{clust_i}{day_i} = max(meanFrames_pre{clust_i}{day_i},[],3); + %maxMeanFrames_pre{clust_i}{day_i} = imresize(maxMeanFrames_pre{clust_i}{day_i},scaling); + maxMeanFrames_dur{clust_i}{day_i} = max(meanFrames_dur{clust_i}{day_i},[],3); + maxMeanFrames_dur{clust_i}{day_i} = imresize(maxMeanFrames_dur{clust_i}{day_i},scaling); + %maxMeanFrames_post{clust_i}{day_i} = max(meanFrames_post{clust_i}{day_i},[],3); + %maxMeanFrames_post{clust_i}{day_i} = imresize(maxMeanFrames_post{clust_i}{day_i},scaling); + end + cd(dirTop(1).folder); + disp(num2str(day_i)) + clear vidData; +end + + +activity_allTrials.batId = batId; +activity_allTrials.act_pre = act_pre; +activity_allTrials.act_dur = act_dur; +activity_allTrials.act_post = act_post; +activity_allTrials.vel_pre = vel_pre; +activity_allTrials.vel_dur = vel_dur; +activity_allTrials.vel_post = vel_post; +activity_allTrials.XY_dur = XY_dur; +%activity_allTrials.meanFrames_pre = meanFrames_pre; +activity_allTrials.meanFrames_dur = meanFrames_dur; +%activity_allTrials.meanFrames_post = meanFrames_post; +%activity_allTrials.maxMeanFrames_pre = maxMeanFrames_pre; +activity_allTrials.maxMeanFrames_dur = maxMeanFrames_dur; +%activity_allTrials.maxMeanFrames_post = maxMeanFrames_post; +activity_allTrials.YmaxFull = YmaxFull; + +%flightAligned_vidData.frames_pre = frames_pre; +%flightAligned_vidData.framesRaw_dur = framesRaw_dur; +%flightAligned_vidData.framesFilt_dur = framesFilt_dur; +%flightAligned_vidData.frames_post = frames_post; + +if saveFlag == 1 + if strcmp(batId,'Gal') + save([saveDir 'Gal_200311to200324_activity_allTrials_allClusts_' saveTag '.mat'],'activity_allTrials','-v7.3'); + % save([saveDir 'Gal_200311to200324_flightAligned_vidData_' saveTag '.mat'],'flightAligned_vidData','-v7.3'); + elseif strcmp(batId,'Gen') + save([saveDir 'Gen_200319to200324_activity_allTrials_allClusts_' saveTag '.mat'],'activity_allTrials','-v7.3'); + % save([saveDir 'Gen_200319to200324_flightAligned_vidData_' saveTag '.mat'],'flightAligned_vidData','-v7.3'); + elseif strcmp(batId,'Z2') + save([saveDir 'Z2_190701to190808_activity_allTrials_allClusts_' saveTag '.mat'],'activity_allTrials','-v7.3'); + % save([saveDir 'Z2_190319to190808_flightAligned_vidData_' saveTag '.mat'],'flightAligned_vidData','-v7.3'); + elseif strcmp(batId,'Za') + save([saveDir 'Za_190524to190530_activity_allTrials_allClusts_' saveTag '.mat'],'activity_allTrials','-v7.3'); + % save([saveDir 'Za_190524to190530_flightAligned_vidData_' saveTag '.mat'],'flightAligned_vidData','-v7.3'); + elseif strcmp(batId,'Gi') + save([saveDir 'Gi_200407to200418_activity_allTrials_allClusts_' saveTag '.mat'],'activity_allTrials','-v7.3'); + % save([saveDir 'Za_190524to190530_flightAligned_vidData_' saveTag '.mat'],'flightAligned_vidData','-v7.3'); + end +end + diff --git a/analysis_tobias/ImBat_extract_dataPreDurPost.m b/analysis_tobias/ImBat_extract_dataPreDurPost.m new file mode 100644 index 0000000..1b76c85 --- /dev/null +++ b/analysis_tobias/ImBat_extract_dataPreDurPost.m @@ -0,0 +1,263 @@ +function dataPreDurPost = ImBat_extract_dataPreDurPost(batId) +saveFlag = 1; +saveTag = 'sMat_newDff'; +cRaw = 0; +%load first day placeCellStableROI data +if strcmp(batId,'Gal') + %cd([dirTop(day1).folder filesep 'plots\200911-preDurPost cells across days']); + if cRaw ==1 + load('200311to200320_Gal_activity_allTrials_allClusts_cRaw_vel.mat'); %load activity for pre,dur,post + else + load('Gal_200311to200324_activity_allTrials_allClusts_allTrials_sMat_newDff_newOrder.mat'); %load s matrix activity data + end + dirDates = dir('Gal*preDurPostCells'); +elseif strcmp(batId,'Gen') + if cRaw ==1 + load('200319to200324_Gen_activity_allTrials_allClusts_cRaw_vel.mat'); %load activity for pre,dur,post + else + load('Gen_200319to200324_activity_allTrials_allClusts_sMat_newDff_newOrder.mat'); %load s matrix activity data + end + dirDates = dir('Gen*preDurPostCells'); + +end +nDays = length(dirDates); +day1 = 1; %first day to start comparing +dayEnd = nDays; %last day to start comparing +days = [1:dayEnd]; %all days concat +clusts = 2; +CNMFe_Fs = 30; +track_Fs = 120; +preDur = 3; %pre takeoff +postDur = 7; %post takeoff +if strcmp(batId,'Gal') + clustList = [2 2 2 2 2 2 2 2 2; 3 5 3 3 3 3 3 3 5; 1 3 4 6 4 11 1 1 8]; +elseif strcmp(batId,'Gen') + clustList = [2 2 2 2 2; 3 3 3 3 3]; +end + +minFlightLength = cell(1,max(max(clustList))); +minBehavFlightLength= cell(1,max(max(clustList))); +flightLength= cell(1,max(max(clustList))); +behavLength= cell(1,max(max(clustList))); +act_aligned= cell(1,max(max(clustList))); +act_pre= cell(1,max(max(clustList))); +act_dur= cell(1,max(max(clustList))); +act_post= cell(1,max(max(clustList))); +vel_aligned= cell(1,max(max(clustList))); +vel_pre= cell(1,max(max(clustList))); +vel_dur= cell(1,max(max(clustList))); +vel_post= cell(1,max(max(clustList))); +XY_dur = cell(1,max(max(clustList))); +%pull in/cutout all the aligned, pre, dur, and post data +for clust_i = 1:15%max(max(clustList)) + minFlightSizesVect = cellfun('size',activity_allTrials.act_dur{clust_i}(:,1),2); + minFlightLength{clust_i} = min(minFlightSizesVect(minFlightSizesVect>0)); + %minFlightLength{clust_i} = min(cellfun('size',activity_allTrials.act_dur{clust_i}(:,1),2)(cellfun('size',activity_allTrials.act_dur{clust_i}(:,1),2)>0)); %shortest flight length for each day since they may be slightly different lengths + minBehavSizesVect = cellfun('size',activity_allTrials.vel_dur{clust_i}(1,:),2); + minBehavFlightLength{clust_i} = min(minBehavSizesVect(minBehavSizesVect>0)); + %minBehavFlightLength{clust_i} = min(cellfun('size',activity_allTrials.vel_dur{clust_i}(1,:),2)); %for behavior + flightLength{clust_i} = minFlightLength{clust_i} - preDur*CNMFe_Fs - postDur*CNMFe_Fs; + behavLength{clust_i} = minBehavFlightLength{clust_i} - preDur*track_Fs - postDur*track_Fs; + %try + act_aligned{clust_i} = cellfun(@(c) c(:,1:minFlightLength{clust_i}), activity_allTrials.act_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + act_pre{clust_i} = cellfun(@(c) c(:,1:preDur*CNMFe_Fs), activity_allTrials.act_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + act_dur{clust_i} = cellfun(@(c) c(:,1+preDur*CNMFe_Fs:minFlightLength{clust_i}-postDur*CNMFe_Fs), activity_allTrials.act_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + act_post{clust_i} = cellfun(@(c) c(:,1+ minFlightLength{clust_i}-postDur*CNMFe_Fs:minFlightLength{clust_i}), activity_allTrials.act_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + vel_aligned{clust_i} = cellfun(@(c) c(:,1:minBehavFlightLength{clust_i}), activity_allTrials.vel_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + vel_pre{clust_i} = cellfun(@(c) c(:,1:preDur*track_Fs), activity_allTrials.vel_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + vel_dur{clust_i} = cellfun(@(c) c(:,1+preDur*track_Fs:minBehavFlightLength{clust_i}-postDur*track_Fs), activity_allTrials.vel_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + vel_post{clust_i} = cellfun(@(c) c(:,1+minBehavFlightLength{clust_i}-postDur*track_Fs:minBehavFlightLength{clust_i}), activity_allTrials.vel_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + XY_dur{clust_i} = cellfun(@(c) c(:,:,1+preDur*track_Fs:minBehavFlightLength{clust_i}-postDur*track_Fs), activity_allTrials.XY_dur{clust_i},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + %catch + %end + + %mean and std of the trials as a whole for correlations in future + mean_act_aligned{clust_i} = cellfun(@nanmean,act_aligned{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_act_aligned{clust_i} = cellfun(@nanstd,act_aligned{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_act_pre{clust_i} = cellfun(@nanmean,act_pre{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_act_pre{clust_i} = cellfun(@nanstd,act_pre{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_act_dur{clust_i} = cellfun(@nanmean,act_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_act_dur{clust_i} = cellfun(@nanstd,act_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_act_post{clust_i} = cellfun(@nanmean,act_post{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_act_post{clust_i} = cellfun(@nanstd,act_post{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_vel_aligned{clust_i} = cellfun(@nanmean,vel_aligned{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_vel_aligned{clust_i} = cellfun(@nanstd,vel_aligned{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_vel_pre{clust_i} = cellfun(@nanmean,vel_pre{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_vel_pre{clust_i} = cellfun(@nanstd,vel_pre{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_vel_dur{clust_i} = cellfun(@nanmean,vel_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_vel_dur{clust_i} = cellfun(@nanstd,vel_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_vel_post{clust_i} = cellfun(@nanmean,vel_post{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_vel_post{clust_i} = cellfun(@nanstd,vel_post{clust_i},'UniformOutput',false); %take the mean of the aligned traces + mean_XY_dur{clust_i} = cellfun(@nanmean,XY_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + std_XY_dur{clust_i} = cellfun(@nanstd,XY_dur{clust_i},'UniformOutput',false); %take the mean of the aligned traces + + + %initialize matrices to hold mean and stds of each day/roi + meanMax_act_aligned{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + stdMax_act_aligned{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + meanMax_act_pre{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + stdMax_act_pre{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + meanMax_act_dur{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + stdMax_act_dur{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + meanMax_act_post{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + stdMax_act_post{clust_i} = zeros(size(days,2),size(act_aligned{clust_i},2)); + ylab{clust_i} = cell(1,3); + overlapSorted{clust_i} = cell(size(days,2),3); + intersectDays{clust_i} = cell(1,3); + + %determine the max,mean, and std for the pre, dur, post data + for day_i = 1:length(days) + for roi_i = 1:size(act_aligned{clust_i},2) + for flight_i = 1:size(act_aligned{clust_i}{days(day_i),roi_i},1) + [~,max_act_aligned{clust_i}{day_i,roi_i}(flight_i,1)] = max(act_aligned{clust_i}{days(day_i),roi_i}(flight_i,:)); + [~,max_act_pre{clust_i}{day_i,roi_i}(flight_i,1)] = max(act_pre{clust_i}{days(day_i),roi_i}(flight_i,:)); + [~,max_act_dur{clust_i}{day_i,roi_i}(flight_i,1)] = max(act_dur{clust_i}{days(day_i),roi_i}(flight_i,:)); + [~,max_act_post{clust_i}{day_i,roi_i}(flight_i,1)] = max(act_post{clust_i}{days(day_i),roi_i}(flight_i,:)); + end + meanMax_act_aligned{clust_i}(day_i,roi_i) = round(mean(max_act_aligned{clust_i}{day_i,roi_i})); + stdMax_act_aligned{clust_i}(day_i,roi_i) = round(std(max_act_aligned{clust_i}{day_i,roi_i})); + meanMax_act_pre{clust_i}(day_i,roi_i) = round(mean(max_act_pre{clust_i}{day_i,roi_i})); + stdMax_act_pre{clust_i}(day_i,roi_i) = round(std(max_act_pre{clust_i}{day_i,roi_i})); + meanMax_act_dur{clust_i}(day_i,roi_i) = round(mean(max_act_dur{clust_i}{day_i,roi_i})); + stdMax_act_dur{clust_i}(day_i,roi_i) = round(std(max_act_dur{clust_i}{day_i,roi_i})); + meanMax_act_post{clust_i}(day_i,roi_i) = round(mean(max_act_post{clust_i}{day_i,roi_i})); + stdMax_act_post{clust_i}(day_i,roi_i) = round(std(max_act_post{clust_i}{day_i,roi_i})); + end + %sort the means of maxes for each full, pre, dur, and post + [BmeanMax_act_aligned{clust_i}(day_i,:),ImeanMax_act_aligned{clust_i}(day_i,:)] = sort(meanMax_act_aligned{clust_i}(day_i,:)); + [BmeanMax_act_pre{clust_i}(day_i,:),ImeanMax_act_pre{clust_i}(day_i,:)] = sort(meanMax_act_pre{clust_i}(day_i,:)); + [BmeanMax_act_dur{clust_i}(day_i,:),ImeanMax_act_dur{clust_i}(day_i,:)] = sort(meanMax_act_dur{clust_i}(day_i,:)); + [BmeanMax_act_post{clust_i}(day_i,:),ImeanMax_act_post{clust_i}(day_i,:)] = sort(meanMax_act_post{clust_i}(day_i,:)); + + %load the stable place cell data for each day + cd(dirDates(days(day_i)).name); + dirExtracted = dir('*Extracted_trajectories*'); + load(dirExtracted(end).name); + cd(dirDates(days(day_i)).folder); + %pullout the selectively active cells + selectiveCells{day_i,1} = placeCellsAngStable.ppre_cells; + selectiveCells{day_i,2} = placeCellsAngStable.pp_cells; + selectiveCells{day_i,3} = placeCellsAngStable.ppost_cells; + end +end +%sort the means of the maxes so that they are in chronological order +%across ROIs +for day_i = 1:length(days) + for clust_ii = 1:size(selectiveCells{day_i,1},1) + for phase_i = 1:size(selectiveCells,2) + findSelectiveCells{clust_ii}{day_i,phase_i} = find(selectiveCells{day_i,phase_i}(clust_ii,:)); + if phase_i == 1 + [BSelectiveCells{clust_ii}{day_i,phase_i},ISelectiveCells{clust_ii}{day_i,phase_i}] = sort(meanMax_act_pre{clust_ii}(day_i,findSelectiveCells{clust_ii}{day_i,phase_i})); + elseif phase_i == 2 + [BSelectiveCells{clust_ii}{day_i,phase_i},ISelectiveCells{clust_ii}{day_i,phase_i}] = sort(meanMax_act_dur{clust_ii}(day_i,findSelectiveCells{clust_ii}{day_i,phase_i})); + elseif phase_i == 3 + [BSelectiveCells{clust_ii}{day_i,phase_i},ISelectiveCells{clust_ii}{day_i,phase_i}] = sort(meanMax_act_post{clust_ii}(day_i,findSelectiveCells{clust_ii}{day_i,phase_i})); + end + end + end +end + +%find ROIs that intersect across all days +for clust_ii = 1:size(clustList,1) + for day_i = 1:size(selectiveCells,1) + for phase_i = 1:size(selectiveCells,2) + try %make a list of the intersecting cells so it can be concatenated and sorted later + intersectList{clust_ii,phase_i}{day_i} = ISelectiveCells{clustList(clust_ii,day_i)}{day_i,phase_i}; + catch + end + end + end +end +for clust_ii = 1:size(clustList,1) + for day_i = 1:size(selectiveCells,1) + for phase_i = 1:size(selectiveCells,2) + intersectDays{clust_ii+1}{phase_i} = mintersect(intersectList{clust_ii,phase_i}{:}); + roiNum = 1; %counter + for roi_i = 1:length(ISelectiveCells{clust_ii+1}{day_i,phase_i}) + if ismember(ISelectiveCells{clust_ii+1}{day_i,phase_i}(roi_i),intersectDays{clust_ii+1}{phase_i}) + overlapSorted{clust_ii+1}{day_i,phase_i}(roiNum) = ISelectiveCells{clust_ii+1}{day_i,phase_i}(roi_i); %sort each intersecting ROI based on the sorting from the original data + if day_i ==1 + ylab{clust_ii+1}{phase_i} = [ylab{clust_ii+1}{phase_i} overlapSorted{clust_ii+1}{1,phase_i}(roiNum)];%make label for the yaxis for the plots + end + roiNum = roiNum +1; + end + end + end + end +end + +dataPreDurPost.batId = batId; +dataPreDurPost.nDays = nDays; +dataPreDurPost.day1 = day1; +dataPreDurPost.dayEnd = dayEnd; +dataPreDurPost.days = days; +dataPreDurPost.clusts = clusts; +dataPreDurPost.preDur = preDur; +dataPreDurPost.postDur = postDur; +dataPreDurPost.CNMFe_Fs = CNMFe_Fs; +dataPreDurPost.track_Fs = track_Fs; +dataPreDurPost.minFlightLength = minFlightLength; +dataPreDurPost.flightLength = flightLength; +dataPreDurPost.act_aligned = act_aligned; +dataPreDurPost.act_pre = act_pre; +dataPreDurPost.act_dur = act_dur; +dataPreDurPost.act_post = act_post; +dataPreDurPost.mean_act_aligned = mean_act_aligned; +dataPreDurPost.std_act_aligned = std_act_aligned; +dataPreDurPost.mean_act_pre = mean_act_pre; +dataPreDurPost.std_act_pre = std_act_pre; +dataPreDurPost.mean_act_dur = mean_act_dur; +dataPreDurPost.std_act_dur = std_act_dur; +dataPreDurPost.mean_act_post = mean_act_post; +dataPreDurPost.std_act_post = std_act_post; + +dataPreDurPost.minBehavFlightLength = minBehavFlightLength; +dataPreDurPost.behavLength = behavLength; +dataPreDurPost.vel_aligned = vel_aligned; +dataPreDurPost.vel_pre = vel_pre; +dataPreDurPost.vel_dur = vel_dur; +dataPreDurPost.vel_post = vel_post; +dataPreDurPost.mean_vel_aligned = mean_vel_aligned; +dataPreDurPost.std_vel_aligned = std_vel_aligned; +dataPreDurPost.mean_vel_pre = mean_vel_pre; +dataPreDurPost.std_vel_pre = std_vel_pre; +dataPreDurPost.mean_vel_dur = mean_vel_dur; +dataPreDurPost.std_vel_dur = std_vel_dur; +dataPreDurPost.mean_vel_post = mean_vel_post; +dataPreDurPost.std_vel_post = std_vel_post; +dataPreDurPost.XY_dur = XY_dur; +dataPreDurPost.mean_XY_dur = mean_XY_dur; +dataPreDurPost.std_XY_dur = std_XY_dur; + +dataPreDurPost.meanMax_act_aligned = meanMax_act_aligned; +dataPreDurPost.stdMax_act_aligned = stdMax_act_aligned; +dataPreDurPost.meanMax_act_pre = meanMax_act_pre; +dataPreDurPost.stdMax_act_pre = stdMax_act_aligned; +dataPreDurPost.meanMax_act_dur = meanMax_act_dur; +dataPreDurPost.stdMax_act_dur = stdMax_act_aligned; +dataPreDurPost.meanMax_act_post = meanMax_act_post; +dataPreDurPost.stdMax_act_post = stdMax_act_aligned; +dataPreDurPost.ylab = ylab; +dataPreDurPost.overlapSorted = overlapSorted; +dataPreDurPost.intersectDays = intersectDays; +dataPreDurPost.BmeanMax_act_aligned = BmeanMax_act_aligned; +dataPreDurPost.ImeanMax_act_aligned = ImeanMax_act_aligned; +dataPreDurPost.BmeanMax_act_pre = BmeanMax_act_pre; +dataPreDurPost.ImeanMax_act_pre = ImeanMax_act_pre; +dataPreDurPost.BmeanMax_act_dur = BmeanMax_act_dur; +dataPreDurPost.ImeanMax_act_dur = ImeanMax_act_dur; +dataPreDurPost.BmeanMax_act_post = BmeanMax_act_post; +dataPreDurPost.ImeanMax_act_post = ImeanMax_act_post; +dataPreDurPost.selectiveCells = selectiveCells; +dataPreDurPost.findSelectiveCells = findSelectiveCells; +dataPreDurPost.BSelectiveCells = BSelectiveCells; +dataPreDurPost.ISelectiveCells = ISelectiveCells; + +if saveFlag == 1 + if strcmp(batId,'Gal') + save([pwd filesep '200311to200324_Gal_dataPreDurPost_' saveTag '.mat'],'dataPreDurPost'); + elseif strcmp(batId,'Gen') + save([pwd filesep '200319to200324_Gen_dataPreDurPost_' saveTag '.mat'],'dataPreDurPost'); + end +end + diff --git a/analysis_tobias/ImBat_extract_noResponseCells.asv b/analysis_tobias/ImBat_extract_noResponseCells.asv new file mode 100644 index 0000000..c58aa7a --- /dev/null +++ b/analysis_tobias/ImBat_extract_noResponseCells.asv @@ -0,0 +1,25 @@ +function [placeCells] = ImBat_extract_noReponseCells(placeCells) +nClusters = size(placeCells.pp_cells,1); +roiDir = dir('*ROI_*'); +roiNum = zeros(1,length(roiDir)); +for roi_i = 1:length(roiDir) + %find all ROI numbers + roiLong = extractAfter(roiDir(roi_i).name,'ROI_'); + roiNum(roi_i) = str2num(extractBefore(roiLong,'_cluster')); + +end + +roiNone = []; +for idx_i = 1:length(roiNum) + try +consecIdx = roiNum(idx_i:idx_i+nClusters-2); + catch + end + + if sum(consecIdx)/3 == consecIdx(1) + roiNone = [roiNone consecIdx(1)]; + end +end + +placeCells.cells_none = roiNone; + diff --git a/analysis_tobias/ImBat_extract_noResponseCells.m b/analysis_tobias/ImBat_extract_noResponseCells.m new file mode 100644 index 0000000..a36a444 --- /dev/null +++ b/analysis_tobias/ImBat_extract_noResponseCells.m @@ -0,0 +1,25 @@ +function [placeCells] = ImBat_extract_noResponseCells(placeCells) +nClusters = size(placeCells.pp_cells,1); +roiDir = dir('*ROI_*'); +roiNum = zeros(1,length(roiDir)); +for roi_i = 1:length(roiDir) + %find all ROI numbers + roiLong = extractAfter(roiDir(roi_i).name,'ROI_'); + roiNum(roi_i) = str2num(extractBefore(roiLong,'_cluster')); + +end + +roiNone = []; +for idx_i = 1:length(roiNum) + try +consecIdx = roiNum(idx_i:idx_i+nClusters-2); + catch + end + + if sum(consecIdx)/3 == consecIdx(1) + roiNone = [roiNone consecIdx(1)]; + end +end + +placeCells.cells_none = roiNone; + diff --git a/analysis_tobias/ImBat_extract_placeCells.asv b/analysis_tobias/ImBat_extract_placeCells.asv new file mode 100644 index 0000000..7442f4e --- /dev/null +++ b/analysis_tobias/ImBat_extract_placeCells.asv @@ -0,0 +1,107 @@ +allBatsTag = 0; +inspectNoTuneFlag = 0; +batId = 'Ge'; +saveFlag = 1; +saveTag = '-bitsPerSec-angelo-max'; + +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd')])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd')]) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep]; +end + +if allBatsTag == 1 + allBats = [{'Gal'} {'Ge'} {'Ge_2'} {'Gi'} {'Go'} {'z2'} {'za'} {'zu'}]; + nBats = length(allBats); +else + nBats = 1; +end + +nDays = 2;%length(dayDir); +%initialize matrices +percPre = nan(nBats,nDays); +percPlace = nan(nBats,nDays); +percFlight = nan(nBats,nDays); +percPost = nan(nBats,nDays); +percAny = nan(nBats,nDays); +percNone = nan(nBats,nDays); + + + +%for each day, calculate percentages of each phase +for day_i = 1:2%length(dayDir) + cd([dayDir(day_i).name filesep 'extracted']); + %find all fly directories and enter last one + flyDir = dir('*_fly-*_extraction'); + cd(flyDir(end).name); + %find and enter last analysis folder + analysisDir = dir('analysis_*'); + cd([analysisDir(end).name filesep 'placeCellsAng']); + %load placeCell structure for % analysis + placeCellStruct = dir('*_ExtractedPlaceCells_*'); + load(placeCellStruct.name); + + %save percentages into a cell + percPre(day_i) = placeCells.perc_pre; + percPlace(day_i) = placeCells.perc_place; + percFlight(day_i) = placeCells.perc_place_loose; + percPost(day_i) = placeCells.perc_post; + percNone(day_i) = placeCells.perc_none; + percAny(day_i) = 1 - placeCells.perc_none; + + %transfer the pre/place/post cells into respective folders + [placeCells ] = ImBat_transferPlaceCells(placeCells) + + %find all the cells not tuned to any phase + [placeCells] = ImBat_extract_noResponseCells(placeCells) + cd ..; + save(placeCellStruct.name,'placeCells'); + cd(dayDir(day_i).folder); + + if inspectNoTuneFlag == 1 + % ImBat_inspect_noTuneCells(placeCells) + end + +end + +%% concatenate and average all the days +percMean = [nanmean(percPre); nanmean(percPlace); nanmean(percPost); nanmean(percAny)]; +percSEM = [nanstd(percPre)./sqrt(size(percPre,2)); nanstd(percPlace)./sqrt(size(percPlace,2)); nanstd(percPost)./sqrt(size(percPost,2)); nanstd(percAny)./sqrt(size(percAny,2))]; +percAll = [percPre' percPlace' percFlight' percPost' percAny' percNone']; +%make figure for percentages +figPercMean = figure(); +bar(percMean); +hold on; +er = errorbar(percMean,percSEM); +er.Color = [0 0 0]; +er.LineStyle = 'none'; +xlabel('Flight phase'); +ylabel('%'); +xticklabels({'Pre', 'Place', 'Post', 'Any'}); +title([batId ': Mean % of Pre, Place, Post Cells across ' num2str(nDays) ' days ' saveTag]); + +figPercAll = figure(); +bar(percAll); +hold on; +xlabel('Day'); +ylabel('%'); +legend({'Pre', 'Place','Flight','Post', 'Any','None'}); +title([batId ': % of Pre, Place, Post Cells across ' num2str(nDays) ' days ' saveTag]); + +%save figs +if saveFlag == 1 +savefig(figPercMean,[saveDir batId '_percPrePlacePostCells_mean_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); +saveas(figPercMean, [saveDir batId '_percPrePlacePostCells_mean_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); +savefig(figPercAll,[saveDir batId '_percPrePlacePostCells_all_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); +saveas(figPercAll, [saveDir batId '_percPrePlacePostCells_all_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); +end + + + + diff --git a/analysis_tobias/ImBat_extract_placeCells.m b/analysis_tobias/ImBat_extract_placeCells.m new file mode 100644 index 0000000..caa1a34 --- /dev/null +++ b/analysis_tobias/ImBat_extract_placeCells.m @@ -0,0 +1,109 @@ +allBatsTag = 0; +inspectNoTuneFlag = 0; +batId = 'Ge'; +saveFlag = 1; +saveTag = 'newSI'; + +if saveFlag == 1 + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd')])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd')]) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep]; +end + +if allBatsTag == 1 + allBats = [{'Gal'} {'Ge'} {'Ge_2'} {'Gi'} {'Go'} {'z2'} {'za'} {'zu'}]; + nBats = length(allBats); +else + nBats = 1; +end + +dayDir = dir([batId(1:2) '*']); + +nDays = 2;%length(dayDir); +%initialize matrices +percPre = nan(nBats,nDays); +percPlace = nan(nBats,nDays); +percFlight = nan(nBats,nDays); +percPost = nan(nBats,nDays); +percAny = nan(nBats,nDays); +percNone = nan(nBats,nDays); + + + +%for each day, calculate percentages of each phase +for day_i = 1:2%length(dayDir) + cd([dayDir(day_i).name filesep 'extracted']); + %find all fly directories and enter last one + flyDir = dir('*_fly-*_extraction'); + cd(flyDir(end).name); + %find and enter last analysis folder + analysisDir = dir('analysis_*'); + cd([analysisDir(end).name filesep 'placeCellsAng']); + %load placeCell structure for % analysis + placeCellStruct = dir('*_ExtractedPlaceCells_*'); + load(placeCellStruct.name); + + %save percentages into a cell + percPre(day_i) = placeCells.perc_pre; + percPlace(day_i) = placeCells.perc_place; + percFlight(day_i) = placeCells.perc_place_loose; + percPost(day_i) = placeCells.perc_post; + percNone(day_i) = placeCells.perc_none; + percAny(day_i) = 1 - placeCells.perc_none; + + %transfer the pre/place/post cells into respective folders + [placeCells ] = ImBat_transferPlaceCells(placeCells) + + %find all the cells not tuned to any phase + [placeCells] = ImBat_extract_noResponseCells(placeCells) + cd ..; + save(placeCellStruct.name,'placeCells'); + cd(dayDir(day_i).folder); + + if inspectNoTuneFlag == 1 + % ImBat_inspect_noTuneCells(placeCells) + end + +end + +%% concatenate and average all the days +percMean = [nanmean(percPre); nanmean(percPlace); nanmean(percPost); nanmean(percAny)]; +percSEM = [nanstd(percPre)./sqrt(size(percPre,2)); nanstd(percPlace)./sqrt(size(percPlace,2)); nanstd(percPost)./sqrt(size(percPost,2)); nanstd(percAny)./sqrt(size(percAny,2))]; +percAll = [percPre' percPlace' percFlight' percPost' percAny' percNone']; +%make figure for percentages +figPercMean = figure(); +bar(percMean); +hold on; +er = errorbar(percMean,percSEM); +er.Color = [0 0 0]; +er.LineStyle = 'none'; +xlabel('Flight phase'); +ylabel('%'); +xticklabels({'Pre', 'Place', 'Post', 'Any'}); +title([batId ': Mean % of Pre, Place, Post Cells across ' num2str(nDays) ' days ' saveTag]); + +figPercAll = figure(); +bar(percAll); +hold on; +xlabel('Day'); +ylabel('%'); +legend({'Pre', 'Place','Flight','Post', 'Any','None'}); +title([batId ': % of Pre, Place, Post Cells across ' num2str(nDays) ' days ' saveTag]); + +%save figs +if saveFlag == 1 +savefig(figPercMean,[saveDir batId '_percPrePlacePostCells_mean_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); +saveas(figPercMean, [saveDir batId '_percPrePlacePostCells_mean_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); +savefig(figPercAll,[saveDir batId '_percPrePlacePostCells_all_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); +saveas(figPercAll, [saveDir batId '_percPrePlacePostCells_all_' saveTag '_' datestr(now,'yymmdd-HHMM') '.jpg']); +end + + + + diff --git a/analysis_tobias/ImBat_functionalStability_allDays.m b/analysis_tobias/ImBat_functionalStability_allDays.m new file mode 100644 index 0000000..1ab116c --- /dev/null +++ b/analysis_tobias/ImBat_functionalStability_allDays.m @@ -0,0 +1,223 @@ +function ImBat_functionalStability_allDays(dataPreDurPost) +batId = 'Gen'; +saveFlag = 1; +stdFlag = 0; +cRaw = 0; +%load first day placeCellStableROI data +%cd([dirTop(day1).folder filesep 'plots\200911-preDurPost cells across days']); +%if cRaw == 1 +%load('200311to200320_activity_allTrials_Gal.mat'); %load activity for pre,dur,post +%load('200311to200320_Gal_activity_allTrials_allClusts_sMat.mat'); %load s matrix activity data +saveTag = ['selectiveCells_consistent_allDays_sMat_std']; +if strcmp(batId,'Gal') + dirDates = dir('Gal_*'); +elseif strcmp(batId,'Gen') + dirDates = dir('Gen_*'); +end +nDays = length(dirDates); +day1 = 1; %first day to start comparing +dayEnd = nDays; %last day to start comparing +days = [1:5]; %all days concat +clusts = 2; +preDur = 90; %pre takeoff +postDur = 210; %post takeoff +if strcmp(batId,'Gal') + clustList = [2 2 2 2 2 2 2 2 2; 3 5 3 3 3 3 3 3 5; 1 3 4 6 4 11 1 1 8]; +elseif strcmp(batId,'Gen') + clustList = [2 2 2 2 2; 3 3 3 3 3]; +end + + +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'functionalStability'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'functionalStability']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'functionalStability' '\']; +end +% +% %pull in/cutout all the aligned, pre, dur, and post data +% minFlightLength = min(cellfun('size',activity_allTrials.act_dur{clusts}(:,1),2)); %shortest flight length for each day since they may be slightly different lengths +% flightLength = minFlightLength - preDur - postDur; +% act_aligned = cellfun(@(c) c(:,1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% act_pre = cellfun(@(c) c(:,1:preDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% act_dur = cellfun(@(c) c(:,preDur+1:minFlightLength-postDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% act_post = cellfun(@(c) c(:,minFlightLength-postDur+1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% +% %initialize matrices to hold mean and stds of each day/roi +% meanMax_act_aligned = zeros(size(days,2),size(act_aligned,2)); +% stdMax_act_aligned = zeros(size(days,2),size(act_aligned,2)); +% meanMax_act_pre = zeros(size(days,2),size(act_aligned,2)); +% stdMax_act_pre = zeros(size(days,2),size(act_aligned,2)); +% meanMax_act_dur = zeros(size(days,2),size(act_aligned,2)); +% stdMax_act_dur = zeros(size(days,2),size(act_aligned,2)); +% meanMax_act_post = zeros(size(days,2),size(act_aligned,2)); +% stdMax_act_post = zeros(size(days,2),size(act_aligned,2)); +% ylab = cell(1,3); +% overlapSorted = cell(size(days,2),3); +% intersectDays = cell(1,3); +% +% %determine the max,mean, and std for the pre, dur, post data +% for day_i = 1:length(days) +% for roi_i = 1:size(act_aligned,2) +% for flight_i = 1:size(act_aligned{days(day_i),roi_i},1) +% [~,max_act_aligned{day_i,roi_i}(flight_i,1)] = max(act_aligned{days(day_i),roi_i}(flight_i,:)); +% [~,max_act_pre{day_i,roi_i}(flight_i,1)] = max(act_pre{days(day_i),roi_i}(flight_i,:)); +% [~,max_act_dur{day_i,roi_i}(flight_i,1)] = max(act_dur{days(day_i),roi_i}(flight_i,:)); +% [~,max_act_post{day_i,roi_i}(flight_i,1)] = max(act_post{days(day_i),roi_i}(flight_i,:)); +% end +% meanMax_act_aligned(day_i,roi_i) = round(mean(max_act_aligned{day_i,roi_i})); +% stdMax_act_aligned(day_i,roi_i) = round(std(max_act_aligned{day_i,roi_i})); +% meanMax_act_pre(day_i,roi_i) = round(mean(max_act_pre{day_i,roi_i})); +% stdMax_act_pre(day_i,roi_i) = round(std(max_act_pre{day_i,roi_i})); +% meanMax_act_dur(day_i,roi_i) = round(mean(max_act_dur{day_i,roi_i})); +% stdMax_act_dur(day_i,roi_i) = round(std(max_act_dur{day_i,roi_i})); +% meanMax_act_post(day_i,roi_i) = round(mean(max_act_post{day_i,roi_i})); +% stdMax_act_post(day_i,roi_i) = round(std(max_act_post{day_i,roi_i})); +% end +% %sort the means of maxes for each full, pre, dur, and post +% [BmeanMax_act_aligned(day_i,:),ImeanMax_act_aligned(day_i,:)] = sort(meanMax_act_aligned(day_i,:)); +% [BmeanMax_act_pre(day_i,:),ImeanMax_act_pre(day_i,:)] = sort(meanMax_act_pre(day_i,:)); +% [BmeanMax_act_dur(day_i,:),ImeanMax_act_dur(day_i,:)] = sort(meanMax_act_dur(day_i,:)); +% [BmeanMax_act_post(day_i,:),ImeanMax_act_post(day_i,:)] = sort(meanMax_act_post(day_i,:)); +% +% %load the stable place cell data for each day +% cd(dirGalDates(days(day_i)).name); +% dirExtracted = dir('*Extracted_trajectories*'); +% load(dirExtracted(end).name); +% cd(dirGalDates(days(day_i)).folder); +% %pullout the selectively active cells +% selectiveCells{day_i,1} = placeCellsAngStable.ppre_cells; +% selectiveCells{day_i,2} = placeCellsAngStable.pp_cells; +% selectiveCells{day_i,3} = placeCellsAngStable.ppost_cells; +% +% %sort the means of the maxes so that they are in chronological order +% %across ROIs +% for phase_i = 1:size(selectiveCells,2) +% findSelectiveCells{day_i,phase_i} = find(selectiveCells{day_i,phase_i}(clusts,:)); +% if phase_i == 1 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_pre(day_i,findSelectiveCells{day_i,phase_i})); +% elseif phase_i == 2 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_dur(day_i,findSelectiveCells{day_i,phase_i})); +% elseif phase_i == 3 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_post(day_i,findSelectiveCells{day_i,phase_i})); +% end +% end +% end +% +% %find ROIs that intersect across all days +% for day_i = 1:size(selectiveCells,1) +% for phase_i = 1:size(selectiveCells,2) +% intersectDays{phase_i} = mintersect(ISelectiveCells{:,phase_i}); %all intersecting ROIs across all days +% roiNum = 1; %counter +% for roi_i = 1:length(ISelectiveCells{day_i,phase_i}) +% if ismember(ISelectiveCells{day_i,phase_i}(roi_i),intersectDays{phase_i}) +% overlapSorted{day_i,phase_i}(roiNum) = ISelectiveCells{day_i,phase_i}(roi_i); %sort each intersecting ROI based on the sorting from the original data +% if day_i ==1 +% ylab{phase_i} = [ylab{phase_i} overlapSorted{1,phase_i}(roiNum)];%make label for the yaxis for the plots +% end +% roiNum = roiNum +1; +% end +% end +% end +% end +%% plot only consistent cells +if strcmp(batId,'Gal') + clustList = [2 2 2 2 2 2 2 2 2; 3 5 3 3 3 3 3 3 5; 1 3 4 6 4 11 1 1 8]; +elseif strcmp(batId,'Gen') + clustList = [2 2 2 2 2; 3 3 3 3 3]; +end +functionalStabilityDotPlot_consistent_all = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +for clust_i = 1:size(clustList,1); + sgtitle([batId ': Functional Stability of Consistently Selectively Active Cells: All Days: Cluster ' num2str(clust_i+1)]); + colorDays = jet(length(days)); %make the color vector for each day + for day_i = 1:size(dataPreDurPost.selectiveCells,1) + roiStableCounter = length([dataPreDurPost.intersectDays{clust_i+1}{:}]); %roi counter + for phase_i = 1:size(dataPreDurPost.selectiveCells,2) + for roi_i = 1:length([dataPreDurPost.intersectDays{clust_i+1}{phase_i}]) + hold on; + %plot the mean of the max and std for each ROI + if phase_i == 1 + if stdFlag ==1 + p1(day_i) = plot(dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter-str2num(['0.' num2str(day_i)]),'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + p2 = plot(dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))-round(dataPreDurPost.stdMax_act_pre{clustList(clust_i,day_i)}(day_i,roi_i)/2):1:dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))+round(dataPreDurPost.stdMax_act_pre{clustList(clust_i,day_i)}(day_i,roi_i)/2),... + (ones(round(dataPreDurPost.stdMax_act_pre{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*roiStableCounter)-(ones(round(dataPreDurPost.stdMax_act_pre{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*str2num(['0.' num2str(day_i)])) ,'-','Color',[colorDays(day_i,:) 0.5],'LineWidth',1); + else + p1(day_i) = plot(dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter,'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + end + elseif phase_i == 2 + if stdFlag ==1 + p1(day_i) = plot(preDur + dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter-str2num(['0.' num2str(day_i)]),'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + p2 = plot(1+preDur+dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))-round(stdMax_act_dur{clustList(clust_i,day_i)}(day_i,roi_i)/2):1:preDur+dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))+round(dataPreDurPost.stdMax_act_dur{clustList(clust_i,day_i)}(day_i,roi_i)/2),... + (ones(round(dataPreDurPost.stdMax_act_dur{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*roiStableCounter)-(ones(round(dataPreDurPost.stdMax_act_dur{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*str2num(['0.' num2str(day_i)])) ,'-','Color',[colorDays(day_i,:) 0.5],'LineWidth',1); + else + p1(day_i) = plot(preDur + dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter,'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + end + elseif phase_i == 3 + if stdFlag ==1 + p1(day_i) = plot(preDur + dataPreDurPost.flightLength{clustList(clust_i,day_i)} + dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter-str2num(['0.' num2str(day_i)]),'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + p2 = plot(1+preDur+dataPreDurPost.flightLength{clustList(clust_i,day_i)}+dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))-round(dataPreDurPost.stdMax_act_post{clustList(clust_i,day_i)}(day_i,roi_i)/2):1:preDur+dataPreDurPost.flightLength{clustList(clust_i,day_i)}+dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i))+round(dataPreDurPost.stdMax_act_post{clustList(clust_i,day_i)}(day_i,roi_i)/2),... + (ones(round(dataPreDurPost.stdMax_act_post{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*roiStableCounter)-(ones(round(dataPreDurPost.stdMax_act_post{clustList(clust_i,day_i)}(day_i,roi_i)/2)*2)*str2num(['0.' num2str(day_i)])) ,'-','Color',[colorDays(day_i,:) 0.5],'LineWidth',1); + else + p1(day_i) = plot(preDur + dataPreDurPost.flightLength{clustList(clust_i,day_i)} + dataPreDurPost.BSelectiveCells{clustList(clust_i,day_i)}{day_i,phase_i}(dataPreDurPost.intersectDays{clust_i+1}{phase_i}(roi_i)),roiStableCounter,'.','Color',[colorDays(day_i,:) 0.5],'MarkerSize',20); + end + end + roiStableCounter = roiStableCounter - 1; + hold on; + end + flipYlab{phase_i} = flip(dataPreDurPost.ylab{clustList(clust_i,day_i)}{phase_i}); %flip the ylabels so they are top to bottom in order + end + end + sumOverlaps = length([dataPreDurPost.intersectDays{clust_i+1}{:}]); %total number of ROIs plotted + %make dotted line for pre and post marker + xPre=preDur*ones(1,sumOverlaps*2+1); + xPost=(preDur+dataPreDurPost.flightLength{clustList(clust_i,day_i)})*ones(1,sumOverlaps*2+1); + plot(xPre,1:0.5:sumOverlaps+1,'k.'); + plot(xPost,1:0.5:sumOverlaps+1,'k.'); + axis([0 dataPreDurPost.minFlightLength{clustList(clust_i,day_i)} 0 sumOverlaps+1]); + set(gca,'YTick',[1:sumOverlaps],'yticklabel',[dataPreDurPost.ylab{clustList(clust_i,day_i)}{:}]); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('Time (s)'); + ylabel('ROI #'); + try + if strcmp(batId,'Gen') + legend([p1(1),p1(2),p1(3),p1(4),p1(5)],'Day 1','Day 2','Day 3','Day 4','Day 5'); + elseif strcmp(batId,'Gal') + legend([p1(1),p1(2),p1(3),p1(4),p1(5),p1(6),p1(7),p1(8),p1(9)],'Day 1','Day 2','Day 3','Day 4','Day 5','Day 6','Day 7','Day 8','Day 9'); + end + catch + end + + + if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + + end + + end + + %zoom in and resave + axis([preDur+dataPreDurPost.flightLength{clustList(clust_i,day_i)} 360 0 sumOverlaps+1]); %dataPreDurPost.minFlightLength{clustList(clust_i,day_i)} 0 sumOverlaps+1]); + drawnow; + if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_' saveTag '_zoom_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_' saveTag '_zoom_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(functionalStabilityDotPlot_consistent_all,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_' saveTag '_clust' num2str(clust_i+1) '_' datestr(now,'yymmdd-HHMM') '.fig']); + + end + end + clf; +end diff --git a/analysis_tobias/ImBat_functionalStability_compareDays.m b/analysis_tobias/ImBat_functionalStability_compareDays.m new file mode 100644 index 0000000..cf31b43 --- /dev/null +++ b/analysis_tobias/ImBat_functionalStability_compareDays.m @@ -0,0 +1,338 @@ +function ImBat_functionalStability_compareDays(batId) + +saveFlag = 1; + +%load first day placeCellStableROI data +%cd([dirTop(day1).folder filesep 'plots\200911-preDurPost cells across days']); +if strcmp(batId,'Gal') +load('200311to200320_Gal_activity_allTrials_allClusts_sMat_vel.mat'); %load s matrix activity data +dirDates = dir('Gal_*'); +elseif strcmp(batId,'Gen') +load('200319to200324_Gen_activity_allTrials_allClusts_sMat_vel.mat'); %load s matrix activity data +dirDates = dir('Gen_*'); +end +%load('200311to200320_activity_allTrials_Gal.mat'); %load activity for pre, +%dur, post with craw data +nDays = length(dirDates); +day1 = 1; +dayEnd = 11; +days = [day1 nDays]; +clusts = 2; +preDur = 90; +postDur = 210; + + +if saveFlag == 1 + saveTag = [num2str(day1) 'v' num2str(nDays)]; + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'functionalStability'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'functionalStability']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'functionalStability' '\']; +end + +cd(dirDates(day1).name); +dirExtracted = dir('*Extracted_trajectories*'); +load(dirExtracted(end).name); +selectiveCells1 = placeCellsAngStable; +cd(dirDates(day1).folder); + +%load last day PlaceCellStableROI data +cd(dirDates(nDays).name); +dirExtracted = dir('*Extracted_trajectories*'); +load(dirExtracted(end).name); +selectiveCellsEnd = placeCellsAngStable; +cd(dirDates(day1).folder); + +%pullout the selectively active cells +selectiveCells{1,1} = selectiveCells1.ppre_cells; +selectiveCells{1,2} = selectiveCells1.pp_cells; +selectiveCells{1,3} = selectiveCells1.ppost_cells; +selectiveCells{2,1} = selectiveCellsEnd.ppre_cells; +selectiveCells{2,2} = selectiveCellsEnd.pp_cells; +selectiveCells{2,3} = selectiveCellsEnd.ppost_cells; + +% minFlightLength = min(cellfun('size',activity_allTrials.act_dur{clusts}(:,1),2)); %shortest flight length for each day since they may be slightly different lengths +% flightLength = minFlightLength - preDur - postDur; +% mean_act_full = cellfun(@mean,activity_allTrials.act_dur{clusts},'UniformOutput',false); %take the mean of all the trials for each roi/day +% act_aligned = cellfun(@(c) c(:,1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% mean_act_aligned = cellfun(@mean,act_aligned{clusts},'UniformOutput',false); %take the mean of the aligned traces +% std_act_aligned = cellfun(@std,act_aligned{clusts},'UniformOutput',false); %take the mean of the aligned traces +% +% act_pre = cellfun(@(c) c(:,1:preDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% mean_act_pre = cellfun(@mean,act_pre,'UniformOutput',false); %take the mean of the aligned traces +% std_act_pre = cellfun(@std,act_pre,'UniformOutput',false); %take the mean of the aligned traces +% act_dur = cellfun(@(c) c(:,preDur+1:minFlightLength-postDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% mean_act_dur = cellfun(@mean,act_dur,'UniformOutput',false); %take the mean of the aligned traces +% std_act_dur = cellfun(@std,act_dur,'UniformOutput',false); %take the mean of the aligned traces +% act_post = cellfun(@(c) c(:,minFlightLength-postDur+1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +% mean_act_post = cellfun(@mean,act_post,'UniformOutput',false); %take the mean of the aligned traces +% std_act_post = cellfun(@std,act_post,'UniformOutput',false); %take the mean of the aligned traces +% +% %sort the max of each mean +% [~,max_mean_act_aligned] = cellfun(@max,mean_act_aligned); +% [BMax_mean_act_aligned,IMax_mean_act_aligned] = sort(max_mean_act_aligned,2); +% [~,max_mean_act_pre] = cellfun(@max,mean_act_pre); +% [BMax_mean_act_pre,IMax_mean_act_pre] = sort(max_mean_act_pre,2); +% [~,max_mean_act_dur] = cellfun(@max,mean_act_dur); +% [BMax_mean_act_dur,IMax_mean_act_dur] = sort(max_mean_act_dur,2); +% [~,max_mean_act_post] = cellfun(@max,mean_act_post); +% [BMax_mean_act_post,IMax_mean_act_post] = sort(max_mean_act_post,2); + +%pull in/cutout all the aligned, pre, dur, and post data +minFlightLength = min(cellfun('size',activity_allTrials.act_dur{clusts}(:,1),2)); %shortest flight length for each day since they may be slightly different lengths +flightLength = minFlightLength - preDur - postDur; +act_aligned = cellfun(@(c) c(:,1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +act_pre = cellfun(@(c) c(:,1:preDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +act_dur = cellfun(@(c) c(:,preDur+1:minFlightLength-postDur), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +act_post = cellfun(@(c) c(:,minFlightLength-postDur+1:minFlightLength), activity_allTrials.act_dur{clusts},'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days + +%initialize matrices to hold mean and stds of each day/roi +meanMax_act_aligned = zeros(size(days,2),size(act_aligned,2)); +stdMax_act_aligned = zeros(size(days,2),size(act_aligned,2)); +meanMax_act_pre = zeros(size(days,2),size(act_aligned,2)); +stdMax_act_pre = zeros(size(days,2),size(act_aligned,2)); +meanMax_act_dur = zeros(size(days,2),size(act_aligned,2)); +stdMax_act_dur = zeros(size(days,2),size(act_aligned,2)); +meanMax_act_post = zeros(size(days,2),size(act_aligned,2)); +stdMax_act_post = zeros(size(days,2),size(act_aligned,2)); + +% for day_i = 1:size(selectiveCells,1) +% for phase_i = 1:size(selectiveCells,2) +% findSelectiveCells{day_i,phase_i} = find(selectiveCells{day_i,phase_i}(2,:)); +% if phase_i == 1 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(max_mean_act_pre(days(day_i),findSelectiveCells{day_i,phase_i})); +% elseif phase_i == 2 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(max_mean_act_dur(days(day_i),findSelectiveCells{day_i,phase_i})); +% elseif phase_i == 3 +% [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(max_mean_act_post(days(day_i),findSelectiveCells{day_i,phase_i})); +% end +% end +% sumSelectiveCells(day_i) = length(findSelectiveCells{day_i,1}) + length(findSelectiveCells{day_i,2}) + length(findSelectiveCells{day_i,3}); +% end + +%determine the max,mean, and std for the pre, dur, post data +for day_i = 1:length(days) + for roi_i = 1:size(act_aligned,2) + for flight_i = 1:size(act_aligned{days(day_i),roi_i},1) + [~,max_act_aligned{day_i,roi_i}(flight_i,1)] = max(act_aligned{days(day_i),roi_i}(flight_i,:)); + [~,max_act_pre{day_i,roi_i}(flight_i,1)] = max(act_pre{days(day_i),roi_i}(flight_i,:)); + [~,max_act_dur{day_i,roi_i}(flight_i,1)] = max(act_dur{days(day_i),roi_i}(flight_i,:)); + [~,max_act_post{day_i,roi_i}(flight_i,1)] = max(act_post{days(day_i),roi_i}(flight_i,:)); + end + meanMax_act_aligned(day_i,roi_i) = round(mean(max_act_aligned{day_i,roi_i})); + stdMax_act_aligned(day_i,roi_i) = round(std(max_act_aligned{day_i,roi_i})); + meanMax_act_pre(day_i,roi_i) = round(mean(max_act_pre{day_i,roi_i})); + stdMax_act_pre(day_i,roi_i) = round(std(max_act_pre{day_i,roi_i})); + meanMax_act_dur(day_i,roi_i) = round(mean(max_act_dur{day_i,roi_i})); + stdMax_act_dur(day_i,roi_i) = round(std(max_act_dur{day_i,roi_i})); + meanMax_act_post(day_i,roi_i) = round(mean(max_act_post{day_i,roi_i})); + stdMax_act_post(day_i,roi_i) = round(std(max_act_post{day_i,roi_i})); + end + %sort the means of maxes for each full, pre, dur, and post + [BmeanMax_act_aligned(day_i,:),ImeanMax_act_aligned(day_i,:)] = sort(meanMax_act_aligned(day_i,:)); + [BmeanMax_act_pre(day_i,:),ImeanMax_act_pre(day_i,:)] = sort(meanMax_act_pre(day_i,:)); + [BmeanMax_act_dur(day_i,:),ImeanMax_act_dur(day_i,:)] = sort(meanMax_act_dur(day_i,:)); + [BmeanMax_act_post(day_i,:),ImeanMax_act_post(day_i,:)] = sort(meanMax_act_post(day_i,:)); +%sort the means of the maxes so that they are in chronological order + %across ROIs + for phase_i = 1:size(selectiveCells,2) + findSelectiveCells{day_i,phase_i} = find(selectiveCells{day_i,phase_i}(clusts,:)); + if phase_i == 1 + [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_pre(day_i,findSelectiveCells{day_i,phase_i})); + elseif phase_i == 2 + [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_dur(day_i,findSelectiveCells{day_i,phase_i})); + elseif phase_i == 3 + [BSelectiveCells{day_i,phase_i},ISelectiveCells{day_i,phase_i}] = sort(meanMax_act_post(day_i,findSelectiveCells{day_i,phase_i})); + end + end + sumSelectiveCells(day_i) = length(findSelectiveCells{day_i,1}) + length(findSelectiveCells{day_i,2}) + length(findSelectiveCells{day_i,3}); + +end +%% plot the max peak of each selective pre/dur/post cell +functionalStabilityDotPlot = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +sgtitle([batId ' Functional Stability of Selectively Active Cells: Cluster 2']); +colorDays = ["r","b"]; + +for day_i = 1:size(selectiveCells,1) + roiCounter = sumSelectiveCells(day_i); + for phase_i = 1:size(selectiveCells,2) + %findSelectiveCells{day_i,phase_i} = find(selectiveCells{day_i,phase_i}(2,:)); + for roi_i = 1:size(findSelectiveCells{day_i,phase_i},2) + subplot(1,3,day_i); %plot the individual day 1 and day 9 + if phase_i == 1 + p1 = plot(BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(max_mean_act_pre(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + elseif phase_i == 2 + p1 = plot(preDur+BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(preDur + max_mean_act_dur(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)), roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + elseif phase_i == 3 + p1 = plot(preDur + flightLength + BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(preDur + flightLength + max_mean_act_post(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)), roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + end + hold on; + xPre=preDur*ones(1,max(sumSelectiveCells)*2+1); + xPost=(preDur+flightLength)*ones(1,max(sumSelectiveCells)*2+1); + plot(xPre,1:0.5:max(sumSelectiveCells)+1,'k.'); + plot(xPost,1:0.5:max(sumSelectiveCells)+1,'k.'); + title(['Day ' num2str(days(day_i))]); + axis([0 minFlightLength 0 max(sumSelectiveCells)+1]); + set(gca,'YTick',[1:sumSelectiveCells(day_i)],'yticklabel',flip([ISelectiveCells{day_i,:}]),'ycolor',char(colorDays(day_i))); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('Time (s)'); + ylabel('ROI #'); + + subplot(1,3,3); %plot the overlap + colororder({'r','b'}) + if day_i == 1 + yyaxis left + else + yyaxis right + end + if phase_i == 1 + p1 = plot(BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(max_mean_act_pre(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)), roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + elseif phase_i == 2 + p1 = plot(preDur+BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(preDur + max_mean_act_dur(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)), roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + elseif phase_i == 3 + plot(preDur + flightLength + BSelectiveCells{day_i,phase_i}(roi_i),roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + %plot(preDur + flightLength + max_mean_act_post(days(day_i),findSelectiveCells{day_i,phase_i}(roi_i)), roiCounter,[char(colorDays(day_i)) '.'],'MarkerSize',20); + end + hold on; + plot(xPre,1:0.5:max(sumSelectiveCells)+1,'k.'); + plot(xPost,1:0.5:max(sumSelectiveCells)+1,'k.'); + title(['Overlap']); + axis([0 minFlightLength 0 max(sumSelectiveCells)+1]); + set(gca,'yticklabel',[]); + xlabel('Time (s)'); + ylabel('ROI #'); + set(gca,'YTick',[1:sumSelectiveCells(day_i)],'yticklabel',flip([ISelectiveCells{day_i,:}])); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + + roiCounter = roiCounter - 1; + end + end +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(functionalStabilityDotPlot,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_selectiveCells_clust' num2str(clusts) '_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(functionalStabilityDotPlot,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_selectiveCells_clust' num2str(clusts) '_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + elseif strcmp(batId,'Gen') + saveas(functionalStabilityDotPlot,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_selectiveCells_clust' num2str(clusts) '_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(functionalStabilityDotPlot,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_selectiveCells_clust' num2str(clusts) '_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + end +end + + +%% plot only consistent cells + +functionalStabilityDotPlot_consistent = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +sgtitle([batId ' Functional Stability of Consistently Selectively Active Cells: Cluster 2']); +colorDays = ["r","b"]; + +%find the overlapping cells and phase +for day_i = 1:size(selectiveCells,1) + for phase_i = 1:size(selectiveCells,2) + if day_i == 1 + [overlapVal{day_i,phase_i},overlapPos{day_i,phase_i}]=intersect(ISelectiveCells{1,phase_i},ISelectiveCells{2,phase_i}); + elseif day_i == 2 + [overlapVal{day_i,phase_i},overlapPos{day_i,phase_i}]=intersect(ISelectiveCells{2,phase_i},ISelectiveCells{1,phase_i}); %reverse if it's for day2 + end + [BoverlapPosSorted{day_i,phase_i},IoverlapPosSorted{day_i,phase_i}] = sort(overlapPos{day_i,phase_i}); + ISelectiveCellsOverlap{day_i,phase_i} = ISelectiveCells{day_i,phase_i}(BoverlapPosSorted{day_i,phase_i}); + end + overlapCat(day_i,:) = vertcat(overlapPos{day_i,:})'; +end + +%sort out and find day2 order based on day1 sorting +for phase_i = 1:size(selectiveCells,2) + for roi_i = 1:length(ISelectiveCellsOverlap{1,phase_i}) + overlapPosSorted_dayEnd{phase_i}(roi_i) = find(ismember(ISelectiveCells{2,phase_i},ISelectiveCellsOverlap{1,phase_i}(roi_i))); + end +end + +%plot day 1 +sumOverlaps = length(overlapPos{1,1})+length(overlapPos{1,2})+length(overlapPos{1,3}); +for plot_i = [1 3] +roiStableCounter = sumOverlaps; +for phase_i = 1:size(selectiveCells,2) + for roi_i = 1:length(BoverlapPosSorted{1,phase_i}) + subplot(1,3,plot_i); %plot the individual day 1 and overlap + if phase_i == 1 + p1 = plot(BSelectiveCells{1,phase_i}(BoverlapPosSorted{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(1)) '.'],'MarkerSize',20); + elseif phase_i == 2 + p1 = plot(preDur+BSelectiveCells{1,phase_i}(BoverlapPosSorted{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(1)) '.'],'MarkerSize',20); + elseif phase_i == 3 + p1 = plot(preDur + flightLength + BSelectiveCells{1,phase_i}(BoverlapPosSorted{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(1)) '.'],'MarkerSize',20); + end + hold on; + p1.Color(4) = 0.5; + xPre=preDur*ones(1,sumOverlaps*2+1); + xPost=(preDur+flightLength)*ones(1,sumOverlaps*2+1); + plot(xPre,1:0.5:sumOverlaps+1,'k.'); + plot(xPost,1:0.5:sumOverlaps+1,'k.'); + title(['Day ' num2str(days(1))]); + axis([0 minFlightLength 0 sumOverlaps+1]); + set(gca,'YTick',[1:sumOverlaps],'yticklabel',flip(vertcat(IoverlapPosSorted{1,:})'));%,'ycolor',char(colorDays(1))); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('Time (s)'); + ylabel('ROI #'); + roiStableCounter = roiStableCounter - 1; + end +end +end +%plot the day2 +for plot_ii = [2 3] +roiStableCounter = sumOverlaps; +for phase_i = 1:size(selectiveCells,2) + for roi_i = 1:length(BoverlapPosSorted{1,phase_i}) + subplot(1,3,plot_ii); %plot the individual day 1 and day 9 + if phase_i == 1 + p2 = plot(BSelectiveCells{2,phase_i}(overlapPosSorted_dayEnd{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(2)) '.'],'MarkerSize',20); + elseif phase_i == 2 + p2 = plot(preDur+BSelectiveCells{2,phase_i}(overlapPosSorted_dayEnd{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(2)) '.'],'MarkerSize',20); + elseif phase_i == 3 + p2 = plot(preDur + flightLength + BSelectiveCells{2,phase_i}(overlapPosSorted_dayEnd{1,phase_i}(roi_i)),roiStableCounter,[char(colorDays(2)) '.'],'MarkerSize',20); + end + hold on; + p2.Color(4) = 0.5; + xPre=preDur*ones(1,sumOverlaps*2+1); + xPost=(preDur+flightLength)*ones(1,sumOverlaps*2+1); + plot(xPre,1:0.5:sumOverlaps+1,'k.'); + plot(xPost,1:0.5:sumOverlaps+1,'k.'); + if plot_ii == 2 + title(['Day ' num2str(days(end))]); + else + title('Overlap'); + end + axis([0 minFlightLength 0 sumOverlaps+1]); + set(gca,'YTick',[1:sumOverlaps],'yticklabel',flip(vertcat(IoverlapPosSorted{1,:})'));%,'ycolor',char(colorDays(2))); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('Time (s)'); + ylabel('ROI #'); + roiStableCounter = roiStableCounter - 1; + end +end +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(functionalStabilityDotPlot_consistent,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_selectiveCells_clust2_consistent_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(functionalStabilityDotPlot_consistent,[saveDir filesep 'Gal_200311and20_functionalStability_dotPlot_selectiveCells_clust2_consistent_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + elseif strcmp(batId,'Gen') + saveas(functionalStabilityDotPlot_consistent,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_selectiveCells_clust2_consistent_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(functionalStabilityDotPlot_consistent,[saveDir filesep 'Gen_200319and24_functionalStability_dotPlot_selectiveCells_clust2_consistent_' saveTag '_' datestr(now,'yymmdd-HHMMSS') '.fig']); + end +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_histogram_stabilityCorrelations.m b/analysis_tobias/ImBat_histogram_stabilityCorrelations.m new file mode 100644 index 0000000..c10b30a --- /dev/null +++ b/analysis_tobias/ImBat_histogram_stabilityCorrelations.m @@ -0,0 +1,107 @@ +function ImBat_histogram_stabilityCorrelations(batId,dataPreDurPost) +saveFlag = 1; +%batId = 'Gal'; +cRaw_tag = 1; +clustNum = 2; +saveTag = ['cRaw']; +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + % Check if folder exists + if exist([saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays'])>0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays']) + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'histogram_peakCorr_acrossDays' '\']; +end + +%set sizes of variables +CNMFe_Fs = 30; %sampling frequency of imaging to divide the timing into seconds +smoothFactor = 10; +nPhases = size(dataPreDurPost.findSelectiveCells{clustNum},2); +nDays = size(dataPreDurPost.findSelectiveCells{clustNum},1); +timeCorr = cell(1,nPhases); +timeDiff = cell(1,nPhases); +%create figure +histogram_peakCorr_acrossDays = figure(); +sgtitle([batId ' Pairwise Selectively Active Cells Across Days, Clust ' num2str(clustNum) ' ' saveTag]); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +%find the overlapping ROIs for each day/phase, then gather all the +%differences between max peaks and correlation coefficients for each pair +%of cells that is active across multiple days +for phase_i = 1:nPhases + overlapCount = 1; + timeCorr{phase_i} = zeros(nDays,nDays); + timeDiff{phase_i} = zeros(nDays,nDays); + for day_i = 1:nDays + rois = dataPreDurPost.findSelectiveCells{clustNum}{day_i,phase_i}; + nRois = length(dataPreDurPost.findSelectiveCells{clustNum}{day_i,phase_i}); + for roi_i = 1:nRois + for day_ii = day_i+1:nDays + w = gausswin(smoothFactor); %smooth the S matrix by gaussian window of 10 + [~,b] = ismember(rois(roi_i),dataPreDurPost.findSelectiveCells{clustNum}{day_ii,phase_i}); + if b > 0 + %smooth the smatrix and take the difference in peak times + if phase_i == 1 + spikeSmooth1 = filter(w,1,dataPreDurPost.mean_act_pre{clustNum}{day_i,rois(roi_i)}); + spikeSmooth2 = filter(w,1,dataPreDurPost.mean_act_pre{clustNum}{day_ii,b}); + timeDiff{phase_i}(day_i,day_ii) = (dataPreDurPost.meanMax_act_pre{clustNum}(day_ii,b) - dataPreDurPost.meanMax_act_pre{clustNum}(day_i,b))/CNMFe_Fs; + elseif phase_i == 2 + spikeSmooth1 = filter(w,1,dataPreDurPost.mean_act_dur{clustNum}{day_i,rois(roi_i)}); + spikeSmooth2 = filter(w,1,dataPreDurPost.mean_act_dur{clustNum}{day_ii,b}); + timeDiff{phase_i}(day_i,day_ii) = (dataPreDurPost.meanMax_act_dur{clustNum}(day_ii,b) - dataPreDurPost.meanMax_act_dur{clustNum}(day_i,b))/CNMFe_Fs; + elseif phase_i == 3 + spikeSmooth1 = filter(w,1,dataPreDurPost.mean_act_post{clustNum}{day_i,rois(roi_i)}); + spikeSmooth2 = filter(w,1,dataPreDurPost.mean_act_post{clustNum}{day_ii,b}); + timeDiff{phase_i}(day_i,day_ii) = (dataPreDurPost.meanMax_act_post{clustNum}(day_ii,b) - dataPreDurPost.meanMax_act_post{clustNum}(day_i,b))/CNMFe_Fs; + end + %find correlation coefficient between the two time series + R1 = corrcoef(spikeSmooth1,spikeSmooth2); + timeCorr{phase_i}(day_i,day_ii) = R1(1,2); + overlapCount = overlapCount + 1; + end + end + end + end + + %plot histograms of the time differences and correlations + phase = ["Pre","Dur","Post"]; + hold on; + subplot(3,2,2*phase_i-1); + histogram(timeDiff{phase_i}(find(abs(timeDiff{phase_i})>0)),round(size(timeDiff{phase_i}(find(abs(timeDiff{phase_i})>0)),1)/2)+1,'FaceColor','r'); + try + xlim([-1*max(abs((timeDiff{phase_i}(find(abs(timeDiff{phase_i})>0)))))-1 max(abs((timeDiff{phase_i}(find(abs(timeDiff{phase_i})>0)))))+1]); + catch + end + if phase_i == 1 + title(['Time diff b/w mean max peaks: ' char(phase(phase_i))]); + else + title(char(phase(phase_i))); + end + if phase_i ==3 + xlabel('Time (s)'); + ylabel('# ROIs'); + end + subplot(3,2,2*phase_i); + histogram(timeCorr{phase_i}(find(abs(timeCorr{phase_i})>0)),round(size(timeCorr{phase_i}(find(abs(timeCorr{phase_i})>0)),1)/2)+1,'FaceColor','b'); + xlim([-1.2 1.2]); + if phase_i == 1 + title(['CorrCoef of selectively active pairs: ' char(phase(phase_i))]); + else + title(char(phase(phase_i))); + end + if phase_i == 3 + xlabel('R'); + ylabel('# ROIs'); + end +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(histogram_peakCorr_acrossDays,[saveDir filesep 'Gal_200311and20_histogram_peakDiff_corr_' saveTag '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(histogram_peakCorr_acrossDays,[saveDir filesep 'Gal_200311and20_histogram_peakDiff_corr_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(histogram_peakCorr_acrossDays,[saveDir filesep 'Gen_200319and24_histogram_peakDiff_corr_' saveTag '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(histogram_peakCorr_acrossDays,[saveDir filesep 'Gen_200319and24_histogram_peakDiff_corr_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + end +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_inspect_noTuneCells.asv b/analysis_tobias/ImBat_inspect_noTuneCells.asv new file mode 100644 index 0000000..55cff29 --- /dev/null +++ b/analysis_tobias/ImBat_inspect_noTuneCells.asv @@ -0,0 +1,47 @@ +function ImBat_inspect_noTuneCells(placeCells,results) + batName = 'Ge'; + dateSesh = '200319'; +Atemp = full(results.A); %spatial masks +% Plot binary mask of all neurons in the A matrix + %convert A matrix into full matrix + Ysiz = size(results.Cn); + nRois = length(placeCells.cells_none); + scaling = 10; %depends on size of frame and downsampling from extraction step + col = zeros(nRois,3); + + +figCheckRoi = figure(); + subplot(4,1,1:3); + imagesc(imresize(results.Cn,scaling)); + colormap(gray); + hold on; +for roi_i = placeCells.cells_none + %plot the map of the cell + sgtitle([batName ' ' dateSesh ' ROI #' num2str(roi_i)]); + roiMask = imresize(mat2gray(reshape(Atemp(:,roi_i),Ysiz(1),Ysiz(2))),10); + binaryMask = imbinarize(roiMask);%mat2gray(reshape(resultsA{inputDay(roi_i)}(:,inputROI(roi_i)),Ysiz(1),Ysiz(2)))); + + [y,x]=find(binaryMask); + %get ROI coordinates + ROI_coords(roi_i,1) = {x};%*scaling}; + ROI_coords(roi_i,2) = {y};%*scaling}; + %calculate centroids + centroid(roi_i,1) = mean(ROI_coords{roi_i,1});%*scaling; + centroid(roi_i,2) = mean(ROI_coords{roi_i,2});%*scaling;%get the centroid of mask + %plot the mask + p = plot(ROI_coords{roi_i,1},ROI_coords{roi_i,2},'LineWidth',4); + title(['ROI Mask']); + xticklabels([]); + yticklabels([]); + + %plot the time series from each cell + subplot(4,1,4); + timeseries(:,roi_i) = zscore(smoothdata(results.C_raw(roi_i,1:end),2,'movmedian',30))'; + plot(timeseries(:,roi_i));%+plot_i*6); + xt = get(gca,'xtick'); + set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); + title(['ROI Time Series']); + %ylabel('ROIs (Day.ROI)'); + xlabel('Time (m)'); + hold off +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_inspect_noTuneCells.m b/analysis_tobias/ImBat_inspect_noTuneCells.m new file mode 100644 index 0000000..d47a51e --- /dev/null +++ b/analysis_tobias/ImBat_inspect_noTuneCells.m @@ -0,0 +1,49 @@ +function ImBat_inspect_noTuneCells(placeCells,results) + batName = 'Ge'; + dateSesh = '200319'; +Atemp = full(results.A); %spatial masks +% Plot binary mask of all neurons in the A matrix + %convert A matrix into full matrix + Ysiz = size(results.Cn); + nRois = length(placeCells.cells_none); + scaling = 10; %depends on size of frame and downsampling from extraction step + col = zeros(nRois,3); + + +figCheckRoi = figure(); + +for roi_i = placeCells.cells_none + subplot(4,1,1:3); + imagesc(imresize(results.Cn,scaling)); + colormap(gray); + hold on; + + %plot the map of the cell + sgtitle([batName ' ' dateSesh ' ROI #' num2str(roi_i)]); + roiMask = imresize(mat2gray(reshape(Atemp(:,roi_i),Ysiz(1),Ysiz(2))),10); + binaryMask = imbinarize(roiMask);%mat2gray(reshape(resultsA{inputDay(roi_i)}(:,inputROI(roi_i)),Ysiz(1),Ysiz(2)))); + + [y,x]=find(binaryMask); + %get ROI coordinates + ROI_coords(roi_i,1) = {x};%*scaling}; + ROI_coords(roi_i,2) = {y};%*scaling}; + %calculate centroids + centroid(roi_i,1) = mean(ROI_coords{roi_i,1});%*scaling; + centroid(roi_i,2) = mean(ROI_coords{roi_i,2});%*scaling;%get the centroid of mask + %plot the mask + p = plot(ROI_coords{roi_i,1},ROI_coords{roi_i,2},'LineWidth',4); + title(['ROI Mask']); + xticklabels([]); + yticklabels([]); + + %plot the time series from each cell + subplot(4,1,4); + timeseries(:,roi_i) = zscore(smoothdata(results.C_raw(roi_i,1:end),2,'movmedian',30))'; + plot(timeseries(:,roi_i));%+plot_i*6); + xt = get(gca,'xtick'); + set(gca,'XTick',xt, 'xticklabel',xt/(results.Fs*60)); + title(['ROI Time Series']); + %ylabel('ROIs (Day.ROI)'); + xlabel('Time (m)'); + hold off +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_maxProj_flightAligned.m b/analysis_tobias/ImBat_maxProj_flightAligned.m new file mode 100644 index 0000000..085e30c --- /dev/null +++ b/analysis_tobias/ImBat_maxProj_flightAligned.m @@ -0,0 +1,63 @@ +batId = 'Gen'; +clustNum = 3; +saveFlag = 1; +saveTag = 'sMat'; +%load first day placeCellStableROI data +if strcmp(batId,'Gal') + %cd([dirTop(day1).folder filesep 'plots\200911-preDurPost cells across days']); + load('200311to200320_Gal_activity_allTrials_allClusts_sMat_dff.mat'); %load activity for pre,dur,post +elseif strcmp(batId,'Gen') + load('200319to200324_Gen_activity_allTrials_allClusts_sMat_dff.mat'); %load activity for pre,dur,post +end +%make saving directory +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + if ~exist([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']) + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign']); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'maxProjFlightAlign' filesep]; +end + +nDays = size(activity_allTrials.maxMeanFrames_dur{clustNum},2); +maxProjflightAlign = figure('units','normalized','outerposition',[0 0 0.8 1]); +sgtitle([batId ': Flight Aligned Max Projections Pre,Dur,Post']); +if strcmp(batId,'Gal') + ha = tight_subplot(3,6,[.02 .01],[.01 .1],[.01 .01]); +elseif strcmp(batId,'Gen') + ha = tight_subplot(2,6,[.02 .01],[.01 .1],[.01 .01]); +end +for day_i = 1:nDays +% if strcmp(batId,'Gal') +% subplot(3,3,day_i); +% elseif strcmp(batId,'Gen') +% subplot(2,3,day_i) +% end +%plot the flight aligned max projections + axes(ha(2*day_i-1)); + imagesc(activity_allTrials.maxMeanFrames_dur{2}{day_i}); + hold on; + colormap(gray); + title(['Day ' num2str(day_i) ' Clust ' num2str(clustNum)]); + set(gca,'xticklabel',[],'yticklabel',[]); + + %plot the full session max projections + axes(ha(2*day_i)); + imagesc(activity_allTrials.YmaxFull{day_i}); + hold on; + colormap(gray); + title(['Day ' num2str(day_i) ' full sesh']); + set(gca,'xticklabel',[],'yticklabel',[]); + +end + +if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(maxProjflightAlign,[saveDir filesep 'Gal_200311and20_maxProjFlightAlign_' saveTag '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(maxProjflightAlign,[saveDir filesep 'Gal_200311and20_maxProjFlightAlign_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(maxProjflightAlign,[saveDir filesep 'Gen_200319and24_maxProjFlightAlign_' saveTag '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(maxProjflightAlign,[saveDir filesep 'Gen_200319and24_maxProjFlightAlign_' saveTag '_' datestr(now,'yymmdd-HHMM') '.fig']); + end +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_numActiveRois.m b/analysis_tobias/ImBat_numActiveRois.m new file mode 100644 index 0000000..2ac0320 --- /dev/null +++ b/analysis_tobias/ImBat_numActiveRois.m @@ -0,0 +1,44 @@ +saveFlag = 1; %do you want to save the figures and output structure? +if saveFlag == 1 +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'percSelectiveROI'])>0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'percSelectiveROI']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'percSelectiveROI' '\']; +end + +plot_numSelectiveROI = figure(); +subplot(1,2,1) +plot(squeeze(perc_flight_roi(1,1,:))) +hold on +plot(squeeze(perc_flight_roi(2,1,:))) +plot(squeeze(perc_flight_roi(3,1,:))) +legend('Pre','Dur','Post'); +ylabel('% flights selective'); +xlabel('Day'); +set(gca,'xTick',[1:length(perc_flight_roi(1,1,:))]); +title('% of flights with at least one selective ROI'); +hold off + +subplot(1,2,2) +plot(squeeze(perc_flight_roi(1,2,:))) +hold on +plot(squeeze(perc_flight_roi(2,2,:))) +plot(squeeze(perc_flight_roi(3,2,:))) +legend('Pre','Dur','Post'); +ylabel('% ROIs active'); +xlabel('Day'); +set(gca,'xTick',[1:length(perc_flight_roi(1,1,:))]); +title('% of unique selective ROIs'); +hold off + +if saveFlag == 1 + %save fig and tif of max projection + %set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(plot_numSelectiveROI,[saveDir 'scatterCorrDist_Gen_19to24_' datestr(now,'yymmdd-hhMMss') '.fig']); + saveas(plot_numSelectiveROI, [saveDir 'scatterCorrDist_Gen_19to24_' datestr(now,'yymmdd-hhMMss') '.tif']); + save([saveDir 'percSelectiveFlights_Gen_19to24_' datestr(now,'yymmdd-hhMMss') '.mat'],'perc_flight_roi'); +end diff --git a/analysis_tobias/ImBat_placeCells_Ang.asv b/analysis_tobias/ImBat_placeCells_Ang.asv new file mode 100644 index 0000000..8b89da7 --- /dev/null +++ b/analysis_tobias/ImBat_placeCells_Ang.asv @@ -0,0 +1,517 @@ +function ImBat_placeCells_Ang(flightPaths, cellData, alignment,varargin) + +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +p_val_analysis = 1; +save_data = 1; +flightCircFlag = 1; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; + end +end + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + date = strcat(lower(batName(1:2)),dateSesh); + label = [batName '_' dateSesh '_' sessionType]; + %label = [dateSesh '_' sessionType]; + cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); + alignment = load([pwd '/processed/Alignment.mat']); + load([pwd '/' analysis_Folder '/' label '_flightPaths.mat']); +end + +% P_value calculation params +n_bins = 30; %good around here %number of bins to divide the pre-during-post flight interval +n_rep = 500; %can lower to 10 for debugging %number of shufflings +alfa = 0.05; %can lower to 0.01 or 0.1 %significance level +pre_dur = 3; %play with 3-5 %duration of the pre flight period (s): comparable with flight dur +pst_dur = 3; %play with 3-5 %duration of the post flight period (s): but shorter than half interflight +w = gausswin(1); %keep at 1 for no smoothing %witdh of the gaussian filter (number of bins), use odd values. 1=no filtering +n_space_bins = 30; %correlates with space resolution but good around 30 (20cm chunks) %number of spatial bins + +%converting Angelo's variables to mine +N = size(cellData.results.C_raw,1); %number of ROIs +T = size(cellData.results.C_raw,2); %length of each neural trace +CNMFe_Fs = cellData.results.Fs; %imaging sampling rate +%dsFactor =4; %convert from 120hz behavior start frame to 30hz imaging start frame + +%Flight Room references (provvisory) +xR = +2.85; xL = -2.85; yF = 2.50; yB = -2.50; zT = 2.20; %Flight volume coordinates +F1 = [2.56; 1.23; 1.72]; F2 = [2.56; -1.04; 1.72]; %Feeders coordinates +F3 = [2.56; 1.43; 0.72]; F4 = [2.56; -1.24; 0.72]; %Feeders coordinates +edges_d = {xL:(xR-xL)/10:xR yB:(yF-yB)/10:yF}; %Edges for density histogram + +%% resample the neural data to account for lost frames +%Extract variables from Alignment +img_times = alignment.out.video_times'; +img_sampling = diff(img_times); +img_sampl_interval = mean(img_sampling); +img_Fs = 1/img_sampl_interval; + +%Calculate real sampling frequency +CNMF_Fs_real = round(T/(img_times(end)-img_times(1))); +CNMF_time = downsample(img_times,round(img_Fs/CNMF_Fs_real)); + +%Generate evenly spaced times +t_even = linspace(img_times(1),img_times(end),length(img_times)); +CNMF_time_even = downsample(t_even,round(img_Fs/CNMF_Fs_real)); +%normalize firing rate by size of neuron +%A = reshape(cellData.results.A,size(cellData.results.A,2),2); A = permute(A, [3 1 2]); %Spatial footprints: cell# x pixels x pixels +%fr_area = sum(A,[2 3])./sum(A,'all');%sum(cellData.results.A,[2 3])./sum(cellData.results.A,'all'); %Fractional area for each Spatial footprint +FC_raw = cellData.results.C_raw;%.*fr_area; %Raw fluorescence (normalized) +FC = cellData.results.C;%.*fr_area; %Denoised fluorescence (normalized) +S = full(cellData.results.S);%.*fr_area; %Deconvolved spike trace (normalized) + +%Resample at even time intervals +try + FC_raw_rs = interp1(CNMF_time',FC_raw',CNMF_time_even','linear','extrap')';%cellData.results.C_raw',CNMF_time_even','linear','extrap')'; + S_rs = interp1(CNMF_time',S',CNMF_time_even','nearest','extrap')';%cellData.results.S',CNMF_time_even','nearest','extrap')'; +catch + recDiff = length(CNMF_time) - length(cellData.results.C_raw); + FC_raw_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.C_raw)',CNMF_time_even(1,1:end-recDiff)','linear','extrap')'; + S_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.S)',CNMF_time_even(1,1:end-recDiff)','nearest','extrap')'; +end + +%Ca-activity and inferred spike-rate are constrained to zero for 5s at the beginning and end of the session and inferred spike-rate is normalized (SD units) and smoothed +Activity = FC_raw_rs; +Activity(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + +Rate = normalize(S_rs,2,'scale'); Rate = movmean(Rate,CNMF_Fs_real*0.5,2); %normalize by STD and smooth on 0.5s +Rate(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + + +% %Create analysis folder for storing the results +% analysis_directory=fullfile(pwd,['Analysis_',datestr(now, 'yymmdd_HHMM')]); +% if ~exist(analysis_directory,'dir') +% mkdir(analysis_directory); +% end +%% Code in the middle + + + +%% --------------------------------- REFINED ANALYSIS START FROM HERE------------------------------ +%////////////////////////////////////////////////////////////////////////////////////////////////// +% Calculations are done on the Rate matrix, which is the S matrix, +% normalized by standard deviation and smoothed on a 0.5s window + +if p_val_analysis + until_cluster = 4;%min(length(flightPaths.clusterIndex),100); %change this if you want less clusters + + %Create folder to store figures + figures_directory1=fullfile(pwd,'Spatial_information'); + delete([figures_directory1 '\*']); + if exist(figures_directory1,'dir')~=7 + mkdir(figures_directory1); + end + + %Initialization of matrices and arrays + frames_to_shift(1)=0; frames_to_shift(2:n_rep) = randi([10*CNMFe_Fs T-10*CNMFe_Fs],1,n_rep-1); %Shifting in time (longer than 10s) + p_val = zeros(3,until_cluster,N); %pre(1),during(2),post(3)/#cluster/#nueron %p values for pre, during, post active neurons + response = zeros(3,until_cluster,N); %sum of each phase %Integrated response during pre, during, post periods 'sum(median(Rate)' + avg_bnd_act = zeros((3*n_bins),until_cluster,N); %n_bins per section, for each pre/dur/post and for each cluster & cell %Activity across bins from pre to post + sp_bnd_response = zeros(n_space_bins,until_cluster,N); %Spatially binned activity along the trajectory + sp_bnd_velCel = cell(until_cluster,1); + S_Info = zeros(2,until_cluster,N); %2 b/c 1dim=actual info, 2dim=p-val %bits and p value for spatial information + S_Info_corrected = zeros(until_cluster,N); %make corrected info vector + %Binning in time and space, p values calculation + figure(); set(gcf, 'units','normalized','outerposition',[0.2 0 0.5 1]); + for id_cluster_SI = 2:until_cluster %for each cluster + id = []; %id = find(flight_clus.id==id_cluster_SI); %find all flights that belong to that cluster + id = flightPaths.clusterIndex{id_cluster_SI}; + for cell_n = 1:N %for each cell, initialize the below matrices + sgtitle(['ROI: ' num2str(cell_n) ' Cluster: ' num2str(id_cluster_SI)]); + disp(['Cell number: ' num2str(cell_n) ' Trajectory number: ' num2str(id_cluster_SI)]); + %matrices for keeping the data used in calcuating spatial info + bnd_act_pre = zeros(n_bins,size(id,1)); + bnd_act_dur = zeros(n_bins,size(id,1)); + bnd_act_pst = zeros(n_bins,size(id,1)); + sp_bnd_act = zeros(n_space_bins,size(id,1)); + sp_bnd_act_pre = zeros(n_space_bins,size(id,1)); + sp_bnd_act_pst = zeros(n_space_bins,size(id,1)); + sp_bnd_vel = zeros(n_space_bins,size(id,1)); + sp_bnd_path = zeros(n_space_bins,size(id,1)); + sp_bnd_lambda = zeros(n_space_bins,size(id,1)); + spikes = zeros(n_rep,3); + info = zeros(n_rep,1); + + if flightCircFlag == 1 + Act_flights{cell_n} = []; + for flight_i = 1:size(id,1) + [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); + [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); + Act_start{cell_n}(flight_i) = length(Act_flights{cell_n}) + 1; + if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate) + Act_flights{cell_n} = [Act_flights{cell_n} Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:length(Rate))]; + else + Act_flights{cell_n} = [Act_flights{cell_n} Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:closestIndexEnd+pst_dur*CNMFe_Fs)]; + end + Act_end{cell_n}(flight_i) = length(Act_flights{cell_n}); + end + end + +% if flightCircFlag == 1 +% for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors +% +% [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); +% [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); +% Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; +% Act_pre = Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1); +% if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames? +% Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd+1); +% else +% Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd); +% end +% if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate(cell_n,:)) +% Act_pst = Rate(cell_n,closestIndexEnd+1:length(Rate(cell_n,:))); +% else +% Act_pst = Rate(cell_n,closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs); +% end +% +% %Temporally binned activity for pre-during-post +% flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output +% bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; +% bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; +% bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; +% sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; +% sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; +% sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; +% sp_bnd_act_flights(:,flight_i) = [sp_bnd_act_pre(:,flight_i) sp_bnd_act(:,flight_i) sp_bnd_act_pst(:,flight_i)]; +% +% end +% end + + for n = 1:n_rep %for each repetition %repetition 1 is nonshuffled repetition + if flightCircFlag == 1 + Rate_sh = circshift(Act_flights{cell_n},frames_to_shift(n))';%2)'; + else + Rate_sh = circshift(Rate(cell_n,:),frames_to_shift(n),2)'; %take rate of cell after doing circular shift by frames_to_shift vector + end + flight_dur = zeros(1,size(id,1)); + + for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors + %grabbing and binning the velocity and activity along + %with other variables + %convert from behavior time to imaging time + [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); + [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); + Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; + if flightCircFlag == 1 + Act_pre = Rate_sh(Act_start{cell_n}(flight_i):Act_start{cell_n}(flight_i)+pre_dur*CNMFe_Fs); + Act_dur = Rate_sh(1+Act_start{cell_n}(flight_i)+pre_dur*CNMFe_Fs:... + Act_end{cell_n}(flight_i)-(pst_dur*CNMFe_Fs)); + Act_pst = Rate_sh(Act_end{cell_n}(flight_i)-(pst_dur*CNMFe_Fs)+1:Act_end{cell_n}(flight_i)); + else + Act_pre = Rate_sh(closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1); + if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames? + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd+1); + else + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd); + end + if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate_sh) + Act_pst = Rate_sh(closestIndexEnd+1:length(Rate_sh)); + else + Act_pst = Rate_sh(closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs); + end + end + + %Temporally binned activity for pre-during-post + flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output + bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; + bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; + bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; + + %Spatially binned activity for spatial information + %during flight (spatial activity) and interpolating + %across the bins + v_trj1 = flightPaths.vel(1,~isnan(flightPaths.pos(1,:,id(flight_i))),id(flight_i)); + v_trj = downsample(v_trj1,4); + sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; + sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; + + sp_bnd_vel(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(v_trj,2)),v_trj',linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_path(:,flight_i) = linspace(1,flightPaths.length(id(flight_i)),n_space_bins)'; + end + + %Spatial information (CRITICAL CALCULATION!) + %prob = 1./sum(sp_bnd_vel,2)*(1/sum(1./(sum(sp_bnd_vel,2)))); + prob = 1./mean(sp_bnd_vel,2)*(1/sum(1./(mean(sp_bnd_vel,2)))); %1./mean... normalization factor by summing all the prob in each spatial bin to sum up to 1 + sp_bnd_lambda = sp_bnd_act; + lambda = mean(sp_bnd_lambda,2);%median(sp_bnd_lambda,2); + lambda_pre = mean(sp_bnd_act_pre,2);%median(sp_bnd_act_pre,2); + lambda_pst = mean(sp_bnd_act_pst,2);%median(sp_bnd_act_pst,2); + lambda_ave = lambda'*prob; + info(n) = sum((lambda.*prob).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + %info(n) = sum((prob.*((lambda+1e-20)./(lambda_ave+1e-20))).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + + %Concatenate activities and plot + bnd_act = [bnd_act_pre(1:end,:);bnd_act_dur(1:end,:);bnd_act_pst(1:end,:)]; + bnd_act_concat = reshape(bnd_act', [], 1)'; + subplot(4,4,[1 2 3 5 6 7 9 10 11]); + plot(linspace(1,90,(3*n_bins)),filter(w,1,median(bnd_act,2)),'k'); hold on; + if n == 1 %save specific names for first rep to use for plotting with shaded area + avg_bnd_act(:,id_cluster_SI, cell_n) = filter(w,1,median(bnd_act,2)); + sp_bnd_response(:,id_cluster_SI,cell_n) = filter(w,1,lambda); + sp_bnd_response_pre(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pre); + sp_bnd_response_pst(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pst); + + sp_bnd_velCel{id_cluster_SI} = sp_bnd_vel; + %standard error mean for bounded line + ciplot(filter(w,1,median(bnd_act,2))-std(bnd_act,[],2)./sqrt(size(id,1)),filter(w,1,median(bnd_act,2))+std(bnd_act,[],2)./sqrt(size(id,1)),linspace(1,90,(3*n_bins))); + alpha(0.3); + line([30,30], [-max(median(bnd_act,2)),max(median(bnd_act,2))],'Color', 'k','LineStyle','--'); + line([60,60], [-max(median(bnd_act,2)),max(median(bnd_act,2))],'Color', 'k','LineStyle','--'); + xlabel('Flight phase'); ylabel('Activity'); + + subplot(4,4,13); imagesc([sp_bnd_act_pre; sp_bnd_act; sp_bnd_act_pst]'); title('PreDurPost Raster'); %set(gca,'xtick',[]); + subplot(4,4,14); imagesc(sp_bnd_vel'); title('Velocity'); %set(gca,'xtick',[]); + subplot(4,4,15); imagesc(sp_bnd_vel'.*sp_bnd_act'); title('Normalized Flight Raster'); %set(gca,'xtick',[]); + end + + %Integrated activity in the pre-during-post periods + %measure of average firing rate of cell in pre,dur, and + %post epochs + spikes(n,1) = sum(mean(bnd_act_pre,2))/pre_dur;%max(median(bnd_act_pre,2))/pre_dur; %mean vs median + spikes(n,2) = sum(mean(bnd_act_dur,2))/mean(flight_dur);%max(median(bnd_act_dur,2))/mean(flight_dur); %uses average flight duration + spikes(n,3) = sum(mean(bnd_act_pst,2))/pst_dur;%max(median(bnd_act_pst,2))/pst_dur; + end + + fig_ord = get(gca,'Children'); set(gca,'Children',circshift(fig_ord,2,1)); hold off; + %% can quantify all p-values for all spike rates and + %Pre analysis + subplot(4,4,4); hi = histogram(spikes(:,1),'Normalization','pdf'); hold on; + stem(spikes(1,1),1); hold off; title('Pre Spikes'); + p_val(1,id_cluster_SI,cell_n) = length(find(spikes(:,1)>=spikes(1,1)))/n_rep; %pval = number of counts that are larger than the spiking of the real trace + response(1,id_cluster_SI,cell_n) = spikes(1,1); %number of responses (spikes) for each flight/average duration of epoch (integrated spike response) + + %During analysis + subplot(4,4,8); hi = histogram(spikes(:,2),'Normalization','pdf'); hold on; + stem(spikes(1,2),1); hold off; title('During Spikes'); + p_val(2,id_cluster_SI,cell_n) = length(find(spikes(:,2)>=spikes(1,2)))/n_rep; + response(2,id_cluster_SI,cell_n) = spikes(1,2); + + %Post analysis + subplot(4,4,12); hi = histogram(spikes(:,3),'Normalization','pdf'); hold on; + stem(spikes(1,3),1); hold off; title('Post Spikes'); + p_val(3,id_cluster_SI,cell_n) = length(find(spikes(:,3)>=spikes(1,3)))/n_rep; + response(3,id_cluster_SI,cell_n) = spikes(1,3); + + %Spatial info analysis + subplot(4,4,16); hi = histogram(info,'Normalization','pdf'); hold on; + %*****bias correction to subtract mean from observed info + S_Info_corrected(id_cluster_SI,cell_n) = info(1)-mean(info(2:end)); + stem(info(1),1); hold off; title('Spatial Info'); + S_Info(1,id_cluster_SI,cell_n) = info(1); + S_Info(2,id_cluster_SI,cell_n) = length(find(info>=info(1)))/n_rep; + + drawnow(); saveas(gcf,[figures_directory1, '/', batName '_' dateSesh '_' sessionType '_ROI_' num2str(cell_n) '_cluster_' num2str(id_cluster_SI) '.jpg']); + end + end + close all; +end + +%% Look at significant cells + +if p_val_analysis + + %Putative place cells(**during activity & **spatial info & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + pp_cells = [false(1,N); squeeze(S_Info(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 & squeeze(p_val(2,2:end,:) 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppre_cells = [false(1,N); squeeze(p_val(1,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppre_cells_activity = round(normalize(bnd_act_pre(:,ppre_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_pre,~] = find(ppre_cells_activity==1); sorted_ppre_fields = ppre_cells_activity(sorted_rows_pre,:); + %figure(); imagesc(sorted_ppre_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_prefields_sorted.jpg']); + [clus_pre,cellNum_pre] = find(ppre_cells); %outputs which cells and which clusters have spatial selectivity + + %Putative post cells(**pre activity & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppost_cells = [false(1,N); squeeze(p_val(3,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppost_cells_activity = round(normalize(bnd_act_pst(:,ppost_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_post,~] = find(ppost_cells_activity==1); sorted_ppost_fields = ppost_cells_activity(sorted_rows_post,:); + %figure(); imagesc(sorted_ppost_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_postfields_sorted.jpg']); + [clus_post,cellNum_post] = find(ppost_cells); %outputs which cells and which clusters have spatial selectivity + + %putative place cells but not looking at spatial info, only based on p-val + pp_cells_loose = [false(1,N); squeeze(p_val(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + [clus_loose,cellNum_loose] = find(pp_cells_loose); + + %putative place cells but not looking at spatial info, only based on + %p-val and no minimum spike rate + pp_cells_looseloose = [false(1,N); squeeze(p_val(2,2:end,:)1 +% cell_pairs = nchoosek(find([Place_field.cell] == cell_i),2); +% for n = 1:size(cell_pairs,1) +% field_dist = [field_dist; norm([Place_field(cell_pairs(n,1)).pos]-[Place_field(cell_pairs(n,2)).pos])]; +% end +% end +% end + + + %Look at the activity of significantly modulated cells + %this may have to be corrected because it is not looking at all + %pre/post/during cells, just looking at during right now + pt_cells = [false(1,N); squeeze(any(p_val(:,2:end,:) length(Rate) + Act_flights{cell_n} = [Act_flights{cell_n} Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:length(Rate))]; + else + Act_flights{cell_n} = [Act_flights{cell_n} Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:closestIndexEnd+pst_dur*CNMFe_Fs)]; + end + Act_end{cell_n}(flight_i) = length(Act_flights{cell_n}); + end + end + +% if flightCircFlag == 1 +% for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors +% +% [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); +% [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); +% Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; +% Act_pre = Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1); +% if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames? +% Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd+1); +% else +% Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd); +% end +% if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate(cell_n,:)) +% Act_pst = Rate(cell_n,closestIndexEnd+1:length(Rate(cell_n,:))); +% else +% Act_pst = Rate(cell_n,closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs); +% end +% +% %Temporally binned activity for pre-during-post +% flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output +% bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; +% bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; +% bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; +% sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; +% sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; +% sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; +% sp_bnd_act_flights(:,flight_i) = [sp_bnd_act_pre(:,flight_i) sp_bnd_act(:,flight_i) sp_bnd_act_pst(:,flight_i)]; +% +% end +% end + + for n = 1:n_rep %for each repetition %repetition 1 is nonshuffled repetition + if flightCircFlag == 1 + Rate_sh = circshift(Act_flights{cell_n},frames_to_shift(n))';%2)'; + else + Rate_sh = circshift(Rate(cell_n,:),frames_to_shift(n),2)'; %take rate of cell after doing circular shift by frames_to_shift vector + end + flight_dur = zeros(1,size(id,1)); + + for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors + %grabbing and binning the velocity and activity along + %with other variables + %convert from behavior time to imaging time + [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); + [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); + Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; + if flightCircFlag == 1 + Act_pre = Rate_sh(Act_start{cell_n}(flight_i):Act_start{cell_n}(flight_i)+pre_dur*CNMFe_Fs); + Act_dur = Rate_sh(1+Act_start{cell_n}(flight_i)+pre_dur*CNMFe_Fs:... + Act_end{cell_n}(flight_i)-(pst_dur*CNMFe_Fs)); + Act_pst = Rate_sh(Act_end{cell_n}(flight_i)-(pst_dur*CNMFe_Fs)+1:Act_end{cell_n}(flight_i)); + else + Act_pre = Rate_sh(closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1); + if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames? + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd+1); + else + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd); + end + if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate_sh) + Act_pst = Rate_sh(closestIndexEnd+1:length(Rate_sh)); + else + Act_pst = Rate_sh(closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs); + end + end + + %Temporally binned activity for pre-during-post + flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output + bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; + bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; + bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; + + %Spatially binned activity for spatial information + %during flight (spatial activity) and interpolating + %across the bins + v_trj1 = flightPaths.vel(1,~isnan(flightPaths.pos(1,:,id(flight_i))),id(flight_i)); + v_trj = downsample(v_trj1,4); + sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; + sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; + + sp_bnd_vel(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(v_trj,2)),v_trj',linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_path(:,flight_i) = linspace(1,flightPaths.length(id(flight_i)),n_space_bins)'; + end + + %Spatial information (CRITICAL CALCULATION!) + %prob = 1./sum(sp_bnd_vel,2)*(1/sum(1./(sum(sp_bnd_vel,2)))); + prob = 1./mean(sp_bnd_vel,2)*(1/sum(1./(mean(sp_bnd_vel,2)))); %1./mean... normalization factor by summing all the prob in each spatial bin to sum up to 1 + sp_bnd_lambda = sp_bnd_act; + lambda = mean(sp_bnd_lambda,2);%median(sp_bnd_lambda,2); + lambda_pre = mean(sp_bnd_act_pre,2);%median(sp_bnd_act_pre,2); + lambda_pst = mean(sp_bnd_act_pst,2);%median(sp_bnd_act_pst,2); + lambda_ave = lambda'*prob; + info(n) = sum((lambda.*prob).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + %info(n) = sum((prob.*((lambda+1e-20)./(lambda_ave+1e-20))).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + + %Concatenate activities and plot + bnd_act = [bnd_act_pre(1:end,:);bnd_act_dur(1:end,:);bnd_act_pst(1:end,:)]; + bnd_act_concat = reshape(bnd_act', [], 1)'; + subplot(4,4,[1 2 3 5 6 7 9 10 11]); + plot(linspace(1,90,(3*n_bins)),filter(w,1,median(bnd_act,2)),'k'); hold on; + if n == 1 %save specific names for first rep to use for plotting with shaded area + avg_bnd_act(:,id_cluster_SI, cell_n) = filter(w,1,mean(bnd_act,2)); + sp_bnd_response(:,id_cluster_SI,cell_n) = filter(w,1,lambda); + sp_bnd_response_pre(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pre); + sp_bnd_response_pst(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pst); + + sp_bnd_velCel{id_cluster_SI} = sp_bnd_vel; + %standard error mean for bounded line + ciplot(filter(w,1,median(bnd_act,2))-std(bnd_act,[],2)./sqrt(size(id,1)),filter(w,1,median(bnd_act,2))+std(bnd_act,[],2)./sqrt(size(id,1)),linspace(1,90,(3*n_bins))); + alpha(0.3); + line([30,30], [-max(median(bnd_act,2)),max(median(bnd_act,2))],'Color', 'k','LineStyle','--'); + line([60,60], [-max(median(bnd_act,2)),max(median(bnd_act,2))],'Color', 'k','LineStyle','--'); + xlabel('Flight phase'); ylabel('Activity'); + + subplot(4,4,13); imagesc([sp_bnd_act_pre; sp_bnd_act; sp_bnd_act_pst]'); title('PreDurPost Raster'); %set(gca,'xtick',[]); + subplot(4,4,14); imagesc(sp_bnd_vel'); title('Velocity'); %set(gca,'xtick',[]); + subplot(4,4,15); imagesc(sp_bnd_vel'.*sp_bnd_act'); title('Normalized Flight Raster'); %set(gca,'xtick',[]); + end + + %Integrated activity in the pre-during-post periods + %measure of average firing rate of cell in pre,dur, and + %post epochs + spikes(n,1) = sum(mean(bnd_act_pre,2))/pre_dur;%max(median(bnd_act_pre,2))/pre_dur; %mean vs median + spikes(n,2) = sum(mean(bnd_act_dur,2))/mean(flight_dur);%max(median(bnd_act_dur,2))/mean(flight_dur); %uses average flight duration + spikes(n,3) = sum(mean(bnd_act_pst,2))/pst_dur;%max(median(bnd_act_pst,2))/pst_dur; + end + + fig_ord = get(gca,'Children'); set(gca,'Children',circshift(fig_ord,2,1)); hold off; + %% can quantify all p-values for all spike rates and + %Pre analysis + subplot(4,4,4); hi = histogram(spikes(:,1),'Normalization','pdf'); hold on; + stem(spikes(1,1),1); hold off; title('Pre Spikes'); + p_val(1,id_cluster_SI,cell_n) = length(find(spikes(:,1)>=spikes(1,1)))/n_rep; %pval = number of counts that are larger than the spiking of the real trace + response(1,id_cluster_SI,cell_n) = spikes(1,1); %number of responses (spikes) for each flight/average duration of epoch (integrated spike response) + + %During analysis + subplot(4,4,8); hi = histogram(spikes(:,2),'Normalization','pdf'); hold on; + stem(spikes(1,2),1); hold off; title('During Spikes'); + p_val(2,id_cluster_SI,cell_n) = length(find(spikes(:,2)>=spikes(1,2)))/n_rep; + response(2,id_cluster_SI,cell_n) = spikes(1,2); + + %Post analysis + subplot(4,4,12); hi = histogram(spikes(:,3),'Normalization','pdf'); hold on; + stem(spikes(1,3),1); hold off; title('Post Spikes'); + p_val(3,id_cluster_SI,cell_n) = length(find(spikes(:,3)>=spikes(1,3)))/n_rep; + response(3,id_cluster_SI,cell_n) = spikes(1,3); + + %Spatial info analysis + subplot(4,4,16); hi = histogram(info,'Normalization','pdf'); hold on; + %*****bias correction to subtract mean from observed info + S_Info_corrected(id_cluster_SI,cell_n) = info(1)-mean(info(2:end)); + stem(info(1),1); hold off; title('Spatial Info'); + S_Info(1,id_cluster_SI,cell_n) = info(1); + S_Info(2,id_cluster_SI,cell_n) = length(find(info>=info(1)))/n_rep; + + drawnow(); saveas(gcf,[figures_directory1, '/', batName '_' dateSesh '_' sessionType '_ROI_' num2str(cell_n) '_cluster_' num2str(id_cluster_SI) '.jpg']); + end + end + close all; +end + +%% Look at significant cells + +if p_val_analysis + + %Putative place cells(**during activity & **spatial info & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + pp_cells = [false(1,N); squeeze(S_Info(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 & squeeze(p_val(2,2:end,:) 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppre_cells = [false(1,N); squeeze(p_val(1,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppre_cells_activity = round(normalize(bnd_act_pre(:,ppre_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_pre,~] = find(ppre_cells_activity==1); sorted_ppre_fields = ppre_cells_activity(sorted_rows_pre,:); + %figure(); imagesc(sorted_ppre_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_prefields_sorted.jpg']); + [clus_pre,cellNum_pre] = find(ppre_cells); %outputs which cells and which clusters have spatial selectivity + + %Putative post cells(**pre activity & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppost_cells = [false(1,N); squeeze(p_val(3,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppost_cells_activity = round(normalize(bnd_act_pst(:,ppost_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_post,~] = find(ppost_cells_activity==1); sorted_ppost_fields = ppost_cells_activity(sorted_rows_post,:); + %figure(); imagesc(sorted_ppost_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_postfields_sorted.jpg']); + [clus_post,cellNum_post] = find(ppost_cells); %outputs which cells and which clusters have spatial selectivity + + %putative place cells but not looking at spatial info, only based on p-val + pp_cells_loose = [false(1,N); squeeze(p_val(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + [clus_loose,cellNum_loose] = find(pp_cells_loose); + + %putative place cells but not looking at spatial info, only based on + %p-val and no minimum spike rate + pp_cells_looseloose = [false(1,N); squeeze(p_val(2,2:end,:)1 +% cell_pairs = nchoosek(find([Place_field.cell] == cell_i),2); +% for n = 1:size(cell_pairs,1) +% field_dist = [field_dist; norm([Place_field(cell_pairs(n,1)).pos]-[Place_field(cell_pairs(n,2)).pos])]; +% end +% end +% end + + + %Look at the activity of significantly modulated cells + %this may have to be corrected because it is not looking at all + %pre/post/during cells, just looking at during right now + pt_cells = [false(1,N); squeeze(any(p_val(:,2:end,:)0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep batName{day_i} '_' dateSesh{day_i} '_preDurPostCells']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep batName{day_i} '_' dateSesh{day_i} '_preDurPostCells' '\']; + + %converting Angelo's variables to mine + N = size(ROIs_manual(day_i,:),2); %number of ROIs + %N = size(cellData.results.C_raw,1); %number of ROIs + T = size(cellData.results.C_raw,2); %length of each neural trace + CNMFe_Fs = cellData.results.Fs; %imaging sampling rate + dsFactor =4; %convert from 120hz behavior start frame to 30hz imaging start frame + + %Flight Room references (provvisory) + xR = +2.85; xL = -2.85; yF = 2.50; yB = -2.50; zT = 2.20; %Flight volume coordinates + F1 = [2.56; 1.23; 1.72]; F2 = [2.56; -1.04; 1.72]; %Feeders coordinates + F3 = [2.56; 1.43; 0.72]; F4 = [2.56; -1.24; 0.72]; %Feeders coordinates + edges_d = {xL:(xR-xL)/10:xR yB:(yF-yB)/10:yF}; %Edges for density histogram + + %% resample the neural data to account for lost frames + %Extract variables from Alignment + img_times = alignment.out.video_times'; + img_sampling = diff(img_times); + img_sampl_interval = mean(img_sampling); + img_Fs = 1/img_sampl_interval; + + %Calculate real sampling frequency + CNMF_Fs_real = round(T/(img_times(end)-img_times(1))); + CNMF_time = downsample(img_times,round(img_Fs/CNMF_Fs_real)); + + %Generate evenly spaced times + t_even = linspace(img_times(1),img_times(end),length(img_times)); + CNMF_time_even = downsample(t_even,round(img_Fs/CNMF_Fs_real)); + %normalize firing rate by size of neuron + %A = reshape(cellData.results.A,size(cellData.results.A,2),2); A = permute(A, [3 1 2]); %Spatial footprints: cell# x pixels x pixels + %fr_area = sum(A,[2 3])./sum(A,'all');%sum(cellData.results.A,[2 3])./sum(cellData.results.A,'all'); %Fractional area for each Spatial footprint + FC_raw = cellData.results.C_raw;%.*fr_area; %Raw fluorescence (normalized) + FC = cellData.results.C;%.*fr_area; %Denoised fluorescence (normalized) + S = cellData.results.S;%.*fr_area; %Deconvolved spike trace (normalized) + + %Resample at even time intervals + try + FC_raw_rs = interp1(CNMF_time',FC_raw',CNMF_time_even','linear','extrap')';%cellData.results.C_raw',CNMF_time_even','linear','extrap')'; + S_rs = interp1(CNMF_time',S',CNMF_time_even','nearest','extrap')';%cellData.results.S',CNMF_time_even','nearest','extrap')'; + catch + recDiff = length(CNMF_time) - length(cellData.results.C_raw); + FC_raw_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.C_raw)',CNMF_time_even(1,1:end-recDiff)','linear','extrap')'; + S_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.S)',CNMF_time_even(1,1:end-recDiff)','nearest','extrap')'; + end + + %Ca-activity and inferred spike-rate are constrained to zero for 5s at the beginning and end of the session and inferred spike-rate is normalized (SD units) and smoothed + Activity = FC_raw_rs; + Activity(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + + Rate = normalize(S_rs,2,'scale'); Rate = movmean(Rate,CNMF_Fs_real*0.5,2); %normalize by STD and smooth on 0.5s + Rate(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + + + % %Create analysis folder for storing the results + % analysis_directory=fullfile(pwd,['Analysis_',datestr(now, 'yymmdd_HHMM')]); + % if ~exist(analysis_directory,'dir') + % mkdir(analysis_directory); + % end + %% Code in the middle + + + + %% --------------------------------- REFINED ANALYSIS START FROM HERE------------------------------ + %////////////////////////////////////////////////////////////////////////////////////////////////// + % Calculations are done on the Rate matrix, which is the S matrix, + % normalized by standard deviation and smoothed on a 0.5s window + + if p_val_analysis + until_cluster = min(length(flightPaths.clusterIndex),100); %change this if you want less clusters + + %Initialization of matrices and arrays + frames_to_shift(1)=0; frames_to_shift(2:n_rep) = randi([10*CNMFe_Fs T-10*CNMFe_Fs],1,n_rep-1); %Shifting in time (longer than 10s) + p_val = zeros(3,until_cluster,N); %pre(1),during(2),post(3)/#cluster/#nueron %p values for pre, during, post active neurons + response = zeros(3,until_cluster,N); %sum of each phase %Integrated response during pre, during, post periods 'sum(median(Rate)' + avg_bnd_act = zeros(3*n_bins,until_cluster,N); %n_bins per section, for each pre/dur/post and for each cluster & cell %Activity across bins from pre to post + sp_bnd_response = zeros(n_space_bins,until_cluster,N); %Spatially binned activity along the trajectory + sp_bnd_velCel = cell(until_cluster,1); + S_Info = zeros(2,until_cluster,N); %2 b/c 1dim=actual info, 2dim=p-val %bits and p value for spatial information + %bnd_act_pre = zeros(n_bins,until_cluster,N); + %bnd_act_post = zeros(n_bins,until_cluster,N); + + + %Binning in time and space, p values calculation + figure(); set(gcf, 'units','normalized','outerposition',[0.2 0 0.5 1]); + for id_cluster_SI = 1:3%until_cluster %for each cluster + id = []; %id = find(flight_clus.id==id_cluster_SI); %find all flights that belong to that cluster + id = flightPaths.clusterIndex{id_cluster_SI}; + ROIcounter = 1; + for cell_n = ROIs_manual(day_i,:)%1:N %for each cell, initialize the below matrices + if ~isnan(cell_n) + sgtitle([batName{day_i} ' ' dateSesh{day_i} ' ROI: ' num2str(ROIcounter) ' (' num2str(cell_n) ') Cluster: ' num2str(id_cluster_SI)]); + disp(['Cell number: ' num2str(ROIcounter) ' (' num2str(cell_n) ') Trajectory number: ' num2str(id_cluster_SI)]); + %matrices for keeping the data used in calcuating spatial info + bnd_act_pre = zeros(n_bins,size(id,1)); + bnd_act_dur = zeros(n_bins,size(id,1)); + bnd_act_pst = zeros(n_bins,size(id,1)); + sp_bnd_act = zeros(n_space_bins,size(id,1)); + sp_bnd_vel = zeros(n_space_bins,size(id,1)); + sp_bnd_path = zeros(n_space_bins,size(id,1)); + sp_bnd_lambda = zeros(n_space_bins,size(id,1)); + spikes = zeros(n_rep,3); + info = zeros(n_rep,1); + + for n = 1:n_rep %for each repetition %repetition 1 is nonshuffled repetition + Rate_sh = circshift(Rate(cell_n,:),frames_to_shift(n),2)'; %take rate of cell after doing circular shift by frames_to_shift vector + flight_dur = zeros(1,size(id,1)); + + for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors + %grabbing and binning the velocity and activity along + %with other variables + %convert from behavior time to imaging time + [minValueStart,closestIndexStart] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); + [minValueEnd,closestIndexEnd] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); + Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; + Act_pre = Rate_sh(closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1); + if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames? + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd+1); + else + Act_dur = Rate_sh(closestIndexStart:closestIndexEnd); + end + if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate_sh) + Act_pst = Rate_sh(closestIndexEnd+1:length(Rate_sh)); + else + Act_pst = Rate_sh(closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs); + end + + %Temporally binned activity for pre-during-post + flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output + bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; + bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; + bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; + + %Spatially binned activity for spatial information + %during flight (spatial activity) and interpolating + %across the bins + v_trj1 = flightPaths.vel(1,~isnan(flightPaths.pos(1,:,id(flight_i))),id(flight_i)); + v_trj = downsample(v_trj1,4); + sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_vel(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(v_trj,2)),v_trj',linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_path(:,flight_i) = linspace(1,flightPaths.length(id(flight_i)),n_space_bins)'; + end + + %Spatial information (CRITICAL CALCULATION!) + prob = 1./mean(sp_bnd_vel,2)*(1/sum(1./mean(sp_bnd_vel,2))); + sp_bnd_lambda = sp_bnd_act; + lambda = median(sp_bnd_lambda,2); + lambda_ave = lambda'*prob; + info(n) = sum(lambda.*prob.*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + + %Concatenate activities and plot + bnd_act = [bnd_act_pre;bnd_act_dur;bnd_act_pst]; + subplot(4,4,[1 2 3 5 6 7 9 10 11]); + plot(linspace(1,100,3*n_bins),filter(w,1,median(bnd_act,2)),'k'); hold on; + if n == 1 %save specific names for first rep to use for plotting with shaded area + avg_bnd_act(:,id_cluster_SI, ROIcounter) = filter(w,1,mean(bnd_act,2)); + sp_bnd_response(:,id_cluster_SI,ROIcounter) = filter(w,1,lambda); + sp_bnd_velCel{id_cluster_SI} = sp_bnd_vel; + + ciplot(filter(w,1,mean(bnd_act,2))-std(bnd_act,[],2)./sqrt(size(id,1)),filter(w,1,mean(bnd_act,2))+std(bnd_act,[],2)./sqrt(size(id,1)),linspace(1,100,3*n_bins)); + alpha(0.3); + line([33,33], [-max(mean(bnd_act,2)),max(mean(bnd_act,2))],'Color', 'k','LineStyle','--'); + line([66,66], [-max(mean(bnd_act,2)),max(mean(bnd_act,2))],'Color', 'k','LineStyle','--'); + xlabel('Flight phase'); ylabel('Activity'); + + subplot(4,4,13); imagesc(sp_bnd_act'); set(gca,'xtick',[]); + subplot(4,4,14); imagesc(sp_bnd_vel'); set(gca,'xtick',[]); + subplot(4,4,15); imagesc(sp_bnd_vel'.*sp_bnd_act'); set(gca,'xtick',[]); + end + + %Integrated activity in the pre-during-post periods + %measure of average firing rate of cell in pre,dur, and + %post epochs + spikes(n,1) = sum(mean(bnd_act_pre,2))/pre_dur; + spikes(n,2) = sum(mean(bnd_act_dur,2))/mean(flight_dur); %uses average flight duration + spikes(n,3) = sum(mean(bnd_act_pst,2))/pst_dur; + end + + fig_ord = get(gca,'Children'); set(gca,'Children',circshift(fig_ord,2,1)); hold off; + %% can quantify all p-values for all spike rates and + %Pre analysis + subplot(4,4,4); hi = histogram(spikes(:,1),'Normalization','pdf'); hold on; + stem(spikes(1,1),1); hold off; title('Pre Spikes'); + p_val(1,id_cluster_SI,ROIcounter) = length(find(spikes(:,1)>=spikes(1,1)))/n_rep; %pval = number of counts that are larger than the spiking of the real trace + response(1,id_cluster_SI,ROIcounter) = spikes(1,1); %number of responses (spikes) for each flight/average duration of epoch (integrated spike response) + + %During analysis + subplot(4,4,8); hi = histogram(spikes(:,2),'Normalization','pdf'); hold on; + stem(spikes(1,2),1); hold off; title('During Spikes'); + p_val(2,id_cluster_SI,ROIcounter) = length(find(spikes(:,2)>=spikes(1,2)))/n_rep; + response(2,id_cluster_SI,ROIcounter) = spikes(1,2); + + %Post analysis + subplot(4,4,12); hi = histogram(spikes(:,3),'Normalization','pdf'); hold on; + stem(spikes(1,3),1); hold off; title('Post Spikes'); + p_val(3,id_cluster_SI,ROIcounter) = length(find(spikes(:,3)>=spikes(1,3)))/n_rep; + response(3,id_cluster_SI,ROIcounter) = spikes(1,3); + + %Spatial info analysis + subplot(4,4,16); hi = histogram(info,'Normalization','pdf'); hold on; + stem(info(1),1); hold off; title('Spatial Info'); + S_Info(1,id_cluster_SI,ROIcounter) = info(1); + S_Info(2,id_cluster_SI,ROIcounter) = length(find(info>=info(1)))/n_rep; + + drawnow(); saveas(gcf,[saveDir batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} '_ROI_' num2str(ROIcounter) '_' num2str(cell_n) '_cluster_' num2str(id_cluster_SI) '.tif']); + end + ROIcounter = ROIcounter +1; + end + end + + close all; + end + + %% Look at significant cells + + if p_val_analysis + + %Putative place cells(**during activity & **spatial info & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + pp_cells = [false(1,N); squeeze(alfa>S_Info(2,2:end,:)>0) & squeeze(alfa>p_val(2,2:end,:)>0) & squeeze(max(sp_bnd_response(:,2:end,:),[],1))>3*mean(Rate,'all')']; %false for cluster #1 + [clusP,roiP] = find(pp_cells==1); + pp_cells_activity = round(normalize(sp_bnd_response(:,pp_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + [sorted_rows,~] = find(pp_cells_activity==1); sorted_pp_fields = pp_cells_activity(sorted_rows,:); + figure(); imagesc(sorted_pp_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + hold on; + title([batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' pfields sorted']); + rname = []; + for i = 1:length(sorted_rows); + rname{i} = [num2str(roiP(sorted_rows(i))) '.' num2str(clusP(sorted_rows(i)))]; + end + set(gca,'ytick',[1:length(sorted_rows)],'yTickLabel',rname); + ylabel('ROI#.Clust#'); + xlabel('Time Bin'); + saveas(gcf,[saveDir batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' pfields sorted.tif']); + + %Putative pre and post cells(**pre/post activity & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppre_cells = [false(1,N); squeeze(alfa>p_val(1,2:end,:)>0) & squeeze(max(avg_bnd_act(1:n_bins,2:end,:),[],1))>3*mean(Rate,'all')']; %false for cluster #1 + [clusPre,roiPre] = find(ppre_cells==1); + ppre_cells_activity = round(normalize(avg_bnd_act(1:n_bins,ppre_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + [sorted_rows_pre,~] = find(ppre_cells_activity==1); sorted_ppre_fields = ppre_cells_activity(sorted_rows_pre,:); + figure(); imagesc(sorted_ppre_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + hold on; + title([batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' preCells sorted']); + for i = 1:length(sorted_rows_pre); + rname{i} = [num2str(roiPre(sorted_rows_pre(i))) '.' num2str(clusPre(sorted_rows_pre(i)))]; + end + set(gca,'ytick',[1:length(sorted_rows_pre)],'yTickLabel',rname); + ylabel('ROI#.Clust#'); + xlabel('Time Bin'); + saveas(gcf,[saveDir batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' preCells sorted.tif']); + + %post cells + ppost_cells = [false(1,N); squeeze(alfa>p_val(3,2:end,:)>0) & squeeze(max(avg_bnd_act(n_bins*2+1:n_bins*3,2:end,:),[],1))>3*mean(Rate,'all')']; %false for cluster #1 + [clusPost,roiPost] = find(ppost_cells==1); + ppost_cells_activity = round(normalize(avg_bnd_act(n_bins*2+1:n_bins*3,ppost_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + [sorted_rows_post,~] = find(ppost_cells_activity==1); sorted_ppost_fields = ppost_cells_activity(sorted_rows_post,:); + figure(); imagesc(sorted_ppost_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + hold on; + title([batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' postCells sorted']); + for i = 1:length(sorted_rows_post); + rname{i} = [num2str(roiPost(sorted_rows_post(i))) '.' num2str(clusPost(sorted_rows_post(i)))]; + end + set(gca,'ytick',[1:length(sorted_rows_post)],'yTickLabel',rname); + ylabel('ROI#.Clust#'); + xlabel('Time Bin'); + saveas(gcf,[saveDir batName{day_i} ' ' dateSesh{day_i} ' ' sessionType{day_i} ' postCells sorted.tif']); + + %Visualize place fields and calculate centroids + %outputs every place field as a centroid heatmap along each trajectory + figure(); set(gcf, 'units','normalized','outerposition',[0.2 0.3 0.5 0.45]); + [clus,cellNum] = find(pp_cells); %outputs which cells and which clusters have spatial selectivity + Place_field = struct([]); + max_position = []; + for clus_i = 1:length(clus) %for each cluster + + %take each flight from a place cell cluster, take the shortest + %flight, and generate an average trajectory based off the shortest + %flight + id = flightPaths.clusterIndex{clus(clus_i)};%find(flight_clus_ds.id==clus(i)); + shortest_flight_i = min(squeeze(sum(~isnan(flightPaths.pos(:,:,id)),2)),[],2); + ave_trajectory = nanmean(flightPaths.pos(:,1:shortest_flight_i(1),id),3); + %ave_acceleratn = nanmean(flight_clus_ds.acc(1,1:shortest_flight_i(1),id),3); + + npo = size(ave_trajectory,2); %length of average trajectory + take_off = mean(squeeze(flightPaths.pos(:,1,id)),2); + map = interp1(linspace(1,100,size(sp_bnd_response(:,clus(clus_i),cellNum(clus_i)),1)),sp_bnd_response(:,clus(clus_i),cellNum(clus_i)),linspace(1,100,npo),'linear')'; + map_color = uint8(round(normalize(map,'range',[2 100]))); %make the mapping between activity and color + + %Determine location of the max activity + [~,max_bin] = max(sp_bnd_velCel{clus(clus_i)}.*sp_bnd_response(:,clus(clus_i),cellNum(clus_i)),[],1,'linear'); + max_position = round(size(ave_trajectory,2)*max_bin/n_space_bins); %find centroid of place field + %plot the firing activity along the average + sgtitle([batName{day_i} ' ' dateSesh{day_i} ' ROI: ' num2str(cellNum(clus_i)) ' (' num2str(ROIs_manual(day_i,cellNum(clus_i))) ') Cluster: ' num2str(clus(clus_i))]); + subplot(121); cmap = viridis(100); + p = plot3(ave_trajectory(1,:),ave_trajectory(2,:),ave_trajectory(3,:),'r', 'LineWidth',5); + grid on; + cdata = [uint8(cmap(map_color,:)*255) uint8(ones(npo,1))].'; + drawnow(); set(p.Edge, 'ColorBinding','interpolated', 'ColorData',cdata); + hold on; + textscatter3(take_off(1),take_off(2),take_off(3),"Take-off"); + scatter3(ave_trajectory(1,max_position(1)),ave_trajectory(2,max_position(1)),ave_trajectory(3,max_position(1))); + xlim([-3 3]); ylim([-3 3]); zlim([0 2.5]); + xlabel('x'); ylabel('y'); zlabel('z'); + drawnow(); hold off; + + subplot(122); + plot([1:1:n_space_bins],sp_bnd_response(:,clus(clus_i),cellNum(clus_i)),'LineWidth',3); xlabel('Space along trajectory'); ylabel('Activity (SD units)'); + xticks([1 n_space_bins]); xticklabels({'Take-off','Landing'}); + %save info for each place field (position, cell num, clust num) + Place_field(clus_i).pos = ave_trajectory(:,max_position(1)); + Place_field(clus_i).cell = cellNum(clus_i); + Place_field(clus_i).clus = clus(clus_i); + + saveas(gcf,[saveDir batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} '_Place_field' num2str(clus_i) '.tif']); + end + close all; + + %Calculate percentage of place cells + perc_place = length(unique(cellNum))./N; + perc_pre = length(unique(roiPre))./N; + perc_post = length(unique(roiPost))./N; + + %Evaluate distances between centroids for corresponding place fields, within a + %single cell + field_dist = []; + for cell_i = 1:N + try + if length(find([Place_field.cell] == cell_i))>1 + cell_pairs = nchoosek(find([Place_field.cell] == cell_i),2); + for n = 1:size(cell_pairs,1) + field_dist = [field_dist; norm([Place_field(cell_pairs(n,1)).pos]-[Place_field(cell_pairs(n,2)).pos])]; + end + end + catch + end + end + + %Calculate percentage of pre, during, post cells on any trajectory (excluding cluster 1) + percentage = sum(squeeze(any(alfa>p_val(:,2:end,:)>0,2)),2)./N; + + %Look at the activity of significantly modulated cells + %this may have to be corrected because it is not looking at all + %pre/post/during cells, just looking at during right now + pt_cells = [false(1,N); squeeze(any(alfa>p_val(:,2:end,:)>0))]; %pt cells have signif pval in any period (pre,during, post) + [clusAll,roiAll] = find(pt_cells==1); + pt_cells_activity = round(normalize(avg_bnd_act(:,pp_cells),1,'range'),5)'; + [sorted_rows_all,~] = find(pt_cells_activity==1); sorted_cells = pt_cells_activity(sorted_rows_all,:); + figure(); set(gcf, 'units','normalized','outerposition',[0.25 0.25 0.5 0.5]); + ax1 = subplot(1,3,1); imagesc(sorted_cells(:,1:n_bins),[0 1]); colormap(viridis); + ax2 = subplot(1,3,2); imagesc(sorted_cells(:,n_bins+1:2*n_bins),[0 1]); + ax3 = subplot(1,3,3); imagesc(sorted_cells(:,2*n_bins+1:end),[0 1]); + ax1.Title.String = 'Pre-Flight'; ax2.Title.String = 'During-Flight'; ax3.Title.String = 'Post-Flight'; + ax1.XLabel.String = 'Bin'; ax2.XLabel.String = 'Bin'; ax3.XLabel.String = 'Bin'; + ax1.YLabel.String = 'ROI#.Clust#'; ax2.YTickLabel= []; ax3.YTickLabel= []; + for i = 1:length(sorted_rows_all); + rname{i} = [num2str(roiAll(sorted_rows_all(i))) '.' num2str(clusAll(sorted_rows_all(i)))]; + end + set(gca,'ytick',[1:length(sorted_rows_all)],'yTickLabel',rname); + saveas(gcf,[saveDir batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} '_activity_sorted.tif']); + + end + + %% Save (modify this to save only relevant variables) + if saveFlag == 1 + a_filename = [saveDir batName{day_i} '_' dateSesh{day_i} '_' 'Extracted_trajectories_&_activity',datestr(now, 'yymmdd_HHMM'),'.mat']; + placeCellsAngStable.meta.n_bins = n_bins; + placeCellsAngStable.meta.n_rep = n_rep; + placeCellsAngStable.meta.alfa = alfa; + placeCellsAngStable.meta.pre_dur = pre_dur; + placeCellsAngStable.meta.pst_dur = pst_dur; + placeCellsAngStable.meta.nSpace_bins = n_space_bins; + placeCellsAngStable.meta.N = N; + placeCellsAngStable.meta.T = T; + placeCellsAngStable.meta.CNMFe_Fs = CNMFe_Fs; + placeCellsAngStable.meta.dsFactor = dsFactor; + placeCellsAngStable.meta.frames_to_shift = frames_to_shift; + placeCellsAngStable.meta.batName = batName{day_i}; + placeCellsAngStable.meta.dateSesh = dateSesh{day_i}; + placeCellsAngStable.meta.sessionType = sessionType{day_i}; + + placeCellsAngStable.ROIs_manual = ROIs_manual; + placeCellsAngStable.Rate = Rate; + placeCellsAngStable.p_val = p_val; + placeCellsAngStable.response = response; + placeCellsAngStable.avg_bnd_act = avg_bnd_act; + placeCellsAngStable.sp_bnd_response = sp_bnd_response; + placeCellsAngStable.sp_bnd_velCel = sp_bnd_velCel; + placeCellsAngStable.S_Info = S_Info; + placeCellsAngStable.max_position = max_position; + placeCellsAngStable.Place_field = Place_field; + placeCellsAngStable.percentage = percentage; + placeCellsAngStable.perc_place = perc_place; + placeCellsAngStable.perc_pre = perc_pre; + placeCellsAngStable.perc_post = perc_post; + placeCellsAngStable.pp_cells = pp_cells; + placeCellsAngStable.pp_cells_activity = pp_cells_activity; + placeCellsAngStable.sorted_rows = sorted_rows; + placeCellsAngStable.sorted_pp_fields = sorted_pp_fields; + placeCellsAngStable.pt_cells = pt_cells; + placeCellsAngStable.pt_cells_activity = pt_cells_activity; + placeCellsAngStable.ppre_cells = ppre_cells; + placeCellsAngStable.ppre_cells_activity = ppre_cells_activity; + placeCellsAngStable.sorted_rows_pre = sorted_rows_pre; + placeCellsAngStable.sorted_ppre_fields = sorted_ppre_fields; + placeCellsAngStable.ppost_cells = ppost_cells; + placeCellsAngStable.ppost_cells_activity = ppost_cells_activity; + placeCellsAngStable.sorted_rows_post = sorted_rows_post; + placeCellsAngStable.sorted_ppost_fields = sorted_ppost_fields; + placeCellsAngStable.clusP = clusP; + placeCellsAngStable.roiP = roiP; + placeCellsAngStable.clusPre = clusPre; + placeCellsAngStable.roiPre = roiPre; + placeCellsAngStable.clusPost = clusPost; + placeCellsAngStable.roiPost = roiPost; + placeCellsAngStable.clusAll = clusAll; + placeCellsAngStable.roiAll = roiAll; + placeCellsAngStable.clus = clus; + placeCellsAngStable.cellNum = cellNum; + + + save(a_filename,'placeCellsAngStable'); +% if analyze_Ca +% save([saveDir '/A_', batdate, '.mat'],'A'); %save spatial footprints +% end + end + disp(datestr(now)); + + cd(dirTop(day_i).folder) +end +close all; \ No newline at end of file diff --git a/analysis_tobias/ImBat_placeCells_Will.asv b/analysis_tobias/ImBat_placeCells_Will.asv new file mode 100644 index 0000000..2f24e65 --- /dev/null +++ b/analysis_tobias/ImBat_placeCells_Will.asv @@ -0,0 +1,510 @@ +function ImBat_placeCells_Will(flightPaths, cellData, alignment,varargin) + +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +p_val_analysis = 1; +save_data = 1; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; + end +end + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + date = strcat(lower(batName(1:2)),dateSesh); + label = [batName '_' dateSesh '_' sessionType]; + %label = [dateSesh '_' sessionType]; + cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); + alignment = load([pwd '/processed/Alignment.mat']); + load([pwd '/' analysis_Folder '/' label '_flightPaths.mat']); +end + +% P_value calculation params +n_rep = 100; % # of itterations for the shuffle can lower to 10 for debugging +n_bins = 30; %good around here %number of bins to divide the pre-during-post flight interval +alfa = 0.05; %can lower to 0.01 or 0.1 %significance level +pre_dur = 3; %play with 3-5 %duration of the pre flight period (s): comparable with flight dur +pst_dur = 3; %play with 3-5 %duration of the post flight period (s): but shorter than half interflight +w = gausswin(1); %keep at 1 for no smoothing %witdh of the gaussian filter (number of bins), use odd values. 1=no filtering +n_space_bins = 30; %correlates with space resolution but good around 30 (20cm chunks) %number of spatial bins +until_cluster = 4;%min(length(flightPaths.clusterIndex),100); %change this if you want less clusters + +%neural data variables +N = size(cellData.results.C_raw,1); %number of ROIs +T = size(cellData.results.C_raw,2); %length of each neural trace +CNMFe_Fs = cellData.results.Fs; %imaging sampling rate + +%% resample the neural data to make all the trials the same length +%Extract variables from Alignment +img_times = alignment.out.video_times'; +img_sampling = diff(img_times); +img_sampl_interval = mean(img_sampling); +img_Fs = 1/img_sampl_interval; + +%Calculate real sampling frequency +CNMF_Fs_real = round(T/(img_times(end)-img_times(1))); +CNMF_time = downsample(img_times,round(img_Fs/CNMF_Fs_real)); + +%Generate evenly spaced times +t_even = linspace(img_times(1),img_times(end),length(img_times)); +CNMF_time_even = downsample(t_even,round(img_Fs/CNMF_Fs_real)); + +FC_raw = cellData.results.C_raw;%.*fr_area; %Raw fluorescence (normalized) +FC = cellData.results.C;%.*fr_area; %Denoised fluorescence (normalized) +S = full(cellData.results.S);%.*fr_area; %Deconvolved spike trace (normalized) + +%Resample at even time intervals +try + FC_raw_rs = interp1(CNMF_time',FC_raw',CNMF_time_even','linear','extrap')';%cellData.results.C_raw',CNMF_time_even','linear','extrap')'; + S_rs = interp1(CNMF_time',S',CNMF_time_even','nearest','extrap')';%cellData.results.S',CNMF_time_even','nearest','extrap')'; +catch + recDiff = length(CNMF_time) - length(cellData.results.C_raw); + FC_raw_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.C_raw)',CNMF_time_even(1,1:end-recDiff)','linear','extrap')'; + S_rs = interp1(CNMF_time(1,1:end-recDiff)',full(cellData.results.S)',CNMF_time_even(1,1:end-recDiff)','nearest','extrap')'; +end + +%Ca-activity and inferred spike-rate are constrained to zero for 5s at the beginning and end of the session and inferred spike-rate is normalized (SD units) and smoothed +Activity = FC_raw_rs; +Activity(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + +Rate = normalize(S_rs,2,'scale'); Rate = movmean(Rate,CNMF_Fs_real*0.5,2); %normalize by STD and smooth on 0.5s +Rate(:,[1:CNMF_Fs_real*5,end-CNMF_Fs_real*5-1:end])=0; %cut activity at the start and stop of the recording (5s) + +%% --------------------------------- REFINED ANALYSIS START FROM HERE------------------------------ +%////////////////////////////////////////////////////////////////////////////////////////////////// +% Calculations are done on the Rate matrix, which is the S matrix, +% normalized by standard deviation and smoothed on a 0.5s window + +if p_val_analysis + + %Create folder to store figures + figures_directory1=fullfile(pwd,'Spatial_information'); + delete([figures_directory1 '\*']); + if exist(figures_directory1,'dir')~=7 + mkdir(figures_directory1); + end + + %Initialization of matrices and arrays + %frames_to_shift(1)=0; frames_to_shift(2:n_rep) = randi([10*CNMFe_Fs T-10*CNMFe_Fs],1,n_rep-1); %Shifting in time (longer than 10s) + p_val = zeros(3,until_cluster,N); %pre(1),during(2),post(3)/#cluster/#nueron %p values for pre, during, post active neurons + response = zeros(3,until_cluster,N); %sum of each phase %Integrated response during pre, during, post periods 'sum(median(Rate)' + avg_bnd_act = zeros((3*n_bins),until_cluster,N); %n_bins per section, for each pre/dur/post and for each cluster & cell %Activity across bins from pre to post + sp_bnd_response = zeros(n_space_bins,until_cluster,N); %Spatially binned activity along the trajectory + sp_bnd_velCel = cell(until_cluster,1); + S_Info = zeros(2,until_cluster,N); %2 b/c 1dim=actual info, 2dim=p-val %bits and p value for spatial information + S_Info_corrected = zeros(until_cluster,N); %make corrected info vector + + %Binning in time and space, p values calculation + figure(); set(gcf, 'units','normalized','outerposition',[0.2 0 0.5 1]); + for id_cluster_SI = 2:until_cluster %for each cluster + id = []; %id = find(flight_clus.id==id_cluster_SI); %find all flights that belong to that cluster + id = flightPaths.clusterIndex{id_cluster_SI}; + for cell_n = 1:N %for each cell, initialize the below matrices + sgtitle([batName ' ' dateSesh ' - ' 'ROI: ' num2str(cell_n) ' Cluster: ' num2str(id_cluster_SI)]); + disp(['Cell number: ' num2str(cell_n) ' Trajectory number: ' num2str(id_cluster_SI)]); + %matrices for keeping the data used in calcuating spatial info + bnd_act_pre = zeros(n_bins,size(id,1)); + bnd_act_dur = zeros(n_bins,size(id,1)); + bnd_act_pst = zeros(n_bins,size(id,1)); + sp_bnd_act = zeros(n_space_bins,size(id,1)); + sp_bnd_act_pre = zeros(n_space_bins,size(id,1)); + sp_bnd_act_pst = zeros(n_space_bins,size(id,1)); + sp_bnd_vel = zeros(n_space_bins,size(id,1)); + sp_bnd_path = zeros(n_space_bins,size(id,1)); + sp_bnd_lambda = zeros(n_space_bins,size(id,1)); + sp_bnd_act_sh = zeros(n_rep,n_space_bins,size(id,1)); + sp_bnd_act_pre_sh = zeros(n_rep,n_space_bins,size(id,1)); + sp_bnd_act_pst_sh = zeros(n_rep,n_space_bins,size(id,1)); + sp_bnd_concat_sh = zeros(n_rep,size(id,1),n_space_bins*3); + spikes = zeros(n_rep,3); + info = zeros(n_rep,3); + %for i = 1: n_rep; + for flight_i=1:size(id,1) %for all flights within the cluster, define the following vectors + %grabbing and binning the velocity and activity along with other variables + %convert from behavior time to imaging time + [minValueStart,closestIndexStart] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(id(flight_i))))); + [minValueEnd,closestIndexEnd] = min(abs(CNMF_time_even-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i)))));%min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(id(flight_i))))); + Act_pre = []; Act_dur = []; Act_pst = []; v_trj = []; + + Act_pre = Rate(cell_n,closestIndexStart-pre_dur*CNMFe_Fs:closestIndexStart-1)'; + if closestIndexEnd-closestIndexStart == 0 %if flight is 0 frames + Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd+1)'; + else + Act_dur = Rate(cell_n,closestIndexStart:closestIndexEnd)'; + end + if closestIndexEnd+pst_dur*CNMFe_Fs > length(Rate) + Act_pst = Rate(cell_n,closestIndexEnd+1:length(Rate))'; + else + Act_pst = Rate(cell_n,closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs)'; + end + %Temporally binned activity for pre-during-post + flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output + bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; + bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; + bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; + + %Spatially binned activity for spatial information + %during flight (spatial activity) and interpolating + %across the bins + v_trj1 = flightPaths.vel(1,~isnan(flightPaths.pos(1,:,id(flight_i))),id(flight_i)); + v_trj = downsample(v_trj1,4); + sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; + sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; + + sp_bnd_vel(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(v_trj,2)),v_trj',linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_path(:,flight_i) = linspace(1,flightPaths.length(id(flight_i)),n_space_bins)'; + end + + %concatenate the data and shuffle the true matrix + sp_bnd_concat = cat(1, sp_bnd_act_pre, sp_bnd_act, sp_bnd_act_pst)'; + frames_to_shift = randi(size(sp_bnd_concat,2),1,size(sp_bnd_concat,1)); + sp_bnd_concat_sh1=cell2mat(arrayfun(@(x) circshift(sp_bnd_concat(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0)); + + % plot the sp matrix, and the shuffle + %figure(); + subplot(4,4,13); + imagesc(sp_bnd_concat); + title('true spike matrix'); + subplot(4,4,14); + imagesc(sp_bnd_concat_sh1) + title('circshift spike matrix'); + subplot(4,4,15); + imagesc(sp_bnd_vel'); + title('Velocity'); %set(gca,'xtick',[]); + + % plot the means of the true, and n itterations of the shuffled data + %figure(); + subplot(4,4,[1:3,5:7,9:11]) + hold on; + plot(mean(sp_bnd_concat),'r','LineWidth',4); + for i = 1: n_rep; + if i ==1 + sp_bnd_act_sh(i,:,:) = sp_bnd_act; + sp_bnd_act_pre_sh(i,:,:) = sp_bnd_act_pre; + sp_bnd_act_pst_sh(i,:,:) = sp_bnd_act_pst; + sp_bnd_concat_sh(i,:,:) = sp_bnd_concat; + + elseif i == 2 + sp_bnd_act = sp_bnd_act'; + sp_bnd_act_pre = sp_bnd_act_pre'; + sp_bnd_act_pst = sp_bnd_act_pst'; + end + if i > 1 + frames_to_shift=randi(size(sp_bnd_concat,2),1,size(sp_bnd_concat,1)); + sp_bnd_act_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_act_pre_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act_pre(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_act_pst_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act_pst(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_concat_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_concat(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0)); + end + plot(squeeze(mean(sp_bnd_concat_sh(i,:,:),2)),'b'); + + %spatial info calc + prob = 1./mean(sp_bnd_vel,2)*(1/sum(1./(mean(sp_bnd_vel,2)))); %1./mean... normalization factor by summing all the prob in each spatial bin to sum up to 1 + sp_bnd_lambda = sp_bnd_act_sh(i,:,:); + lambda = mean(sp_bnd_lambda,3)';%median(sp_bnd_lambda,2); + lambda_pre = mean(sp_bnd_act_pre_sh(i,:,:),3);%median(sp_bnd_act_pre,2); + lambda_pst = mean(sp_bnd_act_pst_sh(i,:,:),3);%median(sp_bnd_act_pst,2); + lambda_ave = lambda'*prob; + %during flight using flight occupancy + info(i,2) = sum((lambda.*prob).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + %pre and post flight info calc adapted from Will + info(i,1) = abs(nansum((mean(sp_bnd_act_pre_sh(1,:,:),3)./(lambda_pre+1e-20)).*log2(mean(sp_bnd_act_pre_sh(1,:,:),3)+1e-20)./(lambda_pre+1e-20))); + info(i,3) = abs(nansum((mean(sp_bnd_act_pst_sh(1,:,:),3)./(lambda_pst+1e-20)).*log2(mean(sp_bnd_act_pst_sh(1,:,:),3)+1e-20)./(lambda_pst+1e-20))); + %if true data for first rep, use the original calculated values + if i == 1 + avg_bnd_act(:,id_cluster_SI, cell_n) = filter(w,1,mean(sp_bnd_concat)); + sp_bnd_response(:,id_cluster_SI,cell_n) = filter(w,1,lambda); + sp_bnd_response_pre(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pre); + sp_bnd_response_pst(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pst); + sp_bnd_velCel{id_cluster_SI} = sp_bnd_vel; + end + + %Integrated activity in the pre-during-post periods + %measure of average firing rate of cell in pre,dur, and + %post epochs + spikes(i,1) = sum(mean(sp_bnd_act_pre_sh(i,:,:),3))/pre_dur;%max(median(bnd_act_pre,2))/pre_dur; %mean vs median + spikes(i,2) = sum(mean(sp_bnd_act_sh(i,:,:),3))/mean(flight_dur);%max(median(bnd_act_dur,2))/mean(flight_dur); %uses average flight duration + spikes(i,3) = sum(mean(sp_bnd_act_pst_sh(i,:,:),3))/pst_dur;%max(median(bnd_act_pst,2))/pst_dur; + end + plot(squeeze(mean(sp_bnd_concat_sh(1,:,:),2)),'r','LineWidth',4); % plot again so line is on top.. + plot(squeeze(mean(sp_bnd_concat_sh(1,:,:),2)),'b'); + legend('true','shifted'); + title('true mean(spikeMatrix) vs circshift'); + + + %fig_ord = get(gca,'Children'); set(gca,'Children',circshift(fig_ord,2,1)); hold off; + %% can quantify all p-values for all spike rates and + %Pre analysis + subplot(4,4,4); hi = histogram(info(:,1),'Normalization','pdf'); hold on; + stem(info(1,1),1); hold off; title('Pre Spikes'); + p_val(1,id_cluster_SI,cell_n) = length(find(info(:,1)>=info(1,1)))/n_rep; %pval = number of counts that are larger than the spiking of the real trace + response(1,id_cluster_SI,cell_n) = spikes(1,1); %number of responses (spikes) for each flight/average duration of epoch (integrated spike response) + + %During analysis + subplot(4,4,8); hi = histogram(info(:,2),'Normalization','pdf'); hold on; + stem(info(1,2),1); hold off; title('During Spikes'); + p_val(2,id_cluster_SI,cell_n) = length(find(info(:,2)>=info(1,2)))/n_rep; + response(2,id_cluster_SI,cell_n) = spikes(1,2); + + %Post analysis + subplot(4,4,12); hi = histogram(info(:,3),'Normalization','pdf'); hold on; + stem(info(1,3),1); hold off; title('Post Spikes'); + p_val(3,id_cluster_SI,cell_n) = length(find(info(:,3)>=info(1,3)))/n_rep; + response(3,id_cluster_SI,cell_n) = spikes(1,3); + + %Spatial info analysis + subplot(4,4,16); hi = histogram(info(:,2),'Normalization','pdf'); hold on; + %*****bias correction to subtract mean from observed info + S_Info_corrected(id_cluster_SI,cell_n) = info(1,2)-mean(info(2:end,2)); + stem(info(1,2),1); hold off; title('Spatial Info'); + S_Info(1,id_cluster_SI,cell_n) = info(1,2); + S_Info(2,id_cluster_SI,cell_n) = length(find(info(:,2)>=info(1,2)))/n_rep; + + drawnow(); saveas(gcf,[figures_directory1, '/', batName '_' dateSesh '_' sessionType '_ROI_' num2str(cell_n) '_cluster_' num2str(id_cluster_SI) '.jpg']); + + end + end + close all; +end + +%% Look at significant cells + +if p_val_analysis + + %Putative place cells(**during activity & **spatial info & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + pp_cells = [false(1,N); squeeze(S_Info(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 & squeeze(p_val(2,2:end,:) 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppre_cells = [false(1,N); squeeze(p_val(1,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppre_cells_activity = round(normalize(bnd_act_pre(:,ppre_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_pre,~] = find(ppre_cells_activity==1); sorted_ppre_fields = ppre_cells_activity(sorted_rows_pre,:); + %figure(); imagesc(sorted_ppre_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_prefields_sorted.jpg']); + [clus_pre,cellNum_pre] = find(ppre_cells); %outputs which cells and which clusters have spatial selectivity + + %Putative post cells(**pre activity & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppost_cells = [false(1,N); squeeze(p_val(3,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppost_cells_activity = round(normalize(bnd_act_pst(:,ppost_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_post,~] = find(ppost_cells_activity==1); sorted_ppost_fields = ppost_cells_activity(sorted_rows_post,:); + %figure(); imagesc(sorted_ppost_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_postfields_sorted.jpg']); + [clus_post,cellNum_post] = find(ppost_cells); %outputs which cells and which clusters have spatial selectivity + + %putative place cells but not looking at spatial info, only based on p-val + pp_cells_loose = [false(1,N); squeeze(p_val(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + [clus_loose,cellNum_loose] = find(pp_cells_loose); + + %putative place cells but not looking at spatial info, only based on + %p-val and no minimum spike rate + pp_cells_looseloose = [false(1,N); squeeze(p_val(2,2:end,:) length(Rate) + Act_pst = Rate(cell_n,closestIndexEnd+1:length(Rate))'; + else + Act_pst = Rate(cell_n,closestIndexEnd+1:closestIndexEnd+pst_dur*CNMFe_Fs)'; + end + %Temporally binned activity for pre-during-post + flight_dur(1,flight_i) = flightPaths.dur(id(flight_i)); %this comes from the flightPaths output + bnd_act_pre(:,flight_i) = interp1(linspace(1,100,size(Act_pre,1)),Act_pre,linspace(1,100,n_bins),'linear')'; + bnd_act_dur(:,flight_i) = interp1(linspace(1,100,size(Act_dur,1)),Act_dur,linspace(1,100,n_bins),'linear')'; + bnd_act_pst(:,flight_i) = interp1(linspace(1,100,size(Act_pst,1)),Act_pst,linspace(1,100,n_bins),'linear')'; + + %Spatially binned activity for spatial information + %during flight (spatial activity) and interpolating + %across the bins + v_trj1 = flightPaths.vel(1,~isnan(flightPaths.pos(1,:,id(flight_i))),id(flight_i)); + v_trj = downsample(v_trj1,4); + sp_bnd_act(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(Act_dur,1)),Act_dur,linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_act_pre(:,flight_i) = interp1(linspace(1,size(Act_pre,1),size(Act_pre,1)),Act_pre,linspace(1,size(Act_pre,1),n_space_bins),'linear')'; + sp_bnd_act_pst(:,flight_i) = interp1(linspace(1,size(Act_pst,1),size(Act_pst,1)),Act_pst,linspace(1,size(Act_pst,1),n_space_bins),'linear')'; + + sp_bnd_vel(:,flight_i) = interp1(linspace(1,flightPaths.length(id(flight_i)),size(v_trj,2)),v_trj',linspace(1,flightPaths.length(id(flight_i)),n_space_bins),'linear')'; + sp_bnd_path(:,flight_i) = linspace(1,flightPaths.length(id(flight_i)),n_space_bins)'; + end + + %concatenate the data and shuffle the true matrix + sp_bnd_concat = cat(1, sp_bnd_act_pre, sp_bnd_act, sp_bnd_act_pst)'; + frames_to_shift = randi(size(sp_bnd_concat,2),1,size(sp_bnd_concat,1)); + sp_bnd_concat_sh1=cell2mat(arrayfun(@(x) circshift(sp_bnd_concat(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0)); + + % plot the sp matrix, and the shuffle + %figure(); + subplot(4,4,13); + imagesc(sp_bnd_concat); + title('true spike matrix'); + subplot(4,4,14); + imagesc(sp_bnd_concat_sh1) + title('circshift spike matrix'); + subplot(4,4,15); + imagesc(sp_bnd_vel'); + title('Velocity'); %set(gca,'xtick',[]); + + % plot the means of the true, and n itterations of the shuffled data + %figure(); + subplot(4,4,[1:3,5:7,9:11]) + hold on; + plot(mean(sp_bnd_concat),'r','LineWidth',4); + for i = 1: n_rep; + if i ==1 + sp_bnd_act_sh(i,:,:) = sp_bnd_act; + sp_bnd_act_pre_sh(i,:,:) = sp_bnd_act_pre; + sp_bnd_act_pst_sh(i,:,:) = sp_bnd_act_pst; + sp_bnd_concat_sh(i,:,:) = sp_bnd_concat; + + elseif i == 2 + sp_bnd_act = sp_bnd_act'; + sp_bnd_act_pre = sp_bnd_act_pre'; + sp_bnd_act_pst = sp_bnd_act_pst'; + end + if i > 1 + frames_to_shift=randi(size(sp_bnd_concat,2),1,size(sp_bnd_concat,1)); + sp_bnd_act_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_act_pre_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act_pre(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_act_pst_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_act_pst(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0))'; + sp_bnd_concat_sh(i,:,:) = cell2mat(arrayfun(@(x) circshift(sp_bnd_concat(x,:),[1 frames_to_shift(x)]),(1:numel(frames_to_shift))','un',0)); + end + plot(squeeze(mean(sp_bnd_concat_sh(i,:,:),2)),'b'); + + %spatial info calc + prob = 1./mean(sp_bnd_vel,2)*(1/sum(1./(mean(sp_bnd_vel,2)))); %1./mean... normalization factor by summing all the prob in each spatial bin to sum up to 1 + sp_bnd_lambda = sp_bnd_act_sh(i,:,:); + lambda = mean(sp_bnd_lambda,3)';%median(sp_bnd_lambda,2); + lambda_pre = mean(sp_bnd_act_pre_sh(i,:,:),3);%median(sp_bnd_act_pre,2); + lambda_pst = mean(sp_bnd_act_pst_sh(i,:,:),3);%median(sp_bnd_act_pst,2); + lambda_ave = lambda'*prob; + %during flight using flight occupancy + info(i,2) = sum((lambda.*prob).*log2((lambda+1e-20)./(lambda_ave+1e-20))); %bits/second + %pre and post flight info calc adapted from Will + info(i,1) = abs(nansum((mean(sp_bnd_act_pre_sh(1,:,:),3)./(lambda_pre+1e-20)).*log2(mean(sp_bnd_act_pre_sh(1,:,:),3)+1e-20)./(lambda_pre+1e-20))); + info(i,3) = abs(nansum((mean(sp_bnd_act_pst_sh(1,:,:),3)./(lambda_pst+1e-20)).*log2(mean(sp_bnd_act_pst_sh(1,:,:),3)+1e-20)./(lambda_pst+1e-20))); + %if true data for first rep, use the original calculated values + if i == 1 + avg_bnd_act(:,id_cluster_SI, cell_n) = filter(w,1,mean(sp_bnd_concat)); + sp_bnd_response(:,id_cluster_SI,cell_n) = filter(w,1,lambda); + sp_bnd_response_pre(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pre); + sp_bnd_response_pst(:,id_cluster_SI,cell_n) = filter(w,1,lambda_pst); + sp_bnd_velCel{id_cluster_SI} = sp_bnd_vel; + end + + %Integrated activity in the pre-during-post periods + %measure of average firing rate of cell in pre,dur, and + %post epochs + spikes(i,1) = sum(mean(sp_bnd_act_pre_sh(i,:,:),3))/pre_dur;%max(median(bnd_act_pre,2))/pre_dur; %mean vs median + spikes(i,2) = sum(mean(sp_bnd_act_sh(i,:,:),3))/mean(flight_dur);%max(median(bnd_act_dur,2))/mean(flight_dur); %uses average flight duration + spikes(i,3) = sum(mean(sp_bnd_act_pst_sh(i,:,:),3))/pst_dur;%max(median(bnd_act_pst,2))/pst_dur; + end + plot(squeeze(mean(sp_bnd_concat_sh(1,:,:),2)),'r','LineWidth',4); % plot again so line is on top.. + plot(squeeze(mean(sp_bnd_concat_sh(1,:,:),2)),'b'); + legend('true','shifted'); + title('true mean(spikeMatrix) vs circshift'); + + + %fig_ord = get(gca,'Children'); set(gca,'Children',circshift(fig_ord,2,1)); hold off; + %% can quantify all p-values for all spike rates and + %Pre analysis + subplot(4,4,4); hi = histogram(info(:,1),'Normalization','pdf'); hold on; + stem(info(1,1),1); hold off; title('Pre Spikes'); + p_val(1,id_cluster_SI,cell_n) = length(find(info(:,1)>=info(1,1)))/n_rep; %pval = number of counts that are larger than the spiking of the real trace + response(1,id_cluster_SI,cell_n) = spikes(1,1); %number of responses (spikes) for each flight/average duration of epoch (integrated spike response) + + %During analysis + subplot(4,4,8); hi = histogram(info(:,2),'Normalization','pdf'); hold on; + stem(info(1,2),1); hold off; title('During Spikes'); + p_val(2,id_cluster_SI,cell_n) = length(find(info(:,2)>=info(1,2)))/n_rep; + response(2,id_cluster_SI,cell_n) = spikes(1,2); + + %Post analysis + subplot(4,4,12); hi = histogram(info(:,3),'Normalization','pdf'); hold on; + stem(info(1,3),1); hold off; title('Post Spikes'); + p_val(3,id_cluster_SI,cell_n) = length(find(info(:,3)>=info(1,3)))/n_rep; + response(3,id_cluster_SI,cell_n) = spikes(1,3); + + %Spatial info analysis + subplot(4,4,16); hi = histogram(info(:,2),'Normalization','pdf'); hold on; + %*****bias correction to subtract mean from observed info + S_Info_corrected(id_cluster_SI,cell_n) = info(1,2)-mean(info(2:end,2)); + stem(info(1,2),1); hold off; title('Spatial Info'); + S_Info(1,id_cluster_SI,cell_n) = info(1,2); + S_Info(2,id_cluster_SI,cell_n) = length(find(info(:,2)>=info(1,2)))/n_rep; + + drawnow(); saveas(gcf,[figures_directory1, '/', batName '_' dateSesh '_' sessionType '_ROI_' num2str(cell_n) '_cluster_' num2str(id_cluster_SI) '.jpg']); + + end + end + close all; +end + +%% Look at significant cells + +if p_val_analysis + + %Putative place cells(**during activity & **spatial info & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + pp_cells = [false(1,N); squeeze(S_Info(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 & squeeze(p_val(2,2:end,:) 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppre_cells = [false(1,N); squeeze(p_val(1,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppre_cells_activity = round(normalize(bnd_act_pre(:,ppre_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_pre,~] = find(ppre_cells_activity==1); sorted_ppre_fields = ppre_cells_activity(sorted_rows_pre,:); + %figure(); imagesc(sorted_ppre_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_prefields_sorted.jpg']); + [clus_pre,cellNum_pre] = find(ppre_cells); %outputs which cells and which clusters have spatial selectivity + + %Putative post cells(**pre activity & Peak Firing > 3 average firing) + %pp_cells is matrix of 0 and 1 to show if cell within each cluster + %(ncluster x ncells) + ppost_cells = [false(1,N); squeeze(p_val(3,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + %ppost_cells_activity = round(normalize(bnd_act_pst(:,ppost_cells),1,'range'),5)'; %normalize activity between 0-1 for putative place fields along 30 space fields + %[sorted_rows_post,~] = find(ppost_cells_activity==1); sorted_ppost_fields = ppost_cells_activity(sorted_rows_post,:); + %figure(); imagesc(sorted_ppost_fields,[0 1]); colormap(viridis); %plots the normalized activity sorted of putative place fields (cells sig/trajectory) + %saveas(gcf,[pwd, '/', batName '_' dateSesh '_' sessionType '_postfields_sorted.jpg']); + [clus_post,cellNum_post] = find(ppost_cells); %outputs which cells and which clusters have spatial selectivity + + %putative place cells but not looking at spatial info, only based on p-val + pp_cells_loose = [false(1,N); squeeze(p_val(2,2:end,:)3*mean(Rate(:,:),2)']; %false for cluster #1 + [clus_loose,cellNum_loose] = find(pp_cells_loose); + + %putative place cells but not looking at spatial info, only based on + %p-val and no minimum spike rate + pp_cells_looseloose = [false(1,N); squeeze(p_val(2,2:end,:)0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd')]) +end +saveDir = [saveDir1 datestr(now,'yymmdd') '\']; + +offset = 0; % account for slow calcium estimation ~move locations back 100ms in time... This is the knob to turn for 'prospective' coding... +speedThresh = 0.7; %threshold for when to eliminate nonflying moments +spikeThreshMult = 5; %number of times to multiply std of s vector for determining spike threshold +if strcmp(batId,'Gal') +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_manual = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 14 3 16 21 2 1 5 7 8 26 NaN 9 27 6 4; + 5 13 41 23 1 21 3 24 6 22 2 25 16 15 7; + 12 3 34 19 2 14 6 15 9 36 5 10 35 20 1; + 25 26 16 32 1 12 4 19 5 28 15 NaN 34 3 2; + 32 34 29 51 7 10 6 40 16 45 5 8 42 26 43]; +g = dir('Ga*'); +elseif strcmp(batId,'Gen') +% 20 stable manually selected ROIs across 5 days for Gen +ROIs_manual = [NaN NaN 10 3 16 12 17 18 27 29 8 9 NaN NaN 21 11 31 15 20 25; + 8 17 5 1 2 6 21 10 18 31 NaN 11 51 53 28 4 38 19 2 20; + 50 54 12 3 48 18 27 15 31 34 NaN NaN 28 NaN 29 25 24 22 38 14; + 8 NaN 4 28 3 18 10 35 42 25 13 NaN 50 39 46 NaN 49 2 32 26; + 14 NaN 3 28 2 6 33 26 18 45 NaN NaN 25 NaN 32 NaN 37 8 28 11]; +g = dir('Ge*'); +end +z = dir('Z1*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +%ROI_duplicate = cell(length(dirTop),1); %make cell for indices of duplicated ROIS + + +for d = 1:length(dirTop) + %load results data + try %extract metadata names and enter processed folder + cd([dirTop(d).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + batName{d} = flyFolders(end).name(1:3); + dateSesh{d} = flyFolders(end).name(5:10); + sessionType{d} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + if strcmp(batName{d}(1),'G') + cd(dirProcessed(end).name); + else + cd(dirProcessed(end).name); + end + catch + cd(dirTop(d).name); + flyFolders = dir('*fly*extraction'); + batName{d} = flyFolders(end).name(1:3); + dateSesh{d} = flyFolders(end).name(5:10); + sessionType{d} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + dirProcessed = dir('processed_*'); + cd(dirProcessed(end).name); + end + cellData = load('results.mat'); + alignment = load('Alignment.mat'); + cd(dirProcessed(end).folder); + + %load flightPaths data + %extract metadata names and enter analysis folder + dirAnalysis = dir('analysis_*'); + if strcmp(batName{d}(1),'G') + cd(dirAnalysis(end).name); + else + cd(dirAnalysis(end).name); + end + fp = dir('*flightPaths.mat'); + load(fp(end).name); + close all; + + %% + % Remove that pesky first flight that starts at 0:0; + try + a = find(alignment.out.flights(:,1) == 0); + a2 = isnan(alignment.out.flights(a(1):end,1)); + a3 = find(a2>0); + alignment.out.flights(a(1):a(1)+a3(1),:) = NaN; + alignment.out.Location2 = alignment.out.flights; + catch + end + + % Plot the location in space that each cell is active in 1 figure + plotFiringTrajectory = figure('units','normalized','outerposition',[0 0 1 0.8]); + sgtitle([batName{d} ' ' dateSesh{d} ' ' sessionType{d} ': Firing Fields']); + n = 1; + for ii = ROIs_manual(d,:)%1:length(cellData.results.S(:,1)); % for each cell + set(0,'CurrentFigure',plotFiringTrajectory); + subplot(ceil(length(ROIs_manual(d,:))/3),3,n) + hold on; + plot(alignment.out.flights(:,1),alignment.out.flights(:,2),'k');% plot the flight trajectory in space + %plot3(alignment.out.flights(:,1),alignment.out.flights(:,2),alignment.out.flights(:,3),'k');%,'LineWidth',2);% plot the flight trajectory in space + try + spikeThresh(n) = median(cellData.results.S(ii,:)) + std(cellData.results.S(ii,:))*spikeThreshMult; %threshold for eliminating noise from the S matrix + [~,xy] = find(cellData.results.S(ii,:)>spikeThresh(n)); % get time neuron is active + xy = xy(xy0; + disp('Youve been working today..'); + else + mkdir([saveDir1 datestr(now,'yymmdd')]) + end + saveDir = [saveDir1 datestr(now,'yymmdd') '\']; +end + +nDays = size(activity_allTrials.act_dur,1); %number of days for the comparison +nRois = size(activity_allTrials.act_dur,2); %number of ROIs/day +minFlightLength = min(cellfun('size',activity_allTrials.act_dur(:,1),2)); %shortest flight length for each day since they may be slightly different lengths +preDur = 90; +postDur = 210; + + +mean_act_full = cellfun(@mean,activity_allTrials.act_dur,'UniformOutput',false); %take the mean of all the trials for each roi/day +act_aligned = cellfun(@(c) c(:,1:minFlightLength), activity_allTrials.act_dur,'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +mean_act_aligned = cellfun(@mean,act_aligned,'UniformOutput',false); %take the mean of the aligned traces + +act_pre = cellfun(@(c) c(:,1:preDur), activity_allTrials.act_dur,'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +mean_act_pre = cellfun(@mean,act_pre,'UniformOutput',false); %take the mean of the aligned traces +act_dur = cellfun(@(c) c(:,preDur+1:minFlightLength-postDur), activity_allTrials.act_dur,'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +mean_act_dur = cellfun(@mean,act_dur,'UniformOutput',false); %take the mean of the aligned traces +act_post = cellfun(@(c) c(:,minFlightLength-postDur+1:minFlightLength), activity_allTrials.act_dur,'UniformOutput',false); %cut the traces so they are aligned to the shortest flight trajectory across all the days +mean_act_post = cellfun(@mean,act_post,'UniformOutput',false); %take the mean of the aligned traces + +%sort the max of each mean +[~,max_mean_act_aligned] = cellfun(@max,mean_act_aligned); +[BMax_mean_act_aligned,IMax_mean_act_aligned] = sort(max_mean_act_aligned,2); +[~,max_mean_act_pre] = cellfun(@max,mean_act_pre); +[BMax_mean_act_pre,IMax_mean_act_pre] = sort(max_mean_act_pre,2); +[~,max_mean_act_dur] = cellfun(@max,mean_act_dur); +[BMax_mean_act_dur,IMax_mean_act_dur] = sort(max_mean_act_dur,2); +[~,max_mean_act_post] = cellfun(@max,mean_act_post); +[BMax_mean_act_post,IMax_mean_act_post] = sort(max_mean_act_post,2); +%% plot all the data sorted by each day's daily peaks +plotSortedDaily = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +sgtitle('Gal Pre/Dur/Post sorted by daily peaks'); +ha = tight_subplot(1,9,[.06 .03],[.06 .1],[.05 .02]); +for day_i = 1:nDays + actCat = cell2mat(mean_act_aligned(day_i,:)'); + axes(ha(day_i)); + imagesc(actCat(IMax_mean_act_aligned(day_i,:),:)); + %set(gca,'xtick',[]); + title(['Day ' num2str(day_i)]); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_aligned(day_i,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end + +end + +if saveFlag == 1 + saveas(plotSortedDaily,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDaily' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(plotSortedDaily,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDaily' datestr(now,'yymmdd-HHMMSS') '.fig']); + +end + +%% plot all the data sorted by the activity on day 1 +plotSortedDay1 = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 0.8 0.6]); +sgtitle('Gal Pre/Dur/Post sorted by day 1'); +ha = tight_subplot(1,9,[.06 .03],[.06 .1],[.05 .02]); +for day_i = 1:nDays + actCat = cell2mat(mean_act_aligned(day_i,:)'); + axes(ha(day_i)); + imagesc(actCat(IMax_mean_act_aligned(1,:),:)); + %set(gca,'xtick',[]); + title(['Day ' num2str(day_i)]); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_aligned(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end +end + +if saveFlag == 1 + saveas(plotSortedDay1,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDay1_cRaw' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(plotSortedDay1,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDay1_cRaw' datestr(now,'yymmdd-HHMMSS') '.fig']); +end + +%% plot pre/dur/post stable ROIs based on daily peak +plotSortedDaily_preDurPost = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +sgtitle('Gal Pre/Dur/Post sorted by daily peak'); +ha = tight_subplot(3,9,[.05 .02],[.06 .1],[.05 .02]); +for day_i = 1:nDays + actCat = cell2mat(mean_act_aligned(day_i,:)'); %extract from cell to matrix + actCatPre = cell2mat(mean_act_pre(day_i,:)'); + actCatDur = cell2mat(mean_act_dur(day_i,:)'); + actCatPost = cell2mat(mean_act_post(day_i,:)'); + + axes(ha(day_i)); + imagesc(actCatPre(IMax_mean_act_pre(day_i,:),:)); + %set(gca,'xtick',[]); + title(['Day ' num2str(day_i) ': Pre']); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_pre(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end + + axes(ha(nDays+day_i)); + imagesc(actCatDur(IMax_mean_act_dur(day_i,:),:)); + %set(gca,'xtick',[]); + title('Dur'); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_dur(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end + + axes(ha(2*nDays+day_i)); + imagesc(actCatPost(IMax_mean_act_post(day_i,:),:)); + %set(gca,'xtick',[]); + title(['Post']); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_post(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end +end + +if saveFlag == 1 + saveas(plotSortedDay1_preDurPost,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDaily_cRaw_preDurPost' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(plotSortedDay1_preDurPost,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDaily_cRaw_preDurPost' datestr(now,'yymmdd-HHMMSS') '.fig']); +end + +%% plot pre/dur/post stable ROIs based on day 1 + plotSortedDay1_preDurPost = figure(); +set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +sgtitle('Gal Pre/Dur/Post sorted by day 1'); +ha = tight_subplot(3,9,[.06 .03],[.06 .1],[.05 .02]); +for day_i = 1:nDays + actCat = cell2mat(mean_act_aligned(day_i,:)'); %extract from cell to matrix + actCatPre = cell2mat(mean_act_pre(day_i,:)'); + actCatDur = cell2mat(mean_act_dur(day_i,:)'); + actCatPost = cell2mat(mean_act_post(day_i,:)'); + + axes(ha(day_i)); + imagesc(actCatPre(IMax_mean_act_pre(1,:),:)); + %set(gca,'xtick',[]); + title(['Day ' num2str(day_i) ': Pre']); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_pre(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end + + axes(ha(nDays+day_i)); + imagesc(actCatDur(IMax_mean_act_dur(1,:),:)); + %set(gca,'xtick',[]); + title('Dur'); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_dur(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end + + axes(ha(2*nDays+day_i)); + imagesc(actCatPost(IMax_mean_act_post(1,:),:)); + %set(gca,'xtick',[]); + title(['Post']); + xt = get(gca,'XTick'); + set(gca,'XTickLabel',round(xt/30,1),'YTick',[1:nRois],'yticklabel',IMax_mean_act_post(1,:)); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + end +end + +if saveFlag == 1 + saveas(plotSortedDay1_preDurPost,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDay1_cRaw_preDurPost' datestr(now,'yymmdd-HHMMSS') '.tif']); + savefig(plotSortedDay1_preDurPost,[saveDir filesep 'Gal_200311to20_snakePlot_sortedDay1_cRaw_preDurPost' datestr(now,'yymmdd-HHMMSS') '.fig']); +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_plotFlightsVsCells.m b/analysis_tobias/ImBat_plotFlightsVsCells.m index 32357b1..cf61a0c 100644 --- a/analysis_tobias/ImBat_plotFlightsVsCells.m +++ b/analysis_tobias/ImBat_plotFlightsVsCells.m @@ -25,6 +25,8 @@ saveFlag = varargin{i+1}; case 'loadflag' loadFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; end end @@ -32,10 +34,12 @@ if loadFlag == 1 date = strcat(lower(batName(1:2)),dateSesh); label = [batName '_' dateSesh '_' sessionType]; - - cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); - alignment = load([pwd '/processed/Alignment.mat']); - load([pwd '/analysis/' label '_flightPaths.mat']); + processedFolders = dir('processed*'); + processedNewest = sort({processedFolders(end).name}); + processedNewest = char(processedNewest); + cellData = load([pwd processedNewest '/Motion_corrected_Data_DS_results.mat']); + alignment = load([pwd processedNewest '/Alignment.mat']); + load([pwd '/' analysis_Folder '/' label '_flightPaths.mat']); end if saveFlag ==1 @@ -52,48 +56,76 @@ smoothVelocity = zscore(smooth(flightPaths.batSpeed,100)); %image_preprocessing, smooth and average #cells spike responses -smoothAvgSpiking = zscore(smooth(mean((full(cellData.results.C_raw(1:topROILocal,:))),1),25));%-min(data(p).image_data.S(1:numCells,:)); +%smoothAvgSpiking = zscore(smooth(mean((full(cellData.results.C_raw(1:topROILocal,:))),1),25));%-min(data(p).image_data.S(1:numCells,:)); flightVsVelocity = figure('units','normalized','outerposition',[0 0 1 1]); %plot zscored spike data for #cells a1 = subplot(topROILocal+11,1,11:topROILocal+11); hold on + normSmoothData = zeros(topROILocal,length(cellData.results.C_raw(1,:))); for i = 1:topROILocal %[9 31 16 27 26 29 41 46 54 61 68 98 86 87 151]% + normSmoothData(i,:) = zscore(smoothdata(cellData.results.C_raw(i,:),'movmedian',3)); %normalize each ROI trace try - plot(alignment.out.video_times,(zscore(smoothdata(cellData.results.C_raw(i,:),'movmedian',3)))+i*2) %may have to tweak the +i*6 at the end - catch + plot(alignment.out.video_times,(zscore(smoothdata(cellData.results.C_raw(i,:),'movmedian',3)))+i*6) %may have to tweak the +i*6 at the end + catch %if the tracking recording was turned on before the imaging recording + try + diffVidTimes = length(cellData.results.C_raw(i,:)) - length(alignment.out.video_times); + plot(alignment.out.video_times,(zscore(smoothdata(cellData.results.C_raw(i,1:end-diffVidTimes),'movmedian',3)))+i*2) %may have to tweak the +i*6 at the end + catch %if the imaging data misaligned with tracking data by 1 due to dropped frames + plot(alignment.out.video_times(1:end-1),(zscore(smoothdata(cellData.results.C_raw(i,:),'movmedian',3)))+i*6) %may have to tweak the +i*6 at the end + end end end - title(['Velocity vs Cell Activity: ' batName ' ' dateSesh ' ' sessionType]) - ylabel('z-score dff') + sgtitle(['Velocity vs Cell Activity: ' batName ' ' dateSesh ' ' sessionType]) + ylabel(['z-score dff: ' num2str(length(cellData.results.C(:,1))) ' ROIs']) + xlabel('Time (s)') + set(gca,'yticklabel',[]); xlim([0 alignment.out.video_times(end)])%xlim([0 alignment.out.video_times(end)]) + meanSmoothAvgSpiking = mean(normSmoothData,1); %take average of the normalized smoothed data + minSmoothAvgSpiking = min(meanSmoothAvgSpiking); + smoothAvgSpiking = meanSmoothAvgSpiking - minSmoothAvgSpiking; + %plot smoothed z-scored average firing rate of #cells a2 = subplot(topROILocal+11,1,6:9);%topROILocal+3:topROILocal+6); hold on - plot(alignment.out.video_times,smoothAvgSpiking) - ylim([-1 8]) + if length(alignment.out.video_times) == length(smoothAvgSpiking) + plot(alignment.out.video_times,smoothAvgSpiking) + else + diffTimes = length(alignment.out.video_times) - length(smoothAvgSpiking); + plot(alignment.out.video_times(1:end-diffTimes),smoothAvgSpiking) + end + ylim([0 max(smoothAvgSpiking)+0.3]) xlim([0 alignment.out.video_times(end)])%xlim([0 alignment.out.video_times(end)]) - title('Avg Cell Response') - ylabel('z-score dff') + %title('Avg Cell Response') + ylabel('Avg dff') + set(gca,'xticklabel',{[]}) - %plot the smoothed z-scored velocity of bat + %plot the smoothed z-scored velocity of bat & reward vector + %[rewardR,rewardLT,rewardUT] = risetime(alignment.out.RewardVector); a3 = subplot(topROILocal+11,1,1:4);%topROILocal+8:topROILocal+11); hold on plot(alignment.out.Location_time(1:end),smoothVelocity,'color','r') - title('Velocity') + %plot(alignment.out.Location_time(1:end),(alignment.out.RewardVector-abs(min(alignment.out.RewardVector)))/2,'color','b') +% for ii = 1:length(rewardLT) +% plot(((alignment.out.Location_time(1)*120)+rewardLT(ii))/120,max(smoothVelocity),'ob'); +% hold on +% lh = legend('velocity','reward','Location','east'); +% set(lh,'position',[.86 .925 .03 .03]); +% end + %title('Velocity') ylim([-1 8]) xlim([0 alignment.out.video_times(end)]) - xlabel('Time (s)') - ylabel('z-score velocity') - - + %xlabel('Time (s)') + ylabel('v (m/s)') + set(gca,'xticklabel',{[]}) + linkaxes([a1, a2, a3], 'x'); if saveFlag == 1 - saveas(flightVsVelocity, [pwd '\analysis\flights\' label '_flightVsVelocity_handPicked.svg']); - saveas(flightVsVelocity, [pwd '\analysis\flights\' label '_flightVsVelocity_handPicked.tif']); - savefig(flightVsVelocity, [pwd '\analysis\flights\' label '_flightVsVelocity_handPicked.fig']); + saveas(flightVsVelocity, [pwd '\' analysis_Folder '\flights\' label '_flightVsVelocity_handPicked.svg']); + saveas(flightVsVelocity, [pwd '\' analysis_Folder '\flights\' label '_flightVsVelocity_handPicked.jpg']); + savefig(flightVsVelocity, [pwd '\' analysis_Folder '\flights\' label '_flightVsVelocity_handPicked.fig']); end diff --git a/analysis_tobias/ImBat_plotFlightvsCells_transitions.m b/analysis_tobias/ImBat_plotFlightvsCells_transitions.m new file mode 100644 index 0000000..4669cb6 --- /dev/null +++ b/analysis_tobias/ImBat_plotFlightvsCells_transitions.m @@ -0,0 +1,1030 @@ +function [traceAnalysis] = ImBat_plotFlightvsCells_transitions(snakeTrace,flightTransitions,flightPaths,goodCellIdx,flightTiming,varargin) +plotEachFlag = 0; +plotPreFlightPostFlag = 0; +plotMeanSpikeFlag = 0; +plotMeanSortedFlag = 0; +histoTraceStatsFlag = 0; +plotSortedFWHMFlag = 0; +plotTimeJitterSortFlag = 1; + +batName = snakeTrace.batName; +dateSesh = snakeTrace.dateSesh; +sessionType = snakeTrace.sessionType; +loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +saveFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +meanSmooth = 30; %number of video frames to smooth the calcium mean spiking activity +out = 0; %save output variables? + +traceDataAll = snakeTrace.normTraceRawPreFlightPost; +meanTraceDataAll = snakeTrace.meanTracePreFlightPost; +traceDataPre = snakeTrace.meanTracePre; +traceDataFlight = snakeTrace.meanTraceFlight; +traceDataPost = snakeTrace.meanTracePost; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + end +end + +%%plot the pre/post/and flight traces for each cell by their transitions +if plotEachFlag == 1 + plotFlightvsCells_transitions = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(3,6,1); %plot trajectories pre-flight + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + title('Pre-Flight: A to B'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(3,6,2); %plot trajectories during flight + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i)):flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i)):flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))),'LineWidth',1,'Color','k')%,jj(traj*100,:)) + %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),25,'r','filled') + hold on + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('During Flight: A to B'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p3 = subplot(3,6,3); %plot trajectories post-flight A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i)):flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i)):flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),25,'r','filled') + hold on + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('Post-Flight: A to B'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p7 = subplot(3,6,7); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawPre{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPre{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %xlim([1 length(snakeTrace.smoothSpeedRawPre{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + + p8 = subplot(3,6,8); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawFlight{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawFlight{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + + %xlim([1 length(snakeTrace.smoothSpeedRawFlight{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + + p9 = subplot(3,6,9); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %xlim([1 length(snakeTrace.smoothSpeedRawPost{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + end + + %for each flight in the subgroup B to A + for flight_i = 1:length(flightTransitions.BtoA) + p4 = subplot(3,6,4); %plot trajectories pre-flight B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + title('Pre-Flight: B to A'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p5 = subplot(3,6,5); %plot trajectories during flight B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i)):flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i)):flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))),'LineWidth',1,'Color','k')%,jj(traj*100,:)) + %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),25,'r','filled') + hold on + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('During Flight: B to A'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p6 = subplot(3,6,6); %plot trajectories post flight B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i)):flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i)):flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),25,'r','filled') + hold on + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('Post-Flight: B to A'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p10 = subplot(3,6,10); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawPre{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPre{1}(:,1)),:)),snakeTrace.smoothSpeedRawPre{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPre{1}(:,1)),:)) + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %xlim([1 length(snakeTrace.smoothSpeedRawPre{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + + p11 = subplot(3,6,11); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawFlight{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawFlight{1}(:,1)),:)),snakeTrace.smoothSpeedRawFlight{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawFlight{1}(:,1)),:)) + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + + %xlim([1 length(snakeTrace.smoothSpeedRawFlight{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + + p12 = subplot(3,6,12); %plot speed pre flight A to B + %plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); + %hold on + plot(1:length(snakeTrace.smoothSpeedRawPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPost{1}(:,1)),:)) + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %xlim([1 length(snakeTrace.smoothSpeedRawPost{1}(flightPaths.clusterIndex{1}(flight_i,:)))]); + + end + + for cell_i = 1:10%length(snakeTrace.smoothTraceRawFlight{1}(:,1,:)) + for flight_i = 1:length(flightTransitions.AtoB) + p13 = subplot(3,6,13); %plot neuron traces for each pre-flight A to B + plot(1:length(traceDataPre{1}(1,:,1)),traceDataPre{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + + p14 = subplot(3,6,14); %plot neuron traces for each pre-flight A to B + plot(1:length(traceDataFlight{1}(1,:,1)),traceDataFlight{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + + p15 = subplot(3,6,15); %plot neuron traces for each pre-flight A to B + plot(1:length(traceDataPost{1}(1,:,1)),traceDataPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + + for flight_i = 1:length(flightTransitions.BtoA) + p16 = subplot(3,6,16); %plot neuron traces for each pre-flight B to A + plot(1:length(traceDataPre{2}(1,:,1)),traceDataPre{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(traceDataPre{1}(:,1)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + + p17 = subplot(3,6,17); %plot neuron traces for each during flight B to A + plot(1:length(traceDataFlight{2}(1,:,1)),traceDataFlight{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(traceDataFlight{1}(:,1)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + + p18 = subplot(3,6,18); %plot neuron traces for each post-flight B to A + plot(1:length(traceDataPost{2}(1,:,1)),traceDataPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(traceDataPost{1}(:,1)),:,cell_i)) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + + pause + cla(p13) + cla(p14) + cla(p15) + cla(p16) + cla(p17) + cla(p18) + end +end + +%% plot flight vs cell traces for each cluster for each cell with the pre/flight/post concatenated together in 1 plot +if plotPreFlightPostFlag == 1 + + plotPreFlightPostvsCells_transitions = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(5,2,1); %plot trajectories pre/flight/post for A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('A to B (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(5,2,3); %plot speed pre/flight/post A to B + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:))]); + end + + %for each flight in the subgroup BtoA + for flight_i = 1:length(flightTransitions.BtoA) + + p3 = subplot(5,2,2); %plot trajectories pre/flight/post for A to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('B to A (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p4 = subplot(5,2,4); %plot speed pre/flight/post B to A + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:))]); + end + + for cell_i = 1:length(snakeTrace.smoothTraceRawPreFlightPost{1}(:,1,:)) + for flight_i = 1:length(flightTransitions.AtoB) + p5 = subplot(5,2,[5 7]); %plot neuron traces for each pre-flight A to B + normTraceRawAllAtoB(flight_i,:) = traceDataAll{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:,cell_i); + plot(1:length(traceDataAll{1}(1,:,1)),traceDataAll{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:,cell_i)+flight_i*2) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + set(gca,'xticklabel',{[]}); + xlim([1 length(traceDataAll{1}(1,:,1))]); + end + p7 = subplot(5,2,9); + imagesc(normTraceRawAllAtoB) + colormap('hot'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('flight trials'); + + for flight_i = 1:length(flightTransitions.BtoA) + p6 = subplot(5,2,[6 8]); %plot neuron traces for each pre-flight B to A + normTraceRawAllBtoA(flight_i,:) = traceDataAll{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(traceDataAll{1}(:,1,1)),:,cell_i); + plot(1:length(traceDataAll{2}(1,:,1)),traceDataAll{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(traceDataAll{1}(:,1,1)),:,cell_i)+flight_i*2) + hold on + title(['Cell # ' num2str(cell_i)]); + ylabel('Norm df/f'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + set(gca,'xticklabel',{[]}); + xlim([1 length(traceDataAll{2}(1,:,1))]); + end + p8 = subplot(5,2,10); + imagesc(normTraceRawAllBtoA) + colormap('hot'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('flight trials'); + linkaxes([p5, p7], 'x'); + linkaxes([p6, p8], 'x'); + sgtitle(['Flights aligned to A or B: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + if saveFlag ==1 + % Save 'each cell' as jpg and fig files.. + set(findall(gcf,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '\' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_cell' num2str(cell_i) '.tif']); + savefig(gcf,[pwd '\' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_cell' num2str(cell_i) '.fig']); + saveas(gcf,[pwd '\' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_cell' num2str(cell_i) '.svg']); + else + pause + end + + cla(p5) + cla(p6) + cla(p7) + cla(p8) + end +end + +%% plot flight vs spike Means for each cluster for each cell with the pre/flight/post concatenated together in 1 plot +concAtoB = []; +concBtoA = []; +concSemAtoB = []; +concSemBtoA = []; +%normalize all the A to B data +for cell_i = 1:length(meanTraceDataAll{1}(:,1)) + concAtoB = [concAtoB meanTraceDataAll{1}(cell_i,:)]; %concatenate all the data, zscore, then split it up + concSemAtoB = [ concSemAtoB snakeTrace.semTracePreFlightPost{1}(cell_i,:)]; +end +normConcAtoB = zscore(concAtoB); +normConcAtoB = normConcAtoB - min(normConcAtoB); +normConcSemAtoB = zscore(concSemAtoB); +normConcSemAtoB = normConcSemAtoB - min(normConcSemAtoB); +for cell_i = goodCellIdx.lowCorrIndex%1:length(meanTraceDataAll{1}(:,1)) + normAtoB(cell_i,:) = concAtoB(1+(length(meanTraceDataAll{1}(1,:))*(cell_i-1)):length(meanTraceDataAll{1}(1,:))*cell_i); + normSemAtoB(cell_i,:) = concSemAtoB(1+(length(meanTraceDataAll{1}(1,:))*(cell_i-1)):length(meanTraceDataAll{1}(1,:))*cell_i); +end +%normalize all the B to A data +for cell_i = 1:length(meanTraceDataAll{2}(:,1)) + concBtoA = [concBtoA meanTraceDataAll{2}(cell_i,:)]; %concatenate all the data, zscore, then split it up + concSemBtoA = [ concSemBtoA snakeTrace.semTracePreFlightPost{2}(cell_i,:)]; +end +normConcBtoA = zscore(concBtoA); +normConcBtoA = normConcBtoA - min(normConcBtoA); +normConcSemBtoA = zscore(concSemBtoA); +normConcSemBtoA = normConcSemBtoA - min(normConcSemBtoA); +for cell_i = goodCellIdx.lowCorrIndex%1:length(meanTraceDataAll{2}(:,1)) + normBtoA(cell_i,:) = concBtoA(1+(length(meanTraceDataAll{2}(1,:))*(cell_i-1)):length(meanTraceDataAll{2}(1,:))*cell_i); + normSemBtoA(cell_i,:) = concSemBtoA(1+(length(meanTraceDataAll{2}(1,:))*(cell_i-1)):length(meanTraceDataAll{2}(1,:))*cell_i); +end +%smooth the data +for cell_i = goodCellIdx.lowCorrIndex%1:length(snakeTrace.smoothTraceRawPreFlightPost{1}(:,1,:)) + %smooth data and calculate full-width half max + offset from flight starts + %smoothAtoB(cell_i,:) = smooth(meanTraceDataAll{1}(cell_i,:),meanSmooth); %smooth the data + smoothAtoB(cell_i,:) = smooth(normAtoB(cell_i,:),meanSmooth); %smooth the normalized data + smoothSDAtoB(cell_i,:) = smooth(snakeTrace.sdTracePreFlightPost{1}(cell_i,:),meanSmooth); %smooth the data + smoothSEMAtoB(cell_i,:) = smooth(snakeTrace.semTracePreFlightPost{1}(cell_i,:),meanSmooth); %smooth the data + %smoothSEMAtoB(cell_i,:) = smooth(normSemAtoB,meanSmooth); + [maxAtoB(cell_i),indMaxAtoB(cell_i)] = max(smoothAtoB(cell_i,5:end-5)); + tStartAtoMax(cell_i) = indMaxAtoB(cell_i) - length(traceDataPre{1}(cell_i,:)); %find offset from start of flight A to peak + halfMaxAtoB(cell_i) = maxAtoB(cell_i)/2; %find halfmax + try + indRiseAtoB(cell_i) = find(smoothAtoB(cell_i,5:indMaxAtoB(cell_i))<=halfMaxAtoB(cell_i),1,'last') + 5; %find where data goes above half max (-5 because we start with the 6th element) + catch + indRiseAtoB(cell_i) = 1; %in case the activity never drops below the fwhm by beginning of sample + end + try + indFallAtoB(cell_i) = find(smoothAtoB(cell_i,indMaxAtoB(cell_i):end-5)<=halfMaxAtoB(cell_i),1,'first')+indMaxAtoB(cell_i)-1; %find where data drops below half max (-1 because you need to look 1 back from the first below half max) + catch + indFallAtoB(cell_i) = length(smoothAtoB(cell_i,:)); %in case the activity never drops below the fwhm by end of sample + end + if indFallAtoB(cell_i) < indRiseAtoB(cell_i) + indFallAtoB(cell_i) = length(smoothAtoB(cell_i,:)); + end + fwhmAtoB(cell_i) = indRiseAtoB(cell_i) - indFallAtoB(cell_i); %fwhm by subtracting the indices + + %plot neuron traces for each pre-flight B to A + %smooth data and calculate full-width half max + offset from flight starts + %smoothBtoA(cell_i,:) = smooth(meanTraceDataAll{2}(cell_i,:),meanSmooth); + smoothBtoA(cell_i,:) = smooth(normBtoA(cell_i,:),meanSmooth); %smooth the normalized data + smoothSDBtoA(cell_i,:) = smooth(snakeTrace.sdTracePreFlightPost{2}(cell_i,:),meanSmooth); + smoothSEMBtoA(cell_i,:) = smooth(snakeTrace.semTracePreFlightPost{2}(cell_i,:),meanSmooth); + %smoothSEMBtoA(cell_i,:) = smooth(normSemBtoA,meanSmooth); %smooth the normalized SEM + [maxBtoA(cell_i),indMaxBtoA(cell_i)] = max(smoothBtoA(cell_i,5:end-5)); + tStartBtoMax(cell_i) = indMaxBtoA(cell_i) - length(traceDataPre{2}(cell_i,:)); %find offset from start of flight A to peak + halfMaxBtoA(cell_i) = maxBtoA(cell_i)/2; %find halfmax + try + indRiseBtoA(cell_i) = find(smoothBtoA(cell_i,5:indMaxBtoA(cell_i))<=halfMaxBtoA(cell_i),1,'last')+5; %find where data goes above half max + catch + indRiseBtoA(cell_i) = 1; %in case the activity never drops below the fwhm by beginning of sample + end + try + indFallBtoA(cell_i) = find(smoothBtoA(cell_i,indMaxBtoA(cell_i):end-5)<=halfMaxBtoA(cell_i),1,'first')+indMaxBtoA(cell_i)-1; %find where data drops below half max + catch + indFallBtoA(cell_i) = length(smoothBtoA(cell_i,:)); %in case the activity never drops below the fwhm by end of sample + end + if indFallBtoA(cell_i) < indRiseBtoA(cell_i) + indFallBtoA(cell_i) = length(smoothBtoA(cell_i,:)); + end + fwhmBtoA(cell_i) = indRiseBtoA(cell_i) - indFallBtoA(cell_i); %fwhm by subtracting the indices +end +% normAtoB = zscore(meanTraceDataAll{1},0,2); +% normAtoB = normAtoB - min(normAtoB); +% normBtoA = zscore(meanTraceDataAll{2},0,2); +% normBtoA = normBtoA - min(normBtoA); + +if plotMeanSpikeFlag == 1 + + plotMeanSpike_transitions = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(5,2,1); %plot trajectories pre/flight/post for A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('A to B (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(5,2,3); %plot speed pre/flight/post A to B + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:))]); + end + + %for each flight in the subgroup BtoA + for flight_i = 1:length(flightTransitions.BtoA) + + p3 = subplot(5,2,2); %plot trajectories pre/flight/post for B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('B to A (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p4 = subplot(5,2,4); %plot speed pre/flight/post B to A + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:))]); + end + + %plot neural traces + for cell_i = goodCellIdx.lowCorrIndex%1:length(snakeTrace.smoothTraceRawPreFlightPost{1}(:,1,:)) + + %plot average spike activity for flights A to B + p5 = subplot(5,2,[5 7]); %plot neuron traces for each pre-flight A to B + boundedline(1:length(meanTraceDataAll{1}(1,:)),smoothAtoB(cell_i,:),smoothSEMAtoB(cell_i,:),'r'); + hold on + plot(1:length(meanTraceDataAll{1}(1,:)),meanTraceDataAll{1}(cell_i,:)); + %plot(1:length(meanTraceDataAll{1}(1,:)),smoothAtoB(cell_i,:)); %plot the smoothed trace on top + plot(indMaxAtoB(cell_i),maxAtoB(cell_i),'o','MarkerFaceColor','r','MarkerSize',10) %plot peak on + plot(indRiseAtoB(cell_i):indFallAtoB(cell_i),halfMaxAtoB(cell_i),'o') %plot the half width max height + %titles + title(['Cell # ' num2str(cell_i)]); + ylabel('z-scored # spikes (std)');%ylabel('# Spikes'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + set(gca,'xticklabel',{[]}); + xlim([1 length(meanTraceDataAll{1}(1,:))]); + %plot heatmap for each pre-flight A to B + p7 = subplot(5,2,9); + imagesc(meanTraceDataAll{1}(cell_i,:)) + colormap('hot'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('flight trials'); + + %plots BtoA + p6 = subplot(5,2,[6 8]); + boundedline(1:length(meanTraceDataAll{2}(1,:)),smoothBtoA(cell_i,:),smoothSEMBtoA(cell_i,:),'r'); + hold on + plot(1:length(meanTraceDataAll{2}(1,:)),meanTraceDataAll{2}(cell_i,:)); %plot the mean spiking activity aligned to start of flight B + %plot(1:length(meanTraceDataAll{2}(1,:)),smoothBtoA(cell_i,:)); %plot the smoothed trace on top + plot(indMaxBtoA(cell_i),maxBtoA(cell_i),'o','MarkerFaceColor','r','MarkerSize',10) %plot the peak of the activity + plot(indRiseBtoA(cell_i):indFallBtoA(cell_i),halfMaxBtoA(cell_i),'o') %plot the half width max height + %titles + title(['Cell # ' num2str(cell_i)]); + ylabel('z-scored # spikes (std)');%ylabel('# Spikes'); + yt = get(gca,'YTick'); + %set(gca,'YTick',yt,'YTickLabel',yt/10); + set(gca,'xticklabel',{[]}); + xlim([1 length(meanTraceDataAll{2}(1,:))]); + %plot heatmap for each pre-flight B to A + p8 = subplot(5,2,10); + imagesc(meanTraceDataAll{2}(cell_i,:)) + colormap('hot'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('flight trials'); + linkaxes([p5, p7], 'x'); + linkaxes([p6, p8], 'x'); + sgtitle(['Flights aligned to A or B: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + + if saveFlag ==1 + % Save 'each cell' as jpg and fig files.. + set(findall(gcf,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_sPeaks_cell' num2str(cell_i) '.tif']); + savefig(gcf,[pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_sPeaks_cell' num2str(cell_i) '.fig']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_transAtoB_sPeaks_cell' num2str(cell_i) '.svg']); + else + pause + end + + cla(p5) + cla(p6) + cla(p7) + cla(p8) + end +end + +traceAnalysis.smoothAtoB = smoothAtoB; +traceAnalysis.smoothSDAtoB = smoothSDAtoB; +traceAnalysis.smoothSEMAtoB = smoothSEMAtoB; +traceAnalysis.maxAtoB =maxAtoB; +traceAnalysis.indMaxAtoB = indMaxAtoB; +traceAnalysis.tStartAtoMax = tStartAtoMax; +traceAnalysis.halfMaxAtoB = halfMaxAtoB; +traceAnalysis.indRiseAtoB = indRiseAtoB; +traceAnalysis.indFallAtoB = indFallAtoB; +traceAnalysis.fwhmAtoB = fwhmAtoB; +traceAnalysis.smoothBtoA = smoothBtoA; +traceAnalysis.smoothSDAtoB = smoothSDBtoA; +traceAnalysis.smoothSEMAtoB = smoothSEMBtoA; +traceAnalysis.maxBtoA = maxBtoA; +traceAnalysis.indMaxBtoA = indMaxBtoA; +traceAnalysis.tStartBtoMax = tStartBtoMax; +traceAnalysis.halfMaxBtoA = halfMaxBtoA; +traceAnalysis.indRiseBtoA = indRiseBtoA; +traceAnalysis.indFallBtoA = indFallBtoA; +traceAnalysis.fwhmBtoA = fwhmBtoA; +if saveFlag ==1 + save([pwd '/' batName '_' dateSesh '_' sessionType '_traceAnalysis.mat'],'traceAnalysis'); +end +%% sort and plot the cells according to their peak from flight time +for cell_i = goodCellIdx.lowCorrIndex + traceNormAtoB(cell_i,:) = zscore(traceAnalysis.smoothAtoB(cell_i,:)); + traceNormAtoB(cell_i,:) = traceNormAtoB(cell_i,:) - min(traceNormAtoB(cell_i,:)); + traceNormBtoA(cell_i,:) = zscore(traceAnalysis.smoothBtoA(cell_i,:)); + traceNormBtoA(cell_i,:) = traceNormBtoA(cell_i,:) - min(traceNormBtoA(cell_i,:)); + + [~,maxSmoothBtoA(cell_i,1)] = max(traceAnalysis.smoothBtoA(cell_i,:)); + [~,maxSmoothAtoB(cell_i,1)] = max(traceAnalysis.smoothAtoB(cell_i,:)); + %[~,maxSmoothAtoB(cell_i,1)] = max(traceNormAtoB(cell_i,:)); + %[~,maxSmoothBtoA(cell_i,1)] = max(traceNormBtoA(cell_i,:)); + +end +[BTraceAtoB,ITraceAtoB] = sort(maxSmoothAtoB); +[BTraceBtoA,ITraceBtoA] = sort(maxSmoothBtoA); + +if plotMeanSortedFlag == 1 + + plotSortedPeaks = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(6,2,1); %plot trajectories pre/flight/post for A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('A to B (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(6,2,3); %plot speed pre/flight/post A to B + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:))]); + end + + %for each flight in the subgroup BtoA + for flight_i = 1:length(flightTransitions.BtoA) + + p3 = subplot(6,2,2); %plot trajectories pre/flight/post for B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('B to A (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p4 = subplot(6,2,4); %plot speed pre/flight/post B to A + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:))]); + end + %plot heat maps of the high correlated cells aligned to A or B with + %sorting of A or B by their peaks + p5 = subplot(6,2,[5 7]) + %imagesc(smoothAtoB(ITraceAtoB,:)); + imagesc(traceNormAtoB(ITraceAtoB,:)); + colormap(hot) + title(['Aligned A to B: Sorted A to B']); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + xlabel('time (s)'); + ylabel('ROI #'); + + p6 = subplot(6,2,[6 8]) + %imagesc(smoothBtoA(ITraceBtoA,:)); + imagesc(traceNormBtoA(ITraceBtoA,:)); + colormap(hot) + title(['Aligned B to A: Sorted B to A']); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + ylabel('ROI #'); + + p7 = subplot(6,2,[9 11]) + %imagesc(smoothBtoA(ITraceAtoB,:)); + imagesc(traceNormBtoA(ITraceAtoB,:)); + colormap(hot) + title(['Aligned B to A: Sorted A to B']); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('ROI #'); + + p8 = subplot(6,2,[10 12]) + %imagesc(smoothAtoB(ITraceBtoA,:)); + imagesc(traceNormAtoB(ITraceBtoA,:)); + colormap(hot) + title(['Aligned A to B: Sorted B to A']); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('ROI #'); + + if saveFlag ==1 + saveas(plotSortedPeaks, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMap_highCorr_sortedPeaks_NORM_AvB.svg']); + saveas(plotSortedPeaks, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMap_highCorr_sortedPeaks_NORM_AvB.tif']); + savefig(plotSortedPeaks, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMap_highCorr_sortedPeaks_NORM_AvB.fig']); + end +end + +traceAnalysis.traceNormAtoB = traceNormAtoB; +traceAnalysis.maxSmoothAtoB = maxSmoothAtoB; +traceAnalysis.ITraceAtoB = ITraceAtoB; +traceAnalysis.BTraceAtoB = BTraceAtoB; +traceAnalysis.traceNormBtoA = traceNormBtoA; +traceAnalysis.maxSmoothBtoA = maxSmoothBtoA; +traceAnalysis.ITraceBtoA = ITraceBtoA; +traceAnalysis.BTraceBtoA = BTraceBtoA; + +if saveFlag ==1 + save([pwd '/' batName '_' dateSesh '_' sessionType '_traceAnalysis.mat'],'traceAnalysis'); +end + +%% plot the stats of the height, time from flight to peak, and full width half max of peaks aligned to A or B +if histoTraceStatsFlag == 1 + + figure; histogram(traceAnalysis.halfMaxAtoB) + hold on; histogram(traceAnalysis.halfMaxBtoA) + title('Height of half-max aligned to A or B') + legend('Aligned to A','Aligned to B') + xlabel('Height of half-max (SD)') + if saveFlag == 1 + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_halfMaxHeight_AvB.svg']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_halfMaxHeight_AvB.tif']); + savefig(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_halfMaxHeight_AvB.fig']); + end + + figure; histogram(abs(traceAnalysis.fwhmAtoB)) + hold on; histogram(abs(traceAnalysis.fwhmBtoA),11) + title('Width of halfmax aligned to A or B') + legend('Aligned to A','Aligned to B') + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + if saveFlag == 1 + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_fwhm_AvB.svg']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_fwhm_AvB.tif']); + savefig(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_fwhm_AvB.fig']); + end + + figure; histogram(traceAnalysis.tStartAtoMax,10) + hold on; histogram(traceAnalysis.tStartBtoMax) + title('Time from flight start to peak') + legend('Aligned to A','Aligned to B') + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + if saveFlag == 1 + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_timeStartPeak_AvB.svg']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_timeStartPeak_AvB.tif']); + savefig(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_histo_timeStartPeak_AvB.fig']); + end +end + +%% Plot the fwhm across time sorted by the width of the half max +if plotSortedFWHMFlag ==1 + [BfwhmAtoB,IfwhmAtoB] = sort(traceAnalysis.fwhmAtoB); + [BfwhmBtoA,IfwhmBtoA] = sort(traceAnalysis.fwhmBtoA); + + plotSortedFWHM = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(6,2,1); %plot trajectories pre/flight/post for A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('A to B (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(6,2,3); %plot speed pre/flight/post A to B + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:))]); + end + + %for each flight in the subgroup BtoA + for flight_i = 1:length(flightTransitions.BtoA) + + p3 = subplot(6,2,2); %plot trajectories pre/flight/post for B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('B to A (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p4 = subplot(6,2,4); %plot speed pre/flight/post B to A + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:))]); + end + + %plot the fwhm aligned by flight A or B + for cell_i = goodCellIdx.lowCorrIndex + p5 = subplot(6,2,[5 7]); + plot(traceAnalysis.indRiseAtoB(cell_i):traceAnalysis.indFallAtoB(cell_i),find(IfwhmAtoB==cell_i),'o') + hold on; + title('Aligned A to B: Sorted A to B'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + ylabel('ROI #'); + + p6 = subplot(6,2,[6 8]); + plot(traceAnalysis.indRiseBtoA(cell_i):traceAnalysis.indFallBtoA(cell_i),find(IfwhmBtoA==cell_i),'o') + hold on; + title('Aligned B to A: Sorted B to A'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + ylabel('ROI #'); + + p7 = subplot(6,2,[9 11]); + plot(traceAnalysis.indRiseAtoB(cell_i):traceAnalysis.indFallAtoB(cell_i),find(IfwhmBtoA==cell_i),'o') + hold on; + title('Aligned A to B: Sorted B to A'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('ROI #'); + + p8 = subplot(6,2,[10 12]); + plot(traceAnalysis.indRiseBtoA(cell_i):traceAnalysis.indFallBtoA(cell_i),find(IfwhmAtoB==cell_i),'o') + hold on; + title('Aligned B to A: Sorted A to B'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('ROI #'); + %pause + end + % subplot(2,2,1); + % imagesc(traceAnalysis.smoothAtoB(IfwhmAtoB,:)); + % subplot(2,2,2); + % imagesc(traceAnalysis.smoothBtoA(IfwhmBtoA,:)); + % subplot(2,2,3); + % imagesc(traceAnalysis.smoothAtoB(IfwhmBtoA,:)); + % subplot(2,2,4); + % imagesc(traceAnalysis.smoothBtoA(IfwhmAtoB,:)); + if saveFlag == 1 + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_SortedFWHM_AvB.svg']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_SortedFWHM_AvB.tif']); + savefig(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_SortedFWHM_AvB.fig']); + end + + +end + +%% +if plotTimeJitterSortFlag == 1 + + [BdiffStartAtoB,IdiffStartAtoB] = sort(flightTiming.diffStartAtoStartB); + [BdiffSBtoSA,IdiffSBtoSA] = sort(flightTiming.diffSBtoSA); + + plotSortedFWHM = figure('units','normalized','outerposition',[0 0 1 1]); + %for each flight in the subgroup AtoB + for flight_i = 1:length(flightTransitions.AtoB) + + p1 = subplot(6,2,1); %plot trajectories pre/flight/post for A to B + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.AtoB(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.AtoB(flight_i),2),50,'k','filled') + title('A to B (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p2 = subplot(6,2,3); %plot speed pre/flight/post A to B + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)),snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{1}(find([flightPaths.clusterIndex{:}]==flightTransitions.AtoB(flight_i)),:))]); + end + + %for each flight in the subgroup BtoA + for flight_i = 1:length(flightTransitions.BtoA) + + p3 = subplot(6,2,2); %plot trajectories pre/flight/post for B to A + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','m')%,jj(traj*100,:)) + hold on + scatter(flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_starts_xyz(flightTransitions.BtoA(flight_i),2),50,'r','filled') + scatter(flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),1),flightPaths.flight_ends_xyz(flightTransitions.BtoA(flight_i),2),50,'k','filled') + title('B to A (r=start,b=ends)'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + p4 = subplot(6,2,4); %plot speed pre/flight/post B to A + plot(1:length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)),snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:)) + hold on + ylabel('velocity (cm/s)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + xlim([1 length(snakeTrace.smoothSpeedRawPreFlightPost{2}(find([flightPaths.clusterIndex{:}]==flightTransitions.BtoA(flight_i))-length(snakeTrace.smoothSpeedRawPreFlightPost{1}(:,1)),:))]); + end + for cell_i = goodCellIdx.lowCorrIndex + p5 = subplot(6,2,[5 7]); + imagesc(snakeTrace.tracePreFlightPost{1}(IdiffStartAtoB,:,cell_i)); + hold on; + title('Aligned A to B: Sorted from start of A to start of B'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + ylabel('Trial #'); + colormap('hot'); + + + p6 = subplot(6,2,[6 8]); + imagesc(snakeTrace.tracePreFlightPost{2}(IdiffSBtoSA,:,cell_i)); + hold on; + title('Aligned B to A: Sorted from start of B to start of A'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + ylabel('Trial #'); + colormap('hot'); + + + p7 = subplot(6,2,[9 11]); + imagesc(snakeTrace.tracePreFlightPost{1}(IdiffSBtoSA,:,cell_i)); + hold on; + title('Aligned A to B: Sorted from start of B to start of A'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('Trial #'); + colormap('hot'); + + + p8 = subplot(6,2,[10 12]); + imagesc(snakeTrace.tracePreFlightPost{2}(IdiffStartAtoB,:,cell_i)); + hold on; + title('Aligned B to A: Sorted from start of A to start of B'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('Trial #'); + colormap('hot'); + sgtitle(['Sorting each trial from short to long interval: Cell # ' num2str(cell_i) ' : ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + + + + if saveFlag == 1 + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMapTimeJitterSort_AvB-cell' num2str(cell_i) '.svg']); + saveas(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMapTimeJitterSort_AvB-cell' num2str(cell_i) '.tif']); + savefig(gcf, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_heatMapTimeJitterSort_AvB-cell' num2str(cell_i) '.fig']); + else + pause + end + cla(p5) + cla(p6) + cla(p7) + cla(p8) + end +end + diff --git a/analysis_tobias/ImBat_plotPeaks.m b/analysis_tobias/ImBat_plotPeaks.m new file mode 100644 index 0000000..53bf1ee --- /dev/null +++ b/analysis_tobias/ImBat_plotPeaks.m @@ -0,0 +1,71 @@ +function [peaks] = ImBat_plotPeaks(snakeTrace,goodCellIdx,varargin) + +batName = snakeTrace.batName; +dateSesh = snakeTrace.dateSesh; +sessionType = snakeTrace.sessionType; +loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +saveFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +meanSmooth = 30; %number of video frames to smooth the calcium mean spiking activity + +traceDataAll = snakeTrace.meanTracePreFlightPost; +traceDataPre = snakeTrace.meanTracePre; +traceDataFlight = snakeTrace.meanTraceFlight; +traceDataPost = snakeTrace.meanTracePost; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + end +end + +%pks = cell(1,length(goodCellIdx)); +%locs = cell(1,length(goodCellIdx.goodCellIndex)); +%w = cell(1,length(goodCellIdx.goodCellIndex)); +%p = cell(1,length(goodCellIdx.goodCellIndex)); + +smoothAtoB = []; +figure(); +for cell_i = goodCellIdx + smoothAtoB(cell_i,:) = smooth(traceDataAll{1}(cell_i,:),meanSmooth); %smooth the data + [pks,locs,w,p] = findpeaks(smoothAtoB(cell_i,5:end-5),'MinPeakProminence',0.075); + plot(traceDataAll{1}(cell_i,5:end-5)); + hold on; + plot(smoothAtoB(cell_i,5:end-5)); + text(locs+.02,pks,num2str((1:numel(pks))')); + for pk_i = 1:length(pks) + tStartAtoMax(cell_i) = locs(pk_i) - length(traceDataPre{1}(pk_i,:)); %find offset from start of flight A to peak + halfMaxAtoB(pk_i) = pks(pk_i)/2; %find halfmax + try + indRiseAtoB(pk_i) = find(smoothAtoB(pk_i,5:locs(pk_i))<=halfMaxAtoB(pk_i),1,'last') + 5; %find where data goes above half max (-5 because we start with the 6th element) + catch + indRiseAtoB(pk_i) = 1; %in case the activity never drops below the fwhm by beginning of sample + end + try + indFallAtoB(pk_i) = find(smoothAtoB(cell_i,locs(pk_i):end-5)<=halfMaxAtoB(pk_i),1,'first')+locs(pk_i)-1; %find where data drops below half max (-1 because you need to look 1 back from the first below half max) + catch + indFallAtoB(pk_i) = length(smoothAtoB(pk_i,:)); %in case the activity never drops below the fwhm by end of sample + end + if indFallAtoB(pk_i) < indRiseAtoB(pk_i) + indFallAtoB(pk_i) = length(smoothAtoB(pk_i,:)); + end + fwhmAtoB(pk_i) = indRiseAtoB(pk_i) - indFallAtoB(pk_i); %fwhm by subtracting the indices + plot(locs(pk_i),pks(pk_i)+0.1,'o','MarkerFaceColor','r','MarkerSize',10) %plot peak on + plot(indRiseAtoB(pk_i):indFallAtoB(pk_i),halfMaxAtoB(pk_i),'o') %plot the half width max height + + end + + + pause + clf +end \ No newline at end of file diff --git a/analysis_tobias/ImBat_test_medFiltAutoregression.asv b/analysis_tobias/ImBat_test_medFiltAutoregression.asv new file mode 100644 index 0000000..72ef89a --- /dev/null +++ b/analysis_tobias/ImBat_test_medFiltAutoregression.asv @@ -0,0 +1,107 @@ +%function ImBat_test_medFiltAutoregression +Afull = full(results.A); %convert matrix from sparse to full +Amat = reshape(Afull,60,80,[]); %reshape so 4800 is now 60x80 pixels +trace_full = zeros(2,length(Y(1,1,:))); +trace = zeros(2,length(Y(1,1,6:end-5))); +trace_M3 = zeros(2,length(Y(1,1,6:end-5))); +trace_M5 = zeros(2,length(Y(1,1,6:end-5))); +trace_M9 = zeros(2,length(Y(1,1,6:end-5))); +maxIter = 2; + +smoothVelocity = zscore(smooth(flightPaths.batSpeed,100)); + +deconv_options = struct('type', 'ar1', ... % model of the calcium traces. {'ar1', 'ar2'} + 'method', 'foopsi', ... % method for running deconvolution {'foopsi', 'constrained', 'thresholded'} + 'smin', -5, ... % minimum spike size. When the value is negative, the actual threshold is abs(smin)*noise level + 'optimize_pars', true, ... % optimize AR coefficients + 'optimize_b', true, ...% optimize the baseline); + 'max_tau', 100); % maximum decay time (unit: frame); + +for i = 1:2 +trace_temp = mean((Amat(:,:,i).*Y),[1,2]); %take mean of each frame within the first cell ID from cnmfe +trace_full(i,:) = reshape(trace_temp,1,[]); +trace(i,:) = trace_full(i,6:end-5); +trace(i,:) = trace(i,:)-min(trace(i,:)); +trace_M3(i,:) = medfilt1(trace(i,:),3); +trace_M5(i,:) = medfilt1(trace(i,:),5); +trace_M9(i,:) = medfilt1(trace(i,:),9); +trace_M9_smooth(i,:) = smooth(trace_M9(i,:),2); + +deconv_options.type = 'ar1'; + +[c3_ar1(i,:), s3_ar1(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_ar1(i,:), s5_ar1(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_ar1(i,:), s9_ar1(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_ar1_smooth(i,:), s9_ar1_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + +deconv_options.type = 'ar2'; + +[c3_ar2(i,:), s3_ar2(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_ar2(i,:), s5_ar2(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_ar2(i,:), s9_ar2(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_ar2_smooth(i,:), s9_ar2_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + +deconv_options.type = 'exp2'; + +[c3_exp2(i,:), s3_exp2(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_exp2(i,:), s5_exp2(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_exp2(i,:), s9_exp2(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_exp2_smooth(i,:), s9_exp2_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + + +end +%% +for p = 1:2 +plot_flightsVSar(p) = figure('units','normalized','outerposition',[0 0 0.5 1]); + +p1 = subplot(4,1,1); %plot median filter 3 +plot(smoothVelocity(21:end-20),'color','r') +hold on +ylabel('velocity (cm/s)'); +yt = get(gca,'YTick'); +set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); +set(gca,'xticklabel',{[]}); +ylim([0 7]); +title('velocity') + +p2 = subplot(4,1,2); %plot median filter 3 +plot(c3_ar1(p,:)) +hold on; +plot(c3_ar2(1,:)) +plot(c3_exp2(1,:)) +plot(trace_M3(1,:)) +title(['cell #' num2str(p) ': Median filter 3']) +legend('ar1','ar2','exp2','raw') +set(gca,'xticklabel',{[]}); + +p3 = subplot(4,1,3); %plot median filter 5 +plot(c5_ar1(p,:)) +hold on; +plot(c5_ar2(1,:)) +plot(c5_exp2(1,:)) +plot(trace_M5(1,:)) +title('Median filter 5') +legend('ar1','ar2','exp2','raw') +set(gca,'xticklabel',{[]}); + +p4 = subplot(4,1,4); %plot median filter 5 +plot(c9_ar1(p,:)) +hold on; +plot(c9_ar2(1,:)) +plot(c9_exp2(1,:)) +%plot(c9_ar1_smooth(1,:)) +%plot(c9_ar2_smooth(1,:)) +plot(trace_M9(1,:)) +title('Median filter 9') +legend('ar1','ar2','exp2','raw','smooth-ar1','smooth-ar2') +xt = get(gca, 'XTick'); +set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); +xlabel('time (s)'); + +linkaxes([p2 p3 p4], 'xy') +end + + + + + diff --git a/analysis_tobias/ImBat_test_medFiltAutoregression.m b/analysis_tobias/ImBat_test_medFiltAutoregression.m new file mode 100644 index 0000000..493699a --- /dev/null +++ b/analysis_tobias/ImBat_test_medFiltAutoregression.m @@ -0,0 +1,107 @@ +%function ImBat_test_medFiltAutoregression +Afull = full(results.A); %convert matrix from sparse to full +Amat = reshape(Afull,60,80,[]); %reshape so 4800 is now 60x80 pixels +trace_full = zeros(2,length(Y(1,1,:))); +trace = zeros(2,length(Y(1,1,6:end-5))); +trace_M3 = zeros(2,length(Y(1,1,6:end-5))); +trace_M5 = zeros(2,length(Y(1,1,6:end-5))); +trace_M9 = zeros(2,length(Y(1,1,6:end-5))); +maxIter = 2; + +smoothVelocity = zscore(smooth(flightPaths.batSpeed,100)); + +deconv_options = struct('type', 'ar1', ... % model of the calcium traces. {'ar1', 'ar2'} + 'method', 'foopsi', ... % method for running deconvolution {'foopsi', 'constrained', 'thresholded'} + 'smin', -9, ... % minimum spike size. When the value is negative, the actual threshold is abs(smin)*noise level + 'optimize_pars', true, ... % optimize AR coefficients + 'optimize_b', true, ...% optimize the baseline); + 'max_tau', 100); % maximum decay time (unit: frame); + +for i = 1:2 +trace_temp = mean((Amat(:,:,i).*Y),[1,2]); %take mean of each frame within the first cell ID from cnmfe +trace_full(i,:) = reshape(trace_temp,1,[]); +trace(i,:) = trace_full(i,6:end-5); +trace(i,:) = trace(i,:)-min(trace(i,:)); +trace_M3(i,:) = medfilt1(trace(i,:),3); +trace_M5(i,:) = medfilt1(trace(i,:),5); +trace_M9(i,:) = medfilt1(trace(i,:),8.5); +trace_M9_smooth(i,:) = smooth(trace_M9(i,:),2); + +deconv_options.type = 'ar1'; + +[c3_ar1(i,:), s3_ar1(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_ar1(i,:), s5_ar1(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_ar1(i,:), s9_ar1(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_ar1_smooth(i,:), s9_ar1_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + +deconv_options.type = 'ar2'; + +[c3_ar2(i,:), s3_ar2(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_ar2(i,:), s5_ar2(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_ar2(i,:), s9_ar2(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_ar2_smooth(i,:), s9_ar2_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + +deconv_options.type = 'exp2'; + +[c3_exp2(i,:), s3_exp2(i,:), options] = deconvolveCa(trace_M3(i,:), deconv_options,'maxIter', maxIter); +[c5_exp2(i,:), s5_exp2(i,:), options] = deconvolveCa(trace_M5(i,:), deconv_options,'maxIter', maxIter); +[c9_exp2(i,:), s9_exp2(i,:), options] = deconvolveCa(trace_M9(i,:), deconv_options,'maxIter', maxIter); +[c9_exp2_smooth(i,:), s9_exp2_smooth(i,:), options] = deconvolveCa(trace_M9_smooth(i,:), deconv_options,'maxIter', maxIter); + + +end +%% +for p = 1:2 +plot_flightsVSar(p) = figure('units','normalized','outerposition',[0 0 0.5 1]); + +p1 = subplot(4,1,1); %plot median filter 3 +plot(smoothVelocity(21:end-20),'color','r') +hold on +ylabel('velocity (cm/s)'); +yt = get(gca,'YTick'); +set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); +set(gca,'xticklabel',{[]}); +ylim([0 7]); +title('velocity') + +p2 = subplot(4,1,2); %plot median filter 3 +plot(c3_ar1(p,:)) +hold on; +plot(c3_ar2(1,:)) +plot(c3_exp2(1,:)) +plot(trace_M3(1,:)) +title(['cell #' num2str(p) ': Median filter 3']) +legend('ar1','ar2','exp2','raw') +set(gca,'xticklabel',{[]}); + +p3 = subplot(4,1,3); %plot median filter 5 +plot(c5_ar1(p,:)) +hold on; +plot(c5_ar2(1,:)) +plot(c5_exp2(1,:)) +plot(trace_M5(1,:)) +title('Median filter 5') +legend('ar1','ar2','exp2','raw') +set(gca,'xticklabel',{[]}); + +p4 = subplot(4,1,4); %plot median filter 5 +plot(c9_ar1(p,:)) +hold on; +plot(c9_ar2(1,:)) +plot(c9_exp2(1,:)) +%plot(c9_ar1_smooth(1,:)) +%plot(c9_ar2_smooth(1,:)) +plot(trace_M9(1,:)) +title('Median filter 9') +legend('ar1','ar2','exp2','raw','smooth-ar1','smooth-ar2') +xt = get(gca, 'XTick'); +set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); +xlabel('time (s)'); + +linkaxes([p2 p3 p4], 'xy') +end + + + + + diff --git a/analysis_tobias/ImBat_transferPlaceCells.asv b/analysis_tobias/ImBat_transferPlaceCells.asv new file mode 100644 index 0000000..930cc69 --- /dev/null +++ b/analysis_tobias/ImBat_transferPlaceCells.asv @@ -0,0 +1,115 @@ +function [placeCells] = ImBat_transferPlaceCells(placeCells) + +if ~exist('placeCells') +extractedPlaceCells = dir('*ExtractedPlaceCells*'); +load(extractedPlaceCells.name); +end + +cd([pwd filesep 'Spatial_information']); + +nClust =size(placeCells.pp_cells,1)-1; %number of clusters to look at excluding the first cluster +%initialize cells +cells_prePlacePost = cell(nClust,1); +cells_prePlace = cell(nClust,1); +cells_prePost = cell(nClust,1); +cells_placePost = cell(nClust,1); +cells_pre = cell(nClust,1); +cells_place = cell(nClust,1); +cells_post = cell(nClust,1); + +%check if directories already exist and make if not +if ~exist([pwd filesep 'cells_prePlacePost']) + mkdir([pwd filesep 'cells_prePlacePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePlacePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePlacePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePlace']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePlace']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'placePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'placePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'pre']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'pre']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'place']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'place']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'post']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'post']) +end + +for clust_i = 1:nClust + %pull out the putative pre,place,post cells from logical + pp_cells = find(placeCells.pp_cells(clust_i+1,:)); + ppre_cells = find(placeCells.ppre_cells(clust_i+1,:)); + ppost_cells = find(placeCells.ppost_cells(clust_i+1,:)); + + %find the different combos of pre, place, and post cells + cells_prePlacePost{clust_i,:} = intersect(intersect(pp_cells,ppre_cells),ppost_cells); + for cell_i = 1:length(cells_prePlacePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePlacePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePlacePost' filesep sourceFile.name]); + end + end + cells_prePlace{clust_i,:} = setdiff(intersect(pp_cells,ppre_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_prePlace{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePlace{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePlace' filesep sourceFile.name]); + end + end + cells_prePost{clust_i,:} = setdiff(intersect(ppre_cells,ppost_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_prePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePost' filesep sourceFile.name]); + end + end + cells_placePost{clust_i,:} = setdiff(intersect(pp_cells,ppost_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_placePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_placePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'placePost' filesep sourceFile.name]); + end + end + cells_pre{clust_i,:} = setdiff(setdiff(ppre_cells,cells_prePlace{clust_i,:}),cells_prePost{clust_i,:}); + for cell_i = 1:length(cells_pre{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_pre{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'pre' filesep sourceFile.name]); + end + end + cells_place{clust_i,:} = setdiff(setdiff(pp_cells,cells_placePost{clust_i,:}),cells_prePlace{clust_i,:}); + for cell_i = 1:length(cells_place{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_place{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'place' filesep sourceFile.name]); + end + end + cells_post{clust_i,:} = setdiff(setdiff(ppost_cells,cells_placePost{clust_i,:}),cells_prePost{clust_i,:}); + for cell_i = 1:length(cells_post{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_post{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'post' filesep sourceFile.name]); + end + end + + +end + +placeCells.cells_place = cells_place; +placeCells.cells_pre +placeCells.cells_post +placeCells.cells_prePlace +placeCells.cells_prePost +placeCells.cells_placePost +placeCells.cells_prePlacePost + + + diff --git a/analysis_tobias/ImBat_transferPlaceCells.m b/analysis_tobias/ImBat_transferPlaceCells.m new file mode 100644 index 0000000..6404a22 --- /dev/null +++ b/analysis_tobias/ImBat_transferPlaceCells.m @@ -0,0 +1,115 @@ +function [placeCells] = ImBat_transferPlaceCells(placeCells) + +if ~exist('placeCells') +extractedPlaceCells = dir('*ExtractedPlaceCells*'); +load(extractedPlaceCells.name); +end + +cd([pwd filesep 'Spatial_information']); + +nClust =size(placeCells.pp_cells,1)-1; %number of clusters to look at excluding the first cluster +%initialize cells +cells_prePlacePost = cell(nClust,1); +cells_prePlace = cell(nClust,1); +cells_prePost = cell(nClust,1); +cells_placePost = cell(nClust,1); +cells_pre = cell(nClust,1); +cells_place = cell(nClust,1); +cells_post = cell(nClust,1); + +%check if directories already exist and make if not +if ~exist([pwd filesep 'cells_prePlacePost']) + mkdir([pwd filesep 'cells_prePlacePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePlacePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePlacePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePlace']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePlace']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'prePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'prePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'placePost']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'placePost']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'pre']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'pre']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'place']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'place']) +end +if ~exist([pwd filesep 'cells_prePlacePost' filesep 'post']) + mkdir([pwd filesep 'cells_prePlacePost' filesep 'post']) +end + +for clust_i = 1:nClust + %pull out the putative pre,place,post cells from logical + pp_cells = find(placeCells.pp_cells(clust_i+1,:)); + ppre_cells = find(placeCells.ppre_cells(clust_i+1,:)); + ppost_cells = find(placeCells.ppost_cells(clust_i+1,:)); + + %find the different combos of pre, place, and post cells + cells_prePlacePost{clust_i,:} = intersect(intersect(pp_cells,ppre_cells),ppost_cells); + for cell_i = 1:length(cells_prePlacePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePlacePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePlacePost' filesep sourceFile.name]); + end + end + cells_prePlace{clust_i,:} = setdiff(intersect(pp_cells,ppre_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_prePlace{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePlace{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePlace' filesep sourceFile.name]); + end + end + cells_prePost{clust_i,:} = setdiff(intersect(ppre_cells,ppost_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_prePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_prePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'prePost' filesep sourceFile.name]); + end + end + cells_placePost{clust_i,:} = setdiff(intersect(pp_cells,ppost_cells),cells_prePlacePost{clust_i,:}); + for cell_i = 1:length(cells_placePost{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_placePost{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'placePost' filesep sourceFile.name]); + end + end + cells_pre{clust_i,:} = setdiff(setdiff(ppre_cells,cells_prePlace{clust_i,:}),cells_prePost{clust_i,:}); + for cell_i = 1:length(cells_pre{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_pre{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'pre' filesep sourceFile.name]); + end + end + cells_place{clust_i,:} = setdiff(setdiff(pp_cells,cells_placePost{clust_i,:}),cells_prePlace{clust_i,:}); + for cell_i = 1:length(cells_place{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_place{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'place' filesep sourceFile.name]); + end + end + cells_post{clust_i,:} = setdiff(setdiff(ppost_cells,cells_placePost{clust_i,:}),cells_prePost{clust_i,:}); + for cell_i = 1:length(cells_post{clust_i,:}) + sourceFile = dir(['*_ROI_' num2str(cells_post{clust_i}(cell_i)) '_cluster_' num2str(clust_i+1) '.jpg']); + if ~isempty(sourceFile) + movefile(sourceFile.name,[pwd filesep 'cells_prePlacePost' filesep 'post' filesep sourceFile.name]); + end + end + + +end + +placeCells.cells_place = cells_place; +placeCells.cells_pre = cells_pre; +placeCells.cells_post = cells_post; +placeCells.cells_prePlace = cells_prePlace; +placeCells.cells_prePost = cells_prePost; +placeCells.cells_placePost = cells_placePost; +placeCells.cells_prePlacePost = cells_prePlacePost; + + + diff --git a/analysis_tobias/archived/ImBat_Analyze.m b/analysis_tobias/archived/ImBat_Analyze.m new file mode 100644 index 0000000..c8bd642 --- /dev/null +++ b/analysis_tobias/archived/ImBat_Analyze.m @@ -0,0 +1,282 @@ +function ImBat_Analyze + +global topROI + +% Main wrapper for all analyzing bat calcium imaging and flight data. +% Goals: +% 1. Sanity checks: max projection w/ ROI overlay, flight + traces, flights in 3d +% 2. Quantify behavior: #total flights, #rewarded flights, variability of +% flights (covariance matrix), stability of flights over days (Karthik code) +% 3. Cells aligned to behavior: +% a. Place cell plots: heat maps, plot3, schnitzer plots +% b. Preflight activity: 2 sec, 20 sec before +% c. Postflight activity: 2 sec, 20 sec, rewarded vs nonrewarded + +% TAS +% d07/24/2019 + +%topROI is top% of cells you want to look at +topROI = 80; +% Manual inputs +analysisFlag = 1; +reAnalyze = 1; +%roi plot flags +plotROIFlag = 1; +centroidFlag = 1; +roiHeatFlag = 1; +binaryMaskFlag = 1; +%flight plot flags +plotFlightsFlag = 1; +flightPathsAllFlag = 1; +flightPathsFeederFlag = 1; +%place cells plot flags +plotPlaceCellsFlag = 0; +%snake/schnitz plot flags +plotSnakesFlag = 1; +plotSnakePrePostFlag = 1; +%check transitions between dominant flights A-B +transitionFlag = 1; + +% Get all folders in directory +files = dir(pwd); +files(ismember( {files.name}, {'.', '..','.DS_Store','Thumbs.db'})) = []; %remove . and .. and DS_Store + +% Get a logical vector that tells which is a directory. +dirFlags = [files.isdir]; +% Extract only those that are directories. +subFolders = files(dirFlags); +% Print folder names to command window. +for k = 1 : length(subFolders) + fprintf('Date folder #%d = %s\n', k, subFolders(k).name); +end + +%% Perform analysis on each folder +for i = 1:length(subFolders) + disp(['entering folder ', char(subFolders(i).name)]) + cd([subFolders(i).folder,'/',subFolders(i).name]); + + % index every subfolder... + trackFiles = dir('*track.mat'); + imageFolders = dir('*_extraction'); + %print image data folder names + for kk = 1 : length(imageFolders) + fprintf('Image data folder #%d = %s\n', kk, imageFolders(kk).name); + %check that track data matches image data + if strcmp(imageFolders(kk).name(1:end-10),trackFiles(kk).name(1:end-9)) == 0 + fprintf('Tracking and image data do not match'); + analysisFlag = 0; + end + + % Check if folder exists + if exist([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis'])>0; + disp('Folder already analyzed..'); + if reAnalyze ==1 + disp('Re-Analyzing...'); + else + disp('Moving to the next folder...'); + analysisFlag = 0 ; + end + end + + % load tracking and cell data + if analysisFlag == 1 + trackData = load([trackFiles(kk).folder,'/',trackFiles(kk).name]); + cellData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS_results.mat']); + videoData = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Motion_corrected_Data_DS.mat']); + alignment = load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','processed','/','Alignment.mat']); + fileName = extractBefore(imageFolders(kk).name,'_extraction'); %get filename for titles + dateSesh = imageFolders(kk).folder(end-5:end); + batName = extractBefore(fileName,['_' dateSesh]); + sessionType = extractAfter(fileName,[dateSesh '_']); + % make new analysis directory for .fig and .tif files + cd([imageFolders(kk).folder,'/',imageFolders(kk).name]); + mkdir('analysis'); + disp('Analyzing!!'); + end +% if strcmp(extractBefore(sessionType,'-'),'fly') +% plotFlightsFlag = 1; +% flightPathsAllFlag = 1; +% flightPathsFeederFlag = 1; +% plotPlaceCellsFlag = 1; +% else +% plotFlightsFlag = 0; +% flightPathsAllFlag = 0; +% flightPathsFeederFlag = 0; +% plotPlaceCellsFlag = 0; +% end + %%perform basic sanity checks on imaging and flight data + if plotROIFlag == 1 + mkdir('analysis/ROI'); + % max projection from each session without ROI overlay + [Ymax, Y, maxFig] = ImBat_Dff(videoData.Y,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + hold on + %save fig and tif of max projection + set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.fig']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProject.tif']); + % max projection with ROI overlay + [ROIoverlay] = ImBat_ROIoverlay(cellData.results,videoData.Ysiz,centroidFlag,binaryMaskFlag,roiHeatFlag,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + if centroidFlag == 1 || binaryMaskFlag == 1 + %save fig and tif of max projection + set(findall(maxFig,'-property','FontSize'),'FontSize',20); + savefig(maxFig,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.fig']); + saveas(maxFig, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROI.tif']); + end + if roiHeatFlag == 1 + set(findall(ROIoverlay,'-property','FontSize'),'FontSize',20); + savefig(ROIoverlay,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.fig']); + saveas(ROIoverlay, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/ROI/' fileName '_maxProjectROIheatMap.tif']); + end + hold off + end + + %plot flights in 3d and their clusters + if plotFlightsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir('analysis/flights') + %plot all flights in 3D + if flightPathsAllFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + [flightPaths] = ImBat_plotFlights(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'flightPaths'); + set(findall(flightPaths.flightPathsAll,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.fig']); + saveas(flightPaths.flightPathsAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAll.tif']); + set(findall(flightPaths.flightPathsStartStop,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsStartStop,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.fig']); + saveas(flightPaths.flightPathsStartStop, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsAllStartStop.tif']); + set(findall(flightPaths.flightPathsClusterEach,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsClusterEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.fig']); + saveas(flightPaths.flightPathsClusterEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterEach.tif']); + set(findall(flightPaths.flightPathsClusterAll,'-property','FontSize'),'FontSize',20); + savefig(flightPaths.flightPathsClusterAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.fig']); + saveas(flightPaths.flightPathsClusterAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterAll.tif']); + end + %plot flights to/from feeder in 3D + if flightPathsFeederFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + [flightPathsToFeeder, flightPathsFromFeeder,flightPathsClusterToFeederEach, flightPathsClusterToFeederAll, flightFeedersStartStop] = ImBat_plotFlightsToFeeder(trackData,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + set(findall(flightPathsToFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); + saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); + set(findall(flightPathsFromFeeder,'-property','FontSize'),'FontSize',20); + savefig(flightPathsFromFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.fig']); + saveas(flightPathsFromFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsFromFeeder.tif']); + set(findall(flightPathsClusterToFeederEach,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederEach,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.fig']); + saveas(flightPathsClusterToFeederEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederEach.tif']); + set(findall(flightPathsClusterToFeederAll,'-property','FontSize'),'FontSize',20); + savefig(flightPathsClusterToFeederAll,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.fig']); + saveas(flightPathsClusterToFeederAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsClusterToFeederAll.tif']); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightsToFromFeeders.mat'],... + 'flightFeedersStartStop'); + end + %plot flights over traces + load([imageFolders(kk).folder,'/',imageFolders(kk).name,'/','analysis','/',fileName '_flightPaths.mat']); + [flightVsVelocity,smoothAvgSpiking,smoothVelocity] = ImBat_plotFlightsVsCells(cellData,alignment,flightPaths,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_flightPaths.mat'],'smoothVelocity','smoothAvgSpiking','-append'); + set(findall(flightVsVelocity,'-property','FontSize'),'FontSize',20); + savefig(flightVsVelocity,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.fig']); + saveas(flightVsVelocity, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightVsVelocity.tif']); + end + + %number of total flights and rewarded flights + %numTotalFlights = length(flightPaths.flight_starts_idx); + %numRewardedFlights = length(flightFeedersStartStop.flightToFeederStart); + + %variability of flights + %covariance matrix + + %place cells + %spike activity over flight trajectories + if plotPlaceCellsFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + mkdir('analysis/placeCells') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/placeCells']) + ImBat_PlaceCells_Tobias(flightPaths, cellData, alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + savefig(flightPathsToFeeder,[imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.fig']); + saveas(flightPathsToFeeder, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/flights/' fileName '_flightPathsToFeeder.tif']); + + end + + %snake plots: raw fluorescent traces for each cell sorted by timing of + %peak activity for the smoothed zscored mean across all trials in a cluster + if plotSnakesFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis']) + mkdir('snakePlots') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/snakePlots']) + %load([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/',batName,'_',dateSesh,'_',sessionType,'_flightPaths.mat']); + [snakeTrace] = ImBat_snakeData(cellData,flightPaths,alignment) + [snakeTrace] = ImBat_plotSnake(snakeTrace) + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clust.svg']); + saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustOddEven.svg']); + saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1.svg']); + saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustAll.tif']); + saveas(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustOddEven.tif']); + saveas(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_clustBy1.tif']); + saveas(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.tif']); + saveas(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.tif']); + saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.tif']); + saveas(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefAll.svg']); + saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.tif']); + saveas(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); + saveas(snakeTrace.snakePlot_prefEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEach.tif']); + saveas(snakeTrace.snakePlot_prefEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEach.svg']); + + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakePlotData.mat'],'snakeTrace'); + savefig(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustAll.fig']); + savefig(snakeTrace.snakePlot_clustOddEven, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlos_clustOddEven.fig']); + savefig(snakeTrace.snakePlot_clustBy1, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1.fig']); + savefig(snakeTrace.snakePlot_clustPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); + savefig(snakeTrace.snakePlot_prefEachPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.fig']); + savefig(snakeTrace.snakePlot_prefAll, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlots_prefAll.fig']); + savefig(snakeTrace.snakePlot_clustBy1PrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.fig']); + savefig(snakeTrace.snakePlot_prefEach, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_prefEach.fig']); + end + + if plotSnakePrePostFlag == 1 && strcmp(extractBefore(sessionType,'-'),'fly') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis']) + + %run snakePlot on top 5 clusters with pre/flight/post activity plotted + [snakeTrace] = ImBat_plotSnake_allPreFlightPost(snakeTrace) + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakePlotData.mat'],'snakeTrace'); + savefig(snakeTrace.snakePlot_allPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_allPrePostFlight.fig']); + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_allPrePostFlight.tif']); + saveas(snakeTrace.snakePlot_clust, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_allPrePostFlight.svg']); + + %run pre/post/during analysis with large borders to examine overall + %population activity of all neurons in snakePlot format + [snakeTracePrePost] = ImBat_snakeDataPrePost(cellData,flightPaths,alignment) + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakeTracePrePost.mat'],'snakeTracePrePost'); + + [snakeTracePrePost] = ImBat_plotSnakePrePost(snakeTracePrePost) + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_snakeTracePrePost.mat'],'snakeTracePrePost'); + savefig(snakeTracePrePost.snakePlot_concat_preFlightPost, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_concat_preFlightPost.fig']); + saveas(snakeTracePrePost.snakePlot_concat_preFlightPost, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_concat_preFlightPost.tif']); + saveas(snakeTracePrePost.snakePlot_concat_preFlightPost, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_concat_preFlightPost.svg']); + savefig(snakeTracePrePost.snakePlot_noClust_withinPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_withinPrePostFlight.fig']); + saveas(snakeTracePrePost.snakePlot_noClust_withinPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_withinPrePostFlight.tif']); + saveas(snakeTracePrePost.snakePlot_noClust_withinPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_withinPrePostFlight.svg']); + savefig(snakeTracePrePost.snakePlot_noClust_acrossPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_acrossPrePostFlight.fig']); + saveas(snakeTracePrePost.snakePlot_noClust_acrossPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_acrossPrePostFlight.tif']); + saveas(snakeTracePrePost.snakePlot_noClust_acrossPrePostFlight, [imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/snakePlots/' fileName '_snakePlot_noClust_acrossPrePostFlight.svg']); + + + end + + %plot the dominant A-B transitions with neural data aligned to flight A + %or B + if transitionFlag == 1 + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis']) + mkdir('AtoB') + cd([subFolders(i).folder,'/',subFolders(i).name,'/',imageFolders(kk).name,'/analysis/AtoB']) + [flightTransitions] = ImBat_transition_flights(flightPaths) + save([imageFolders(kk).folder '/' imageFolders(kk).name '/analysis/' fileName '_transitions_AtoB.mat'],'flightTransitions'); + %plot each cell + ImBat_plotFlightvsCells_transitions(snakeTrace,flightTransitions,flightPaths,'saveflag',1,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType) + end + + close all; + end + + +close all; +end \ No newline at end of file diff --git a/analysis_tobias/convert_tiffTOmat.m b/analysis_tobias/convert_tiffTOmat.m new file mode 100644 index 0000000..10e0fc7 --- /dev/null +++ b/analysis_tobias/convert_tiffTOmat.m @@ -0,0 +1,15 @@ + +FileTif='DSampled_190528_fly1.tif'; +InfoImage=imfinfo(FileTif); +Ysiz = [InfoImage(1).Height InfoImage(1).Width length(InfoImage)]; +%mImage=InfoImage(1).Width; +%nImage=InfoImage(1).Height; +%NumberImages=length(InfoImage); +Y=zeros(Ysiz(1),Ysiz(2),Ysiz(3),'single'); + +TifLink = Tiff(FileTif, 'r'); +for i=1:Ysiz(3) + TifLink.setDirectory(i); + Y(:,:,i)=TifLink.read(); +end +TifLink.close(); \ No newline at end of file diff --git a/behavior/FlightAlignment_d04032020/.DS_Store b/behavior/FlightAlignment_d04032020/.DS_Store new file mode 100644 index 0000000..3be0df5 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/.DS_Store differ diff --git a/behavior/FlightAlignment_d04032020/ImBat_Align_Tracking.m b/behavior/FlightAlignment_d04032020/ImBat_Align_Tracking.m new file mode 100644 index 0000000..a804fd5 --- /dev/null +++ b/behavior/FlightAlignment_d04032020/ImBat_Align_Tracking.m @@ -0,0 +1,15 @@ +function Location_adjusted = ImBat_Align_Tracking(Location,out,date2use); +% Load in Location data, adjust it to the day/day alignment from the +% Master_Tracking_File.mat + +% WAL3 +% 3/30/2020 + +% Get appropriate transform from the master tracking file: +Index = find(contains(out.date,date2use)); + +% Get apply transform from the master tracking file: +TEMP = pointCloud(Location); +ptCloudTformed = pctransform(TEMP,out.tform{Index}); +Location_adjusted = ptCloudTformed.Location; + diff --git a/behavior/FlightAlignment_d04032020/ImBat_Create_Master_Track.m b/behavior/FlightAlignment_d04032020/ImBat_Create_Master_Track.m new file mode 100644 index 0000000..9596782 --- /dev/null +++ b/behavior/FlightAlignment_d04032020/ImBat_Create_Master_Track.m @@ -0,0 +1,46 @@ +function out = ImBat_Create_Master_Track + +% run in folder with calibration .c3d files +% WAL3 +% d03/31/2020 + + + +% Housekeeping: +out.Creation_date = datestr(now); + +% STEP 1: get all .c3d files in folder: +DIR = pwd; +mov_listing=dir(fullfile(DIR,'*.c3d')); +mov_listing={mov_listing(:).name}; + + +for i=1:length(mov_listing) + +% STEP 2: extract Markers + [path,file,ext]=fileparts(mov_listing{i}); + FILE = fullfile(DIR,mov_listing{i}) + +[Markers,~,~,~,~,~,~,~]=readC3D_analog(FILE); +out.date{i} = file(7:12); % read date from filename +out.Markers_Raw{i} = Markers; % save markers +end + + +% STEP 3: Align Markers to first day +disp('aligning all days...'); +out.ReferenceDate = out.date{1}; +for i = 1:size(out.date,2) +[out.tform{i},out.Markers_Adjusted{i}] = ImBat_AlignPoints(out.Markers_Raw{4},out.Markers_Raw{i}); + +% % STEP 4: Use tform to adjust markers ( for reference) +% +% TEMP = pointCloud(out.Markers_Raw{i}); +% ptCloudTformed = pctransform(TEMP,out.tform{i}); +% out.Markers_Adjusted = ptCloudTformed.Location; + +end + + +save('Master_Tracking_File.mat','out'); + diff --git a/behavior/FlightAlignment_d04032020/Master_Tracking_File.mat b/behavior/FlightAlignment_d04032020/Master_Tracking_File.mat new file mode 100644 index 0000000..65f8cde Binary files /dev/null and b/behavior/FlightAlignment_d04032020/Master_Tracking_File.mat differ diff --git a/behavior/FlightAlignment_d04032020/demo.m b/behavior/FlightAlignment_d04032020/demo.m new file mode 100644 index 0000000..926cd01 --- /dev/null +++ b/behavior/FlightAlignment_d04032020/demo.m @@ -0,0 +1,35 @@ + +% Behavioral ALignment Demo (run in FlightAlignment folder) +% WAL3 04/03/2020 + +% Load example data +out1 = load('example_data/alignment/Gal_200311_fly-1_Alignment.mat','out'); +date1 = '200311'; +Location_01 = out1.out.Location; + +out2 = load('example_data/alignment/Gal_200315_fly-1_Alignment.mat','out'); +Location_02 = out2.out.Location; +date2 = '200315'; + +% Load master Tracking File +MasterTrack = load('Master_Tracking_File.mat','out') + + +% Run alignment +Location_01_adjusted = ImBat_Align_Tracking(Location_01,MasterTrack.out,date1); +Location_02_adjusted = ImBat_Align_Tracking(Location_02,MasterTrack.out,date2); + +% Plot unadjusted flights +figure(); +hold on; +plot(Location_01(:,1),Location_01(:,2)); +plot(Location_02(:,1),Location_02(:,2)); +title('Unaligned data'); + + +% Plot adjusted flights +figure(); +hold on; +plot(Location_01_adjusted(:,1),Location_01_adjusted(:,2)); +plot(Location_02_adjusted(:,1),Location_02_adjusted(:,2)); +title('Aligned data'); diff --git a/behavior/FlightAlignment_d04032020/example_data/.DS_Store b/behavior/FlightAlignment_d04032020/example_data/.DS_Store new file mode 100644 index 0000000..683f353 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/example_data/.DS_Store differ diff --git a/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200311_fly-1_Alignment.mat b/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200311_fly-1_Alignment.mat new file mode 100644 index 0000000..bdfcc14 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200311_fly-1_Alignment.mat differ diff --git a/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200315_fly-1_Alignment.mat b/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200315_fly-1_Alignment.mat new file mode 100644 index 0000000..c521815 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/example_data/alignment/Gal_200315_fly-1_Alignment.mat differ diff --git a/behavior/FlightAlignment_d04032020/example_data/track/Gal_200311_fly-1_track.mat b/behavior/FlightAlignment_d04032020/example_data/track/Gal_200311_fly-1_track.mat new file mode 100644 index 0000000..39fb246 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/example_data/track/Gal_200311_fly-1_track.mat differ diff --git a/behavior/FlightAlignment_d04032020/example_data/track/Gal_200315_fly-1_track.mat b/behavior/FlightAlignment_d04032020/example_data/track/Gal_200315_fly-1_track.mat new file mode 100644 index 0000000..f378dd3 Binary files /dev/null and b/behavior/FlightAlignment_d04032020/example_data/track/Gal_200315_fly-1_track.mat differ diff --git a/behavior/ImBat_RepairFlightData.m b/behavior/ImBat_RepairFlightData.m new file mode 100644 index 0000000..41d25fc --- /dev/null +++ b/behavior/ImBat_RepairFlightData.m @@ -0,0 +1,103 @@ +function ROI_Data = ImBat_RepairFlightData(ROI_Data); +% Repair flight data + +n = 100; % minimum length of gap to repair: +hang1 = 3;%overhang + +for day2use = 1:size(ROI_Data,2) + + disp(['Processing day ',num2str(day2use)]); +GG = ROI_Data{day2use}.Alignment.out.Location3(:,1); +Flights_Smoothed = ROI_Data{day2use}.Alignment.out.Location3(:,:); +Flights_Original = ROI_Data{day2use}.Alignment.out.Location(:,:); + + + +GG2 = GG; +hold on; +% find stretches of zeros: +x = diff(smooth(GG,1)); +transitions = diff([0; x == 0; 0]); %find where the array goes from non-zero to zero and vice versa +runstarts = find(transitions == 1); +runends = find(transitions == -1); %one past the end +runlengths = runends - runstarts; +%keep only those runs of length n or more: +runstarts(runlengths < n) = []; +runends(runlengths < n) = []; +%expand each run into a list indices: +indices = arrayfun(@(s, e) s:e-1, runstarts, runends, 'UniformOutput', false); +indices = [indices{:}]; %concatenate the list of indices into one vector +GG2(indices) = NaN; %replace the indices with 2 +indices = [indices size(GG2,1)]; +%plot(GG2); + +% replace zeros: +Flights_new = ROI_Data{day2use}.Alignment.out.Location2(:,:); +Flights_new(indices,:) = Flights_Smoothed(indices,:); +% figure(); hold on; plot(Flights_new(:,1)); plot(GG); + +%% do it again: +clear transitions runstarts runends indices GG GG2; +GG = Flights_new(:,1); +GG2 = GG; +GG3 = GG; +% find stretches of zeros: +x = diff(smooth(GG,1)); +transitions = diff([0; x == 0; 0]); %find where the array goes from non-zero to zero and vice versa +runstarts = find(transitions == 1); +runends = find(transitions == -1); %one past the end +runlengths = runends - runstarts; +%keep only those runs of length n or more: +runstarts(runlengths < n) = []; +runends(runlengths < n) = []; +%expand each run into a list indices: +indices = arrayfun(@(s, e) s:e-1, runstarts, runends, 'UniformOutput', false); +indices = [indices{:}]; %concatenate the list of indices into one vector +GG2(indices) = NaN; %replace the indices with 2 +indices = [indices size(GG2,1)]; + + +Flights_fixed = Flights_new; +% now, get rid of them.. + +for i = 1: size(runstarts,1) + % check which side is bigger: + if runstarts(i) ==1; + b = Flights_new(runends(i)+hang1,:); + toUse = b; + Flights_fixed(runstarts(i):runends(i)+hang1,:) = ones(size(runstarts(i):runends(i)+hang1,2),3).*toUse; + + elseif runends(i) > length(GG3)-hang1 + a = Flights_new(runstarts(i)-hang1,:); + toUse = a; + Flights_fixed(runstarts(i)-hang1:runends(i),:) = ones(size(runstarts(i)-hang1:runends(i),2),3).*toUse; + + else + a = Flights_new(runstarts(i)-hang1,:); + b = Flights_new(runends(i)+hang1,:); + if a(:,1)>b(:,1); toUse = a; + else + toUse = b; + end + Flights_fixed(runstarts(i)-hang1:runends(i)+hang1,:) = ones(size(runstarts(i)-hang1:runends(i)+hang1,2),3).*toUse; + + end +end + +for i = 1:3 +Flights_fixed(:,i) = smooth(Flights_fixed(:,i),50); +end +figure(); +hold on; +plot(Flights_Original(:,1),'k--'); + +plot(Flights_new(:,1),'b--'); +plot(Flights_fixed(:,1),'r'); + + legend('original','smoothed','repaired'); + title(['day: ',num2str(day2use)]); + hold off +ROI_Data{day2use}.Alignment.out.Flights_Repaired = []; + ROI_Data{day2use}.Alignment.out.Flights_Repaired(:,:) = Flights_fixed; + +end \ No newline at end of file diff --git a/behavior/ImBat_flight_timing.m b/behavior/ImBat_flight_timing.m new file mode 100644 index 0000000..988cdd2 --- /dev/null +++ b/behavior/ImBat_flight_timing.m @@ -0,0 +1,203 @@ +function [flightTiming] = ImBat_flight_timing(flightPaths,snakeTrace,flightTransitions,varargin) + +%% Plot the time differences between flights A to B & BtoA +histAtoBFlag = 1; +boxplotAtoBFlag = 1; +plotFlightTimesFlag = 1; +saveFlag = 0; +batName = []; +dateSesh = []; +sessionType = []; + +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'saveflag' + saveFlag = varargin{i+1}; + case 'batname' + batName = varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + end +end +snakeTrace.batName = batName; +snakeTrace.dateSesh = dateSesh; +snakeTrace.sessionType = sessionType; + + +%calculate timing difference from start/end of flight A to start of flight B +for flight_i = 1:length(flightTransitions.AtoB(1,:)) + %timing from flight B to A + flightStartA(flight_i) = flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i)); + flightStartB(flight_i) = flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i)+1); + flightEndA(flight_i) = flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i)); + flightEndB(flight_i) = flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i)+1); + + + diffStartAtoStartB(flight_i) = flightStartB(flight_i) - flightStartA(flight_i); + diffStartAtoStartB(flight_i) = diffStartAtoStartB(flight_i)/120; %convert to seconds + diffEndAtoStartB(flight_i) = flightStartB(flight_i) - flightEndA(flight_i); + diffEndAtoStartB(flight_i) = diffEndAtoStartB(flight_i)/120; %convert to seconds +end + +%calculate timing difference from start/end of flight B to start of flight A +for flight_i = 1:length(flightTransitions.BtoA(1,:)) + %timing from flight B to A + flightSB(flight_i) = flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i)); + flightSA(flight_i) = flightPaths.flight_starts_idx(flightTransitions.BtoA(flight_i)+1); + flightEB(flight_i) = flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i)); + flightEA(flight_i) = flightPaths.flight_ends_idx(flightTransitions.BtoA(flight_i)+1); + + diffSBtoSA(flight_i) = flightSA(flight_i) - flightSB(flight_i); + diffSBtoSA(flight_i) = diffSBtoSA(flight_i)/120; %convert to seconds + diffEBtoSA(flight_i) = flightSA(flight_i) - flightEB(flight_i); + diffEBtoSA(flight_i) = diffEBtoSA(flight_i)/120; %convert to seconds + + % flightConcat = [flightConcat flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed... + % :flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightTransitions.AtoB(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_ends_idx(flightTransitions.AtoB(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color','b')%,jj(traj*100,:)) + +end + +%plot the 6 histograms of timing from A to B and from B to A +if histAtoBFlag == 1 + nBins = 9; %number of bins to use for the histogram + hist_flightTiming_AtoB = figure('units','normalized','outerposition',[0.5 0 0.5 1]); + subplot(3,2,1); + histogram(diffStartAtoStartB,nBins); + title('Timing Start Flight A to Start Flight B'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + subplot(3,2,2); + histogram(diffEndAtoStartB,nBins); + title('Timing End Flight A to Start Flight B'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + subplot(3,2,3); + histogram(diffSBtoSA,nBins,'FaceColor','r'); + title('Timing Start Flight B to Start Flight A'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + subplot(3,2,4); + histogram(diffEBtoSA,nBins,'FaceColor','r'); + title('Timing End Flight B to Start Flight A'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + subplot(3,2,5); + histogram(diffSBtoSA(find(diffSBtoSA<40)),6,'FaceColor','r'); + title('Timing Start Flight B to Start Flight A'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + subplot(3,2,6); + histogram(diffEBtoSA(find(diffEBtoSA<40)),6,'FaceColor','r'); + title('Timing End Flight B to Start Flight A'); + ylabel('Num flights'); + xlabel('Time between flights (sec)'); + + sgtitle(['Flight timing/jitter for A/B flights: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + if saveFlag ==1 + saveas(hist_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_flightTiming_AtoB.svg']); + saveas(hist_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_flightTiming_AtoB.tif']); + savefig(hist_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_flightTiming_AtoB.fig']); + end + +end + +%plot the 6 boxplots of timing from A to B and from B to A +if boxplotAtoBFlag == 1 + boxplot_flightTiming_AtoB = figure('units','normalized','outerposition',[0 0 0.5 1]); + subplot(3,2,1); + boxplot(diffStartAtoStartB); + title('Timing Start Flight A to Start Flight B'); + ylabel('Time between flights (s)'); + + subplot(3,2,2); + boxplot(diffEndAtoStartB); + title('Timing End Flight A to Start Flight B'); + ylabel('Time between flights (s)'); + + subplot(3,2,3); + boxplot(diffSBtoSA); + title('Timing Start Flight B to Start Flight A'); + ylabel('Time between flights (s)'); + + subplot(3,2,4); + boxplot(diffEBtoSA); + title('Timing End Flight B to Start Flight A'); + ylabel('Time between flights (s)'); + + subplot(3,2,5); + boxplot(diffSBtoSA(find(diffSBtoSA<40))); + title('Timing Start Flight B to Start Flight A'); + ylabel('Time between flights (s)'); + + subplot(3,2,6); + boxplot(diffEBtoSA(find(diffEBtoSA<40))); + title('Timing End Flight B to Start Flight A'); + ylabel('Time between flights (s)'); + + sgtitle(['Flight timing/jitter for A/B flights: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + if saveFlag ==1 + saveas(boxplot_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_boxplot_flightTiming_AtoB.svg']); + saveas(boxplot_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_boxplot_flightTiming_AtoB.tif']); + savefig(boxplot_flightTiming_AtoB, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_boxplot_flightTiming_AtoB.fig']); + end + +end + +%% Plot each of the flights as a star in a timeline with a different color for each traj cluster + +if plotFlightTimesFlag ==1 + jj = jet(flightPaths.nClusters); %make color vector + plotFlightTimes = figure('units','normalized','outerposition',[0 0 1 0.5]); + for clust_i = 1:flightPaths.nClusters + %make height vector for the plot + ht = ones(1,length(flightPaths.clusterIndex{clust_i})); + %plot each flight in the color of the trajectory + for flight_i = 1:length(flightPaths.clusterIndex{clust_i}) + legendData{clust_i} = plot(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(flight_i)),ht,'*','Color',jj(clust_i,:)); + ylim([0 1]); + xline(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(flight_i)),'-','Color',jj(clust_i,:),'LineWidth',3); + hold on; + end + %make dummy points for the legend so the colors match the trajectories + l(clust_i) = plot([NaN,NaN],'*', 'color', jj(clust_i,:)); + + end + title(['Flight times of each trajectory: ' batName ' ' dateSesh ' ' sessionType]); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/120,1)); + xlabel('time (s)'); + set(gca,'yticklabel',{[]}); + legend([l(1) l(2) l(3)],{'traj 1','traj 2','traj 3'}); + + if saveFlag ==1 + saveas(plotFlightTimes, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotFlightTimes.svg']); + saveas(plotFlightTimes, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotFlightTimes.tif']); + savefig(plotFlightTimes, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotFlightTimes.fig']); + end +end + +%% +flightTiming.flightStartA = flightStartA; +flightTiming.flightStartB = flightStartB; +flightTiming.flightEndA = flightEndA; +flightTiming.flightEndB = flightEndB; +flightTiming.diffStartAtoStartB = diffStartAtoStartB; +flightTiming.diffEndAtoStartB = diffEndAtoStartB; +flightTiming.flightSB = flightSB; +flightTiming.flightSA = flightSA; +flightTiming.flightEB = flightEB; +flightTiming.flightEA = flightEA; +flightTiming.diffSBtoSA = diffSBtoSA; +flightTiming.diffEBtoSA = diffEBtoSA; + +if saveFlag ==1 + save([pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_flightTiming.mat'],'flightTiming'); +end \ No newline at end of file diff --git a/behavior/ImBat_flightsAng.m b/behavior/ImBat_flightsAng.m new file mode 100644 index 0000000..5476935 --- /dev/null +++ b/behavior/ImBat_flightsAng.m @@ -0,0 +1,411 @@ +function [flightPaths] = ImBat_flightsAng(trackData,alignment,varargin) + +batName = []; +dateSesh = []; +sessionType = []; +saveFlag = 0; +loadFlag = 0; +flightAdjustFlag = 0; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + end +end + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + trackDir = dir('*_track.mat'); + trackData = load(trackDir(1).name); +% if flightFixedFlag == 1 +% load('\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\ForTobias\plots\210113\ROI_Data_za190524_za190527_za190528_za190529_za190530.mat'); +% %trackData.AnalogFrameRate = 120; +% trackData.AnalogySignals = ROI_Data{day_i}.Alignment.out.Flights_Repaired; +% %trackData.VideoFrameFrate = 120; +% trackData.Markers = repmat(ROI_Data{day_i}.Alignment.out.Flights_Repaired,1,1,3); +% end + dateSesh = datestr(trackDir(1).date, 'yymmdd'); + batName = extractBefore(trackDir(1).name,['_' dateSesh]); + sessionTypeTemp = extractBefore(trackDir(1).name,'_track.mat'); + sessionType = extractAfter(sessionTypeTemp, [batName '_' dateSesh '_']); +end + +% General Params +CNMF_Fs = 30;%6; %Acquisition frequency (Hz) Ca-imaging (after CNMF-e) +use_bat_cluster = true; %If using bat_cluster +dwn_sample = false; %down-sample to CNMF-e +save_data = false; %save after extraction +save_img = false; %save cluster image + +% Clustering params +ds_clus = 6; %number of 3D-points/flight for clustering +%madeleine 25 splines, PCA+, 1m linkage +%angelo 6 splines, PCA-, 0.7m linakge, min 5 +pca_features = false; %if using PCA +k_means = false; %if using k-means +dist = 0.8; %linkage distance +reassign = true; %re-order clusters according to density +N_min = 3; %min number of flights for being a cluster + +% Flight Room references (provvisory) +xR = +2.85; xL = -2.85; yF = 2.50; yB = -2.50; zT = 2.20; %Flight volume coordinates +F3 = [2.56; 1.43; 0.72]; F4 = [2.56; -1.24; 0.72]; %Feeders coordinates + +%Use day to day flight adjustment? +if flightAdjustFlag == 1 + % Load master Tracking File + masterDir = extractBefore(pwd,'topQualityData'); + MasterTrack = load([masterDir 'topQualityData' filesep 'Master_Tracking_File.mat'],'out'); + + % Run alignment + locMarkers = trackData.Markers(:,1,:); + loc_inpt = alignment.out.Location;%queeze(locMarkers); +% if flightFixedFlag == 1 +% loc_inpt = ROI_Data{day_i}.Alignment.out.Flights_Repaired; +% end + dFlightAligned = ImBat_Align_Tracking(loc_inpt,MasterTrack.out,dateSesh); + dataFlight = reshape(dFlightAligned,length(dFlightAligned),1,3); +else + if isfield(trackData,'Markers_Original') + dataFlight = trackData.Markers_Original; + else + dataFlight = trackData.Markers; + end +end + +T_tk = size(dataFlight,1); t = [0:1/trackData.VideoFrameRate:(T_tk-1)/trackData.VideoFrameRate]; %Generate time vector +rew_signal = trackData.AnalogSignals(:,1); %Reward signal, usually on Analog Ch1 + + +%% Trajectory extraction +if use_bat_cluster + x_mean = [dataFlight(:,1,1) dataFlight(:,1,2) dataFlight(:,1,3)]'./1000; x_mean(x_mean==0) = nan; +else + Markers_nan = dataFlight; Markers_nan(Markers_nan==0) = nan; + Markers_mean = mean(Markers_nan,2,'omitnan'); + x_mean = [Markers_mean(:,1,1) Markers_mean(:,1,2) Markers_mean(:,1,3)]'./1000; +end + +% Filter and interpolate +x_filt = medfilt1(x_mean,trackData.VideoFrameRate/2,[],2,'omitnan','truncate'); %filter after interpolating +x_intr = fillmissing(x_filt,'next',2,'EndValues','nearest'); +x_spl = csaps(t, x_intr, 0.9, t); + +%Frame rate +new_t = t; +tracking_Fs = trackData.VideoFrameRate; + +%% Calculate velocity and flight segmentation +v = diff(x_spl,1,2)./[diff(new_t);diff(new_t);diff(new_t)]; v=[zeros(3,1) v]; +v_abs = vecnorm(v,2,1); + +nonflying = find(v_abs < 1); toofast = find(v_abs > 30); +x_flying = x_spl; x_flying(:,[nonflying toofast]) = nan; +batspeed = v_abs; batspeed([nonflying; toofast]) = nan; +bflying=~isnan(batspeed)'; %vector of 1s when the bat is flying + +% For each sample, sum up the next 1s of data(flights are longer than 1s),Code from Nick D. +allsums = []; +for bf = 1 : size(bflying,1)-tracking_Fs + allsums(bf) = sum(bflying(bf:bf+tracking_Fs)); +end + +% Detect flight starts and stops +[R,rLT,rUT,rLL,rUL] = risetime(allsums); +[F,fLT,fUT,fLL,fUL] = falltime(allsums); +if length(R) ~= length(F) +fLT(length(R)) = length(allsums); +fUT(length(R)) = length(allsums); +F(length(R)) = F(length(F)); +end +flight_starts = round(rLT+tracking_Fs/2); +flight_ends = round(fLT+tracking_Fs/2); %... +Fs is a sistematic correction, useful +num_flights = size(R,2); +ref = ones(size(flight_starts)); +avg_flight_time = mean((flight_ends-flight_starts)./tracking_Fs); + +%% Plot results + +% Plot 2D flight trajectories +plotFlightPathsAll = figure(); set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +subplot(1,2,1); +plot(x_mean(1,:),x_mean(2,:),'.'); +hold on; rectangle('Position',[xL yB xR-xL yF-yB]); +scatter([F3(1) F4(1)],[F3(2) F4(2)],'filled'); hold off; +xlim([-3 3]); ylim([-3 3]); zlim([0 2.5]); +title(['Raw flights: ' batName ' ' dateSesh ' ' sessionType]); +xlabel('m'); ylabel('m'); +hold off + +subplot(1,2,2); +plot(x_spl(1,:),x_spl(2,:)); hold on; plot(x_mean(1,:),x_mean(2,:),'.','MarkerSize',1); +rectangle('Position',[xL yB xR-xL yF-yB]); hold off; +xlim([-3 3]); ylim([-3 3]); zlim([0 2.5]); +title(['Spline flights: ' batName ' ' dateSesh ' ' sessionType]); +xlabel('m'); ylabel('m'); +hold off + +% Plot session timeline +plotFlightTimeline = figure(); set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +ax1 = subplot(3,1,1); plot(t,x_mean(1,:),'.'); hold on; +plot(new_t,x_spl(1,:),'--'); refline(0,F3(1)); hold off; +legend('cluster/mean','spl'); ylabel('x (m)'); +ax2 = subplot(3,1,2); plot(new_t,v_abs,'.'); +hold on; stem(new_t(flight_starts),ref); stem(new_t(flight_ends),ref); hold off; +ylabel('v (m/s)'); +ax3 = subplot(3,1,3); plot(t,rew_signal); +ylabel('Rewards'); +linkaxes([ax1,ax2,ax3],'x'); xlabel('Samples'); +sgtitle(['Session timeline: ' batName ' ' dateSesh ' ' sessionType]); + +% Plot flights in color time order +plotFlightPathsStartStop = figure(); +if size(R,2) > 0 + CM = jet(size(R,2)); + for nf = 1 : size(R,2) + hold on + plot3(x_spl(1,flight_starts(nf):flight_ends(nf)),x_spl(2,flight_starts(nf):flight_ends(nf)),x_spl(3,flight_starts(nf):flight_ends(nf)),'LineWidth',1,'Color',CM(nf,:)) + hold on + + fstartxyz(nf,1) = x_spl(1,flight_starts(nf)); %round(nanmean(x_spl(1,flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + fstartxyz(nf,2) = x_spl(2,flight_starts(nf)); %round(nanmean(x_spl(2,flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + fstartxyz(nf,3) = x_spl(3,flight_starts(nf)); %round(nanmean(x_spl(3,flight_starts(nf):flight_starts(nf)+trackData.VideoFrameRate/2))); + + fendxyz(nf,1) = x_spl(1,flight_ends(nf)); %round(nanmean(x_spl(1,flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + fendxyz(nf,2) = x_spl(2,flight_ends(nf)); %round(nanmean(x_spl(2,flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + fendxyz(nf,3) = x_spl(3,flight_ends(nf)); %round(nanmean(x_spl(3,flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); + + scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),50,'r','filled') + hold on + scatter3(fendxyz(nf,1),fendxyz(nf,2),fendxyz(nf,3),50,'k','filled') + %pause + end +else + fstartxyz(1,1) = (0); + fstartxyz(1,2) = (0); + fstartxyz(1,3) = (0); + + fendxyz(1,1) = (0); + fendxyz(1,2) = (0); + fendxyz(1,3) = (0); +end +title(['All flights start(r)/stop(b): ' batName ' ' dateSesh ' ' sessionType]); +% modify labels for tick marks +view(0,90) +xlim([-3 3]) +ylim([-3 3]) +xlabel('m'); ylabel('m'); + +hold off + +%% Clustering flights +%Cut out flights, downsample to ds_clus positions per flight +all_flights = NaN(3,max(flight_ends-flight_starts),num_flights); %3D matrix with all flights +all_flights_ds = NaN(3,ds_clus,num_flights); %3D matrix with all flights(downsampled) + +for nf = 1 : size(all_flights,3) + trajectory = x_spl(:,flight_starts(nf):flight_ends(nf)); + velocity = v_abs(:,flight_starts(nf):flight_ends(nf)); + all_flights(:,1:(flight_ends(nf)-flight_starts(nf))+1,nf) = trajectory; + all_flights_vel(1,1:(flight_ends(nf)-flight_starts(nf)+1),nf) = velocity; + all_flights_ds(:,:,nf) = interp1(linspace(1,3,size(trajectory,2)),trajectory',linspace(1,3,ds_clus),'spline')'; + + % %Uncomment if you want to see how the downsampled flights look like + % plot3(all_flights(1,:,nf),all_flights(2,:,nf),all_flights(3,:,nf),'Color','b'); + % hold on; + % plot3(all_flights_ds(1,:,nf),all_flights_ds(2,:,nf),all_flights_ds(3,:,nf),'Color','r'); + % hold off; + % w = waitforbuttonpress; +end + +% Define X matrix of features for clustering (downsampled coordinates, stacked together) +X = [all_flights_ds(1,:,:), all_flights_ds(2,:,:), all_flights_ds(3,:,:)]; +X = reshape(X,3*size(all_flights_ds,2),size(R,2)); +X = X'; %so then X = #flights x #features + +% If dimensionality reduction is needed +if pca_features + [coeff,score,latent] = pca(X); X = score(:,1:5); +end + +% k-means or hierarchical clustering (with euclidean distance and shortest linkage) +if k_means + n_clusters = 15; idx = kmeans(X,n_clusters); +else + plotClusterDistance = figure(); + Y = pdist(X,'euclidean'); Z = linkage(Y); + hLines = dendrogram(Z,0); hold on; refline(0,dist); hold off; + idx = cluster(Z,'Cutoff',dist,'Criterion','distance'); + title([num2str(length(unique(idx))) ' clusters: ' batName ' ' dateSesh ' ' sessionType]); + ylim([0 10]); +end + +% Create structure with flight start stop frames, id of the trajectory +clear flight; +flight.strt_frame = ceil(flight_starts)'; +flight.stop_frame = ceil(flight_ends)'; +flight.pos = all_flights; +flight.vel = all_flights_vel; +flight.id = idx; +flight.Fs = tracking_Fs; + +% Sort structure according to cluster id +clear flight_sorted; +[flight_sorted.id,I] = sort(flight.id); +flight_sorted.strt_frame = flight.strt_frame(I); +flight_sorted.stop_frame = flight.stop_frame(I); +flight_sorted.pos = flight.pos(:,:,I); +flight_sorted.vel = flight.vel(:,:,I); +flight_sorted.Fs = flight.Fs; +flight_sorted.N = size(flight_sorted.id,1); + +% Assign isolated clusters to cluster #flights+1 +[Ns,b] = histc(flight_sorted.id,unique(flight_sorted.id)); +flight_sorted.id(Ns(b) 35); %set low speed points to zero -%mx([nonflying]) = nan;%mx(nonflying) = nan; %mx([nonflying; toofast]) = nan; -%my([nonflying]) = nan;%my(nonflying) = nan;%my([nonflying; toofast]) = nan; -%mz([nonflying]) = nan;%mz(nonflying) = nan;%mz([nonflying; toofast]) = nan; +mxFull([nonflying]) = nan;%mx(nonflying) = nan; %mx([nonflying; toofast]) = nan; +myFull([nonflying]) = nan;%my(nonflying) = nan;%my([nonflying; toofast]) = nan; +mzFull([nonflying]) = nan;%mz(nonflying) = nan;%mz([nonflying; toofast]) = nan; @@ -88,32 +93,32 @@ trajectories_continuous(2,:) = myFull'; trajectories_continuous(3,:) = mzFull'; -%plot all flights in black +%% plot all flights in black plotFlightPathsAll = figure(); -%plot3(mxFull,myFull,mzFull,'LineWidth',2,'Color','k') +plot3(mx,my,mz,'LineWidth',2,'Color','k') %scatter3(mxFull,myFull,mzFull,'.','k') hold on -col = jet(100); -for i = 2:length(trackData.Markers(:,1,:)) -plot3(mxFull(i), myFull(i), mzFull(i), 'color',col(vecnorm([mxFull(i),myFull(i),mzFull(i) - mxFull(i-1),myFull(i-1),mzFull(i-1)], 2, 2))) -hold on -end +% col = jet(100); +% for i = 2:length(trackData.Markers(:,1,:)) +% plot3(mxFull(i), myFull(i), mzFull(i), 'color',col(vecnorm([mxFull(i),myFull(i),mzFull(i) - mxFull(i-1),myFull(i-1),mzFull(i-1)], 2, 2))) +% hold on +% end + % % modify labels for tick marks -% xticks = get(gca,'xtick'); -% yticks = get(gca,'ytick'); -% zticks = get(gca,'ztick'); -% scaling = 0.1; %1.1um per pixel -% newlabelsX = arrayfun(@(ax) sprintf('%g', scaling * ax), xticks, 'un', 0); -% newlabelsY = arrayfun(@(ay) sprintf('%g', scaling * ay), yticks, 'un', 0); -% newlabelsZ = arrayfun(@(az) sprintf('%g', scaling * az), zticks, 'un', 0); -% set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY,'zticklabel',newlabelsZ); -title(['All flights: ' batName ' ' dateSesh ' ' sessionType]); -xlabel('mm'); ylabel('mm'); zlabel('mm'); view(0,90) +xlim([-3000 3000]) +ylim([-3000 3000]) +xticks = get(gca,'xtick'); +yticks = get(gca,'ytick'); +newlabelsX = arrayfun(@(ax) sprintf('%g', ax/1000), xticks, 'un', 0); +newlabelsY = arrayfun(@(ay) sprintf('%g', ay/1000), yticks, 'un', 0); +set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +title(['All flights: ' batName ' ' dateSesh ' ' sessionType]); +xlabel('m'); ylabel('m'); hold off -%splice out individual flights +%% splice out individual flights batspeed = batSpeed; batspeed(nonflying) = nan; %batspeed(toofast) = nan; @@ -130,8 +135,11 @@ [F,fLT,fUT,fLL,fUL] = falltime(allsums); flight_starts = round(rLT); flight_ends = round(fLT); +if length(flight_starts) ~= length(flight_ends) + flight_ends = [flight_ends size(allsums,2)]; +end -%cut out flights and save +%% cut out flights and save plotFlightPathsStartStop = figure(); if size(R,2) > 0 CM = jet(size(R,2)); @@ -148,7 +156,7 @@ fendxyz(nf,2) = round(nanmean(myFull(flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); fendxyz(nf,3) = round(nanmean(mzFull(flight_ends(nf):flight_ends(nf)+trackData.VideoFrameRate/2))); - %scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),75,'r','filled') + scatter3(fstartxyz(nf,1),fstartxyz(nf,2),fstartxyz(nf,3),50,'r','filled') hold on scatter3(fendxyz(nf,1),fendxyz(nf,2),fendxyz(nf,3),50,'k','filled') %pause @@ -163,22 +171,32 @@ fendxyz(1,3) = (0); end title(['All flights start(r)/stop(b): ' batName ' ' dateSesh ' ' sessionType]); -xlabel('mm'); ylabel('mm'); zlabel('mm'); +% modify labels for tick marks +view(0,90) +xlim([-3000 3000]) +ylim([-3000 3000]) +xticks = get(gca,'xtick'); +yticks = get(gca,'ytick'); +newlabelsX = arrayfun(@(ax) sprintf('%g', ax/1000), xticks, 'un', 0); +newlabelsY = arrayfun(@(ay) sprintf('%g', ay/1000), yticks, 'un', 0); +set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +xlabel('m'); ylabel('m'); + hold off %try -%k means cluster of flight trajectories into nclusters +%% k means cluster of flight trajectories into nclusters %find pairs of start and endpoints with a high number of flights rng(2) %control random number generation try kstart = kmeans(fstartxyz,nclusters); catch - kstart = kmeans(fstartxyz,nclusters/2); + kstart = kmeans(fstartxyz,round(nclusters/2)); end rng(2) try kend = kmeans(fendxyz,nclusters); catch - kend = kmeans(fendxyz,nclusters/2); + kend = kmeans(fendxyz,round(nclusters/2)); end nflights = []; allflights = []; @@ -194,25 +212,36 @@ end [~, ssf] = sort(nflights,'descend'); %sort clustered flights -%plot clustered flights +%% plot clustered flights plotFlightPathsClusterEach = figure(); -jj = jet; +sgtitle(['Flight Clusters start(r)/stop(b): ' batName ' ' dateSesh ' ' sessionType]); +jj = jet(ntrajectories); for traj = 1 : 10 try if traj4.5)) = nan; -%plot flight paths of bat to feeder +%% plot flight paths of bat to feeder flightPathsToFeeder = figure(); CM = jet(length(LT)); flightToFeederEnd = zeros(length(LT),1); @@ -76,47 +80,79 @@ %try for i = 1:length(LT) flightToFeederEnd(i) = round(LT(i) * trackData.VideoFrameRate); - flightToFeederStart(i) = find(batSpeed(1:flightToFeederEnd(i))<1.5,1,'last'); %flightToFeederEnd(i) - (trackData.VideoFrameRate*preflightTime); %minus the preflight # of seconds + flightToFeederStart(i) = find(batSpeedMean(1:flightToFeederEnd(i))==0,1,'last'); %minus the preflight # of seconds flightToFeederEnd(i) - preFlightTime %scatter3(markerSet(flightStart:flightEnd,1,1),markerSet(flightStart:flightEnd,1,2),markerSet(flightStart:flightEnd,1,3)) - plot3(mx(flightToFeederStart(i):flightToFeederEnd(i)),my(flightToFeederStart(i):flightToFeederEnd(i)),mz(flightToFeederStart(i):flightToFeederEnd(i)),'LineWidth',2,'color',CM(i,:)) + plot3(mxFull(flightToFeederStart(i):flightToFeederEnd(i)),myFull(flightToFeederStart(i):flightToFeederEnd(i)),mzFull(flightToFeederStart(i):flightToFeederEnd(i)),'LineWidth',2,'color',CM(i,:)) hold on %get start/stop xyz position of the flights to feeders - fFeedStartxyz(i,1) = round(nanmean(mx(flightToFeederStart(i):flightToFeederStart(i)+trackData.VideoFrameRate/2))); - fFeedStartxyz(i,2) = round(nanmean(my(flightToFeederStart(i):flightToFeederStart(i)+trackData.VideoFrameRate/2))); - fFeedStartxyz(i,3) = round(nanmean(mz(flightToFeederStart(i):flightToFeederStart(i)+trackData.VideoFrameRate/2))); + fFeedStartxyz(i,1) = round(nanmean(mxFull(flightToFeederStart(i):flightToFeederStart(i))));%+trackData.VideoFrameRate/4))); + fFeedStartxyz(i,2) = round(nanmean(myFull(flightToFeederStart(i):flightToFeederStart(i))));%+trackData.VideoFrameRate/4))); + fFeedStartxyz(i,3) = round(nanmean(mzFull(flightToFeederStart(i):flightToFeederStart(i))));%+trackData.VideoFrameRate/4))); - fFeedEndxyz(i,1) = round(nanmean(mx(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); - fFeedEndxyz(i,2) = round(nanmean(my(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); - fFeedEndxyz(i,3) = round(nanmean(mz(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); + fFeedEndxyz(i,1) = round(nanmean(mxFull(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); + fFeedEndxyz(i,2) = round(nanmean(myFull(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); + fFeedEndxyz(i,3) = round(nanmean(mzFull(flightToFeederEnd(i):flightToFeederEnd(i)+trackData.VideoFrameRate/2))); - %scatter3(fFeedStartxyz(i,1),fFeedStartxyz(i,2),fFeedStartxyz(i,3),100,'r','filled') + scatter3(fFeedStartxyz(i,1),fFeedStartxyz(i,2),fFeedStartxyz(i,3),50,'r','filled') hold on - scatter3(fFeedEndxyz(i,1),fFeedEndxyz(i,2),fFeedEndxyz(i,3),100,'k','filled') + scatter3(fFeedEndxyz(i,1),fFeedEndxyz(i,2),fFeedEndxyz(i,3),50,'k','filled') end title(['Flights to feeder: ' batName ' ' dateSesh ' ' sessionType]); -xlabel('mm'); ylabel('mm'); zlabel('mm'); +% % modify labels for tick marks +view(0,90); +xlim([-3000 3000]); +ylim([-3000 3000]); +xticks = get(gca,'xtick'); +yticks = get(gca,'ytick'); +newlabelsX = arrayfun(@(ax) sprintf('%g', ax/1000), xticks, 'un', 0); +newlabelsY = arrayfun(@(ay) sprintf('%g', ay/1000), yticks, 'un', 0); +set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); +xlabel('m'); ylabel('m'); hold off -%plot flight paths of bat from feeder +%% plot flight paths of bat from feeder flightFromFeederEnd = zeros(length(LT)); flightFromFeederStart = zeros(length(LT)); flightPathsFromFeeder = figure(); for i = 1:length(LT) - flightFromFeederStart(i) = round(LT(i) * trackData.VideoFrameRate); - flightFromFeederEnd(i) = flightFromFeederStart(i) + delay + (trackData.VideoFrameRate*preflightTime); + flightFromFeederMid(i) = find(batSpeedFilt(flightToFeederEnd(i):end)>3,1); %minus the preflight # of seconds flightToFeederEnd(i) - preFlightTime + %flightFromFeederStart(i) = round(LT(i) * trackData.VideoFrameRate); + flightFromFeederEnd(i) = flightToFeederEnd(i) + flightFromFeederMid(i) + find(batSpeedMean(flightToFeederEnd(i)+flightFromFeederMid(i):end)==0,1); + %flightFromFeederEnd(i) = flightFromFeederStart(i) + delay + (trackData.VideoFrameRate*preflightTime); %check that the end of the flight does not occur after session finishes - if flightFromFeederEnd(i) > length(mx) - flightFromFeederEnd(i) = length(mx) + if flightFromFeederEnd(i) > length(mxFull) + flightFromFeederEnd(i) = length(mxFull) end - plot3(mx(flightFromFeederStart(i):flightFromFeederEnd(i)),my(flightFromFeederStart(i):flightFromFeederEnd(i)),mz(flightFromFeederStart(i):flightFromFeederEnd(i)),'LineWidth',2,'color',CM(i,:)) + plot3(mxFull(flightToFeederEnd(i):flightFromFeederEnd(i)),myFull(flightToFeederEnd(i):flightFromFeederEnd(i)),mzFull(flightToFeederEnd(i):flightFromFeederEnd(i)),'LineWidth',2,'color',CM(i,:)) hold on + %get start/stop xyz position of the flights to feeders + %fLeaveStartxyz(i,1) = round(nanmean(mxFull(flightFromFeederStart(i):flightFromFeederStart(i)+trackData.VideoFrameRate/4))); + %fLeaveStartxyz(i,2) = round(nanmean(myFull(flightFromFeederStart(i):flightFromFeederStart(i)+trackData.VideoFrameRate/4))); + %fLeaveStartxyz(i,3) = round(nanmean(mzFull(flightFromFeederStart(i):flightFromFeederStart(i)+trackData.VideoFrameRate/4))); + + fLeaveEndxyz(i,1) = round(nanmean(mxFull(flightFromFeederEnd(i):flightFromFeederEnd(i))));%+trackData.VideoFrameRate/2))); + fLeaveEndxyz(i,2) = round(nanmean(myFull(flightFromFeederEnd(i):flightFromFeederEnd(i))));%+trackData.VideoFrameRate/2))); + fLeaveEndxyz(i,3) = round(nanmean(mzFull(flightFromFeederEnd(i):flightFromFeederEnd(i))));%+trackData.VideoFrameRate/2))); + + scatter3(fFeedEndxyz(i,1),fFeedEndxyz(i,2),fFeedEndxyz(i,3),50,'r','filled') + hold on + scatter3(fLeaveEndxyz(i,1),fLeaveEndxyz(i,2),fLeaveEndxyz(i,3),50,'k','filled') %pause(0.1) end title(['Flights from feeder: ' batName ' ' dateSesh ' ' sessionType]); -xlabel('mm'); ylabel('mm'); zlabel('mm'); -hold off + % % modify labels for tick marks + view(0,90); + xlim([-3000 3000]); + ylim([-3000 3000]); + xticks = get(gca,'xtick'); + yticks = get(gca,'ytick'); + newlabelsX = arrayfun(@(ax) sprintf('%g', ax/1000), xticks, 'un', 0); + newlabelsY = arrayfun(@(ay) sprintf('%g', ay/1000), yticks, 'un', 0); + set(gca,'xticklabel',newlabelsX,'yticklabel',newlabelsY); + xlabel('m'); ylabel('m'); + hold off -%k means cluster of flight trajectories into nclusters +%% k means cluster of flight trajectories into nclusters %find pairs of start and endpoints with a high number of flights rng(2) %control random number generation @@ -144,23 +180,31 @@ [~, ssf] = sort(nflights,'descend'); %sort clustered flights -%plot clustered flights individually by each cluster +%% plot clustered flights individually by each cluster flightPathsClusterToFeederEach = figure(); -jj = jet; +jj = jet(ntrajectories); for traj = 1 : 10 try if traj 30); +x_flying = x_spl; x_flying(:,[nonflying toofast]) = nan; +batspeed = v_abs; batspeed([nonflying; toofast]) = nan; +bflying=~isnan(batspeed)'; %vector of 1s when the bat is flying + +% For each sample, sum up the next 1s of data(flights are longer than 1s),Code from Nick D. +allsums = []; +for bf = 1 : size(bflying,1)-tracking_Fs + allsums(bf) = sum(bflying(bf:bf+tracking_Fs)); +end + +% Detect flight starts and stops +[R,rLT,rUT,rLL,rUL] = risetime(allsums); flight_starts = round(rLT+tracking_Fs/2); +[F,fLT,fUT,fLL,fUL] = falltime(allsums); flight_ends = round(fLT+tracking_Fs/2); %... +Fs is a sistematic correction, useful +num_flights = size(R,2); +ref = ones(size(flight_starts)); +avg_flight_time = mean((flight_ends-flight_starts)./tracking_Fs); + +%% Plot results + +% Plot sampling interval counts +if analyze_Ca + figure(); + hist(img_sampling); set(gca, 'YScale', 'log'); ylabel('counts'); xlabel('interframe(s)'); +end + +% Plot 2D flight trajectories +figure(); set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +subplot(1,2,1); +plot(x_mean(1,:),x_mean(2,:),'.'); +hold on; rectangle('Position',[xL yB xR-xL yF-yB]); +scatter([F3(1) F4(1)],[F3(2) F4(2)],'filled'); hold off; +xlim([-3 3]); ylim([-3 3]); zlim([0 2.5]); + +subplot(1,2,2); +plot(x_spl(1,:),x_spl(2,:)); hold on; plot(x_mean(1,:),x_mean(2,:),'.','MarkerSize',1); +rectangle('Position',[xL yB xR-xL yF-yB]); hold off; +xlim([-3 3]); ylim([-3 3]); zlim([0 2.5]); + +% Plot session timeline +figure(); set(gcf, 'units','normalized','outerposition',[0 0 1 1]); +ax1 = subplot(3,1,1); plot(t,x_mean(1,:),'.'); hold on; +plot(new_t,x_spl(1,:),'--'); refline(0,F3(1)); hold off; +legend('cluster/mean','spl'); ylabel('x (m)'); +ax2 = subplot(3,1,2); plot(new_t,v_abs,'.'); +hold on; stem(new_t(flight_starts),ref); stem(new_t(flight_ends),ref); hold off; +ylabel('v (m/s)'); +ax3 = subplot(3,1,3); plot(t,rew_signal); +ylabel('Rewards'); +linkaxes([ax1,ax2,ax3],'x'); xlabel('Samples'); + +%% Clustering flights +%Cut out flights, downsample to ds_clus positions per flight +all_flights = NaN(3,max(flight_ends-flight_starts),num_flights); %3D matrix with all flights +all_flights_ds = NaN(3,ds_clus,num_flights); %3D matrix with all flights(downsampled) + +for nf = 1 : size(all_flights,3) + trajectory = x_spl(:,flight_starts(nf):flight_ends(nf)); + velocity = v_abs(:,flight_starts(nf):flight_ends(nf)); + all_flights(:,1:(flight_ends(nf)-flight_starts(nf))+1,nf) = trajectory; + all_flights_vel(1,1:(flight_ends(nf)-flight_starts(nf)+1),nf) = velocity; + all_flights_ds(:,:,nf) = interp1(linspace(1,3,size(trajectory,2)),trajectory',linspace(1,3,ds_clus),'spline')'; + + % %Uncomment if you want to see how the downsampled flights look like + % plot3(all_flights(1,:,nf),all_flights(2,:,nf),all_flights(3,:,nf),'Color','b'); + % hold on; + % plot3(all_flights_ds(1,:,nf),all_flights_ds(2,:,nf),all_flights_ds(3,:,nf),'Color','r'); + % hold off; + % w = waitforbuttonpress; +end + +% Define X matrix of features for clustering (downsampled coordinates, stacked together) +X = [all_flights_ds(1,:,:), all_flights_ds(2,:,:), all_flights_ds(3,:,:)]; +X = reshape(X,3*size(all_flights_ds,2),size(R,2)); +X = X'; %so then X = #flights x #features + +% If dimensionality reduction is needed +if pca_features + [coeff,score,latent] = pca(X); X = score(:,1:5); +end + +% k-means or hierarchical clustering (with euclidean distance and shortest linkage) +if k_means + n_clusters = 15; idx = kmeans(X,n_clusters); +else + figure(); + Y = pdist(X,'euclidean'); Z = linkage(Y); + hLines = dendrogram(Z,0); hold on; refline(0,dist); hold off; + idx = cluster(Z,'Cutoff',dist,'Criterion','distance'); + title([num2str(length(unique(idx))) ' clusters']); + ylim([0 10]); +end + +% Create structure with flight start stop frames, id of the trajectory +clear flight; +flight.strt_frame = ceil(flight_starts)'; +flight.stop_frame = ceil(flight_ends)'; +flight.pos = all_flights; +flight.vel = all_flights_vel; +flight.id = idx; +flight.Fs = tracking_Fs; + +% Sort structure according to cluster id +clear flight_sorted; +[flight_sorted.id,I] = sort(flight.id); +flight_sorted.strt_frame = flight.strt_frame(I); +flight_sorted.stop_frame = flight.stop_frame(I); +flight_sorted.pos = flight.pos(:,:,I); +flight_sorted.vel = flight.vel(:,:,I); +flight_sorted.Fs = flight.Fs; +flight_sorted.N = size(flight_sorted.id,1); + +% Assign isolated clusters to cluster #flights+1 +[Ns,b] = histc(flight_sorted.id,unique(flight_sorted.id)); +flight_sorted.id(Ns(b) Uses a linear chordal +% approximation to compute the arc length. +% This method is the most efficient. +% +% method == 'pchip' --> Fits a parametric pchip +% approximation, then integrates the +% segments numerically. +% +% method == 'spline' --> Uses a parametric spline +% approximation to fit the curves, then +% integrates the segments numerically. +% Generally for a smooth curve, this +% method may be most accurate. +% +% DEFAULT: 'linear' +% +% +% arguments: (output) +% arclen - scalar total arclength of all curve segments +% +% seglen - arclength of each independent curve segment +% there will be n-1 segments for which the +% arc length will be computed. +% +% +% Example: +% % Compute the length of the perimeter of a unit circle +% theta = linspace(0,2*pi,10); +% x = cos(theta); +% y = sin(theta); +% +% % The exact value is +% 2*pi +% % ans = +% % 6.28318530717959 +% +% % linear chord lengths +% arclen = arclength(x,y,'l') +% % arclen = +% % 6.1564 +% +% % Integrated pchip curve fit +% arclen = arclength(x,y,'p') +% % arclen = +% % 6.2782 +% +% % Integrated spline fit +% arclen = arclength(x,y,'s') +% % arclen = +% % 6.2856 +% +% Example: +% % A (linear) space curve in 5 dimensions +% x = 0:.25:1; +% y = x; +% z = x; +% u = x; +% v = x; +% +% % The length of this curve is simply sqrt(5) +% % since the "curve" is merely the diagonal of a +% % unit 5 dimensional hyper-cube. +% [arclen,seglen] = arclength(x,y,z,u,v,'l') +% % arclen = +% % 2.23606797749979 +% % seglen = +% % 0.559016994374947 +% % 0.559016994374947 +% % 0.559016994374947 +% % 0.559016994374947 +% +% +% See also: interparc, spline, pchip, interp1 +% +% Author: John D'Errico +% e-mail: woodchips@rochester.rr.com +% Release: 1.0 +% Release date: 3/10/2010 + +% unpack the arguments and check for errors +if nargin < 2 + error('ARCLENGTH:insufficientarguments', ... + 'at least px and py must be supplied') +end + +n = length(px); +% are px and py both vectors of the same length? +if ~isvector(px) || ~isvector(py) || (length(py) ~= n) + error('ARCLENGTH:improperpxorpy', ... + 'px and py must be vectors of the same length') +elseif n < 2 + error('ARCLENGTH:improperpxorpy', ... + 'px and py must be vectors of length at least 2') +end + +% compile the curve into one array +data = [px(:),py(:)]; + +% defaults for method and tol +method = 'linear'; + +% which other arguments are included in varargin? +if numel(varargin) > 0 + % at least one other argument was supplied + for i = 1:numel(varargin) + arg = varargin{i}; + if ischar(arg) + % it must be the method + validmethods = {'linear' 'pchip' 'spline'}; + ind = strmatch(lower(arg),validmethods); + if isempty(ind) || (length(ind) > 1) + error('ARCLENGTH:invalidmethod', ... + 'Invalid method indicated. Only ''linear'',''pchip'',''spline'' allowed.') + end + method = validmethods{ind}; + + else + % it must be pz, defining a space curve in higher dimensions + if numel(arg) ~= n + error('ARCLENGTH:inconsistentpz', ... + 'pz was supplied, but is inconsistent in size with px and py') + end + + % expand the data array to be a 3-d space curve + data = [data,arg(:)]; %#ok + end + end + +end + +% what dimension do we live in? +nd = size(data,2); + +% compute the chordal linear arclengths +seglen = sqrt(sum(diff(data,[],1).^2,2)); +arclen = sum(seglen); + +% we can quit if the method was 'linear'. +if strcmpi(method,'linear') + % we are now done. just exit + return +end + +% 'spline' or 'pchip' must have been indicated, +% so we will be doing an integration. Save the +% linear chord lengths for later use. +chordlen = seglen; + +% compute the splines +spl = cell(1,nd); +spld = spl; +diffarray = [3 0 0;0 2 0;0 0 1;0 0 0]; +for i = 1:nd + switch method + case 'pchip' + spl{i} = pchip([0;cumsum(chordlen)],data(:,i)); + case 'spline' + spl{i} = spline([0;cumsum(chordlen)],data(:,i)); + nc = numel(spl{i}.coefs); + if nc < 4 + % just pretend it has cubic segments + spl{i}.coefs = [zeros(1,4-nc),spl{i}.coefs]; + spl{i}.order = 4; + end + end + + % and now differentiate them + xp = spl{i}; + xp.coefs = xp.coefs*diffarray; + xp.order = 3; + spld{i} = xp; +end + +% numerical integration along the curve +polyarray = zeros(nd,3); +for i = 1:spl{1}.pieces + % extract polynomials for the derivatives + for j = 1:nd + polyarray(j,:) = spld{j}.coefs(i,:); + end + + % integrate the arclength for the i'th segment + % using quadgk for the integral. I could have + % done this part with an ode solver too. + seglen(i) = quadgk(@(t) segkernel(t),0,chordlen(i)); +end + +% and sum the segments +arclen = sum(seglen); + +% ========================== +% end main function +% ========================== +% begin nested functions +% ========================== + function val = segkernel(t) + % sqrt((dx/dt)^2 + (dy/dt)^2) + + val = zeros(size(t)); + for k = 1:nd + val = val + polyval(polyarray(k,:),t).^2; + end + val = sqrt(val); + + end % function segkernel + +end % function arclength + + + diff --git a/behavior/strava_tracking.m b/behavior/strava_tracking.m new file mode 100644 index 0000000..8b73511 --- /dev/null +++ b/behavior/strava_tracking.m @@ -0,0 +1,14 @@ +fileList = dir('*.gpx'); +colors = jet(length(fileList)); +webmap('openstreetmap') +for track_i = 1:length(fileList) +tracks(track_i) = gpxread(fileList(track_i).name, 'Index', 1:2); +wmline(tracks(track_i), 'Color', colors(track_i,:)) +%fprintf(fileList(track_i).name) +pause +end +%wmline(tracks, 'Color', colors(track_i,:)) + +%webmap('openstreetmap') +%colors = {'cyan'}; +%wmline(tracks, 'Color', colors) \ No newline at end of file diff --git a/cnmfe/.DS_Store b/cnmfe/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/cnmfe/.DS_Store differ diff --git a/cnmfe/ImBat_START.m b/cnmfe/ImBat_START.m index 9e0332e..7bfc785 100644 --- a/cnmfe/ImBat_START.m +++ b/cnmfe/ImBat_START.m @@ -166,10 +166,10 @@ function ImBat_START(varargin) if ROI_flag ==1; disp('extracting ROIs...') nam = './Motion_corrected_Data.mat' - try + %try CNMFe_extract2(nam,'metadata',metadata); - catch - end + %catch + %end diff --git a/extract_data/.DS_Store b/extract_data/.DS_Store new file mode 100644 index 0000000..68159db Binary files /dev/null and b/extract_data/.DS_Store differ diff --git a/extract_data/FS_AV_Parse_batch_extractMac.m b/extract_data/FS_AV_Parse_batch_extractMac.m new file mode 100644 index 0000000..06c0fe7 --- /dev/null +++ b/extract_data/FS_AV_Parse_batch_extractMac.m @@ -0,0 +1,254 @@ +function FS_AV_Parse_batch_extractMac(DIR,varargin) +% FS_AV_Parse + +% Parse Data from FreedomScopes +% Created: 2015/08/02 +% By: WALIII +% Updated: 2019/05/02 % added better wireless and large file handeling +% By: WALIII + +% FS_AV_parse will do several things: +% +% 1. Seperate Audio and Video, and place them into .mat files in a .mat +% directory +% 2. Make spectrogram .gif files for extracted audio, for perusing +% manually. +% 3. Uses the dependancy extractmedia(), an amazing script created by Nathan Perkins + +% Run in the Directory of the .mov files. FS_AVparse should be run first: +% FS_AVparse-->FS_TemplateMatch-->FS_FS_Plot_ROI--> BatchDff2----> FS_Image_ROI--> FS_FS_Plot_ROI + +macFlag = 0; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'macflag' + macFlag=varargin{i+1}; + end +end + +mat_dir=[pwd,'/mat']; +gif_dir=[pwd,'/gif']; +error_dir =[pwd,'/error']; +plot_spectrogram =0; +% resize_factor = 0.25; +frames_per_file = 100; +aspect_update =0; + + + +if exist(mat_dir,'dir') rmdir(mat_dir,'s'); end +if exist(gif_dir,'dir') rmdir(gif_dir,'s'); end +% if exist(error_dir,'dir') rmdir(error_dir,'s'); end + +mkdir(mat_dir); +mkdir(gif_dir); +mkdir(error_dir); + + + + +outlier_flag=0; +if nargin<1 | isempty(DIR), DIR=pwd; end + +mov_listing=dir(fullfile(DIR,'*.mov')); +mov_listing={mov_listing(:).name}; + + + +filenames=mov_listing; + + +disp('Parsing Audio and Video files'); + +[nblanks formatstring]=fb_progressbar(100); +fprintf(1,['Progress: ' blanks(nblanks)]); + +for i=1:length(mov_listing) +clear file + [path,file,ext]=fileparts(filenames{i}); + fprintf(1,formatstring,round((i/length(mov_listing))*100)); + FILE = fullfile(DIR,mov_listing{i}) + if macFlag == 1 + fileName = extractAfter(FILE,[DIR '/']); + batName = extractBefore(fileName,'_'); + dateSesh = extractAfter(fileName, [batName '_']); + processedDir = ['/Users/imbat_mini/Desktop/flight_data/extraction_processing/extracted_scopeTracking/' batName(1:2) dateSesh(1:6)]; + if ~exist(processedDir) + mkdir(processedDir) + end + mkdir([processedDir filesep file '_extraction']); + + end + mkdir([mat_dir,'/',file,'_extraction']); + + file = [file,'_extraction/',file]; + +% Break into many smaller filles: + file_info = VideoReader(FILE); + + vtimes = 0:frames_per_file:file_info.Duration; + vtimes = cat(2,vtimes,file_info.Duration); + + +for iii = 1:size(vtimes,2)-1; + + try +[a_ts, a, v_ts, v] = extractmedia(FILE,vtimes(iii),vtimes(iii+1)); + +% Format VIDEO DATA +[video.height, video.width, video.channels] = size(v{1}); + +if video.height/video.width == 9/16; + aspect_update =1; + % calculate resize factor +resize_factor = video.height/240; +resize_factor = 1/resize_factor; +video.resize_factor = resize_factor; +resize_factor = 0.5; % this is the true resize + +else +aspect_update =0; +% calculate resize factor +resize_factor = video.height/240; +resize_factor = 1/resize_factor; +video.resize_factor = resize_factor; +end + +for ii = 1: size(v,1) + %video.frames(:,:,:,ii) = v{ii}-(noise(ii,:)-min(noise(30:end,:))); + temp = v{ii}; %-(noise(ii,:)-min(noise(30:end))); + temp = squeeze(mean(temp,3)); + + if aspect_update == 1; % update to the proper + temp = imresize(temp,[480 640]); + end + video.frames(:,:,ii) = imresize(temp,resize_factor); + + v{ii} = []; % empty the buffer + temp = []; +end + + catch + disp(' No audio found in file'); + v1 = VideoReader(FILE); + k = 1; + while hasFrame(v1) + temp = readFrame(v1); + if k ==1; + % Format VIDEO DATA + [video.height, video.width, video.channels] = size(temp); + + + + +if video.height/video.width == 9/16; + aspect_update =1; + % calculate resize factor +resize_factor = video.height/240; +resize_factor = 1/resize_factor; +video.resize_factor = resize_factor; +resize_factor = 0.5; % this is the true resize + +else +aspect_update =0; +% calculate resize factor +resize_factor = video.height/240; +resize_factor = 1/resize_factor; +video.resize_factor = resize_factor; +end + + + + end + temp = squeeze(mean(temp,3)); + temp = imresize(temp,video.resize_factor); + video.frames(:,:,k) = temp; + k = k+1; + end + a = 0; + a_ts = 0; + v_ts = 0; + clear k V1; + end + + + +video.times = v_ts;% 0.1703*(day-1); + +video.nrFramesTotal = size(video.frames,3); +video.FrameRate = 1/mean(diff(v_ts)); + + + +% filtering video: +% disp('remove artifacts'); +% video.frames = ImBat_denoise(video.frames); +if macFlag ==1 + fname = [processedDir,'/',file,'_',sprintf('%03d', iii), '.tif']; + +else + fname = [mat_dir,'/',file,'_',sprintf('%03d', iii), '.tif']; +end +FS_tiff(video.frames,'fname',fname); + +%dont save video.frames ( its already a tif... +video.frames = []; + +try +disp('Performing Gain correction') +noise = squeeze(mean(mean(squeeze(video.frames(:,[1:30, video.height-30:video.height],3,:)),1),2)); % blue channel +noise2 = squeeze(mean(mean(squeeze(video.frames([1:30 video.width-30:video.width],:,3,:)),1),2)); % blue channel +noise = (noise+noise2)/2; +% sig = squeeze(est(:,:,2,:)); % green channel +% sig = (squeeze(mean(mean(sig(:,1:80,:),1)))); +video.gain = noise; +clear noise; +clear est; +catch + video.gain = []; +end + + +% Format AUDIO DATA +audio.nrChannels = size(a,2); +audio.bits = 16; +audio.nrFrames = length(a); +audio.data = double(a); +audio.rate = 48000; +audio.TotalDurration = audio.nrFrames/48000; +audio.times = a_ts; +mic_data = double(a); +fs = 48000; + + + +if plot_spectrogram ==1; + [b,a]=ellip(5,.2,80,[500]/(fs/2),'high'); + plot_data=mic_data./abs(max(mic_data)); + try + [s,f,t]=fb_pretty_sonogram(filtfilt(b,a,mic_data./abs(max(mic_data))),fs,'low',2.5,'zeropad',0); + + + minpt=1; + maxpt=min(find(f>=10e3)); + + imwrite(flipdim(uint8(s(minpt:maxpt,:)),1),hot,fullfile(gif_dir,[file '.gif']),'gif'); + catch + disp('no audio... skipping spectrogram'); + end +end +if macFlag ==1 + save(fullfile(processedDir,[file,'_',sprintf('%03d', iii), '.mat']),'audio','video','-v7.3'); +else + save(fullfile(mat_dir,[file,'_',sprintf('%03d', iii), '.mat']),'audio','video','-v7.3'); +end + % clear the buffer +clear video audio a_ts a v_ts v; +aspect_update = 0; +end +end +fprintf(1,'\n'); +%% \ No newline at end of file diff --git a/extract_data/ROIselection_pearsonCorr.m b/extract_data/ROIselection_pearsonCorr.m new file mode 100644 index 0000000..205a4f6 --- /dev/null +++ b/extract_data/ROIselection_pearsonCorr.m @@ -0,0 +1,246 @@ +function [cellsPearsonCorr,goodCellIdx] = ROIselection_pearsonCorr(snakeTrace,goodCellIdx,varargin) + +traceData = snakeTrace.tracePreFlightPost; %which data stream to use? +batName = snakeTrace.batName; +dateSesh = snakeTrace.dateSesh; +sessionType = snakeTrace.sessionType; +saveFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +highCorrThresh = 0.5; %threshold for which cells are deemed to be high correlation to use for analyses +plotOddEvenAllFlag = 1; +plotHighCorrFlag = 1; +plotHeatMapFlag = 1; + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'saveflag' + saveFlag = varargin{i+1}; + end +end +%% calculate the mean neural traces for odd and even flights (& normalize) + +%initialize the variables for odd and even flights +meanTraceFlightOdd = zeros(length(traceData{2}(1,1,:)),length(traceData{2}(1,:,1))); +meanTraceFlightEven = zeros(length(traceData{2}(1,1,:)),length(traceData{2}(1,:,1))); +normMeanTraceFlightOdd = zeros(length(traceData{2}(1,1,:)),length(traceData{2}(1,:,1))); +normMeanTraceFlightEven = zeros(length(traceData{2}(1,1,:)),length(traceData{2}(1,:,1))); +traceFlightOdd = zeros(floor(length(traceData{2}(:,1,1))/2),length(traceData{2}(1,:,1)),length(traceData{2}(1,1,:))); +traceFlightEven = zeros(floor(length(traceData{2}(:,1,1))/2),length(traceData{2}(1,:,1)),length(traceData{2}(1,1,:))); +for cell_i = goodCellIdx.goodCellIndex%length(traceData{2}(1,1,:)) + %build vector of odd flights for each cell + for flight_i = 1:2:length(traceData{2}(:,1,1)) + traceFlightOdd(flight_i,:,cell_i) = traceData{2}(flight_i,:,cell_i); + %traceFlightOdd(flight_i,:,cell_i) = traceFlightOdd(flight_i,:,cell_i) - abs(min(traceData{2}(flight_i,:,cell_i))); + end + %build vector of even flights for each cell + for flight_i = 2:2:length(traceData{2}(:,1,1)) + traceFlightEven(flight_i,:,cell_i) = traceData{2}(flight_i,:,cell_i); + %traceFlightEven(flight_i,:,cell_i) = traceFlightEven(flight_i,:,cell_i) - abs(min(traceData{2}(flight_i,:,cell_i))); + end + %calculate the means for all the odd/even flights and normalize these traces + meanTraceFlightOdd(cell_i,:) = mean(traceFlightOdd(1:2:end,:,cell_i),1); + meanTraceFlightEven(cell_i,:) = mean(traceFlightEven(2:2:end,:,cell_i),1); + normMeanTraceFlightOdd(cell_i,:) = zscore(meanTraceFlightOdd(cell_i,:)); + normMeanTraceFlightOdd(cell_i,:) = normMeanTraceFlightOdd(cell_i,:) - min(normMeanTraceFlightOdd(cell_i,:)); + normMeanTraceFlightEven(cell_i,:) = zscore(meanTraceFlightEven(cell_i,:)); + normMeanTraceFlightEven(cell_i,:) = normMeanTraceFlightEven(cell_i,:) - min(normMeanTraceFlightEven(cell_i,:)); +end +%perform pearson correlation of the odd vs even flights +[rho,pval] = corr(meanTraceFlightOdd',meanTraceFlightEven'); + +%plot the histogram of all cells vs all cells correlation +histPearsonCorr = figure(); +histogram(rho); +p1=subplot(2,1,1); +histogram(rho); +title('Pearson Corr: odd vs even trials, all neurons (r)'); +p2=subplot(2,1,2); +histogram(pval); +title('Pearson Corr: odd vs even trials, all neurons (pval)'); +sgtitle([snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + +%build the vector of the r and pval for only the cell-to-cell correlations +for cell_i = 1:length(rho(1,:)) + pairRho(cell_i) = rho(cell_i,cell_i); + pairPval(cell_i) = pval(cell_i,cell_i); +end +%plot the histogram of paired correlation values +histPairedCorr = figure(); +p1=subplot(2,1,1); +histogram(pairRho,10); +title('Pearson Corr Odd vs Even Trials (r)'); +p2=subplot(2,1,2); +histogram(pairPval); +title('Pearson Corr Odd vs Even Trials (pval)'); +sgtitle([snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + +if saveFlag ==1 + if ~exist([pwd,'/PearsonCorr'])>0; + + mkdir('PearsonCorr'); + end + % Save 'each cell' as jpg and fig files.. + set(findall(histPairedCorr,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.tif']); + savefig(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.fig']); + saveas(gcf, [pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.svg']); + set(findall(histPearsonCorr,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.tif']); + savefig(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.fig']); + saveas(gcf, [pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_hist_PearsonCorr_pairedCells30sec.svg']); + + +end +%% plot the means and norm means for all the cells along with the pearson corrs +if plotOddEvenAllFlag ==1 + plotOddEvenFlights = figure('units','normalized','outerposition',[0 0 1 0.5]); + for cell_i = goodCellIdx.goodCellIndex%length(traceData{2}(1,1,:)) + %plot all of the odd traces in left figure + p1 = subplot(1,3,1); + for flight_i = 1:2:length(traceData{2}(:,1,1)) + plot(traceFlightOdd(flight_i,:,cell_i)); + hold on; + end + title(['Odd flights: ROI# ' num2str(cell_i)]); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('df/f'); + %plot all of the even traces in right figure + p2 = subplot(1,3,2); + for flight_i = 2:2:length(traceData{2}(:,1,1)) + plot(traceFlightEven(flight_i,:,cell_i)); + hold on; + end + title(['Even flights: ROI# ' num2str(cell_i)]); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('df/f'); + %plot the mean traces for odd and even in same plot +normalized + p3 = subplot(1,3,3); + plot(meanTraceFlightOdd(cell_i,:),'Color','r'); + hold on + plot(meanTraceFlightEven(cell_i,:),'Color','b'); + plot(normMeanTraceFlightOdd(cell_i,:),'Color','g'); + plot(normMeanTraceFlightEven(cell_i,:),'Color','k'); + legend('Odd','Even','Norm Odd','Norm Even'); + title(['Means of odd and even flights: ROI# ' num2str(cell_i)]); + ylim=get(gca,'ylim'); + xlim=get(gca,'xlim'); + text(xlim(1)+0.05*xlim(2),ylim(1)+0.07*ylim(2),{['r= ' num2str(pairRho(cell_i))];['pval =' num2str(pairPval(cell_i))]}); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('df/f'); + sgtitle([snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + + if saveFlag ==1 + if ~exist([pwd,'/PearsonCorr'])>0 + + mkdir('PearsonCorr'); + end + % Save 'each cell' as jpg and fig files.. + %set(findall(gcf,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_PearsonCorr30sec-' num2str(cell_i) '.tif']); + savefig(gcf,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_PearsonCorr30sec-' num2str(cell_i) '.fig']); + saveas(gcf, [pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_PearsonCorr30sec-' num2str(cell_i) '.svg']); + else + pause + end + clf; + end + close(plotOddEvenFlights) +end +%% plot the mean and normalized odd/even traces for cells above high correlation threshold +if plotHighCorrFlag ==1 + %initialize the variables to store the indices of high and low correlation cells + highCorrIndex = []; + lowCorrIndex = []; + + plotHighCorr = figure(); + for cell_i = 1:length(rho(1,:)) + if pairRho(cell_i)>=highCorrThresh + highCorrIndex = [highCorrIndex cell_i]; + plot(meanTraceFlightOdd(cell_i,:),'Color','r'); + hold on + plot(meanTraceFlightEven(cell_i,:),'Color','b'); + plot(normMeanTraceFlightOdd(cell_i,:),'Color','g'); + plot(normMeanTraceFlightEven(cell_i,:),'Color','k'); + legend('Odd','Even','Norm Odd','Norm Even'); + title([snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType ': High Corr odd and even flights: ROI# ' num2str(cell_i)]); + ylim=get(gca,'ylim'); + xlim=get(gca,'xlim') + text(xlim(1)+0.05*xlim(2),ylim(1)+0.07*ylim(2),{['r= ' num2str(pairRho(cell_i))];['pval =' num2str(pairPval(cell_i))]}); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + ylabel('df/f'); + + if saveFlag ==1 + if ~exist([pwd,'/PearsonCorr/highCorr_cells'])>0 + mkdir([pwd,'/PearsonCorr/highCorr_cells']); + end + % Save 'each cell' as jpg and fig files.. + %set(findall(gcf,'-property','FontSize'),'FontSize',20); + saveas(gcf,[pwd '/PearsonCorr/highCorr_cells/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_highCorr30sec-' num2str(cell_i) '.tif']); + savefig(gcf,[pwd '/PearsonCorr/highCorr_cells/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_highCorr30sec-' num2str(cell_i) '.fig']); + saveas(gcf, [pwd '/PearsonCorr/highCorr_cells/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_meanTrace_oddEven_highCorr30sec-' num2str(cell_i) '.svg']); + else + pause + end + clf + elseif pairRho(cell_i)0 + mkdir('PearsonCorr'); + end + % Save 'each cell' as jpg and fig files.. + %set(findall(gcf,'-property','FontSize'),'FontSize',20); + saveas(oddSortedHeatMap,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_oddSortedHeatMap30sec.tif']); + savefig(oddSortedHeatMap,[pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_oddSortedHeatMap30sec.fig']); + saveas(oddSortedHeatMap, [pwd '/PearsonCorr/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_oddSortedHeatMap30sec.svg']); +end +end diff --git a/extract_data/copy_recentExtraction.m b/extract_data/copy_recentExtraction.m new file mode 100644 index 0000000..772ac10 --- /dev/null +++ b/extract_data/copy_recentExtraction.m @@ -0,0 +1,54 @@ +dirBats = dir('z*'); +%dirZbats = dir('z*'); +homeDir = pwd; +saveDir = 'F:\flight\topQualityData\copydir'; + for bat_i = 1%:length(dirBats) + cd(dirBats(bat_i).name); + batDir = pwd; + dirBatDays = dir([dirBats(bat_i).name(1:2) '*']); + for day_i = 1:length(dirBatDays) + cd([dirBatDays(day_i).name filesep 'extracted']); + dayDir = pwd; + + %find and copy over tracking files + dirTracking = dir('*_track.mat'); + for track_i = 1:length(dirTracking) + sourceTracking = fullfile(dayDir,dirTracking(track_i).name); + destTracking = [saveDir filesep dirBats(bat_i).name filesep dirBatDays(day_i).name filesep 'extracted' filesep]; + if ~exist(destTracking) + mkdir(destTracking) + end + %copyfile(sourceTracking,destTracking); + end + + %find analysis and processed dirs and copy + dirBatSessions = dir('*_extraction'); + %dirBatSessions = dir([dirBats(bat_i).name(1:2) '*_extraction']); + for session_i = 1:length(dirBatSessions) + cd([dirBatSessions(session_i).name]); + %find and copy over processed and analysis folders + dirAnalysis = dir('analysis_*'); + dirProcessed = dir('processed_*'); + sourceAnalysis = fullfile(dirAnalysis(end).folder,dirAnalysis(end).name); + sourceProcessed = fullfile(dirProcessed(end).folder,dirProcessed(end).name); + destDir = [saveDir filesep dirBats(bat_i).name filesep dirBatDays(day_i).name filesep 'extracted' filesep dirBatSessions(session_i).name filesep]; + destAnalysis = fullfile(destDir,dirAnalysis(end).name); + destProcessed = fullfile(destDir,dirProcessed(end).name); + if ~exist(destAnalysis) + mkdir(destAnalysis); + end + if ~exist(destProcessed) + mkdir(destProcessed); + end + copyfile(sourceAnalysis,destAnalysis); + copyfile(sourceProcessed,destProcessed); + + + %go back to day directory + cd(dayDir); + disp(sourceAnalysis) + end + cd(batDir); + end + cd(homeDir); +end \ No newline at end of file diff --git a/extract_data/extract_reward.m b/extract_data/extract_reward.m new file mode 100644 index 0000000..4c3cfe6 --- /dev/null +++ b/extract_data/extract_reward.m @@ -0,0 +1,11 @@ +trackData = load('tracking data file.mat') + +rewardSignal = trackData.AnalogSignals(:,1); +[rewardPks,rewardLocs] = findpeaks(rewardSignal,'MinPeakProminence',2); + + +%plot ttl times of reward landing +figure(); +plot(rewardSignal); +hold on; +text(rewardLocs+.02,rewardPks,num2str((1:numel(rewardPks))')); diff --git a/extract_data/extract_tracking_data.m b/extract_data/extract_tracking_data.m index 4c8f4d1..97ac5b6 100644 --- a/extract_data/extract_tracking_data.m +++ b/extract_data/extract_tracking_data.m @@ -1,25 +1,47 @@ -function extract_tracking_data(wd) -c3dList = dir([wd filesep '*.c3d']); -%make processed directory -processed_dir = [wd filesep 'processed' filesep]; -if ~isdir(processed_dir) - mkdir(processed_dir); +function extract_tracking_data(varargin) + +homeDir = pwd; +if nargin==2 + entry = 1; +else + entry = 0; +end +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'homedir' + homeDir=varargin{i+1}; + end end +if entry ==1 + c3dList = dir([homeDir filesep 'raw_tracking' filesep '*.c3d']); +else + c3dList = dir([homeDir filesep '*.c3d']); +end %run through list of c3d files in that directory, convert to mat, and save %to processed directory for i = 1:length(c3dList) - fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat - %fileName = extractBefore(c3dList(i).name,'-Bat_Cluster.c3d'); %Bat + fileName = extractBefore(c3dList(i).name,'.c3d'); %'-Bat_Cluster.c3d'); %Bat dateSesh = datestr(datetime(c3dList(i).date),'yymmdd'); batName = extractBefore(fileName,['_' dateSesh]); %sessionNum = fileName(end); - copy_dir = [extractBefore(wd,batName) 'processed' filesep batName filesep dateSesh filesep]; - if ~isdir(copy_dir) - mkdir(copy_dir); + %make processed directory + if strcmp(batName,'setup') + processed_dir = [homeDir filesep 'extraction_processing' filesep 'extracted_trackingCalibration' filesep]; + else + processed_dir = [homeDir filesep 'extraction_processing' filesep 'extracted_scopeTracking' filesep batName(1:2) dateSesh filesep]; + end + if ~isdir(processed_dir) + mkdir(processed_dir); + end + if entry == 1 + [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError]=readC3D_analog([homeDir filesep 'raw_tracking' filesep c3dList(i).name]); %convert file + else + [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError]=readC3D_analog([homeDir filesep c3dList(i).name]); %convert file end - [Markers,VideoFrameRate,AnalogSignals,AnalogFrameRate,Event,ParameterGroup,CameraInfo,ResidualError]=readC3D_analog([wd filesep c3dList(i).name]); %convert file %plot ttl impulses to check they are linear and not missing ttl event_ttls = AnalogSignals(:,2); [R,LT,UT,LL,UL] = risetime(event_ttls,VideoFrameRate); @@ -28,5 +50,4 @@ function extract_tracking_data(wd) title(fileName) %save new mat file in both original directory and copied directory for processing save([processed_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); - save([copy_dir fileName '_track' '.mat'],'AnalogFrameRate','AnalogSignals','Markers','VideoFrameRate'); end \ No newline at end of file diff --git a/psth/ImBat_plotPsth_meanAllRoiAllDay.m b/psth/ImBat_plotPsth_meanAllRoiAllDay.m new file mode 100644 index 0000000..aa15e91 --- /dev/null +++ b/psth/ImBat_plotPsth_meanAllRoiAllDay.m @@ -0,0 +1,83 @@ +batId = 'Gal'; +saveFlag = 1; +cRaw = 0; +clustNum = 2; +Fs_trace = 30; +Fs_behav = 120; +tag ='zscore'; + +if cRaw == 1 + saveTag = ['cRaw ' tag]; + smoothTrace = 1; +else + saveTag = ['sMat ' tag]; + smoothTrace = 10; +end +%make saving directory +if saveFlag == 1 + saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; + %saveDir1 = '/Volumes/Tobias_flig/topQualityData/analysis_done/plots/'; + if ~exist([saveDir1 datestr(now,'yymmdd') filesep 'meanAllROIAllDays']) + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'meanAllROIAllDays']); + else + disp('You have been working today...'); + end + saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'meanAllROIAllDays' filesep]; +end + +nRois = length(dataPreDurPost.mean_act_aligned{clustNum}(1,:)); +lenTrace = length(dataPreDurPost.mean_act_aligned{clustNum}{1,1}); +lenBehav = length(dataPreDurPost.mean_vel_aligned{clustNum}{1,1}); +nDays = length(dataPreDurPost.mean_act_aligned{clustNum}(:,1)); + +roiMat = zeros(nDays,nRois,lenTrace); +meanAllRoisEachDay = zeros(nDays,lenTrace); +smoothMeanAllRoisEachDay = zeros(nDays,lenTrace); +stdAllRoisEachDay = zeros(nDays,lenTrace); +meanAllBehavEachDay = zeros(nDays,lenBehav); +smoothMeanAllBehavEachDay = zeros(nDays,lenBehav); +stdAllBehavEachDay = zeros(nDays,lenBehav); +plotMeanAllRoi = figure(); +colDays = jet(nDays); +for day_i = 1:nDays +for roi_i = 1:nRois + roiMat(day_i,roi_i,:) = dataPreDurPost.mean_act_aligned{clustNum}{day_i,roi_i}; +end + +meanAllRoisEachDay(day_i,:) = mean(roiMat(day_i,:,:)); +stdAllRoisEachDay(day_i,:) = std(roiMat(day_i,:,:)); +meanAllBehavEachDay(day_i,:) = dataPreDurPost.mean_vel_aligned{clustNum}{day_i}; +smoothMeanAllRoisEachDay(day_i,:) = zscore(smooth(meanAllRoisEachDay(day_i,:),smoothTrace)); +smoothMeanAllRoisEachDay(day_i,:) = smoothMeanAllRoisEachDay(day_i,:) - min(smoothMeanAllRoisEachDay(day_i,:)); + +subplot(2,1,1) +p1 = plot(1:length(meanAllBehavEachDay(day_i,:)),meanAllBehavEachDay(day_i,:),'Color',colDays(day_i,:),'LineWidth',3); +hold on; +set(gca,'xtick',[]); +ylabel('Vel (m/s)'); +xlim([1 lenBehav]); +legInfo{day_i} = (['Day ' num2str(day_i)]); +legend(legInfo); +title('Velocity'); + +subplot(2,1,2) +p2 = plot(1:length(smoothMeanAllRoisEachDay(day_i,:)),smoothMeanAllRoisEachDay(day_i,:),'Color',colDays(day_i,:),'LineWidth',3); +hold on; +xlim([1 lenTrace]); +title('PSTH'); +end +sgtitle([batId ': Mean PSTH of all ROIs for ' num2str(nDays) ' days (' saveTag ')']); +xdat = get(gca,'xtick'); +set(gca,'xticklabel',round(xdat/Fs_trace)); +xlabel('Time (s)'); +if cRaw == 1 + ylabel('Mean df/f'); +else + ylabel('Spikes'); +end + + +if saveFlag == 1 +savefig(plotMeanAllRoi,[saveDir batId '_plot_meanAllRoiAllDay_' saveTag '_' datestr(now,'YYmmDD_hhMM') '.fig']); +saveas(plotMeanAllRoi,[saveDir batId '_plot_meanAllRoiAllDay_' saveTag '_' datestr(now,'YYmmDD_hhMM') '.tif']); +end diff --git a/snakePlot/ImBat_plotSnake.m b/snakePlot/ImBat_plotSnake.m index adb0bc6..e02f3db 100644 --- a/snakePlot/ImBat_plotSnake.m +++ b/snakePlot/ImBat_plotSnake.m @@ -7,15 +7,18 @@ switch lower(varargin{i}) case 'saveflag' saveFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; end end +snakeTrace.nClusters = snakeTrace.nClusters - 1; + %% % plot clusters normalized and clustered by preferred flight/pre/post (max dff across flights) -snakePlot_prefEachPrePostFlight = figure(); -for p = 1:snakeTrace.nClusters - - p1 = subplot(12,snakeTrace.nClusters,p); +snakePlot_prefEachPrePostFlight = figure('units','normalized','outerposition',[0 0 0.5 1]); +for p = 2:snakeTrace.nClusters + 1 + p1 = subplot(12,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawPre{p},1) @@ -23,76 +26,106 @@ end title(['Cluster ' num2str(p)]); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - %set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPre{p})]); - p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); - imagesc(snakeTrace.normMeanTraceEachPre{p},[0.5 5.5]); + p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); + imagesc(snakeTrace.normMeanTraceEachPre{p},[0.5 4.5]); colormap(hot); %make labels for first left plot only if p == 1 - %ylabel('cell number'); + %ylabel('ROI number'); ylabel('pre-flight'); - else - set(gca,'yticklabel',{[]}); + %else + %set(gca,'yticklabel',{[]},'xticklabel',{[]}); end xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)) %set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - p3 = subplot(12,snakeTrace.nClusters,p+20); + p3 = subplot(12,snakeTrace.nClusters,p-1+(4*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end + if p == 1 + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + - p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+20,2*snakeTrace.nClusters+p+20,3*snakeTrace.nClusters+p+20]); - imagesc(snakeTrace.normMeanTraceEachFlight{p},[0.5 5.5]); + p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters)]); + imagesc(snakeTrace.normMeanTraceEachFlight{p},[0.5 4.5]); colormap(hot); if p == 1 - %ylabel('cell number'); + %ylabel('ROI number'); ylabel('during flight'); - else - set(gca,'yticklabel',{[]}); + %else + %set(gca,'yticklabel',{[]}); end xt = get(gca, 'XTick'); - - p5 = subplot(12,snakeTrace.nClusters,p+40); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + hold off + + + p5 = subplot(12,snakeTrace.nClusters,p-1+(8*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedPost{p}),snakeTrace.smoothSpeedPost{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawPost{p},1) plot(1:length(snakeTrace.smoothSpeedRawPost{p}(cell_ii,:)),snakeTrace.smoothSpeedRawPost{p}(cell_ii,:)); end + if p == 1 + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPost{p})]); + hold off - p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+40,2*snakeTrace.nClusters+p+40,3*snakeTrace.nClusters+p+40]); - imagesc(snakeTrace.normMeanTraceEachPost{p},[0.5 5.5]); + p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters)]); + imagesc(snakeTrace.normMeanTraceEachPost{p},[0.5 4.5]); colormap(hot); if p == 1 - %ylabel('cell number'); + %ylabel('ROI number'); ylabel('post-flight'); - else - set(gca,'yticklabel',{[]}); + %else + %set(gca,'yticklabel',{[]}); end xt = get(gca, 'XTick'); - + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + hold off + xlabel('time (s)'); sgtitle(['Selectivity sort by pre/post/flight preference: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); end -%plot all the flight trajectories concatenated sorted by their preference +%% plot all the flight trajectories concatenated sorted by their preference snakePlot_prefAll = figure(); subplot(3,1,1) imagesc(snakeTrace.normMeanTraceSortPre); colormap(hot); ylabel('pre-flight'); set(gca,'yticklabel',{[]}); -set(gca,'xticklabel',{[]}); +xt = get(gca, 'XTick'); +set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); hold on subplot(3,1,2) @@ -100,7 +133,8 @@ colormap(hot); ylabel('during flight'); set(gca,'yticklabel',{[]}); -set(gca,'xticklabel',{[]}); +xt = get(gca, 'XTick'); +set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); subplot(3,1,3) imagesc(snakeTrace.normMeanTraceSortPost); @@ -116,33 +150,37 @@ %% Plot the FLIGHT clusters normalized and clustered by their preferred flight (max dff across flights) snakePlot_prefEach = figure(); -for p = 1:snakeTrace.nClusters +for p = 2:snakeTrace.nClusters+1 - p1 = subplot(4,snakeTrace.nClusters,p); + p1 = subplot(4,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - %set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); - imagesc(snakeTrace.normMeanTraceEachFlight{p},[0.5 5.5]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); + imagesc(snakeTrace.normMeanTraceEachFlight{p},[0.5 4.5]); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end xt = get(gca, 'XTick'); - %set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); xlabel('time (s)'); %hold off sgtitle(['Spatial selectivity sort by flight preference: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); @@ -152,16 +190,16 @@ snakePlot_prefAll = figure(); imagesc(snakeTrace.normMeanTraceSortFlight); colormap(hot); -ylabel('cell number'); +ylabel('ROI number'); set(gca,'yticklabel',{[]}); title(['Spatial selectivity sort by flight preference: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); xlabel('time (s)'); %% plot the cells according to their peak for each cluster with velocity on top (pre/post/flight) -snakePlot_clustPrePostFlight = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(12,snakeTrace.nClusters,p); +snakePlot_clustPrePostFlight = figure('units','normalized','outerposition',[0 0 0.5 1]); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(12,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) @@ -169,51 +207,58 @@ end title(['Cluster ' num2str(p)]); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'XTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPre{p})]); + + p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTracePre{p}(snakeTrace.IPre{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('pre-flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); end - set(gca,'xticklabel',[]); - hold on + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); - p3 = subplot(12,snakeTrace.nClusters,p+20); + p3 = subplot(12,snakeTrace.nClusters,p-1+(4*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+20,2*snakeTrace.nClusters+p+20,3*snakeTrace.nClusters+p+20]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters)]); imagesc(snakeTrace.normTraceFlight{p}(snakeTrace.IFlight{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('during flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end - set(gca,'xticklabel',[]); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); - p5 = subplot(12,snakeTrace.nClusters,p+40); + p5 = subplot(12,snakeTrace.nClusters,p-1+(8*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedPost{p}),snakeTrace.smoothSpeedPost{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawPost{p},1) @@ -221,20 +266,24 @@ end title(['Cluster ' num2str(p)]); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+40,2*snakeTrace.nClusters+p+40,3*snakeTrace.nClusters+p+40]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPost{p})]); + + p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters)]); imagesc(snakeTrace.normTracePost{p}(snakeTrace.IPost{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('post-flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); @@ -245,9 +294,9 @@ end %plot the cells by cluster sorted by cluster1 order -snakePlot_clustBy1PrePostFlight = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(12,snakeTrace.nClusters,p); +snakePlot_clustBy1PrePostFlight = figure('units','normalized','outerposition',[0 0 0.5 1]); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(12,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawPre{p},1) @@ -255,49 +304,59 @@ end title(['Cluster ' num2str(p)]); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPre{p})]); + + p2 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTracePre{p}(snakeTrace.I1Pre{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('pre-flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end - set(gca,'xticklabel',{[]}); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); - p3 = subplot(12,snakeTrace.nClusters,p+20); + p3 = subplot(12,snakeTrace.nClusters,p-1+(4*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+20,2*snakeTrace.nClusters+p+20,3*snakeTrace.nClusters+p+20]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p4 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(4*snakeTrace.nClusters)]); imagesc(snakeTrace.normTraceFlight{p}(snakeTrace.I1Flight{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('during flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end - set(gca,'xticklabel',{[]}); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); - p5 = subplot(12,snakeTrace.nClusters,p+40); + p5 = subplot(12,snakeTrace.nClusters,p-1+(8*snakeTrace.nClusters)); plot(1:length(snakeTrace.smoothSpeedPost{p}),snakeTrace.smoothSpeedPost{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawPost{p},1) @@ -305,20 +364,24 @@ end title(['Cluster ' num2str(p)]); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p+40,2*snakeTrace.nClusters+p+40,3*snakeTrace.nClusters+p+40]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedPost{p})]); + + p6 = subplot(12,snakeTrace.nClusters,[snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),2*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters),3*snakeTrace.nClusters+p-1+(8*snakeTrace.nClusters)]); imagesc(snakeTrace.normTracePost{p}(snakeTrace.I1Post{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('post-flight'); - else - set(gca,'yticklabel',{[]}); + ylabel('ROI number'); + %else + %set(gca,'yticklabel',{[]}); end xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); @@ -330,27 +393,31 @@ %% %plot the cells according to their peak for each cluster with velocity on top snakePlot_clust = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(4,snakeTrace.nClusters,p); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(4,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTraceFlight{p}(snakeTrace.IFlight{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); + ylabel('ROI number'); else set(gca,'yticklabel',{[]}); end @@ -364,27 +431,31 @@ %plot the cells by cluster sorted by cluster1 order snakePlot_clustBy1 = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(4,snakeTrace.nClusters,p); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(4,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTraceFlight{p}(snakeTrace.I1Flight{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); + ylabel('ROI number'); else set(gca,'yticklabel',{[]}); end @@ -399,41 +470,46 @@ %plot half the odd cells sorted and then plot the even cells according to %the odd sorting snakePlot_clustOddEven = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(4,2*snakeTrace.nClusters,2*p-1); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(4,2*snakeTrace.nClusters,2*(p-1)); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); + title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,2*snakeTrace.nClusters,[2*snakeTrace.nClusters+(2*p-1),4*snakeTrace.nClusters+(2*p-1),6*snakeTrace.nClusters+(2*p-1)]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p2 = subplot(4,2*snakeTrace.nClusters,[2*snakeTrace.nClusters+(2*(p-1)),4*snakeTrace.nClusters+(2*(p-1)),6*snakeTrace.nClusters+(2*(p-1))]); imagesc(snakeTrace.normTraceOdd{p}(snakeTrace.Iodd{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); + ylabel('ROI number'); else set(gca,'yticklabel',{[]}); end - title(['Cluster ' num2str(p) ' Odd']); + title(['Odd']); xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); - xlabel('time (s)'); %ylabel('cell number'); - p3 = subplot(4,2*snakeTrace.nClusters,[2*snakeTrace.nClusters+(2*p),4*snakeTrace.nClusters+(2*p),6*snakeTrace.nClusters+(2*p)]); + xlabel('time (s)'); %ylabel('ROI number'); + + p3 = subplot(4,2*snakeTrace.nClusters,[2*snakeTrace.nClusters+(2*(p-1)-1),4*snakeTrace.nClusters+(2*(p-1)-1),6*snakeTrace.nClusters+(2*(p-1)-1)]); imagesc(snakeTrace.normTraceEven{p}(snakeTrace.Iodd{p},:)); colormap(hot); - title(['Cluster ' num2str(p) ' Even']); + title(['Even']); xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1),'yticklabel',{[]}); - xlabel('time (s)'); %ylabel('cell number'); + xlabel('time (s)'); %ylabel('ROI number'); sgtitle(['Spatial selectivity Odd (sorted) vs Even Trials: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); end @@ -441,27 +517,31 @@ %% %plot the fully normalized cells according to their peak for each cluster with velocity on top snakePlot_clust_allNorm = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(4,snakeTrace.nClusters,p); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(4,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); +title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTraceFlightAll{p}(snakeTrace.InormFlightAll{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); + ylabel('ROI number'); else set(gca,'yticklabel',{[]}); end @@ -475,27 +555,31 @@ %plot the cells by cluster sorted by cluster1 order snakePlot_clustBy1_normAll = figure(); -for p = 1:snakeTrace.nClusters - p1 = subplot(4,snakeTrace.nClusters,p); +for p = 2:snakeTrace.nClusters+1 + p1 = subplot(4,snakeTrace.nClusters,p-1); plot(1:length(snakeTrace.smoothSpeedFlight{p}),snakeTrace.smoothSpeedFlight{p},'k'); hold on for cell_ii = 1:size(snakeTrace.smoothSpeedRawFlight{p},1) plot(1:length(snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)),snakeTrace.smoothSpeedRawFlight{p}(cell_ii,:)); end - title(['Cluster ' num2str(p)]); +title(['Cluster ' num2str(p) ':' num2str(size(snakeTrace.smoothSpeedRawFlight{p},1)) 'f']); if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p,2*snakeTrace.nClusters+p,3*snakeTrace.nClusters+p]); + ylabel('velocity (m/s)'); + %else + %set(gca,'XTickLabel',{[]},'YTickLabel',{[]}); + end + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 5]); + xlim([0 length(snakeTrace.smoothSpeedFlight{p})]); + + p2 = subplot(4,snakeTrace.nClusters,[snakeTrace.nClusters+p-1,2*snakeTrace.nClusters+p-1,3*snakeTrace.nClusters+p-1]); imagesc(snakeTrace.normTraceFlightAll{p}(snakeTrace.I1normFlightAll{p},:)); colormap(hot); %make labels for first left plot only if p == 1 - ylabel('cell number'); + ylabel('ROI number'); else set(gca,'yticklabel',{[]}); end @@ -515,38 +599,39 @@ snakeTrace.snakePlot_clustPrePostFlight = snakePlot_clustPrePostFlight; snakeTrace.snakePlot_clust = snakePlot_clust; snakeTrace.snakePlot_prefAll = snakePlot_prefAll; +snakeTrace.snakePlot_prefEach = snakePlot_prefEach; snakeTrace.snakePlot_clustBy1PrePostFlight = snakePlot_clustBy1PrePostFlight; %% save figures and matlab variable if saveFlag == 1 - saveas(snakePlot_prefEachPrePostFlight, [pwd '\analysis\snakePlots\' label '_snakePlot_prefEachPrePostFlight.svg']); - saveas(snakePlot_prefEachPrePostFlight, [pwd '\analysis\snakePlots\' label '_snakePlot_prefEachPrePostFlight.tif']); - savefig(snakePlot_prefEachPrePostFlight, [pwd '/analysis/snakePlots/' label '_snakePlot_prefEachPrePostFlight.fig']); - saveas(snakePlot_clust, [pwd '\analysis\snakePlots\' label '_snakePlots_clustAll.svg']); - saveas(snakePlot_clustOddEven, [pwd '\analysis\snakePlots\' label '_snakePlots_clustOddEven.svg']); - saveas(snakePlot_clustBy1, [pwd '\analysis\snakePlots\' label '_snakePlots_clustBy1.svg']); - saveas(snakePlot_prefEach, [pwd '\analysis\snakePlots\' label '_snakePlots_prefEach.svg']); - saveas(snakePlot_prefAll, [pwd '\analysis\snakePlots\' label '_snakePlots_prefAll.svg']); - saveas(snakePlot_prefEachPrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); - saveas(snakePlot_clust, [pwd '\analysis\snakePlots\' label '_snakePlots_clustAll.tif']); - saveas(snakePlot_clustOddEven, [pwd '\analysis\snakePlots\' label '_snakePlots_clustOddEven.tif']); - saveas(snakePlot_clustBy1, [pwd '\analysis\snakePlots\' label '_snakePlots_clustBy1.tif']); - saveas(snakePlot_prefEach, [pwd '\analysis\snakePlots\' label '_snakePlots_prefEach.tif']); - saveas(snakePlot_prefAll, [pwd '\analysis\snakePlots\' label '_snakePlots_prefAll.tif']); - saveas(snakePlot_prefEachPrePostFlight, [pwd '\analysis\snakePlots\' fileName '_snakePlot_prefEachPrePostFlight.tif']); - saveas(snakePlot_clustPrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.tif']); - saveas(snakePlot_clustPrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); - saveas(snakePlot_prefAll, [pwd '/analysis/snakePlots/' fileName '_snakePlot_prefAll.tif']); - saveas(snakePlot_prefAll, [pwd '/analysis/snakePlots/' fileName '_snakePlot_prefAll.svg']); - saveas(snakePlot_clustBy1PrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.tif']); - saveas(snakePlot_clustBy1PrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); + saveas(snakePlot_prefEachPrePostFlight, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakePlot_prefEachPrePostFlight, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlot_prefEachPrePostFlight.tif']); + savefig(snakePlot_prefEachPrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' label '_snakePlot_prefEachPrePostFlight.fig']); + saveas(snakePlot_clust, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustAll.svg']); + saveas(snakePlot_clustOddEven, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustOddEven.svg']); + saveas(snakePlot_clustBy1, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustBy1.svg']); + saveas(snakePlot_prefEach, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefEach.svg']); + saveas(snakePlot_prefAll, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefAll.svg']); + saveas(snakePlot_prefEachPrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakePlot_clust, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustAll.tif']); + saveas(snakePlot_clustOddEven, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustOddEven.tif']); + saveas(snakePlot_clustBy1, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustBy1.tif']); + saveas(snakePlot_prefEach, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefEach.tif']); + saveas(snakePlot_prefAll, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefAll.tif']); + saveas(snakePlot_prefEachPrePostFlight, [pwd '\' analysis_Folder '\snakePlots\' fileName '_snakePlot_prefEachPrePostFlight.tif']); + saveas(snakePlot_clustPrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.tif']); + saveas(snakePlot_clustPrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.svg']); + saveas(snakePlot_prefAll, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefAll.tif']); + saveas(snakePlot_prefAll, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_prefAll.svg']); + saveas(snakePlot_clustBy1PrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.tif']); + saveas(snakePlot_clustBy1PrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustBy1PrePostFlight.svg']); - %save([pwd '/analysis/' label '_snakePlotData.mat'],'snakeTrace'); - savefig(snakePlot_prefEachPrePostFlight, [pwd '\analysis\snakePlots\' label '_snakePlot_prefEachPrePostFlight.fig']); - savefig(snakePlot_clustOddEven, [pwd '\analysis\snakePlots\' label '_snakePlots_clustOddEven.fig']); - savefig(snakePlot_clustBy1, [pwd '\analysis\snakePlots\' label '_snakePlots_clustBy1.fig']); - savefig(snakePlot_prefEach, [pwd '\analysis\snakePlots\' label '_snakePlots_prefEach.fig']); - savefig(snakePlot_prefAll, [pwd '\analysis\snakePlots\' label '_snakePlots_prefAll.fig']); - savefig(snakePlot_clustPrePostFlight, [pwd '/analysis/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); - savefig(snakePlot_clustBy1PrePostFlight, [pwd '/analysis/snakePlots/' label '_snakePlot_clustBy1PrePostFlight.fig']); + %save([pwd '/' analysis_Folder '/' label '_snakePlotData.mat'],'snakeTrace'); + savefig(snakePlot_prefEachPrePostFlight, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlot_prefEachPrePostFlight.fig']); + savefig(snakePlot_clustOddEven, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustOddEven.fig']); + savefig(snakePlot_clustBy1, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_clustBy1.fig']); + savefig(snakePlot_prefEach, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefEach.fig']); + savefig(snakePlot_prefAll, [pwd '\' analysis_Folder '\snakePlots\' label '_snakePlots_prefAll.fig']); + savefig(snakePlot_clustPrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' fileName '_snakePlot_clustPrePostFlight.fig']); + savefig(snakePlot_clustBy1PrePostFlight, [pwd '/' analysis_Folder '/snakePlots/' label '_snakePlot_clustBy1PrePostFlight.fig']); end \ No newline at end of file diff --git a/snakePlot/ImBat_plotSnakePrePost.m b/snakePlot/ImBat_plotSnakePrePost.m index 923104f..eefcfcf 100644 --- a/snakePlot/ImBat_plotSnakePrePost.m +++ b/snakePlot/ImBat_plotSnakePrePost.m @@ -1,4 +1,4 @@ -function [snakeTracePrePost] = ImBat_plotSnake(snakeTracePrePost,varargin) +function [snakeTracePrePost] = ImBat_plotSnakePrePost(snakeTracePrePost,varargin) % User inputs overrides saveFlag = 0; @@ -12,7 +12,7 @@ %plot all the flight trajectories concatenated sorted by their preference -snakePlot_prefAll = figure(); +snakePlot_concat_preFlightPost = figure(); imagesc(snakeTracePrePost.normMeanTraceSortPreFlightPost); colormap(hot); ylabel('cell number'); @@ -23,7 +23,7 @@ sgtitle(['Selectivity sort by group preference (pre/post/flight): ' snakeTracePrePost.batName ' ' snakeTracePrePost.dateSesh ' ' snakeTracePrePost.sessionType]); -%% plot the cells according to their peak within each grouping with velocity on top (pre/post/flight) +% plot the cells according to their peak within each grouping with velocity on top (pre/post/flight) snakePlot_noClust_withinPrePostFlight = figure(); p1 = subplot(4,3,1); @@ -88,7 +88,7 @@ sgtitle(['Selectivity sort within groupings (pre/post/flight): ' snakeTracePrePost.batName ' ' snakeTracePrePost.dateSesh ' ' snakeTracePrePost.sessionType]); -%% plot the cells according to their peak across the groupings with velocity on top (pre/post/flight) +% plot the cells according to their peak across the groupings with velocity on top (pre/post/flight) snakePlot_noClust_acrossPrePostFlight = figure(); p1 = subplot(4,3,1); @@ -151,4 +151,8 @@ xlabel('time (s)'); sgtitle(['Selectivity sort across groups (pre/post/flight): ' snakeTracePrePost.batName ' ' snakeTracePrePost.dateSesh ' ' snakeTracePrePost.sessionType]); - \ No newline at end of file + + + snakeTracePrePost.snakePlot_concat_preFlightPost = snakePlot_concat_preFlightPost; + snakeTracePrePost.snakePlot_noClust_withinPrePostFlight = snakePlot_noClust_withinPrePostFlight; + snakeTracePrePost.snakePlot_noClust_acrossPrePostFlight = snakePlot_noClust_acrossPrePostFlight; \ No newline at end of file diff --git a/snakePlot/ImBat_plotSnakeSum.m b/snakePlot/ImBat_plotSnakeSum.m new file mode 100644 index 0000000..f18452d --- /dev/null +++ b/snakePlot/ImBat_plotSnakeSum.m @@ -0,0 +1,306 @@ +function [plotSnakeSum] = ImBat_plotSnakeSum(snakeTrace,flightPaths,goodCellIdx,varargin) +% User inputs overrides +saveFlag = 1; +plotSumFlag = 1; +plotCumSumFlag = 1; +plotSumClusterFlag = 1; + +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'saveflag' + saveFlag = varargin{i+1}; + end +end + +%this is to merge specific clusters if 2 or more of them are the same but +%were separated by the flight k-means +flightPaths.clusterIndex{2}=cat(2,flightPaths.clusterIndex{2},flightPaths.clusterIndex{3}); +flightPaths.clusterIndex{3} =[]; +flightPaths.clusterIndex= flightPaths.clusterIndex(~cellfun('isempty',flightPaths.clusterIndex)); + +%calculate the sums and cumsums for each flight trajectory +%initialize variables for sum and cumsum +sumSnakeFlight = cell(size(snakeTrace.meanTraceFlight,2),1); +sumSnakePost = cell(size(snakeTrace.meanTraceFlight,2),1); +cumSumSnakePre = cell(size(snakeTrace.meanTraceFlight,2),1); +cumSumSnakeFlight = cell(size(snakeTrace.meanTraceFlight,2),1); +cumSumSnakePost = cell(size(snakeTrace.meanTraceFlight,2),1); +%calculate the sums and cumsums for each trajectory pre/flight/post +for traj_i = 1:size(snakeTrace.meanTraceFlight,2) + sumSnakePre{traj_i} = sum(snakeTrace.meanTracePre{traj_i}(goodCellIdx.goodCellIndex,:),1); + sumSnakeFlight{traj_i} = sum(snakeTrace.meanTraceFlight{traj_i}(goodCellIdx.goodCellIndex,:),1); + sumSnakePost{traj_i} = sum(snakeTrace.meanTracePost{traj_i}(goodCellIdx.goodCellIndex,:),1); + + cumSumSnakePre{traj_i} = cumsum(snakeTrace.meanTracePre{traj_i}(goodCellIdx.goodCellIndex,:),1); + cumSumSnakeFlight{traj_i} = cumsum(snakeTrace.meanTraceFlight{traj_i}(goodCellIdx.goodCellIndex,:),1); + cumSumSnakePost{traj_i} = cumsum(snakeTrace.meanTracePost{traj_i}(goodCellIdx.goodCellIndex,:),1); +end + +%% plot all the sums of calcium activity for pre/flight/post separated for +if plotSumFlag ==1 + %each flight cluster + plotSnakeSum = figure(); + for traj_i = 1:size(snakeTrace.meanTraceFlight,2) + %plot sums for preflight times + p1 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+(traj_i-2)); + plot(sumSnakePre{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + ylabel({['Traj ' num2str(traj_i)];'sum dff'}); + if traj_i == 1 + title('Pre-flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + + %plot sums for flight time + p2 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+(traj_i-1)); + plot(sumSnakeFlight{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + if traj_i == 1 + title('Flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + + %plot sums for post flight + p3 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+traj_i) + plot(sumSnakePost{traj_i}) + hold on + set(gca,'xticklabel',{[]}); + if traj_i == 1 + title('Post-flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + end + sgtitle(['Sum of calcium activity: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + + if saveFlag ==1 + saveas(plotSnakeSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSumPreFlightPost.svg']); + saveas(plotSnakeSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSumPreFlightPost.tif']); + savefig(plotSnakeSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSumPreFlightPost.fig']); + end +end +%% plot all the cumsums of calcium activity for pre/flight/post separated for each flight cluster +if plotCumSumFlag == 1 + plotSnakeCumSum = figure(); + for traj_i = 1:size(snakeTrace.meanTraceFlight,2) + %plot cumsum of preflight activity + p1 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+(traj_i-2)) + plot(cumSumSnakePre{traj_i}) + hold on + set(gca,'xticklabel',{[]}); + ylabel({['Traj ' num2str(traj_i)];'sum dff'}); + if traj_i == 1 + title('Pre-flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + + %plot cumsum of flight activity + p2 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+(traj_i-1)) + plot(cumSumSnakeFlight{traj_i}) + hold on + set(gca,'xticklabel',{[]}); + if traj_i == 1 + title('Flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + + %plot cumsum of postflight activity + p3 = subplot(size(snakeTrace.meanTraceFlight,2),3,(2*traj_i)+traj_i) + plot(cumSumSnakePost{traj_i}) + hold on + set(gca,'xticklabel',{[]}); + if traj_i == 1 + title('Post-flight DF Sum') + elseif traj_i == size(snakeTrace.meanTraceFlight,2) + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + end + hold off + end + sgtitle(['Cummulative sum of calcium activity: ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + if saveFlag ==1 + saveas(plotSnakeCumSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotCumSumPreFlightPost.svg']); + saveas(plotSnakeCumSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotCumSumPreFlightPost.tif']); + savefig(plotSnakeCumSum, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotCumSumPreFlightPost.fig']); + end +end + +%% plot the sums with the flight trajectories, speed, and snakeplot included +% plot the cells according to their peak within each grouping with velocity on top (pre/post/flight) + +if plotSumClusterFlag ==1 + jj = jet(size(snakeTrace.meanTraceFlight,2)); + %for each flight cluster, plot a new figure + for traj_i = 1:size(snakeTrace.meanTraceFlight,2) + plotSnakeSum_noClust = figure(); + + for flight_i = 1:length(snakeTrace.smoothSpeedRawPre{traj_i}(:,1)) + %plot trajectories preflight + p1 = subplot(7,3,1); + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i))-snakeTrace.preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i))),'LineWidth',1,'Color',jj(traj_i,:)); + hold on + %scatter(flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),1),flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),2),50,'r','filled') + title('Pre-Flight: A to B'); + ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + %plot trajectories of flight cluster (traj_i) + p2 = subplot(7,3,2); + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i))),flightPaths.trajectories_continuous(2,flightPaths.flight_starts_idx(flightPaths.clusterIndex{traj_i}(flight_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i))),'LineWidth',1,'Color',jj(traj_i,:)); + hold on + scatter(flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),1),flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),2),50,'r','filled') + title('Pre-Flight: A to B'); + %ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + %xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + %plot trajectories post flight + p3 = subplot(7,3,3); + plot(flightPaths.trajectories_continuous(1,flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i))+snakeTrace.postFlightPadSpeed),flightPaths.trajectories_continuous(2,flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{traj_i}(flight_i))+snakeTrace.postFlightPadSpeed),'LineWidth',1,'Color',jj(traj_i,:)); + hold on + %scatter(flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),1),flightPaths.flight_starts_xyz(flightPaths.clusterIndex{traj_i}(flight_i),2),50,'r','filled') + title('Pre-Flight: A to B'); + %ylabel('y (cm)'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt/10); + %xlabel('x (cm)'); + xt = get(gca,'XTick'); + set(gca,'XTick',xt,'XTickLabel',xt/10); + + %plot speed pre flight + p4 = subplot(7,3,4); + plot(1:length(snakeTrace.smoothSpeedRawPre{traj_i}(flight_i,:)),snakeTrace.smoothSpeedRawPre{traj_i}(flight_i,:)); + hold on + ylabel('cm/s'); + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %plot speed during flight + p5 = subplot(7,3,5); %plot speed pre flight A to B + plot(1:length(snakeTrace.smoothSpeedRawFlight{traj_i}(flight_i,:)),snakeTrace.smoothSpeedRawFlight{traj_i}(flight_i,:)); + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + set(gca,'xticklabel',{[]}); + ylim([0 6]); + %plot speed post flight + p6 = subplot(7,3,6); %plot speed pre flight A to B + plot(1:length(snakeTrace.smoothSpeedRawPost{traj_i}(flight_i,:)),snakeTrace.smoothSpeedRawPost{traj_i}(flight_i,:)); + hold on + yt = get(gca,'YTick'); + set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); + ylim([0 6]); + end + + %get rid of bad cells + for bad_i = 1:length(goodCellIdx.badCellIndex) + snakeTrace.IPre{traj_i}(find(snakeTrace.IPre{traj_i}==goodCellIdx.badCellIndex(bad_i)))=[]; + snakeTrace.IFlight{traj_i}(find(snakeTrace.IFlight{traj_i}==goodCellIdx.badCellIndex(bad_i)))=[]; + snakeTrace.IPost{traj_i}(find(snakeTrace.IPost{traj_i}==goodCellIdx.badCellIndex(bad_i)))=[]; + end + + %plot sums for preflight times + p7 = subplot(7,3,7); + plot(sumSnakePre{traj_i}); + hold on + ylabel('sum dff'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + hold off + %plot sums for flight time + p8 = subplot(7,3,8); + plot(sumSnakeFlight{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + hold off + %plot sums for post flight + p9 = subplot(7,3,9); + plot(sumSnakePost{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + hold off + + %plot sums for preflight times + p7 = subplot(7,3,10); + plot(cumSumSnakePre{traj_i}); + hold on + ylabel('cumsum dff'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',[]); + hold off + %plot sums for flight time + p8 = subplot(7,3,11); + plot(cumSumSnakeFlight{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + hold off + %plot sums for post flight + p9 = subplot(7,3,12); + plot(cumSumSnakePost{traj_i}); + hold on + set(gca,'xticklabel',{[]}); + hold off + + %plot heat maps preflight + p10 = subplot(7,3,[13 16 19]); + imagesc(snakeTrace.normTracePre{traj_i}(snakeTrace.IPre{traj_i},:)); + colormap(hot); + ylabel('ROI number'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + %plot head maps during flight + p11 = subplot(7,3,[14 17 20]); + imagesc(snakeTrace.normTraceFlight{traj_i}(snakeTrace.IFlight{traj_i},:)); + colormap(hot); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + set(gca,'yticklabel',{[]}); + %plot head maps post flight + p12 = subplot(7,3,[15 18 21]); + imagesc(snakeTrace.normTracePost{traj_i}(snakeTrace.IPost{traj_i},:)); + colormap(hot); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlabel('time (s)'); + set(gca,'yticklabel',{[]}); + + sgtitle(['Trajectory ' num2str(traj_i) ': ' snakeTrace.batName ' ' snakeTrace.dateSesh ' ' snakeTrace.sessionType]); + if saveFlag ==1 + saveas(plotSnakeSum_noClust, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSnakeSum_noClust_traj' num2str(traj_i) '.svg']); + saveas(plotSnakeSum_noClust, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSnakeSum_noClust_traj' num2str(traj_i) '.tif']); + savefig(plotSnakeSum_noClust, [pwd '/' snakeTrace.batName '_' snakeTrace.dateSesh '_' snakeTrace.sessionType '_plotSnakeSum_noClust_traj' num2str(traj_i) '.fig']); + end + + end +end diff --git a/snakePlot/ImBat_plotSnake_allPreFlightPost.m b/snakePlot/ImBat_plotSnake_allPreFlightPost.m index f683e05..9775c2a 100644 --- a/snakePlot/ImBat_plotSnake_allPreFlightPost.m +++ b/snakePlot/ImBat_plotSnake_allPreFlightPost.m @@ -2,7 +2,7 @@ % plot the cells according to their peak for each cluster with velocity on top (pre/post/flight) snakePlot_allPrePostFlight = figure(); -for p = 2%snakeTrace.nClusters +for p = 1:snakeTrace.nClusters p1 = subplot(snakeTrace.nClusters*3,3,((p-1)*9)+1); plot(1:length(snakeTrace.smoothSpeedPre{p}),snakeTrace.smoothSpeedPre{p},'k'); hold on @@ -75,5 +75,9 @@ xt = get(gca, 'XTick'); set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); xlabel('time (s)'); + + sgtitle('ROI Activity for all cells resorted for each cluster') + +end -end \ No newline at end of file +snakeTrace.snakePlot_allPrePostFlight = snakePlot_allPrePostFlight; \ No newline at end of file diff --git a/snakePlot/ImBat_plotSnake_stableROI.m b/snakePlot/ImBat_plotSnake_stableROI.m new file mode 100644 index 0000000..fc096f3 --- /dev/null +++ b/snakePlot/ImBat_plotSnake_stableROI.m @@ -0,0 +1,837 @@ +%function to plot snakePlots flight paths of the +%bats for each day focusing only on the stable neurons from ROIs_manual +batId = 'Gen'; +clustNum = 2; %which cluster to look across all the days +saveFlag = 1; %do you want to save the figures and output structure? +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'snakePlots'])>0; + disp('Youvee been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'snakePlots']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'snakePlots' '\']; + +xlimFlight = 1560; +xlimCalcium = xlimFlight/4; +xlimFlightPre = 800; +xlimCalciumPre = xlimFlightPre/4; +xlimFlightPost = 800; +xlimCalciumPost = xlimFlightPost/4; +if strcmp(batId,'Gal') +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_manual = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 25 6 30 27 3 1 2 9 8 37 NaN 15 31 24 36; + 8 12 35 20 1 10 2 39 9 30 3 14 31 24 11; + 10 7 39 35 3 31 8 22 9 37 5 11 39 17 2; + 9 27 25 45 1 7 8 46 11 33 23 6 42 3 2; + 20 34 29 51 7 10 6 40 16 45 5 8 42 26 43; + 8 2 25 38 16 44 20 7 14 26 3 35 37 24 41; + 1 7 28 NaN 6 17 2 35 16 33 12 11 27 30 34; + 19 4 16 NaN 27 21 3 24 2 29 14 8 26 32 33]; +g = dir('Ga*'); +elseif strcmp(batId,'Gen') +% 20 stable manually selected ROIs across 5 days for Gen +ROIs_manual = [NaN NaN 10 3 16 12 17 18 27 29 8 9 NaN NaN 21 11 31 15 20 25; + 8 17 5 1 2 6 21 10 18 31 NaN 11 51 53 28 4 38 19 23 20; + 50 54 12 3 48 18 27 15 31 34 NaN NaN 28 NaN 29 25 24 22 38 14; + 9 NaN 7 31 2 22 NaN 20 40 25 13 NaN 34 NaN 26 NaN 45 3 24 21; + 10 36 3 11 2 NaN 21 18 20 9 33 NaN NaN NaN 17 NaN 22 7 30 26]; %14 NaN 3 28 2 6 33 26 18 45 NaN NaN 25 NaN 32 NaN 37 8 28 11 +g = dir('Ge*'); +end +z = dir('Z1*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +for d = 1:length(dirTop) + %load results data + %extract metadata names and enter processed folder + cd([dirTop(d).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + batName{d} = flyFolders(end).name(1:3); + dateSesh{d} = flyFolders(end).name(5:10); + sessionType{d} = flyFolders(end).name(12:16); + + cd(flyFolders(end).name); + + %load snakeTrace data + %extract metadata names and enter analysis folder + dirAnalysis = dir('analysis_*'); + cd(dirAnalysis(end).name); + sp = dir('*snakePlotData_stable.mat'); + snakeTraceT(d) = load(sp(end).name); + fp = dir('*flightPaths.mat'); + flightPathsF(d) = load(fp(end).name); + close all; + cd(dirTop(d).folder) +end + +%% plot all stable ROIs across all 9 days sorted by order of ROIs +plotSnake_acrossDays = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Activity Across 5 Days for Same Flight Path: ' batName{d} ' 20319 to 200324']); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceFlight{clustNum}(:,1:xlimCalcium),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot all stable ROIs across all 9 days sorted by their own preference +plotSnake_acrossDays_prefEach = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Each Day): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred sorting individually + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceFlight{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.IFlight{clustNum},1:xlimCalcium),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot each ROI across all 9 days in same image with different images for each ROI sorted by day 1 preference +plotSnake_acrossDays_pref1 = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Day 1): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred day 1 activity + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceFlight{clustNum}(snakeTraceT(1).snakeTrace.cRaw.IFlight{clustNum},1:xlimCalcium),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +%% Pre-flight activity +%plot all stable ROIs across all 9 days sorted by order of ROIs +plotSnake_acrossDays_pre = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Pre-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path: ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normMeanTraceEachPre{clustNum}(:,1:xlimCalciumPre),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot all stable ROIs across all 9 days sorted by their own preference +plotSnake_acrossDays_prefEach_pre = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Pre-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Each Day): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred sorting individually + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTracePre{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.IPre{clustNum},1:xlimCalciumPre),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot each ROI across all 9 days in same image with different images for each ROI sorted by day 1 preference +plotSnake_acrossDays_pref1_pre = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Pre-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Day 1): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPre{clustNum}(flight_i,1:xlimFlightPre)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred day 1 sorting + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTracePre{clustNum}(snakeTraceT(1).snakeTrace.cRaw.IPre{clustNum},1:xlimCalciumPre),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +%% Post-flight activity +%plot all stable ROIs across all 9 days sorted by order of ROIs +plotSnake_acrossDays_post = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Post-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path: ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normMeanTraceEachPost{clustNum}(:,:),[1 4.5]); %1:xlimCalciumPost),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot all stable ROIs across all 9 days sorted by their own preference +plotSnake_acrossDays_prefEach_post = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Post-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Each Day): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred sorting individually + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTracePost{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.IPost{clustNum},:),[1 4.5]);%1:xlimCalciumPost),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +% plot each ROI across all 9 days in same image with different images for each ROI sorted by day 1 preference +plotSnake_acrossDays_pref1_post = figure('units','normalized','outerposition',[0 0 0.5 1]); +sgtitle(['Mean Post-Activity Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path (Pref Day 1): ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot flightpath for cluster #2 + for flight_i = 1:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1)),day_i); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1)), length(ROIs_manual(:,1)) + day_i); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawPost{clustNum}(flight_i,1:xlimFlightPost)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + + %plot all ROIs according to preferred day 1 activity + subplot(3,length(ROIs_manual(:,1)), 2*length(ROIs_manual(:,1)) + day_i); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTracePost{clustNum}(snakeTraceT(1).snakeTrace.cRaw.IPost{clustNum},:),[1 4.5]); %1:xlimCalciumPost),[1 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +%% Even/odd trials: plot all stable ROIs across all days sorted by order of ROIs +plotSnake_acrossDays_oddEven = figure('units','normalized','outerposition',[0 0 1 1]); +sgtitle(['Odd vs Even Trials Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path: ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + %plot odd flightpath for cluster #2 + for flight_i = 1:2:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1))*2,(day_i*2)-1); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + %plot odd velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*2 + (day_i*2)-1); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + %plot odd trials for all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,2*length(ROIs_manual(:,1)), 4*length(ROIs_manual(:,1)) + (day_i*2)-1); + %imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceOdd{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.Iodd{clustNum},1:xlimCalcium),[1.5 4.5]); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceOdd{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.Iodd{clustNum},1:xlimCalcium),[1.5 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off + + %plot even flightpath for cluster #2 + for flight_i = 2:2:length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum}) + subplot(3,length(ROIs_manual(:,1))*2,day_i*2); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + %plot even velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*2 + (day_i*2)); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + %plot even trials for all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*4 + (day_i*2)); + imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceEven{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.Iodd{clustNum},1:xlimCalcium),[1.5 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end + +%% 1st half/2nd half: plot all stable ROIs across all 9 days sorted by order of ROIs +plotSnake_acrossDays_1st2ndHalf = figure('units','normalized','outerposition',[0 0 1 1]); +sgtitle(['1st Half vs 2nd Half Trials Across ' num2str(length(ROIs_manual(:,1))) ' Days for Same Flight Path: ' batId]); +col = jet(length(ROIs_manual(:,1))); +for day_i = 1:length(ROIs_manual(:,1)) + % split the trials in 1st/2nd half and smooth/normalize + traceSmooth = 3; + firstHalf = zeros(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + secondHalf = zeros(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + meanTrace1stHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + normTrace1stHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + meanTrace2ndHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + normTrace2ndHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + I1stHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + B1stHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + I2ndHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + B2ndHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + maxNormTrace1stHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + maxNormTrace2ndHalf = cell(length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight),1); + for clust_i = 1:length(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight) + firstHalf(clust_i) = round(length(flightPathsF(day_i).flightPaths.clusterIndex{clust_i})/2); + secondHalf(clust_i) = length(flightPathsF(day_i).flightPaths.clusterIndex{clust_i}); + + meanTrace1stHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i},2)); + normTrace1stHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i},2)); + meanTrace2ndHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i},2)); + normTrace2ndHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i},2)); + maxNormTrace1stHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),1); + maxNormTrace2ndHalf{clust_i} = zeros(size(ROIs_manual(1,:),2),1); + %cellCount = 1; + nRois = size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i},3); + nRoisStable = size(ROIs_manual(1,:),2); + for cell_i = 1:nRois + %try + meanTrace1stHalf{clust_i}(cell_i,:) = nanmean(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i}(1:firstHalf(clust_i),:,cell_i),1); + meanTrace2ndHalf{clust_i}(cell_i,:) = nanmean(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i}(firstHalf(clust_i)+1:secondHalf(clust_i),:,cell_i),1); + %catch + %meanTrace1stHalf{clust_i}(cell_i,:) = nan(1,size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i}(1:firstHalf(clust_i),:,1),2)); + %meanTrace2ndHalf{clust_i}(cell_i,:) = nan(1,size(snakeTraceT(day_i).snakeTrace.cRaw.traceFlight{clust_i}(firstHalf(clust_i)+1:secondHalf(clust_i),:,1),2)); + %end + normTrace1stHalf{clust_i}(cell_i,:) = zscore(smooth(meanTrace1stHalf{clust_i}(cell_i,:),traceSmooth)); + normTrace1stHalf{clust_i}(cell_i,:) = normTrace1stHalf{clust_i}(cell_i,:) - min(normTrace1stHalf{clust_i}(cell_i,:)); + [~,maxNormTrace1stHalf{clust_i}(cell_i,1)] = max(normTrace1stHalf{clust_i}(cell_i,:)); + + normTrace2ndHalf{clust_i}(cell_i,:) = zscore(smooth(meanTrace2ndHalf{clust_i}(cell_i,:),traceSmooth)); + normTrace2ndHalf{clust_i}(cell_i,:) = normTrace2ndHalf{clust_i}(cell_i,:) - min(normTrace2ndHalf{clust_i}(cell_i,:)); + [~,maxNormTrace2ndHalf{clust_i}(cell_i,1)] = max(normTrace2ndHalf{clust_i}(cell_i,:)); + + cellCount = cellCount + 1; + end + [B1stHalf{clust_i},I1stHalf{clust_i}] = sort(maxNormTrace1stHalf{clust_i}); + [B2ndHalf{clust_i},I2ndHalf{clust_i}] = sort(maxNormTrace2ndHalf{clust_i}); + end + + %plot 1st half of session flights for cluster #2 + for flight_i = 1:firstHalf(clustNum) + subplot(3,length(ROIs_manual(:,1))*2,(day_i*2)-1); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + %plot 1st half velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*2 + (day_i*2)-1); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + %plot 1st half trials for all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,2*length(ROIs_manual(:,1)), 4*length(ROIs_manual(:,1)) + (day_i*2)-1); + %imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceOdd{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.Iodd{clustNum},1:xlimCalcium),[1.5 4.5]); + imagesc(normTrace1stHalf{clustNum}(I1stHalf{clustNum}(end-nRoisStable:end),1:xlimCalcium),[1.5 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off + + %plot 2nd half flightpath for cluster #2 + for flight_i = (firstHalf(clustNum) + 1):secondHalf(clustNum) + subplot(3,length(ROIs_manual(:,1))*2,day_i*2); + plot3(flightPathsF(day_i).flightPaths.pos(1,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(2,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),flightPathsF(day_i).flightPaths.pos(3,:,flightPathsF(day_i).flightPaths.clusterIndex{clustNum}(flight_i)),... + '-','LineWidth',1,'Color', col(day_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Day ' num2str(day_i)]); + if day_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + %plot 2nd half velocity for cluster #2 + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*2 + (day_i*2)); + plot(1:length(snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)),snakeTraceT(day_i).snakeTrace.cRaw.smoothSpeedRawFlight{clustNum}(flight_i,1:xlimFlight)); + hold on; + if day_i == 1 + ylabel('Velocity (m/s)'); + xlabel('Time (s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + title([num2str(length(flightPathsF(day_i).flightPaths.clusterIndex{clustNum})) ' flights']); + end + %plot 2nd half trials for all ROIs normalized to itself and plotted in 1-n numerical order + %across all days + subplot(3,length(ROIs_manual(:,1))*2, length(ROIs_manual(:,1))*4 + (day_i*2)); + %imagesc(snakeTraceT(day_i).snakeTrace.cRaw.normTraceEven{clustNum}(snakeTraceT(day_i).snakeTrace.cRaw.Iodd{clustNum},1:xlimCalcium),[1.5 4.5]); + imagesc(normTrace2ndHalf{clustNum}(I2ndHalf{clustNum}(end-nRoisStable:end),1:xlimCalcium),[1.5 4.5]); + colormap(hot); + if day_i == 1 + ylabel('ROI #'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + else + set(gca,'xticklabel',[]); + end + hold off +end +%% save +if saveFlag ==1 + saveas(plotSnake_acrossDays,[saveDir filesep batId '_snakePlot_acrossDays.tif']); + savefig(plotSnake_acrossDays,[saveDir filesep batId '_snakePlot_acrossDays.fig']); + saveas(plotSnake_acrossDays_prefEach,[saveDir filesep batId '_snakePlot_acrossDays_prefEach.tif']); + savefig(plotSnake_acrossDays_prefEach,[saveDir filesep batId '_snakePlot_acrossDays_prefEach.fig']); + saveas(plotSnake_acrossDays_pref1,[saveDir filesep batId '_snakePlot_acrossDays_pref1.tif']); + savefig(plotSnake_acrossDays_pref1,[saveDir filesep batId '_snakePlot_acrossDays_pref1.fig']); + saveas(plotSnake_acrossDays_pre,[saveDir filesep batId '_snakePlot_acrossDays_pre.tif']); + savefig(plotSnake_acrossDays_pre,[saveDir filesep batId '_snakePlot_acrossDays_pre.fig']); + saveas(plotSnake_acrossDays_prefEach_pre,[saveDir filesep batId '_snakePlot_acrossDays_prefEach_pre.tif']); + savefig(plotSnake_acrossDays_prefEach_pre,[saveDir filesep batId '_snakePlot_acrossDays_prefEach_pre.fig']); + saveas(plotSnake_acrossDays_pref1_pre,[saveDir filesep batId '_snakePlot_acrossDays_pref1_pre.tif']); + savefig(plotSnake_acrossDays_pref1_pre,[saveDir filesep batId '_snakePlot_acrossDays_pref1_pre.fig']); + saveas(plotSnake_acrossDays_post,[saveDir filesep batId '_snakePlot_acrossDays_pre.tif']); + savefig(plotSnake_acrossDays_post,[saveDir filesep batId '_snakePlot_acrossDays_pre.fig']); + saveas(plotSnake_acrossDays_prefEach_post,[saveDir filesep batId '_snakePlot_acrossDays_prefEach_post.tif']); + savefig(plotSnake_acrossDays_prefEach_post,[saveDir filesep batId '_snakePlot_acrossDays_prefEach_post.fig']); + saveas(plotSnake_acrossDays_pref1_post,[saveDir filesep batId '_snakePlot_acrossDays_pref1_post.tif']); + savefig(plotSnake_acrossDays_pref1_post,[saveDir filesep batId '_snakePlot_acrossDays_pref1_post.fig']); + saveas(plotSnake_acrossDays_oddEven,[saveDir filesep batId '_snakePlot_acrossDays_oddEven.tif']); + savefig(plotSnake_acrossDays_oddEven,[saveDir filesep batId '_snakePlot_acrossDays_oddEven.fig']); + saveas(plotSnake_acrossDays_1st2ndHalf,[saveDir filesep batId '_snakePlot_acrossDays_1st2ndHalf.tif']); + savefig(plotSnake_acrossDays_1st2ndHalf,[saveDir filesep batId '_snakePlot_acrossDays_1st2ndHalf.fig']); +end \ No newline at end of file diff --git a/snakePlot/ImBat_psth_allClust.m b/snakePlot/ImBat_psth_allClust.m new file mode 100644 index 0000000..8648fc4 --- /dev/null +++ b/snakePlot/ImBat_psth_allClust.m @@ -0,0 +1,92 @@ +function [psth_plots] = ImBat_psth_allClust(flightPaths,snakeTrace_cRaw,varargin) +% User inputs overrides +saveFlag = 0; + +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'saveflag' + saveFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + end +end + +%% plot +% for each cell, for each cluster, plot flight paths, velocity, mean/std, and each trial +nCells = size(snakeTrace_cRaw.smoothTraceRawFlight{1},3); %number of cells in this day +nClusts = size(snakeTrace_cRaw.smoothTraceRawFlight,2); %number of clusters in this day + +for cell_i = 1:nCells + psth_each_cell = figure('units','normalized','outerposition',[0 0.1 0.8 0.8]); + sgtitle(['Flight Aligned Activity per cluster: ' batName ' ' dateSesh ' Cell# ' num2str(cell_i)]); + colClust = jet(nClusts); %color each cluster differently) + for clust_i = 1:nClusts + %plot flight paths of each cluster + nFlights = size(snakeTrace_cRaw.smoothTraceRawFlight{clust_i},1); %number of flights in this cluster + colFlight = jet(nFlights); %color each cluster differently) + for flight_i = 1:nFlights + plotPaths = subplot(10,nClusts,[clust_i nClusts+clust_i]); + plot3(flightPaths.pos(1,:,flightPaths.clusterIndex{clust_i}(flight_i)),flightPaths.pos(2,:,flightPaths.clusterIndex{clust_i}(flight_i)),flightPaths.pos(3,:,flightPaths.clusterIndex{clust_i}(flight_i)),... + '-','LineWidth',1,'Color', colClust(clust_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Clust ' num2str(clust_i)]); + if clust_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity of each cluster + plotVelocity = subplot(10,nClusts,[clust_i+2*nClusts clust_i+3*nClusts]); + plot(1:length(snakeTrace_cRaw.smoothSpeedRawFlight{clust_i}(flight_i,:)),snakeTrace_cRaw.smoothSpeedRawFlight{clust_i}(flight_i,:)); + hold on; + if clust_i == 1 + ylabel('Velocity (m/s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + xlim([0 length(snakeTrace_cRaw.smoothSpeedRawFlight{clust_i}(flight_i,:))]); + + %plot each flight activity + plotIndivTraces = subplot(10,nClusts,[clust_i+6*nClusts:nClusts:clust_i+9*nClusts]); + plot(1:length(snakeTrace_cRaw.normTraceRawFlight{clust_i}(flight_i,:,cell_i)),(snakeTrace_cRaw.normTraceRawFlight{clust_i}(flight_i,:,cell_i))+flight_i*6,'Color',colClust(clust_i,:)); + hold on; + if clust_i == 1 + ylabel('Flight trials (df/f)'); + end + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlim([0 length(snakeTrace_cRaw.normTraceRawFlight{clust_i}(flight_i,:,cell_i))]); + end + %plot mean and stdev of activity per cluster + plotMeanTraces = subplot(10,nClusts,[clust_i+4*nClusts clust_i+5*nClusts]); + boundedline(1:length(snakeTrace_cRaw.normTraceFlight{clust_i}(cell_i,:)),snakeTrace_cRaw.normTraceFlight{clust_i}(cell_i,:),snakeTrace_cRaw.sdTraceFlight{clust_i}(cell_i,:),'alpha','cmap',colClust(clust_i,:)); + hold on; + ylabel('Mean stdev df/f'); + set(gca,'xticklabel',[]); + xlim([0 length(snakeTrace_cRaw.normTraceFlight{clust_i}(cell_i,:))]); + end + + %% save + % Save 'place cells' as jpg and fig files.. + saveas(psth_each_cell,[pwd filesep batName '_' dateSesh '_' sessionType '_psth_clusts' num2str(cell_i) '.tif']); + savefig(psth_each_cell,[pwd filesep batName '_' dateSesh '_' sessionType '_psth_clusts' num2str(cell_i) '.fig']); + %saveas(psth_each_cell,[pwd filesep batName '_' dateSesh '_' sessionType '_psth_clusts' num2str(cell_i) '.svg']); + close gcf; +end \ No newline at end of file diff --git a/snakePlot/ImBat_psth_plot_acrossDays.m b/snakePlot/ImBat_psth_plot_acrossDays.m new file mode 100644 index 0000000..f3c4ed2 --- /dev/null +++ b/snakePlot/ImBat_psth_plot_acrossDays.m @@ -0,0 +1,67 @@ +function ImBat_psth_plot_acrossDays(psth_stableROI) +saveFlag = 1; +plotDir = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +colDay = jet(length(psth_stableROI.velocity)); +% Check if folder exists +if exist([plotDir datestr(now,'yymmdd')])>0; + disp('Youve been working today..'); +else + mkdir([plotDir datestr(now,'yymmdd')]) +end +saveDir = [plotDir datestr(now,'yymmdd') '\']; +%cd(saveDir); +plotPSTH_acrossDays = figure('units','normalized','outerposition',[0 0.1 0.4 0.8]); +for cell_ii = 1:size(psth_stableROI.traceMean{1}{1},1) + for day_ii = 1:length(psth_stableROI.velocity) + %try + %plot flight paths of each cluster + nFlights = size(psth_stableROI.velocity{day_ii}{2}{1},1); %number of flights in this cluster + colFlight = jet(nFlights); %color each cluster differently) + for flight_i = 1:nFlights + plotPaths = subplot(10,1,[1 2]); + plot3(squeeze(psth_stableROI.flight{day_ii}{2}{cell_ii}(flight_i,1,:)),squeeze(psth_stableROI.flight{day_ii}{2}{cell_ii}(flight_i,2,:)),squeeze(psth_stableROI.flight{day_ii}{2}{cell_ii}(flight_i,3,:)),... + '-','LineWidth',1,'Color',colDay(day_ii,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['ROI # ' num2str(cell_ii) ': Gal 200311to20 - clust2']); + xlabel('m'); ylabel('m'); + + %plot velocity of each cluster + plotVelocity = subplot(10,1,[3 4]); + plot(1:length(psth_stableROI.velocity{day_ii}{2}{cell_ii}(flight_i,:)),psth_stableROI.velocity{day_ii}{2}{cell_ii}(flight_i,:),'Color',colDay(day_ii,:)); + hold on; + ylabel('Velocity (m/s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + + ylim([0 4.5]); + xlim([0 length(psth_stableROI.velocity{1}{2}{cell_ii}(1,:))]); + + end + %plot mean and stdev of activity per cluster + plotMeanTraces = subplot(10,1,[5 10]); + boundedline(1:length(psth_stableROI.traceMean{day_ii}{2}(cell_ii,:)),psth_stableROI.traceMean{day_ii}{2}(cell_ii,:),psth_stableROI.traceStd{day_ii}{2}(cell_ii,:),... + 'alpha','cmap',colDay(day_ii,:),'nan','gap'); + hold on; + ylabel('Mean stdev df/f'); + set(gca,'xticklabel',[]); + xlim([0 length(psth_stableROI.traceMean{1}{2}(cell_ii,:))]); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + % catch + % sgtitle(['Flight Aligned Activity per cluster: Gal All Cell# ' num2str(cell_ii) ' NO ACTIVITY']); + % end + + end + drawnow; + if saveFlag == 1 + saveas(plotPSTH_acrossDays,[saveDir filesep 'Gal_200311to20_psth_acrossDays_ROI' num2str(cell_ii) datestr(now,'yymmdd_HHMM') '.tif']); + savefig(plotPSTH_acrossDays,[saveDir filesep 'Gal_200311to20_psth_acrossDays_ROI' num2str(cell_ii) datestr(now,'yymmdd_HHMM') '.fig']); + end + clf; +end \ No newline at end of file diff --git a/snakePlot/ImBat_psth_stableROI.m b/snakePlot/ImBat_psth_stableROI.m new file mode 100644 index 0000000..feba2d1 --- /dev/null +++ b/snakePlot/ImBat_psth_stableROI.m @@ -0,0 +1,346 @@ +function [psth_stableROI] = ImBat_psth_stableROI(varargin) +%function to plot firing fields as red dots against the flight paths of the +%bats for each day focusing only on the stable neurons from ROIs_manual +plotPSTHclustFlag = 0; +batId = ''; +saveFlag = 0; %do you want to save the figures and output structure? +cRaw_flag = 1; +clustNum = 2; %which cluster trajectory to look at for each day + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'saveflag' + saveFlag=varargin{i+1}; + case 'batid' + batId = varargin{i+1}; + case 'plotpsthclustflag' + plotPSTHclustFlag = varargin{i+1}; + end +end + +if saveFlag == 1 +saveDir1 = '\\169.229.54.11\server_home\users\tobias\flight\data_processed\topQualityData\analysis_done\plots\'; +% Check if folder exists +if exist([saveDir1 datestr(now,'yymmdd') filesep 'psth_stableROI'])>0; + disp('Youve been working today..'); +else + mkdir([saveDir1 datestr(now,'yymmdd') filesep 'psth_stableROI']) +end +saveDir = [saveDir1 datestr(now,'yymmdd') filesep 'psth_stableROI' '\']; +end + +if strcmp(batId,'Gal') +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_manual = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 25 6 30 27 3 1 2 9 8 37 NaN 15 31 24 36; + 8 12 35 20 1 10 2 39 9 30 3 14 31 24 11; + 10 7 39 35 3 31 8 22 9 37 5 11 39 17 2; + 9 27 25 45 1 7 8 46 11 33 23 6 42 3 2; + 20 34 29 51 7 10 6 40 16 45 5 8 42 26 43; + 8 2 25 38 16 44 20 7 14 26 3 35 37 24 41; + 1 7 28 NaN 6 17 2 35 16 33 12 11 27 30 34; + 19 4 16 NaN 27 21 3 24 2 29 14 8 26 32 33]; +g = dir('Ga*'); +elseif strcmp(batId,'Gen') +% 20 stable manually selected ROIs across 5 days for Gen +ROIs_manual = [NaN NaN 10 3 16 12 17 18 27 29 8 9 NaN NaN 21 11 31 15 20 25; + 8 17 5 1 2 6 21 10 18 31 NaN 11 51 53 28 4 38 19 23 20; + 50 54 12 3 48 18 27 15 31 34 NaN NaN 28 NaN 29 25 24 22 38 14; + 9 NaN 7 31 2 22 NaN 20 40 25 13 NaN 34 NaN 26 NaN 45 3 24 21; + 10 36 3 11 2 NaN 21 18 20 9 33 NaN NaN NaN 17 NaN 22 7 30 26]; %14 NaN 3 28 2 6 33 26 18 45 NaN NaN 25 NaN 32 NaN 37 8 28 11 +g = dir('Ge*'); +end +z = dir('Z1*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +%ROI_duplicate = cell(length(dirTop),1); %make cell for indices of duplicated ROIS + +%initialize cells to collect vectors from each day +traceMean = cell(length(dirTop)); +traceStd = cell(length(dirTop)); +velocity = cell(length(dirTop)); +flight = cell(length(dirTop)); +traceIndiv = cell(length(dirTop)); +colDay = jet(length(dirTop)); + +for day_i = 1:length(dirTop) + %load results data + try %extract metadata names and enter processed folder + cd([dirTop(day_i).name filesep 'extracted']) + flyFolders = dir('*fly*extraction'); + batName{day_i} = flyFolders(end).name(1:3); + dateSesh{day_i} = flyFolders(end).name(5:10); + sessionType{day_i} = flyFolders(end).name(12:16); + cd(flyFolders(end).name); + catch + cd(dirTop(day_i).name); + flyFolders = dir('*fly*extraction'); + batName{day_i} = flyFolders(end).name(1:3); + dateSesh{day_i} = flyFolders(end).name(5:10); + sessionType{day_i} = flyFolders(end).name(12:16); + cd(flyFolders(end).name); + end + + %load flightPaths and snakeTrace data + %extract metadata names and enter analysis folder + dirAnalysis = dir('analysis_*'); + if strcmp(batName{day_i}(1),'G') + cd(dirAnalysis(end).name); + else + cd(dirAnalysis(end).name); + end + %load snakeTrace_cRaw data + st = dir('*snakePlotData.mat'); + load(st(end).name); + if cRaw_flag == 1 + snakeTrace_data = snakeTrace.cRaw; + else + snakeTrace_data = snakeTrace.s; + end + fp = dir('*flightPaths.mat'); + load(fp(end).name); + close all; + %take out means and stds from cluster 2 from each day and cell and save into variable + %to plot later + nROIs = size(ROIs_manual,2); %number of tractable ROIs + nClusts = size(snakeTrace_data.smoothTraceRawFlight,2); %number of clusters in this day + traceMean{day_i} = cell(nClusts,1); + traceStd{day_i} = cell(nClusts,1); + velocity{day_i} = cell(nClusts,1); + flight{day_i} = cell(nClusts,1); + traceIndiv{day_i} = cell(nClusts,1); + + for clust_ii = 1:nClusts + nFlights = size(snakeTrace_data.smoothSpeedRawFlight{clust_ii},1);%size(flightPaths.clusterIndex{clust_ii},1); + traceMean{day_i}{clust_ii} = zeros(nROIs,length(snakeTrace_data.normTraceFlight{clust_ii}(1,:))); + traceStd{day_i}{clust_ii} = zeros(nROIs,length(snakeTrace_data.sdTraceFlight{clust_ii}(1,:))); + velocity{day_i}{clust_ii} = cell(nROIs,1); + flight{day_i}{clust_ii} = cell(nROIs,1); + traceIndiv{day_i}{clust_ii} = cell(nROIs,1); + + for ROI_i = 1:nROIs + try + traceMean{day_i}{clust_ii}(ROI_i,:) = snakeTrace_data.normTraceFlight{clust_ii}(ROIs_manual(day_i,ROI_i),:); + traceStd{day_i}{clust_ii}(ROI_i,:) = snakeTrace_data.sdTraceFlight{clust_ii}(ROIs_manual(day_i,ROI_i),:); + catch + traceMean{day_i}{clust_ii}(ROI_i,:) = zeros(1,length(snakeTrace_data.normTraceFlight{clust_ii}(1,:))); + traceStd{day_i}{clust_ii}(ROI_i,:) = zeros(1,length(snakeTrace_data.sdTraceFlight{clust_ii}(1,:))); + end + velocity{day_i}{clust_ii}{ROI_i} = zeros(nFlights,length(snakeTrace_data.smoothSpeedRawFlight{clust_ii}(1,:))); + flight{day_i}{clust_ii}{ROI_i} = zeros(nFlights,3,length(flightPaths.pos(1,:,1)));%,length(snakeTrace_cRaw.sdTraceFlight{clust_ii}(1,:)),length(snakeTrace_cRaw.sdTraceFlight{clust_ii}(1,:))); + traceIndiv{day_i}{clust_ii}{ROI_i} = zeros(nFlights,length(snakeTrace_data.sdTraceFlight{clust_ii}(1,:))); + for flight_i = 1:nFlights + velocity{day_i}{clust_ii}{ROI_i}(flight_i,:) = snakeTrace_data.smoothSpeedRawFlight{clust_ii}(flight_i,:); + flight{day_i}{clust_ii}{ROI_i}(flight_i,:,:,:) = flightPaths.pos(1:3,:,flightPaths.clusterIndex{clust_ii}(flight_i)); + try + traceIndiv{day_i}{clust_ii}{ROI_i}(flight_i,:) = snakeTrace_data.normTraceRawFlight{clust_ii}(flight_i,:,ROIs_manual(day_i,ROI_i)); + catch + traceIndiv{day_i}{clust_ii}{ROI_i}(flight_i,:) = zeros(1,length(snakeTrace_data.normTraceRawFlight{clust_ii}(flight_i,:,ROIs_manual(day_i,end)))); + end + end + end + end + + %% plot the full psth with all clusters for tractable ROIs + if plotPSTHclustFlag == 1 + %for each cell, for each cluster, plot flight paths, velocity, mean/std, and each trial + nCells = size(ROIs_manual,2); %number of cells in this day + nClusts = size(snakeTrace_data.smoothTraceRawFlight,2); %number of clusters in this day + psth_each_cell = figure('units','normalized','outerposition',[0 0.1 0.8 0.8]); + for cell_i = 1:nCells + sgtitle(['Flight Aligned Activity per cluster: ' batName{day_i} ' ' dateSesh{day_i} ' Cell# ' num2str(cell_i)]); + colClust = jet(nClusts); %color each cluster differently) + try + for clust_i = 1:nClusts + %plot flight paths of each cluster + nFlights = size(snakeTrace_data.smoothTraceRawFlight{clust_i},1); %number of flights in this cluster + colFlight = jet(nFlights); %color each cluster differently) + for flight_i = 1:nFlights + plotPaths = subplot(10,nClusts,[clust_i nClusts+clust_i]); + plot3(flightPaths.pos(1,:,flightPaths.clusterIndex{clust_i}(flight_i)),flightPaths.pos(2,:,flightPaths.clusterIndex{clust_i}(flight_i)),flightPaths.pos(3,:,flightPaths.clusterIndex{clust_i}(flight_i)),... + '-','LineWidth',1,'Color', colDay(clust_i,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + title(['Clust ' num2str(clust_i)]); + if clust_i == 1 + xlabel('m'); ylabel('m'); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + + %plot velocity of each cluster + plotVelocity = subplot(10,nClusts,[clust_i+2*nClusts clust_i+3*nClusts]); + plot(1:length(snakeTrace_data.smoothSpeedRawFlight{clust_i}(flight_i,:)),snakeTrace_data.smoothSpeedRawFlight{clust_i}(flight_i,:),'Color',colDay(clust_i,:)); + hold on; + if clust_i == 1 + ylabel('Velocity (m/s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + else + set(gca,'xticklabel',[],'yticklabel',[]); + end + ylim([0 4.5]); + xlim([0 length(snakeTrace_data.smoothSpeedRawFlight{clust_i}(flight_i,:))]); + + %plot each flight activity + plotIndivTraces = subplot(10,nClusts,[clust_i+6*nClusts:nClusts:clust_i+9*nClusts]); + plot(1:length(snakeTrace_data.normTraceRawFlight{clust_i}(flight_i,:,ROIs_manual(day_i,cell_i))),(snakeTrace_data.normTraceRawFlight{clust_i}(flight_i,:,ROIs_manual(day_i,cell_i)))+flight_i*6,'Color',colDay(clust_i,:)); + hold on; + if clust_i == 1 + ylabel('Flight trials (df/f)'); + end + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + xlim([0 length(snakeTrace_data.normTraceRawFlight{clust_i}(flight_i,:,ROIs_manual(day_i,cell_i)))]); + end + %plot mean and stdev of activity per cluster + plotMeanTraces = subplot(10,nClusts,[clust_i+4*nClusts clust_i+5*nClusts]); + boundedline(1:length(psth_stableROI.traceMean{day_ii}{clustNum}(cell_ii,:)),psth_stableROI.traceMean{day_ii}{clustNum}(cell_ii,:),psth_stableROI.traceStd{day_ii}{clustNum}(cell_ii,:),... + 'alpha','cmap',colDay(day_ii,:),'nan','gap'); + hold on; + ylabel('Mean stdev df/f'); + set(gca,'xticklabel',[]); + xlim([0 length(snakeTrace_data.normTraceFlight{clust_i}(ROIs_manual(day_i,cell_i),:))]); + end + catch + sgtitle(['Flight Aligned Activity per cluster: ' batName{day_i} ' ' dateSesh{day_i} ' Cell# ' num2str(cell_i) ' NO ACTIVITY']); + end + + % save + % Save 'place cells' as jpg and fig files.. + if saveFlag == 1 + saveas(psth_each_cell,[saveDir filesep batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} '_psth_clusts_' num2str(cell_i) '_' datestr(now,'yymmdd-HHMM') '.tif']); + savefig(psth_each_cell,[saveDir filesep batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} '_psth_clusts_' num2str(cell_i) '_' datestr(now,'yymmdd-HHMM') '.fig']); + %saveas(psth_each_cell,[pwd filesep batName '_' dateSesh '_' sessionType '_psth_clusts' num2str(cell_i) '.svg']); + end + clf; + + end + end + cd(dirTop(day_i).folder) +end + + psth_stableROI.traceMean = traceMean; + psth_stableROI.traceStd = traceStd; + psth_stableROI.velocity = velocity; + psth_stableROI.flight = flight; + psth_stableROI.traceIndiv = traceIndiv; + if saveFlag ==1 + save([saveDir filesep batName{day_i} '_' dateSesh{day_i} '_' sessionType{day_i} 'psth_stableROIdata_' datestr(now,'yymmdd-HHMM') '.mat'],'psth_stableROI'); + end + +%% +plotPSTH_acrossDays = figure('units','normalized','outerposition',[0 0.1 0.4 0.8]); +for cell_ii = 1:nROIs + for day_ii = 1:length(dirTop) + try + %plot flight paths of each cluster + nFlights = size(psth_stableROI.velocity{day_ii}{clustNum}{1},1); %number of flights in this cluster + colFlight = jet(nFlights); %color each cluster differently) + for flight_i = 1:nFlights + plotPaths = subplot(10,1,[1 2]); + plot3(squeeze(psth_stableROI.flight{day_ii}{clustNum}{cell_ii}(flight_i,1,:)),squeeze(psth_stableROI.flight{day_ii}{clustNum}{cell_ii}(flight_i,2,:)),squeeze(psth_stableROI.flight{day_ii}{clustNum}{cell_ii}(flight_i,3,:)),... + '-','LineWidth',1,'Color',colDay(day_ii,:)); + hold on; + view(0,90); + xlim([-3 3]) + ylim([-3 3]) + if strcmp(batId,'Gal') + title(['ROI # ' num2str(cell_ii) ': Gal 200311to20 - clust' num2str(clustNum)]); + elseif strcmp(batId,'Gen') + title(['ROI # ' num2str(cell_ii) ': Gen 200319to24 - clust' num2str(clustNum)]); + end + xlabel('m'); ylabel('m'); + + %plot velocity of each cluster + plotVelocity = subplot(10,1,[3 4]); + plot(1:length(psth_stableROI.velocity{day_ii}{clustNum}{cell_ii}(flight_i,:)),psth_stableROI.velocity{day_ii}{clustNum}{cell_ii}(flight_i,:),'Color',colDay(day_ii,:)); + hold on; + ylabel('Velocity (m/s)'); + yt = get(gca,'YTick'); + xt = get(gca,'XTick'); + set(gca,'xticklabel',[]); + %set(gca,'YTick',yt,'YTickLabel',yt,'xTickLabel',round(xt/120,1)); + ylim([0 4.5]); + %xlim([0 length(psth_stableROI.velocity{1}{clustNum}{cell_ii}(1,:))]); + + end + %plot mean and stdev of activity per cluster + plotMeanTraces = subplot(10,1,[5 10]); + p(day_ii) = boundedline(1:length(psth_stableROI.traceMean{day_ii}{clustNum}(cell_ii,:)),psth_stableROI.traceMean{day_ii}{clustNum}(cell_ii,:),psth_stableROI.traceStd{day_ii}{clustNum}(cell_ii,:),... + 'alpha','cmap',colDay(day_ii,:),'nan','gap'); + hold on; + ylabel('Mean stdev df/f'); + xlabel('Time (s)'); + xt = get(gca, 'XTick'); + set(gca,'XTick',xt,'XTickLabel',round(xt/30,1)); + %xlim([0 length(psth_stableROI.traceMean{1}{clustNum}(cell_ii,:))]); + catch + sgtitle(['Flight Aligned Activity per cluster: ' batName{day_ii} ' ' dateSesh{day_ii} ' Cell# ' num2str(cell_ii) ' NO ACTIVITY']); + end + + end + if strcmp(batId,'Gal') + legend([p(1),p(2),p(3),p(4),p(5),p(6),p(7),p(8),p(9)],'Day 1','Day 2','Day 3','Day 4','Day 5','Day 6','Day 7','Day 8','Day 9'); + elseif strcmp(batId,'Gen') + legend([p(1),p(2),p(3),p(4),p(5)],'Day 1','Day 2','Day 3','Day 4','Day 5'); + end + drawnow; + if saveFlag == 1 + if strcmp(batId,'Gal') + saveas(plotPSTH_acrossDays,[saveDir filesep 'Gal_200311to20_psth_acrossDays_clust' num2str(clustNum) '_ROI' num2str(cell_ii) '_' datestr(now,'yymmdd_HHMM') '.tif']); + savefig(plotPSTH_acrossDays,[saveDir filesep 'Gal_200311to20_psth_acrossDays_clust' num2str(clustNum) '_ROI' num2str(cell_ii) '_' datestr(now,'yymmdd_HHMM') '.fig']); + elseif strcmp(batId,'Gen') + saveas(plotPSTH_acrossDays,[saveDir filesep 'Gen_200319to24_psth_acrossDays_clust' num2str(clustNum) '_ROI' num2str(cell_ii) '_' datestr(now,'yymmdd_HHMM') '.tif']); + savefig(plotPSTH_acrossDays,[saveDir filesep 'Gen_200319to24_psth_acrossDays_clust' num2str(clustNum) '_ROI' num2str(cell_ii) '_' datestr(now,'yymmdd_HHMM') '.fig']); + end + end + clf; +end +cd(dirTop(day_i).folder) +end +% +% +% +% % %% load all figures from 1 ROI and save in subplots so can compare across days for same ROI +% % cd(['plots' filesep datestr(now,'yymmdd')]); +% % for cell_ii = 1:length(ROIs_manual(1,:)) +% % figDir = dir(['*psth_clusts_' num2str(cell_ii) '.fig']) +% % plotPSTHAcrossDays(cell_ii) = figure('units','normalized','outerposition',[0 0 1 0.8]); +% % sgtitle(['Gal PSTH 200311-200320: Clust2 ROI' num2str(cell_ii)]); +% % for ii = 1:length(figDir) +% % figure(plotPSTHAcrossDays(cell_ii)) +% % % Prepare subplots +% % velocities(ii)=subplot(10,1,3:4); +% % meanTraces(ii)=subplot(10,1,5:10); +% % paths(ii)=subplot(10,1,1:2); +% % title(['Day ' num2str(ii)]); +% % hold on; +% % +% % % Load saved figures +% % figPaths(ii)=hgload(figDir(ii).name); +% % % Paste figures on the subplots +% % copyobj(figPaths(ii).plotPaths,paths(ii)); +% % copyobj(figPaths(ii).plotVelocity,velocities(ii)); +% % copyobj(figPaths(ii).plotMeanTraces,meanTraces(ii)); +% % %copyobj(allchild(get(figPaths(ii),'CurrentAxes')),paths(ii)); +% % +% % end +% % if saveFlag == 1 +% % saveas(plotFiringTrajectoryAcrossDays(cell_ii),[pwd filesep datestr(now,'yymmdd-HHMM') '_' 'Gal_200311to20_placeCell_' num2str(cell_ii) '_acrossDays.tif']); +% % savefig(plotFiringTrajectoryAcrossDays(cell_ii),[pwd filesep datestr(now,'yymmdd-HHMM') '_' 'Gal_200311to20_placeCell_' num2str(cell_ii) '_acrossDays.fig']); +% % end +% % +% % close gcf; +% % end + diff --git a/snakePlot/ImBat_snakeData.m b/snakePlot/ImBat_snakeData.m index 09c4489..ec919b0 100644 --- a/snakePlot/ImBat_snakeData.m +++ b/snakePlot/ImBat_snakeData.m @@ -1,12 +1,15 @@ -function [snakeTrace] = ImBat_snakeData(cellData,flightPaths,alignment,varargin) +function [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData(cellData,flightPaths,alignment,varargin) batName = []; dateSesh = []; sessionType = []; loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze saveFlag = 0; -%offset = 0.1; % account for slow calcium estimation ~move locations back 100ms in time... This is the knob to turn for 'prospective' coding... -nClusters = 5; %number of flight trajectories to look at and for k means clustering of whole time series by peak +%offset = 0.1; % account for slow calcium estimation ~move locations back 0ms in time... This is the knob to turn for 'prospective' coding... +%clusters = [1 2 4 6]; +%nClusters = 4;%length(clusters); %number of flight trajectories to look at and for k means clustering of whole time series by peak + + % User inputs overrides nparams=length(varargin); @@ -22,6 +25,14 @@ loadFlag = varargin{i+1}; case 'saveflag' saveFlag = varargin{i+1}; + case 'nclusters' + nClusters = varargin{i+1}; + case 'preflightpad' + preFlightPad = varargin{i+1}; + case 'postflightpad' + postFlightPad = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; end end @@ -32,377 +43,560 @@ cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); alignment = load([pwd '/processed/Alignment.mat']); - load([pwd '/analysis/' label '_flightPaths_6clusters.mat']); + load([pewd '/' analysis_Folder '/' label '_flightPaths.mat']); end %padding for during flight snake plot to include some time before and after flight -prePad = 0; %number of seconds to plot before alignment point -postPad = 0; %number of seconds to plot after alignment point +prePad = 3; %number of seconds to plot before alignment point +postPad = 7; %number of seconds to plot after alignment point prePadCalcium = prePad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postPadCalcium = postPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time prePadSpeed = prePad*120; %add 2 seconds * FS of tracking data (120) postPadSpeed = postPad*120;%add 6 seconds * FS of tracking data (120) %padding for pre and post flight snakePlots -preFlightPad = 10; %number of seconds to include before flight starts -postFlightPad = 10; %of of seconds to include after flight ends +preFlightPad = 7; %number of seconds to include before flight starts +postFlightPad = 7; %of of seconds to include after flight ends preFlightPadCalcium = preFlightPad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postFlightPadCalcium = postFlightPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time preFlightPadSpeed = preFlightPad*120; %add 2 seconds * FS of tracking data (120) postFlightPadSpeed = postFlightPad*120;%add 6 seconds * FS of tracking data (120) +smoothSpeed = 100; %number of tracking frames to smooth the data by using mean smooth +smoothTrace = 2; %number of calcium video frames to smooth the data +%number of clusters to plot data against +if isfield(flightPaths,'nClusters') + nClusters = flightPaths.nClusters; +else + nClusters = length(flightPaths.clusterIndex); +end -%meanTrace = cell(1,length(flightPaths.clusterIndex)); -meanTraceFlightAll = []; %initialize the variable to concatenate all traces for uniform zscore -meanTracePreAll = []; %initialize the variable to concatenate all traces for uniform zscore -meanTracePostAll = []; %initialize the variable to concatenate all traces for uniform zscore -meanTracePreFlightPostAll = []; %initialize the variable to concatenate all pre/post/flight traces for uniform zscore - +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_gal = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 14 3 16 21 2 1 5 7 8 26 NaN 9 27 6 4; + 5 13 41 23 1 21 3 24 6 22 2 25 16 15 7; + 12 3 34 19 2 14 6 15 9 36 5 10 35 20 1; + 25 26 16 32 1 12 4 19 5 28 15 NaN 34 3 2; + 32 34 29 51 7 10 6 40 16 45 5 8 42 26 43]; +% if ~isempty(clustDelete) & clustDelete <6 +% flightPaths.clusterIndex{clustDelete} = []; +% end +%flightPaths.clusterIndex cat(2,flightPaths.clusterIndex{clustComb(1)},flightPaths.clusterIndex{clustComb(2)}); -%this is to merge specific clusters if 2 or more of them are the same but -%were separated by the flight k-means -flightPaths.clusterIndex{2}=cat(2,flightPaths.clusterIndex{2},flightPaths.clusterIndex{3}); -flightPaths.clusterIndex{3} =[]; -flightPaths.clusterIndex= flightPaths.clusterIndex(~cellfun('isempty',flightPaths.clusterIndex)); + %flightPaths.clusterIndex{3} =flightPaths.clusterIndex{6}; +% flightPaths.clusterIndex{3} =[]; +%flightPaths.clusterIndex= flightPaths.clusterIndex(~cellfun('isempty',flightPaths.clusterIndex)); -%for each cluster type -for clust_i = 1:nClusters %length(flightPaths.clusterIndex) - %for each cell - for cell_i = 1:length(cellData.results.C(:,1)) +%for each C_raw and C matrix +data_i = 1; %start with the cRaw data +for data_i = 1:3 + if data_i ==1 + traceData = cellData.results.C_raw; %assign the data from cnmfe output for C_raw matrix + traceSmooth = 3; %number of imaging frames to smooth the data by using mean smooth + elseif data_i ==2 + traceData = cellData.results.C; %assign the data from cnmfe output for C matrix + traceSmooth = 3; %number of imaging frames to smooth the data by using mean smooth + elseif data_i ==3 + traceData = cellData.results.S; %assign the data from cnmfe output for C matrix + traceSmooth = 1; %number of imaging frames to smooth the data by using mean smooth + end + + %initialize variables + %meanTrace = cell(1,length(flightPaths.clusterIndex)); + meanTraceFlightAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePreAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePostAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePreFlightPostAll = []; %initialize the variable to concatenate all pre/post/flight traces for uniform zscore + traceFlight = cell(1,nClusters); + tracePre = cell(1,nClusters); + tracePost = cell(1,nClusters); + speedFlight = cell(1,nClusters); + speedPre = cell(1,nClusters); + speedPost = cell(1,nClusters); + posFlight = cell(1,nClusters); + meanTraceFlight = cell(1,nClusters); + sdTraceFlight = cell(1,nClusters); + sdTracePre = cell(1,nClusters); + sdTracePost = cell(1,nClusters); + meanTraceOdd = cell(1,nClusters); + meanTraceEven = cell(1,nClusters); + meanTracePreFlightPost = cell(1,nClusters); + sdTracePreFlightPost = cell(1,nClusters); + normTraceFlight = cell(1,nClusters); + normTraceOdd= cell(1,nClusters); + normTraceEven = cell(1,nClusters); + tracePreFlightPost = cell(1,nClusters); + smoothTraceRawFlight = cell(1,nClusters); + normTraceRawFlight = cell(1,nClusters); + smoothTraceRawPre = cell(1,nClusters); + normTraceRawPre = cell(1,nClusters); + smoothTraceRawPost = cell(1,nClusters); + normTraceRawPost = cell(1,nClusters); + smoothTraceRawPreFlightPost = cell(1,nClusters); + normTraceRawPreFlightPost = cell(1,nClusters); + speedFlight = cell(1,nClusters); + smoothSpeedRawFlight = cell(1,nClusters); + smoothSpeedRawPre = cell(1,nClusters); + speedPre = cell(1,nClusters); + smoothSpeedRawPost = cell(1,nClusters); + speedPost = cell(1,nClusters); + speedPreFlightPost = cell(1,nClusters); + smoothSpeedRawPreFlightPost = cell(1,nClusters); + normTracePre = cell(1,nClusters); + smoothSpeedPre = cell(1,nClusters); + normTracePost = cell(1,nClusters); + normTracePost = cell(1,nClusters); + smoothSpeedPost = cell(1,nClusters); + semTracePreFlightPost = cell(1,nClusters); + normMeanTraceFlightAll = []; + normMeanTracePreAll= []; + normMeanTracePreAll= []; + normMeanTracePostAll = []; + normMeanTracePreFlightPostAll = cell(1,nClusters); + dur = cell(1,nClusters); + durSpeed = cell(1,nClusters); + %for each cluster type + for clust_i = 1:nClusters %length(flightPaths.clusterIndex) %for each trial in cluster, calculate the start/stop times and duration of the calcium videos for dur_i = 1:length(flightPaths.clusterIndex{clust_i}) %get imaging times of start and stop index converting from tracking to video times - [minValueStart(dur_i),closestIndexStart(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); - [minValueEnd(dur_i),closestIndexEnd(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); + [minValueStart(dur_i),closestIndexStart{clust_i}(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); + [minValueEnd(dur_i),closestIndexEnd{clust_i}(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); %calculate duration of each flight in a particular cluster so %you can pad all flights to the longest flight in that cluster - dur(dur_i) = closestIndexEnd(dur_i)-closestIndexStart(dur_i); - durSpeed(dur_i)= flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))-flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i)); + dur{clust_i}(dur_i) = closestIndexEnd{clust_i}(dur_i)-closestIndexStart{clust_i}(dur_i); + durSpeed{clust_i}(dur_i)= flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))-flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i)); end %calculate max duration for each cluster of trajectories - maxDur = max(dur); - maxDurSpeed = max(durSpeed); - %meanTrace{clust_i}=zeros(length(cellData.results.C(:,1)),maxDur+preWindow+1); + + medDur{clust_i} = round(median(dur{clust_i})); + medDurSpeed{clust_i} = round(median(durSpeed{clust_i})); + %meanTrace{clust_i}=zeros(length(traceData(:,1)),maxDur{clust_i}+preWindow+1); %initialize the vector to store the neural activity of each flight - traceFlight = zeros(length(flightPaths.clusterIndex{clust_i}),maxDur+prePadCalcium+postPadCalcium+1); - speedFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),maxDurSpeed+prePadSpeed+postPadSpeed+1); - tracePre = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadCalcium+1); + traceFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),medDur{clust_i}+prePadCalcium+postPadCalcium+1,length(traceData(:,1))); + speedFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),medDurSpeed{clust_i}+prePadSpeed+postPadSpeed+1); + postFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),medDurSpeed{clust_i}+prePadSpeed+postPadSpeed+1); + tracePre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadCalcium+1,length(traceData(:,1))); speedPre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadSpeed+1); - tracePost = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadCalcium+1); + tracePost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadCalcium+1,length(traceData(:,1))); speedPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadSpeed+1); - %build the calcium and speed vectors for each flight within each cluster - for trace_i = 1:length(flightPaths.clusterIndex{clust_i}) - try - traceFlight(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (maxDur-dur(trace_i)) + postPadCalcium); - speedFlight{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - prePadSpeed:flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (maxDurSpeed-durSpeed(trace_i)) + postPadSpeed); - smoothSpeedRawFlight{clust_i}(trace_i,:) = smooth(speedFlight{clust_i}(trace_i,:),100); - tracePre(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); - speedPre{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i))); - smoothSpeedRawPre{clust_i}(trace_i,:) = smooth(speedPre{clust_i}(trace_i,:),100); - tracePost(trace_i,:) = cellData.results.C(cell_i,closestIndexEnd(trace_i):closestIndexEnd(trace_i) + postFlightPadCalcium); - speedPost{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(maxDurSpeed-durSpeed(trace_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (maxDurSpeed-durSpeed(trace_i)) + postFlightPadSpeed); - smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),100); - catch - sizeToRecordingEnd = size(cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:end),2); - sizeToTraceEnd = size(traceFlight(trace_i,:),2); - traceFlight(trace_i,:) = (cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:end + postPadCalcium)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); - speedFlight{clust_i}(trace_i,:) = (flightPaths.batSpeed(closestIndexStart(trace_i) - prePadSpeed:end + postPadSpeed)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); - disp('End of rec') + tracePreFlightPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),length(tracePre{clust_i}(1,:,1)) + length(traceFlight{clust_i}(1,:,1)) + length(tracePost{clust_i}(1,:,1))); %for each cell + for cell_i = 1:length(traceData(:,1)) + %build the calcium and speed vectors for each flight within each cluster + for trace_i = 1:length(flightPaths.clusterIndex{clust_i}) + try + traceFlightIdx{clust_i}(trace_i) = flightPaths.clusterIndex{clust_i}(trace_i); + traceFlight{clust_i}(trace_i,:,cell_i) = traceData(cell_i,closestIndexStart{clust_i}(trace_i) - prePadCalcium:closestIndexEnd{clust_i}(trace_i) + (medDur{clust_i}-dur{clust_i}(trace_i)) + postPadCalcium); + posFlight{clust_i}(trace_i,:,:) = flightPaths.trajectoriesContinous(:,flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - prePadSpeed:flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)) + postPadSpeed); + speedFlight{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - prePadSpeed:flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)) + postPadSpeed); + smoothTraceRawFlight{clust_i}(trace_i,:,cell_i) = smooth(traceFlight{clust_i}(trace_i,:,cell_i),traceSmooth); + normTraceRawFlight{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawFlight{clust_i}(trace_i,:,cell_i),0,smoothTrace); + normTraceRawFlight{clust_i}(trace_i,:,cell_i) = normTraceRawFlight{clust_i}(trace_i,:,cell_i) - min(normTraceRawFlight{clust_i}(trace_i,:,cell_i)); + smoothSpeedRawFlight{clust_i}(trace_i,:) = smooth(speedFlight{clust_i}(trace_i,:),smoothSpeed); + tracePre{clust_i}(trace_i,:,cell_i) = traceData(cell_i,closestIndexStart{clust_i}(trace_i) - preFlightPadCalcium:closestIndexStart{clust_i}(trace_i)); + speedPre{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i))); + smoothTraceRawPre{clust_i}(trace_i,:,cell_i) = smooth(tracePre{clust_i}(trace_i,:,cell_i),traceSmooth); + normTraceRawPre{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawPre{clust_i}(trace_i,:,cell_i),0,smoothTrace); + normTraceRawPre{clust_i}(trace_i,:,cell_i) = normTraceRawPre{clust_i}(trace_i,:,cell_i) - min(normTraceRawPre{clust_i}(trace_i,:,cell_i)); + smoothSpeedRawPre{clust_i}(trace_i,:) = smooth(speedPre{clust_i}(trace_i,:),smoothSpeed); + tracePost{clust_i}(trace_i,:,cell_i) = traceData(cell_i,closestIndexEnd{clust_i}(trace_i):closestIndexEnd{clust_i}(trace_i) + postFlightPadCalcium); + speedPost{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)) + postFlightPadSpeed); + smoothTraceRawPost{clust_i}(trace_i,:,cell_i) = smooth(tracePost{clust_i}(trace_i,:,cell_i),traceSmooth); + normTraceRawPost{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawPost{clust_i}(trace_i,:,cell_i),0,smoothTrace); + normTraceRawPost{clust_i}(trace_i,:,cell_i) = normTraceRawPost{clust_i}(trace_i,:,cell_i) - min(normTraceRawPost{clust_i}(trace_i,:,cell_i)); + smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),smoothSpeed); + tracePreFlightPost{clust_i}(trace_i,:,cell_i) = cat(2,tracePre{clust_i}(trace_i,:,cell_i),traceFlight{clust_i}(trace_i,:,cell_i),tracePost{clust_i}(trace_i,:,cell_i)); + speedPreFlightPost{clust_i}(trace_i,:) = horzcat(speedPre{clust_i}(trace_i,:),speedFlight{clust_i}(trace_i,:),speedPost{clust_i}(trace_i,:)); + smoothTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i) = smooth(tracePreFlightPost{clust_i}(trace_i,:,cell_i),traceSmooth); + normTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i),0,smoothTrace); + normTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i) = normTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i) - min(normTraceRawPreFlightPost{clust_i}(trace_i,:,cell_i)); + smoothSpeedRawPreFlightPost{clust_i}(trace_i,:) = smooth(speedPreFlightPost{clust_i}(trace_i,:),smoothSpeed); + + + catch + % tracePost{clust_i}(trace_i,:,cell_i) = [traceData(cell_i,closestIndexEnd{clust_i}(trace_i):end),zeros(1,size(tracePost{clust_i}(trace_i,:,cell_i),2) - size(traceData(cell_i,closestIndexEnd{clust_i}(trace_i):end),2))]; + % speedPost{clust_i}(trace_i,:) = [flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(maxDurSpeed{clust_i}-durSpeed(trace_i)):end),zeros(1,size(speedPost{clust_i}(trace_i,:),2)-size(flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(maxDurSpeed{clust_i}-durSpeed(trace_i)):end,2)))]; + % smoothTraceRawPost{clust_i}(trace_i,:,cell_i) = smooth(tracePost{clust_i}(trace_i,:,cell_i),traceSmooth); + % normTraceRawPost{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawPost{clust_i}(trace_i,:,cell_i),0,2); + % normTraceRawPost{clust_i}(trace_i,:,cell_i) = normTraceRawPost{clust_i}(trace_i,:,cell_i) - min(normTraceRawPost{clust_i}(trace_i,:,cell_i)); + % smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),speedSmooth); + disp('End of rec') + end + end + + %calculate the mean neural activity across all flights in a cluster for each cell + %meanTraceFlight{clust_i}(cell_i,:) = traceFlight{clust_i}(:,:,cell_i); + %meanTracePre{clust_i}(cell_i,:) = tracePre{clust_i}(:,:,cell_i); + %meanTracePost{clust_i}(cell_i,:) = tracePost{clust_i}(:,:,cell_i); + meanTraceFlight{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(:,:,cell_i),1); + meanTracePre{clust_i}(cell_i,:) = mean(tracePre{clust_i}(:,:,cell_i),1); + meanTracePost{clust_i}(cell_i,:) = mean(tracePost{clust_i}(:,:,cell_i),1); + + sdTraceFlight{clust_i}(cell_i,:) = std(traceFlight{clust_i}(:,:,cell_i)); + sdTracePre{clust_i}(cell_i,:) = std(tracePre{clust_i}(:,:,cell_i)); + sdTracePost{clust_i}(cell_i,:) = std(tracePre{clust_i}(:,:,cell_i)); + meanTraceOdd{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(1:2:end,:,cell_i),1); + meanTraceEven{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(2:2:end,:,cell_i),1); + meanPosFlight{clust_i} = mean(posFlight{clust_i},1); + meanSpeedFlight{clust_i} = mean(speedFlight{clust_i}); + meanSpeedPre{clust_i} = mean(speedPre{clust_i}); + meanSpeedPost{clust_i} = mean(speedPost{clust_i}); + meanTracePreFlightPost{clust_i}(cell_i,:) = mean(tracePreFlightPost{clust_i}(:,:,cell_i)); + sdTracePreFlightPost{clust_i}(cell_i,:) = std(tracePreFlightPost{clust_i}(:,:,cell_i)); + semTracePreFlightPost{clust_i}(cell_i,:) = std(tracePreFlightPost{clust_i}(:,:,cell_i))/sqrt(length(tracePreFlightPost{clust_i}(:,:,cell_i))); + meanSpeedPreFlightPost{clust_i} = mean(speedPreFlightPost{clust_i}); + + %smooth and zscore the neural data. subtract the min of the zscore so the + %min is 0 rather than mean 0 + normTraceFlight{clust_i}(cell_i,:) = zscore(smooth(meanTraceFlight{clust_i}(cell_i,:),traceSmooth)); + normTraceFlight{clust_i}(cell_i,:) = normTraceFlight{clust_i}(cell_i,:) - min(normTraceFlight{clust_i}(cell_i,:)); + smoothSpeedFlight{clust_i} = smooth(meanSpeedFlight{clust_i},smoothSpeed); + normTraceOdd{clust_i}(cell_i,:) = zscore(smooth(meanTraceOdd{clust_i}(cell_i,:),traceSmooth)); + normTraceOdd{clust_i}(cell_i,:) = normTraceOdd{clust_i}(cell_i,:) - min(normTraceOdd{clust_i}(cell_i,:)); + normTraceEven{clust_i}(cell_i,:) = zscore(smooth(meanTraceEven{clust_i}(cell_i,:),traceSmooth)); + normTraceEven{clust_i}(cell_i,:) = normTraceEven{clust_i}(cell_i,:) - min(normTraceEven{clust_i}(cell_i,:)); + normTracePre{clust_i}(cell_i,:) = zscore(smooth(meanTracePre{clust_i}(cell_i,:),traceSmooth)); + normTracePre{clust_i}(cell_i,:) = normTracePre{clust_i}(cell_i,:) - min(normTracePre{clust_i}(cell_i,:)); + smoothSpeedPre{clust_i} = smooth(meanSpeedPre{clust_i},smoothSpeed); + normTracePost{clust_i}(cell_i,:) = zscore(smooth(meanTracePost{clust_i}(cell_i,:),traceSmooth)); + normTracePost{clust_i}(cell_i,:) = normTracePost{clust_i}(cell_i,:) - min(normTracePost{clust_i}(cell_i,:)); + smoothSpeedPost{clust_i} = smooth(meanSpeedPost{clust_i},smoothSpeed); + %find time index of max peaks + [~,maxnormTraceFlight{clust_i}(cell_i,1)] = max(normTraceFlight{clust_i}(cell_i,:)); + [~,maxnormTracePre{clust_i}(cell_i,1)] = max(normTracePre{clust_i}(cell_i,:)); + [~,maxnormTracePost{clust_i}(cell_i,1)] = max(normTracePost{clust_i}(cell_i,:)); + [~,maxNormTraceOdd{clust_i}(cell_i,1)] = max(normTraceOdd{clust_i}(cell_i,:)); + end + %sort each cell by the timing of its peak firing + [BFlight{clust_i},IFlight{clust_i}] = sort(maxnormTraceFlight{clust_i}); + [BPre{clust_i},IPre{clust_i}] = sort(maxnormTracePre{clust_i}); + [BPost{clust_i},IPost{clust_i}] = sort(maxnormTracePost{clust_i}); + if clust_i == 1 + [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{1}); %sort by cluster 1 + [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{1}); %sort by cluster 1 + [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{1}); %sort by cluster 1 + else + [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{2}); %sort by cluster 2 + [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{2}); %sort by cluster 2 + [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{2}); %sort by cluster 2 + end + [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTraceOdd{clust_i}); + %split dataset into even and odd for comparing 2 halves + % normTraceOdd{clust_i} = normTraceFlight{clust_i}(1:2:end,:); + % normTraceEven{clust_i} = normTraceFlight{clust_i}(2:2:end,:); + % %sort odd clusters in ascending order of the peak of the odds + % if length(normTraceOdd{clust_i}(:,1))>length(normTraceEven{clust_i}(:,1)) %if number of odd elements is greater than even + % [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTrace{clust_i}(1:2:end-1)); + % else + % [Bodd{clust_i},Iodd{clust_i}] = sort(maxnormTraceFlight{clust_i}(1:2:end)); + % end - %calculate the mean neural activity across all flights in a cluster for each cell - meanTraceFlight{clust_i}(cell_i,:) = mean(traceFlight); - meanTraceOdd{clust_i}(cell_i,:) = mean(traceFlight(1:2:end,:)); - meanTraceEven{clust_i}(cell_i,:) = mean(traceFlight(2:2:end,:)); - meanTracePre{clust_i}(cell_i,:) = mean(tracePre); - meanTracePost{clust_i}(cell_i,:) = mean(tracePost); - meanSpeedFlight{clust_i} = mean(speedFlight{clust_i}); - meanSpeedPre{clust_i} = mean(speedPre{clust_i}); - meanSpeedPost{clust_i} = mean(speedPost{clust_i}); - + %concatenate all clusters together and then zscore to equalize the + %peaks across all trials + meanTraceFlightAll = [meanTraceFlightAll meanTraceFlight{clust_i}]; %concatenate all traces + meanTracePreAll = [meanTracePreAll meanTracePre{clust_i}]; %concatenate all traces + meanTracePostAll = [meanTracePostAll meanTracePost{clust_i}]; %concatenate all traces + meanTracePreFlightPostAll{clust_i} = [meanTracePre{clust_i} meanTraceFlight{clust_i} meanTracePost{clust_i}]; - %smooth and zscore the neural data. subtract the min of the zscore so the - %min is 0 rather than mean 0 - normTraceFlight{clust_i}(cell_i,:) = zscore(smooth(meanTraceFlight{clust_i}(cell_i,:),3)); - normTraceFlight{clust_i}(cell_i,:) = normTraceFlight{clust_i}(cell_i,:) - min(normTraceFlight{clust_i}(cell_i,:)); - smoothSpeedFlight{clust_i} = smooth(meanSpeedFlight{clust_i},40); - normTraceOdd{clust_i}(cell_i,:) = zscore(smooth(meanTraceOdd{clust_i}(cell_i,:),3)); - normTraceOdd{clust_i}(cell_i,:) = normTraceOdd{clust_i}(cell_i,:) - min(normTraceOdd{clust_i}(cell_i,:)); - normTraceEven{clust_i}(cell_i,:) = zscore(smooth(meanTraceEven{clust_i}(cell_i,:),3)); - normTraceEven{clust_i}(cell_i,:) = normTraceEven{clust_i}(cell_i,:) - min(normTraceEven{clust_i}(cell_i,:)); - normTracePre{clust_i}(cell_i,:) = zscore(smooth(meanTracePre{clust_i}(cell_i,:),3)); - normTracePre{clust_i}(cell_i,:) = normTracePre{clust_i}(cell_i,:) - min(normTracePre{clust_i}(cell_i,:)); - smoothSpeedPre{clust_i} = smooth(meanSpeedPre{clust_i},40); - normTracePost{clust_i}(cell_i,:) = zscore(smooth(meanTracePost{clust_i}(cell_i,:),3)); - normTracePost{clust_i}(cell_i,:) = normTracePost{clust_i}(cell_i,:) - min(normTracePost{clust_i}(cell_i,:)); - smoothSpeedPost{clust_i} = smooth(meanSpeedPost{clust_i},40); - %find time index of max peaks - [~,maxnormTraceFlight{clust_i}(cell_i,1)] = max(normTraceFlight{clust_i}(cell_i,:)); - [~,maxnormTracePre{clust_i}(cell_i,1)] = max(normTracePre{clust_i}(cell_i,:)); - [~,maxnormTracePost{clust_i}(cell_i,1)] = max(normTracePost{clust_i}(cell_i,:)); - [~,maxNormTraceOdd{clust_i}(cell_i,1)] = max(normTraceOdd{clust_i}(cell_i,:)); end - %sort each cell by the timing of its peak firing - [BFlight{clust_i},IFlight{clust_i}] = sort(maxnormTraceFlight{clust_i}); - [BPre{clust_i},IPre{clust_i}] = sort(maxnormTracePre{clust_i}); - [BPost{clust_i},IPost{clust_i}] = sort(maxnormTracePost{clust_i}); - [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{1}); %sort by cluster 1 - [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{1}); %sort by cluster 1 - [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{1}); %sort by cluster 1 - [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTraceOdd{clust_i}); - %split dataset into even and odd for comparing 2 halves - % normTraceOdd{clust_i} = normTraceFlight{clust_i}(1:2:end,:); - % normTraceEven{clust_i} = normTraceFlight{clust_i}(2:2:end,:); - % %sort odd clusters in ascending order of the peak of the odds - % if length(normTraceOdd{clust_i}(:,1))>length(normTraceEven{clust_i}(:,1)) %if number of odd elements is greater than even - % [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTrace{clust_i}(1:2:end-1)); - % else - % [Bodd{clust_i},Iodd{clust_i}] = sort(maxnormTraceFlight{clust_i}(1:2:end)); - % end - %concatenate all clusters together and then zscore to equalize the - %peaks across all trials - meanTraceFlightAll = [meanTraceFlightAll meanTraceFlight{clust_i}]; %concatenate all traces - meanTracePreAll = [meanTracePreAll meanTracePre{clust_i}]; %concatenate all traces - meanTracePostAll = [meanTracePostAll meanTracePost{clust_i}]; %concatenate all traces - meanTracePreFlightPostAll{clust_i} = [meanTracePre{clust_i} meanTraceFlight{clust_i} meanTracePost{clust_i}]; - -end + %% this is to smooth, zscore, and sort the entire cell data by their preferred flight according to a homemade k-means (max dff across flights) + %zscore the full data set and subtract min to start at 0 + for cell_ii = 1:length(traceData(:,1)) + normMeanTraceFlightAll(cell_ii,:) = zscore(smooth(meanTraceFlightAll(cell_ii,:),traceSmooth)); + normMeanTraceFlightAll(cell_ii,:) = normMeanTraceFlightAll(cell_ii,:) - min(normMeanTraceFlightAll(cell_ii,:)); + normMeanTracePreAll(cell_ii,:) = zscore(smooth(meanTracePreAll(cell_ii,:),traceSmooth)); + normMeanTracePreAll(cell_ii,:) = normMeanTracePreAll(cell_ii,:) - min(normMeanTracePreAll(cell_ii,:)); + normMeanTracePostAll(cell_ii,:) = zscore(smooth(meanTracePostAll(cell_ii,:),traceSmooth)); + normMeanTracePostAll(cell_ii,:) = normMeanTracePostAll(cell_ii,:) - min(normMeanTracePostAll(cell_ii,:)); + for clust_i = 1:nClusters + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = zscore(smooth(meanTracePreFlightPostAll{clust_i}(cell_ii,:),traceSmooth)); + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) - min(normMeanTracePreFlightPostAll{clust_i}(cell_ii,:)); + end + end + %split the data back into its clusters + traceFlightIndConcat = [1 length(normTraceFlight{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + tracePreIndConcat = [1 length(normTracePre{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + tracePostIndConcat = [1 length(normTracePost{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + + %find the start and stop indices for 2nd through n cluster + for clust_ii = 2:nClusters + traceFlightIndConcat = vertcat(traceFlightIndConcat,[traceFlightIndConcat(clust_ii-1,2)+1 traceFlightIndConcat(clust_ii-1,2)+length(normTraceFlight{clust_ii}(1,:))]); + tracePreIndConcat = vertcat(tracePreIndConcat,[tracePreIndConcat(clust_ii-1,2)+1 tracePreIndConcat(clust_ii-1,2)+length(normTracePre{clust_ii}(1,:))]); + tracePostIndConcat = vertcat(tracePostIndConcat,[tracePostIndConcat(clust_ii-1,2)+1 tracePostIndConcat(clust_ii-1,2)+length(normTracePost{clust_ii}(1,:))]); + + end + %regroup by each flight cluster + for clust_iii = 1:nClusters + normTraceFlightAll{clust_iii} = normMeanTraceFlightAll(:,traceFlightIndConcat(clust_iii,1):traceFlightIndConcat(clust_iii,2)); + normTracePreAll{clust_iii} = normMeanTracePreAll(:,tracePreIndConcat(clust_iii,1):tracePreIndConcat(clust_iii,2)); + normTracePostAll{clust_iii} = normMeanTracePostAll(:,tracePostIndConcat(clust_iii,1):tracePostIndConcat(clust_iii,2)); + normTracePreClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,1:preFlightPadCalcium); + normTraceFlightClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))); + normTracePostClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+postFlightPadCalcium); + %find the order of the maximum for each cluster within the regrouping + for cell_iii = 1:length(traceData(:,1)) + [~,maxNormFlightAll{clust_iii}(cell_iii,1)] = max(normTraceFlightAll{clust_iii}(cell_iii,:)); + [~,maxNormPreAll{clust_iii}(cell_iii,1)] = max(normTracePreAll{clust_iii}(cell_iii,:)); + [~,maxNormPostAll{clust_iii}(cell_iii,1)] = max(normTracePostAll{clust_iii}(cell_iii,:)); + [~,maxNormPreClustAll{clust_iii}(cell_iii,1)] = max(normTracePreClustAll{clust_iii}(cell_iii,:)); + [~,maxNormFlightClustAll{clust_iii}(cell_iii,1)] = max(normTraceFlightClustAll{clust_iii}(cell_iii,:)); + [~,maxNormPostClustAll{clust_iii}(cell_iii,1)] = max(normTracePostClustAll{clust_iii}(cell_iii,:)); + end + %sort each cell by the timing of its peak firing + [BnormFlightAll{clust_iii},InormFlightAll{clust_iii}] = sort(maxNormFlightAll{clust_iii}); + [BnormPreAll{clust_iii},InormPreAll{clust_iii}] = sort(maxNormPreAll{clust_iii}); + [BnormPostAll{clust_iii},InormPostAll{clust_iii}] = sort(maxNormPostAll{clust_iii}); + [BnormPreClustAll{clust_iii},InormPreClustAll{clust_iii}] = sort(maxNormPreClustAll{clust_iii}); + [BnormFlightClustAll{clust_iii},InormFlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{clust_iii}); + [BnormPostClustAll{clust_iii},InormPostClustAll{clust_iii}] = sort(maxNormPostClustAll{clust_iii}); + if clust_iii == 1 + [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{1}); %sort by cluster 1 + [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{1}); %sort by cluster 1 + [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{1}); %sort by cluster 1 + [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{1}); %sort by cluster 1 + [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{1}); %sort by cluster 1 + [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{1}); %sort by cluster 1 + else + [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{2}); %sort by cluster 2 + [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{2}); %sort by cluster 2 + [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{2}); %sort by cluster 2 + [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{2}); %sort by cluster 2 + [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{2}); %sort by cluster 2 + [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{2}); %sort by cluster 2 + end + + + + + end -%% this is to smooth, zscore, and sort the entire cell data by their preferred flight according to a homemade k-means (max dff across flights) -%zscore the full data set and subtract min to start at 0 -for cell_ii = 1:length(cellData.results.C(:,1)) - normMeanTraceFlightAll(cell_ii,:) = zscore(smooth(meanTraceFlightAll(cell_ii,:),10)); - normMeanTraceFlightAll(cell_ii,:) = normMeanTraceFlightAll(cell_ii,:) - min(normMeanTraceFlightAll(cell_ii,:)); - normMeanTracePreAll(cell_ii,:) = zscore(smooth(meanTracePreAll(cell_ii,:),10)); - normMeanTracePreAll(cell_ii,:) = normMeanTracePreAll(cell_ii,:) - min(normMeanTracePreAll(cell_ii,:)); - normMeanTracePostAll(cell_ii,:) = zscore(smooth(meanTracePostAll(cell_ii,:),10)); - normMeanTracePostAll(cell_ii,:) = normMeanTracePostAll(cell_ii,:) - min(normMeanTracePostAll(cell_ii,:)); + %find max and sort based on the peaks of the cell across the whole + %timeseries + [~,maxAllFlight] = max(normMeanTraceFlightAll,[],2); + [~,maxAllPre] = max(normMeanTracePreAll,[],2); + [~,maxAllPost] = max(normMeanTracePostAll,[],2); for clust_i = 1:nClusters - normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = zscore(smooth(meanTracePreFlightPostAll{clust_i}(cell_ii,:),10)); - normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) - min(normMeanTracePreFlightPostAll{clust_i}(cell_ii,:)); - end -end -%split the data back into its clusters -traceFlightIndConcat = [1 length(normTraceFlight{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster -tracePreIndConcat = [1 length(normTracePre{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster -tracePostIndConcat = [1 length(normTracePost{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster - -%find the start and stop indices for 2nd through n cluster -for clust_ii = 2:nClusters - traceFlightIndConcat = vertcat(traceFlightIndConcat,[traceFlightIndConcat(clust_ii-1,2)+1 traceFlightIndConcat(clust_ii-1,2)+length(normTraceFlight{clust_ii}(1,:))]); - tracePreIndConcat = vertcat(tracePreIndConcat,[tracePreIndConcat(clust_ii-1,2)+1 tracePreIndConcat(clust_ii-1,2)+length(normTracePre{clust_ii}(1,:))]); - tracePostIndConcat = vertcat(tracePostIndConcat,[tracePostIndConcat(clust_ii-1,2)+1 tracePostIndConcat(clust_ii-1,2)+length(normTracePost{clust_ii}(1,:))]); - -end -%regroup by each flight cluster -for clust_iii = 1:nClusters - normTraceFlightAll{clust_iii} = normMeanTraceFlightAll(:,traceFlightIndConcat(clust_iii,1):traceFlightIndConcat(clust_iii,2)); - normTracePreAll{clust_iii} = normMeanTracePreAll(:,tracePreIndConcat(clust_iii,1):tracePreIndConcat(clust_iii,2)); - normTracePostAll{clust_iii} = normMeanTracePostAll(:,tracePostIndConcat(clust_iii,1):tracePostIndConcat(clust_iii,2)); - normTracePreClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,1:preFlightPadCalcium); - normTraceFlightClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))); - normTracePostClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+postFlightPadCalcium); - %find the order of the maximum for each cluster within the regrouping - for cell_iii = 1:length(cellData.results.C(:,1)) - [~,maxNormFlightAll{clust_iii}(cell_iii,1)] = max(normTraceFlightAll{clust_iii}(cell_iii,:)); - [~,maxNormPreAll{clust_iii}(cell_iii,1)] = max(normTracePreAll{clust_iii}(cell_iii,:)); - [~,maxNormPostAll{clust_iii}(cell_iii,1)] = max(normTracePostAll{clust_iii}(cell_iii,:)); - [~,maxNormPreClustAll{clust_iii}(cell_iii,1)] = max(normTracePreClustAll{clust_iii}(cell_iii,:)); - [~,maxNormFlightClustAll{clust_iii}(cell_iii,1)] = max(normTraceFlightClustAll{clust_iii}(cell_iii,:)); - [~,maxNormPostClustAll{clust_iii}(cell_iii,1)] = max(normTracePostClustAll{clust_iii}(cell_iii,:)); + [~,maxAllPreFlightPost{clust_i}] = max(normMeanTracePreFlightPostAll{clust_iii},[],2); end - %sort each cell by the timing of its peak firing - [BnormFlightAll{clust_iii},InormFlightAll{clust_iii}] = sort(maxNormFlightAll{clust_iii}); - [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{1}); %sort by cluster 1 - [BnormPreAll{clust_iii},InormPreAll{clust_iii}] = sort(maxNormPreAll{clust_iii}); - [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{1}); %sort by cluster 1 - [BnormPostAll{clust_iii},InormPostAll{clust_iii}] = sort(maxNormPostAll{clust_iii}); - [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{1}); %sort by cluster 1 - - [BnormPreClustAll{clust_iii},InormPreClustAll{clust_iii}] = sort(maxNormPreClustAll{clust_iii}); - [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{1}); %sort by cluster 1 - [BnormFlightClustAll{clust_iii},InormFlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{clust_iii}); - [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{1}); %sort by cluster 1 - [BnormPostClustAll{clust_iii},InormPostClustAll{clust_iii}] = sort(maxNormPostClustAll{clust_iii}); - [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{1}); %sort by cluster 1 - - - - -end - - -%find max and sort based on the peaks of the cell across the whole -%timeseries -[~,maxAllFlight] = max(normMeanTraceFlightAll,[],2); -[~,maxAllPre] = max(normMeanTracePreAll,[],2); -[~,maxAllPost] = max(normMeanTracePostAll,[],2); -for clust_i = 1:nClusters - [~,maxAllPreFlightPost{clust_i}] = max(normMeanTracePreFlightPostAll{clust_iii},[],2); -end - - -%kPeaks = kmeans(maxAll,nClusters); %take k-means cluster of the peaks of each cell whole time -%sort based on each clustered peaks for flight, pre and post -rng(2); -for n = 1:size(maxAllFlight,1) - for ii = 1:nClusters - if maxAllFlight(n) >= traceFlightIndConcat(ii,1) & maxAllFlight(n) < traceFlightIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster - kPeaksFlight(:,n) = 1; + + + %kPeaks = kmeans(maxAll,nClusters); %take k-means cluster of the peaks of each cell whole time + %sort based on each clustered peaks for flight, pre and post + rng(2); + for n = 1:size(maxAllFlight,1) + for ii = 1:nClusters + if maxAllFlight(n) >= traceFlightIndConcat(ii,1) & maxAllFlight(n) < traceFlightIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksFlight(:,n) = 1; + end + end - end -end -for n = 1:size(maxAllPre,1) - for ii = 1:nClusters - if maxAllPre(n) >= tracePreIndConcat(ii,1) & maxAllPre(n) < tracePreIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster - kPeaksPre(:,n) = 1; + for n = 1:size(maxAllPre,1) + for ii = 1:nClusters + if maxAllPre(n) >= tracePreIndConcat(ii,1) & maxAllPre(n) < tracePreIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksPre(:,n) = 1; + end end end -end -for n = 1:size(maxAllPost,1) - for ii = 1:nClusters - if maxAllPost(n) >= tracePostIndConcat(ii,1) & maxAllPost(n) < tracePostIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster - kPeaksPost(:,n) = 1; + for n = 1:size(maxAllPost,1) + for ii = 1:nClusters + if maxAllPost(n) >= tracePostIndConcat(ii,1) & maxAllPost(n) < tracePostIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksPost(:,n) = 1; + end end end -end -for clust_i = 1:nClusters - for n = 1:size(maxAllPreFlightPost{clust_i},1) - if maxAllPreFlightPost{clust_i}(n) >= 1 & maxAllPreFlightPost{clust_i}(n) < (length(normTraceFlightAll{clust_iii}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1) %if the peak is within each cluster, sort it into that particular cluster - kPeaksPreFlightPost{clust_i}(:,n) = 1; + for clust_i = 1:nClusters + for n = 1:size(maxAllPreFlightPost{clust_i},1) + if maxAllPreFlightPost{clust_i}(n) >= 1 & maxAllPreFlightPost{clust_i}(n) < (length(normTraceFlightAll{clust_iii}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1) %if the peak is within each cluster, sort it into that particular cluster + kPeaksPreFlightPost{clust_i}(:,n) = 1; + end end + [BkPeaksPreFlightPost{clust_i},IkPeaksPreFlightPost{clust_i}] = sort(kPeaksPreFlightPost{clust_i}); + normMeanTraceSortPreFlightPost{clust_i} = normMeanTracePreFlightPostAll{clust_i}(IkPeaksPreFlightPost{clust_i},:); end - [BkPeaksPreFlightPost{clust_i},IkPeaksPreFlightPost{clust_i}] = sort(kPeaksPreFlightPost{clust_i}); - normMeanTraceSortPreFlightPost{clust_i} = normMeanTracePreFlightPostAll{clust_i}(IkPeaksPreFlightPost{clust_i},:); -end - -%sort the clusters according to their peak times -[BkPeaksFlight,IkPeaksFlight] = sort(kPeaksFlight); -normMeanTraceSortFlight = normMeanTraceFlightAll(IkPeaksFlight,:); -[BkPeaksPre,IkPeaksPre] = sort(kPeaksPre); -normMeanTraceSortPre = normMeanTracePreAll(IkPeaksPre,:); -[BkPeaksPost,IkPeaksPost] = sort(kPeaksPost); -normMeanTraceSortPost = normMeanTracePostAll(IkPeaksPost,:); - -%for each cluster, find the peaks of the cluster (aMat aka aTemp), tke the max -%(maxInd), and sort that max (aSort) from the cluster, add this to the -%normMeanTraceSort variable -for c = 1:nClusters - aMatFlight = find(BkPeaksFlight == c); - aTempFlight = normMeanTraceSortFlight(aMatFlight,:); - [~,maxIndFlight] = max(aTempFlight,[],2); - [BmaxFlight,ImaxFlight] = sort(maxIndFlight); - aSortFlight = aTempFlight(ImaxFlight,:); - normMeanTraceSortFlight(aMatFlight,:) = aSortFlight; - clear aMatFlight aTempFlight maxIndFlight ImaxFlight BaxFlight aSortFlight - aMatPre = find(BkPeaksPre == c); - aTempPre = normMeanTraceSortPre(aMatPre,:); - [~,maxIndPre] = max(aTempPre,[],2); - [BmaxPre,ImaxPre] = sort(maxIndPre); - aSortPre = aTempPre(ImaxPre,:); - normMeanTraceSortPre(aMatPre,:) = aSortPre; - clear aMatPre aTempPre maxIndPre ImaxPre BaxPre aSortPre - aMatPost = find(BkPeaksPost == c); - aTempPost = normMeanTraceSortPost(aMatPost,:); - [~,maxIndPost] = max(aTempPost,[],2); - [BmaxPost,ImaxPost] = sort(maxIndPost); - aSortPost = aTempPost(ImaxPost,:); - normMeanTraceSortPost(aMatPost,:) = aSortPost; - clear aMatPost aTempPost maxIndPost ImaxPost BaxPost aSortPost - aMatPreFlightPost = find(BkPeaksPreFlightPost{c} == 1); - aTempPreFlightPost = normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:); - [~,maxIndPreFlightPost] = max(aTempPreFlightPost,[],2); - [BmaxPreFlightPost,ImaxPreFlightPost] = sort(maxIndPreFlightPost); - aSortPreFlightPost = aTempPreFlightPost(ImaxPreFlightPost,:); - normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:) = aSortPreFlightPost; - clear aMatPreFlightPost aTempPreFlightPost maxIndPreFlightPost ImaxPreFlightPost BaxPreFlightPost aSortPreFlightPost - -end -%divide the normMeanTraceSort overall variable into the respective clusters -for c = 1:nClusters - normMeanTraceEachFlight{c} = normMeanTraceSortFlight(:,traceFlightIndConcat(c,1):traceFlightIndConcat(c,2)); - normMeanTraceEachPre{c} = normMeanTraceSortPre(:,tracePreIndConcat(c,1):tracePreIndConcat(c,2)); - normMeanTraceEachPost{c} = normMeanTraceSortPost(:,tracePostIndConcat(c,1):tracePostIndConcat(c,2)); - normMeanTraceEachPFlightP{c} = normMeanTraceSortPreFlightPost{c}(:,preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium); - normMeanTraceEachPreFP{c} = normMeanTraceSortPreFlightPost{c}(:,1:preFlightPadCalcium); - normMeanTraceEachPFPost{c} = normMeanTraceSortPreFlightPost{c}(:,length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1); - + %sort the clusters according to their peak times + [BkPeaksFlight,IkPeaksFlight] = sort(kPeaksFlight); + normMeanTraceSortFlight = normMeanTraceFlightAll(IkPeaksFlight,:); + [BkPeaksPre,IkPeaksPre] = sort(kPeaksPre); + normMeanTraceSortPre = normMeanTracePreAll(IkPeaksPre,:); + [BkPeaksPost,IkPeaksPost] = sort(kPeaksPost); + normMeanTraceSortPost = normMeanTracePostAll(IkPeaksPost,:); + + %for each cluster, find the peaks of the cluster (aMat aka aTemp), tke the max + %(maxInd), and sort that max (aSort) from the cluster, add this to the + %normMeanTraceSort variable + for c = 1:nClusters + aMatFlight = find(BkPeaksFlight == c); + aTempFlight = normMeanTraceSortFlight(aMatFlight,:); + [~,maxIndFlight] = max(aTempFlight,[],2); + [BmaxFlight,ImaxFlight] = sort(maxIndFlight); + aSortFlight = aTempFlight(ImaxFlight,:); + normMeanTraceSortFlight(aMatFlight,:) = aSortFlight; + clear aMatFlight aTempFlight maxIndFlight ImaxFlight BaxFlight aSortFlight + aMatPre = find(BkPeaksPre == c); + aTempPre = normMeanTraceSortPre(aMatPre,:); + [~,maxIndPre] = max(aTempPre,[],2); + [BmaxPre,ImaxPre] = sort(maxIndPre); + aSortPre = aTempPre(ImaxPre,:); + normMeanTraceSortPre(aMatPre,:) = aSortPre; + clear aMatPre aTempPre maxIndPre ImaxPre BaxPre aSortPre + aMatPost = find(BkPeaksPost == c); + aTempPost = normMeanTraceSortPost(aMatPost,:); + [~,maxIndPost] = max(aTempPost,[],2); + [BmaxPost,ImaxPost] = sort(maxIndPost); + aSortPost = aTempPost(ImaxPost,:); + normMeanTraceSortPost(aMatPost,:) = aSortPost; + clear aMatPost aTempPost maxIndPost ImaxPost BaxPost aSortPost + aMatPreFlightPost = find(BkPeaksPreFlightPost{c} == 1); + aTempPreFlightPost = normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:); + [~,maxIndPreFlightPost] = max(aTempPreFlightPost,[],2); + [BmaxPreFlightPost,ImaxPreFlightPost] = sort(maxIndPreFlightPost); + aSortPreFlightPost = aTempPreFlightPost(ImaxPreFlightPost,:); + normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:) = aSortPreFlightPost; + clear aMatPreFlightPost aTempPreFlightPost maxIndPreFlightPost ImaxPreFlightPost BaxPreFlightPost aSortPreFlightPost + + + end + %divide the normMeanTraceSort overall variable into the respective clusters + for c = 1:nClusters + normMeanTraceEachFlight{c} = normMeanTraceSortFlight(:,traceFlightIndConcat(c,1):traceFlightIndConcat(c,2)); + normMeanTraceEachPre{c} = normMeanTraceSortPre(:,tracePreIndConcat(c,1):tracePreIndConcat(c,2)); + normMeanTraceEachPost{c} = normMeanTraceSortPost(:,tracePostIndConcat(c,1):tracePostIndConcat(c,2)); + normMeanTraceEachPFlightP{c} = normMeanTraceSortPreFlightPost{c}(:,preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium); + normMeanTraceEachPreFP{c} = normMeanTraceSortPreFlightPost{c}(:,1:preFlightPadCalcium); + normMeanTraceEachPFPost{c} = normMeanTraceSortPreFlightPost{c}(:,length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1); + + end + + %% save to snakeTrace variable + snakeTraceData.batName = batName; + snakeTraceData.dateSesh = dateSesh; + snakeTraceData.sessionType = sessionType; + snakeTraceData.dur = dur; + snakeTraceData.durSpeed = durSpeed; + snakeTraceData.medDur = medDur; + snakeTraceData.medDurSpeed = medDurSpeed; + snakeTraceData.startIdxTrace = closestIndexStart; + snakeTraceData.endIdxTrace = closestIndexEnd; + snakeTraceData.BPre = BPre; + snakeTraceData.IPre = IPre; + snakeTraceData.BFlight = BFlight; + snakeTraceData.IFlight = IFlight; + snakeTraceData.BPost = BPost; + snakeTraceData.IPost = IPost; + snakeTraceData.Bodd = Bodd; + snakeTraceData.Iodd = Iodd; + snakeTraceData.B1Pre = B1Pre; + snakeTraceData.I1Pre = I1Pre; + snakeTraceData.B1Flight = B1Flight; + snakeTraceData.I1Flight = I1Flight; + snakeTraceData.B1Post = B1Post; + snakeTraceData.I1Post = I1Post; + snakeTraceData.InormFlightAll = InormFlightAll; + snakeTraceData.I1normFlightAll = I1normFlightAll; + snakeTraceData.IkPeaksPreFlightPost=IkPeaksPreFlightPost; + snakeTraceData.kPeaksPreFlightPost=kPeaksPreFlightPost; + snakeTraceData.maxAllPreFlightPost=maxAllPreFlightPost; + snakeTraceData.maxnormTracePre = maxnormTracePre; + snakeTraceData.maxnormTraceFlight = maxnormTraceFlight; + snakeTraceData.maxnormTracePost = maxnormTracePost; + snakeTraceData.meanTracePre = meanTracePre; + snakeTraceData.meanTraceFlight = meanTraceFlight; + snakeTraceData.meanTracePost = meanTracePost; + snakeTraceData.meanSpeedPre = meanSpeedPre; + snakeTraceData.meanSpeedFlight = meanSpeedFlight; + snakeTraceData.meanSpeedPost = meanSpeedPost; + snakeTraceData.meanSpeedPreFlightPost = meanSpeedPreFlightPost; + snakeTraceData.meanTracePreFlightPost = meanTracePreFlightPost; + snakeTraceData.meanTracePreFlightPostAll=meanTracePreFlightPostAll; + snakeTraceData.meanTraceEven = meanTraceEven; + snakeTraceData.meanTraceOdd = meanTraceOdd; + snakeTraceData.nClusters = nClusters; + snakeTraceData.normTracePre = normTracePre; + snakeTraceData.normTraceFlight = normTraceFlight; + snakeTraceData.normTracePost = normTracePost; + snakeTraceData.normTraceEven = normTraceEven; + snakeTraceData.normTraceOdd = normTraceOdd; + snakeTraceData.normTraceFlightAll = normTraceFlightAll; + snakeTraceData.normTraceRawPre = normTraceRawPre; + snakeTraceData.normTraceRawFlight = normTraceRawFlight; + snakeTraceData.normTraceRawPost = normTraceRawPost; + snakeTraceData.normTraceRawPreFlightPost = normTraceRawPreFlightPost; + snakeTraceData.normMeanTraceSortPreFlightPost = normMeanTraceSortPreFlightPost; + snakeTraceData.normMeanTracePreFlightPostAll=normMeanTracePreFlightPostAll; + snakeTraceData.normMeanTraceEachPFlightP = normMeanTraceEachPFlightP; + snakeTraceData.normMeanTraceEachPreFP = normMeanTraceEachPreFP; + snakeTraceData.normMeanTraceEachPFPost = normMeanTraceEachPFPost; + snakeTraceData.normMeanTraceEachPre = normMeanTraceEachPre; + snakeTraceData.normMeanTraceSortPre = normMeanTraceSortPre; + snakeTraceData.normMeanTracePreAll = normMeanTracePreAll; + snakeTraceData.normMeanTraceEachFlight = normMeanTraceEachFlight; + snakeTraceData.normMeanTraceSortFlight = normMeanTraceSortFlight; + snakeTraceData.normMeanTraceFlightAll = normMeanTraceFlightAll; + snakeTraceData.normMeanTraceEachPost = normMeanTraceEachPost; + snakeTraceData.normMeanTraceSortPost = normMeanTraceSortPost; + snakeTraceData.normMeanTracePostAll = normMeanTracePostAll; + snakeTraceData.preFlightPadCalcium = preFlightPadCalcium; + snakeTraceData.postFlightPadCalcium = postFlightPadCalcium; + snakeTraceData.preFlightPadSpeed = preFlightPadSpeed; + snakeTraceData.postFlightPadSpeed = postFlightPadSpeed; + snakeTraceData.preFlightPad = preFlightPad; + snakeTraceData.postFlightPad = postFlightPad; + snakeTraceData.preFlightPad = prePad; + snakeTraceData.postFlightPad = postPad; + snakeTraceData.sdTracePreFlightPost = sdTracePreFlightPost; + snakeTraceData.sdTracePre = sdTracePre; + snakeTraceData.sdTraceFlight = sdTraceFlight; + snakeTraceData.sdTracePost = sdTracePost; + snakeTraceData.semTracePreFlightPost = semTracePreFlightPost; + snakeTraceData.smoothTraceRawPreFlightPost = smoothTraceRawPreFlightPost; + snakeTraceData.posFlight = posFlight; + snakeTraceData.meanPosFlight = meanPosFlight; + snakeTraceData.smoothSpeedPre = smoothSpeedPre; + snakeTraceData.smoothSpeedFlight = smoothSpeedFlight; + snakeTraceData.smoothSpeedPost = smoothSpeedPost; + snakeTraceData.smoothSpeedRawPre = smoothSpeedRawPre; + snakeTraceData.smoothSpeedRawFlight = smoothSpeedRawFlight; + snakeTraceData.smoothSpeedRawPost = smoothSpeedRawPost; + snakeTraceData.smoothTraceRawPre = smoothTraceRawPre; + snakeTraceData.smoothTraceRawFlight = smoothTraceRawFlight; + snakeTraceData.smoothTraceRawPost = smoothTraceRawPost; + snakeTraceData.smoothSpeedRawPreFlightPost = smoothSpeedRawPreFlightPost; + snakeTraceData.speedPreFlightPost = speedPreFlightPost; + snakeTraceData.traceFlightIndConcat = traceFlightIndConcat; + snakeTraceData.tracePreIndConcat = tracePreIndConcat; + snakeTraceData.tracePostIndConcat = tracePostIndConcat; + snakeTraceData.traceFlightIdx = traceFlightIdx; + snakeTraceData.tracePre = tracePre; + snakeTraceData.traceFlight = traceFlight; + snakeTraceData.tracePost = tracePost; + snakeTraceData.tracePreFlightPost = tracePreFlightPost; + if data_i ==1 + snakeTrace_cRaw = snakeTraceData; + elseif data_i == 2 + snakeTrace_c = snakeTraceData; + elseif data_i == 3 + snakeTrace_s = snakeTraceData; + end end - -%% save to snakeTrace variable -snakeTrace.normMeanTraceSortPreFlightPost = normMeanTraceSortPreFlightPost; -snakeTrace.meanTracePreFlightPostAll=meanTracePreFlightPostAll; -snakeTrace.maxAllPreFlightPost=maxAllPreFlightPost; -snakeTrace.normMeanTracePreFlightPostAll=normMeanTracePreFlightPostAll; -snakeTrace.kPeaksPreFlightPost=kPeaksPreFlightPost; -snakeTrace.IkPeaksPreFlightPost=IkPeaksPreFlightPost; -snakeTrace.normMeanTraceEachPFlightP = normMeanTraceEachPFlightP; -snakeTrace.normMeanTraceEachPreFP = normMeanTraceEachPreFP; -snakeTrace.normMeanTraceEachPFPost = normMeanTraceEachPFPost; -snakeTrace.meanTraceFlight = meanTraceFlight; -snakeTrace.normTraceFlight = normTraceFlight; -snakeTrace.maxnormTraceFlight = maxnormTraceFlight; -snakeTrace.meanTracePre = meanTracePre; -snakeTrace.normTracePre = normTracePre; -snakeTrace.maxnormTracePre = maxnormTracePre; -snakeTrace.meanTracePost = meanTracePost; -snakeTrace.normTracePost = normTracePost; -snakeTrace.maxnormTracePost = maxnormTracePost; -snakeTrace.BFlight = BFlight; -snakeTrace.IFlight = IFlight; -snakeTrace.BPre = BPre; -snakeTrace.IPre = IPre; -snakeTrace.BPost = BPost; -snakeTrace.IPost = IPost; -snakeTrace.BOdd = Bodd; -snakeTrace.B1Flight = B1Flight; -snakeTrace.I1Flight = I1Flight; -snakeTrace.B1Pre = B1Pre; -snakeTrace.I1Pre = I1Pre; -snakeTrace.B1Post = B1Post; -snakeTrace.I1Post = I1Post; -snakeTrace.Iodd = Iodd; -snakeTrace.Bodd = Bodd; -snakeTrace.normTraceEven = normTraceEven; -snakeTrace.normTraceOdd = normTraceOdd; -snakeTrace.meanSpeedFlight = meanSpeedFlight; -snakeTrace.smoothSpeedFlight = smoothSpeedFlight; -snakeTrace.meanSpeedPre = meanSpeedPre; -snakeTrace.smoothSpeedPre = smoothSpeedPre; -snakeTrace.meanSpeedPost = meanSpeedPost; -snakeTrace.smoothSpeedPost = smoothSpeedPost; -snakeTrace.smoothSpeedRawPre = smoothSpeedRawPre; -snakeTrace.smoothSpeedRawPost = smoothSpeedRawPost; -snakeTrace.smoothSpeedRawFlight = smoothSpeedRawFlight; -snakeTrace.normMeanTraceEachFlight = normMeanTraceEachFlight; -snakeTrace.normMeanTraceSortFlight = normMeanTraceSortFlight; -snakeTrace.normMeanTraceFlightAll = normMeanTraceFlightAll; -snakeTrace.traceFlightIndConcat = traceFlightIndConcat; -snakeTrace.normMeanTraceEachPre = normMeanTraceEachPre; -snakeTrace.normMeanTraceSortPre = normMeanTraceSortPre; -snakeTrace.normMeanTracePreAll = normMeanTracePreAll; -snakeTrace.tracePreIndConcat = tracePreIndConcat; -snakeTrace.normMeanTraceEachPost = normMeanTraceEachPost; -snakeTrace.normMeanTraceSortPost = normMeanTraceSortPost; -snakeTrace.normMeanTracePostAll = normMeanTracePostAll; -snakeTrace.tracePostIndConcat = tracePostIndConcat; -snakeTrace.nClusters = nClusters; -snakeTrace.batName = batName; -snakeTrace.dateSesh = dateSesh; -snakeTrace.sessionType = sessionType; -snakeTrace.InormFlightAll = InormFlightAll; -snakeTrace.normTraceFlightAll = normTraceFlightAll; -snakeTrace.I1normFlightAll = I1normFlightAll; - -if saveFlag == 1 - snakeTrace.label = label; - save([pwd '/analysis/' label '_snakePlotData.mat'],'snakeTrace'); +if loadFlag ==1 && saveFlag == 1 + snakeTrace_c.label = label; + snakeTrace_cRaw.label = label; + snakeTrace_s.label = label; + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_cRaw.mat'],'snakeTrace_cRaw'); + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_c.mat'],'snakeTrace_c'); + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_s.mat'],'snakeTrace_s'); +elseif loadFlag == 0 && saveFlag ==1 + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_cRaw.mat'],'snakeTrace_cRaw'); + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_c.mat'],'snakeTrace_c'); + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_s.mat'],'snakeTrace_s'); end %snakeTrace.normMeanTraceAllSmooth = normMeanTraceAllSmooth; - -end \ No newline at end of file diff --git a/snakePlot/ImBat_plotSnake.asv b/snakePlot/ImBat_snakeData2.m similarity index 52% rename from snakePlot/ImBat_plotSnake.asv rename to snakePlot/ImBat_snakeData2.m index 21f6e72..9173010 100644 --- a/snakePlot/ImBat_plotSnake.asv +++ b/snakePlot/ImBat_snakeData2.m @@ -1,6 +1,4 @@ -function [snakeTrace] = ImBat_plotSnake(cellData,flightPaths,alignment,varargin) -%global batName dateSesh sessionType - +function [snakeTrace] = ImBat_snakeData2(cellData,flightPaths,alignment,varargin) batName = []; dateSesh = []; @@ -34,18 +32,18 @@ cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); alignment = load([pwd '/processed/Alignment.mat']); - load([pwd '/analysis/' label '_flightPaths_6clusters.mat']); + load([pwd '/analysis/' label '-12Clust_flightPaths.mat']); end %padding for during flight snake plot to include some time before and after flight -prePad = 2; %number of seconds to plot before alignment point -postPad = 6; %number of seconds to plot after alignment point +prePad = 0; %number of seconds to plot before alignment point +postPad = 0; %number of seconds to plot after alignment point prePadCalcium = prePad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postPadCalcium = postPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time prePadSpeed = prePad*120; %add 2 seconds * FS of tracking data (120) postPadSpeed = postPad*120;%add 6 seconds * FS of tracking data (120) %padding for pre and post flight snakePlots -preFlightPad = 10; %number of seconds to include before flight starts -postFlightPad = 10; %of of seconds to include after flight ends +preFlightPad = 15; %number of seconds to include before flight starts +postFlightPad = 15; %of of seconds to include after flight ends preFlightPadCalcium = preFlightPad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postFlightPadCalcium = postFlightPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time preFlightPadSpeed = preFlightPad*120; %add 2 seconds * FS of tracking data (120) @@ -53,6 +51,15 @@ %meanTrace = cell(1,length(flightPaths.clusterIndex)); meanTraceFlightAll = []; %initialize the variable to concatenate all traces for uniform zscore +meanTracePreAll = []; %initialize the variable to concatenate all traces for uniform zscore +meanTracePostAll = []; %initialize the variable to concatenate all traces for uniform zscore +meanTracePreFlightPostAll = []; %initialize the variable to concatenate all pre/post/flight traces for uniform zscore +traceFlight = cell(1,nClusters); +tracePre = cell(1,nClusters); +tracePost = cell(1,nClusters); +speedFlight = cell(1,nClusters); +speedPre = cell(1,nClusters); +speedPost = cell(1,nClusters); %this is to merge specific clusters if 2 or more of them are the same but %were separated by the flight k-means @@ -62,6 +69,7 @@ %for each cluster type for clust_i = 1:nClusters %length(flightPaths.clusterIndex) + %for each cell for cell_i = 1:length(cellData.results.C(:,1)) %for each trial in cluster, calculate the start/stop times and duration of the calcium videos @@ -79,39 +87,43 @@ maxDurSpeed = max(durSpeed); %meanTrace{clust_i}=zeros(length(cellData.results.C(:,1)),maxDur+preWindow+1); %initialize the vector to store the neural activity of each flight - traceFlight = zeros(length(flightPaths.clusterIndex{clust_i}),maxDur+prePadCalcium+postPadCalcium+1); + traceFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),maxDur+prePadCalcium+postPadCalcium+1,length(cellData.results.C(:,1))); speedFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),maxDurSpeed+prePadSpeed+postPadSpeed+1); - tracePre = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadCalcium); - speedPre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadSpeed); - tracePost = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadCalcium); - speedPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadSpeed); + tracePre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadCalcium+1,length(cellData.results.C(:,1))); + speedPre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadSpeed+1); + tracePost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadCalcium+1,length(cellData.results.C(:,1))); + speedPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadSpeed+1); %build the calcium and speed vectors for each flight within each cluster for trace_i = 1:length(flightPaths.clusterIndex{clust_i}) try - traceFlight(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (maxDur-dur(trace_i)) + postPadCalcium); + traceFlight{clust_i}(trace_i,:,cell_i) = cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (maxDur-dur(trace_i)) + postPadCalcium); speedFlight{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - prePadSpeed:flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (maxDurSpeed-durSpeed(trace_i)) + postPadSpeed); + smoothTraceRawFlight{clust_i}(trace_i,:,cell_i) = smooth(traceFlight{clust_i}(trace_i,:,cell_i),3); smoothSpeedRawFlight{clust_i}(trace_i,:) = smooth(speedFlight{clust_i}(trace_i,:),100); - tracePre(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); + tracePre{clust_i}(trace_i,:,cell_i) = cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); speedPre{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i))); - smoothSpeedPreRaw{clust_i}(trace_i,:) = smooth(speedPre{clust_i}(trace_i,:),100); - tracePost(trace_i,:) = cellData.results.C(cell_i,closestIndexEnd(trace_i):closestIndexEnd(trace_i) + postFlightPadCalcium); - speedPost{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + postFlightPadCalcium); - smoothSpeedPostRaw{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),100); + smoothTraceRawPre{clust_i}(trace_i,:,cell_i) = smooth(tracePre{clust_i}(trace_i,:,cell_i),3); + smoothSpeedRawPre{clust_i}(trace_i,:) = smooth(speedPre{clust_i}(trace_i,:),100); + tracePost{clust_i}(trace_i,:,cell_i) = cellData.results.C(cell_i,closestIndexEnd(trace_i):closestIndexEnd(trace_i) + postFlightPadCalcium); + speedPost{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(maxDurSpeed-durSpeed(trace_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (maxDurSpeed-durSpeed(trace_i)) + postFlightPadSpeed); + smoothTraceRawPost{clust_i}(trace_i,:,cell_i) = smooth(tracePost{clust_i}(trace_i,:,cell_i),3); + smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),100); catch + disp('catch') sizeToRecordingEnd = size(cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:end),2); - sizeToTraceEnd = size(traceFlight(trace_i,:),2); - traceFlight(trace_i,:) = (cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:end + postPadCalcium)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); + sizeToTraceEnd = size(traceFlight{clust_i}(trace_i,:),2); + traceFlight{clust_i}(trace_i,:) = (cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:end + postPadCalcium)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); speedFlight{clust_i}(trace_i,:) = (flightPaths.batSpeed(closestIndexStart(trace_i) - prePadSpeed:end + postPadSpeed)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); disp('End of rec') end end %calculate the mean neural activity across all flights in a cluster for each cell - meanTraceFlight{clust_i}(cell_i,:) = mean(traceFlight); - meanTraceOdd{clust_i}(cell_i,:) = mean(traceFlight(1:2:end,:)); - meanTraceEven{clust_i}(cell_i,:) = mean(traceFlight(2:2:end,:)); - meanTracePre{clust_i}(cell_i,:) = mean(tracePre); - meanTracePost{clust_i}(cell_i,:) = mean(tracePost); + meanTraceFlight{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(:,:,cell_i)); + meanTraceOdd{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(1:2:end,:,cell_i)); + meanTraceEven{clust_i}(cell_i,:) = mean(traceFlight{clust_i}(2:2:end,:,cell_i)); + meanTracePre{clust_i}(cell_i,:) = mean(tracePre{clust_i}(:,:,cell_i)); + meanTracePost{clust_i}(cell_i,:) = mean(tracePost{clust_i}(:,:,cell_i)); meanSpeedFlight{clust_i} = mean(speedFlight{clust_i}); meanSpeedPre{clust_i} = mean(speedPre{clust_i}); meanSpeedPost{clust_i} = mean(speedPost{clust_i}); @@ -143,7 +155,9 @@ [BFlight{clust_i},IFlight{clust_i}] = sort(maxnormTraceFlight{clust_i}); [BPre{clust_i},IPre{clust_i}] = sort(maxnormTracePre{clust_i}); [BPost{clust_i},IPost{clust_i}] = sort(maxnormTracePost{clust_i}); - [B1{clust_i},I1{clust_i}] = sort(maxnormTraceFlight{1}); %sort by cluster 1 + [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{1}); %sort by cluster 1 + [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{1}); %sort by cluster 1 + [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{1}); %sort by cluster 1 [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTraceOdd{clust_i}); %split dataset into even and odd for comparing 2 halves % normTraceOdd{clust_i} = normTraceFlight{clust_i}(1:2:end,:); @@ -158,10 +172,14 @@ %concatenate all clusters together and then zscore to equalize the %peaks across all trials meanTraceFlightAll = [meanTraceFlightAll meanTraceFlight{clust_i}]; %concatenate all traces - meanTracePreAll = [meanTracePreAll meanTraceFlight{clust_i}]; %concatenate all traces - meanTracePostAll = [meanTracePostAll meanTraceFlight{clust_i}]; %concatenate all traces + meanTracePreAll = [meanTracePreAll meanTracePre{clust_i}]; %concatenate all traces + meanTracePostAll = [meanTracePostAll meanTracePost{clust_i}]; %concatenate all traces + meanTracePreFlightPostAll{clust_i} = [meanTracePre{clust_i} meanTraceFlight{clust_i} meanTracePost{clust_i}]; + end + + %% this is to smooth, zscore, and sort the entire cell data by their preferred flight according to a homemade k-means (max dff across flights) %zscore the full data set and subtract min to start at 0 for cell_ii = 1:length(cellData.results.C(:,1)) @@ -171,36 +189,58 @@ normMeanTracePreAll(cell_ii,:) = normMeanTracePreAll(cell_ii,:) - min(normMeanTracePreAll(cell_ii,:)); normMeanTracePostAll(cell_ii,:) = zscore(smooth(meanTracePostAll(cell_ii,:),10)); normMeanTracePostAll(cell_ii,:) = normMeanTracePostAll(cell_ii,:) - min(normMeanTracePostAll(cell_ii,:)); + for clust_i = 1:nClusters + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = zscore(smooth(meanTracePreFlightPostAll{clust_i}(cell_ii,:),10)); + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) - min(normMeanTracePreFlightPostAll{clust_i}(cell_ii,:)); + end end %split the data back into its clusters traceFlightIndConcat = [1 length(normTraceFlight{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster tracePreIndConcat = [1 length(normTracePre{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster tracePostIndConcat = [1 length(normTracePost{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + %find the start and stop indices for 2nd through n cluster -for clust_ii = 2:clust_i +for clust_ii = 2:nClusters traceFlightIndConcat = vertcat(traceFlightIndConcat,[traceFlightIndConcat(clust_ii-1,2)+1 traceFlightIndConcat(clust_ii-1,2)+length(normTraceFlight{clust_ii}(1,:))]); tracePreIndConcat = vertcat(tracePreIndConcat,[tracePreIndConcat(clust_ii-1,2)+1 tracePreIndConcat(clust_ii-1,2)+length(normTracePre{clust_ii}(1,:))]); tracePostIndConcat = vertcat(tracePostIndConcat,[tracePostIndConcat(clust_ii-1,2)+1 tracePostIndConcat(clust_ii-1,2)+length(normTracePost{clust_ii}(1,:))]); end %regroup by each flight cluster -for clust_iii = 1:clust_i +for clust_iii = 1:nClusters normTraceFlightAll{clust_iii} = normMeanTraceFlightAll(:,traceFlightIndConcat(clust_iii,1):traceFlightIndConcat(clust_iii,2)); normTracePreAll{clust_iii} = normMeanTracePreAll(:,tracePreIndConcat(clust_iii,1):tracePreIndConcat(clust_iii,2)); normTracePostAll{clust_iii} = normMeanTracePostAll(:,tracePostIndConcat(clust_iii,1):tracePostIndConcat(clust_iii,2)); + normTracePreClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,1:preFlightPadCalcium); + normTraceFlightClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))); + normTracePostClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+postFlightPadCalcium); %find the order of the maximum for each cluster within the regrouping for cell_iii = 1:length(cellData.results.C(:,1)) [~,maxNormFlightAll{clust_iii}(cell_iii,1)] = max(normTraceFlightAll{clust_iii}(cell_iii,:)); [~,maxNormPreAll{clust_iii}(cell_iii,1)] = max(normTracePreAll{clust_iii}(cell_iii,:)); [~,maxNormPostAll{clust_iii}(cell_iii,1)] = max(normTracePostAll{clust_iii}(cell_iii,:)); + [~,maxNormPreClustAll{clust_iii}(cell_iii,1)] = max(normTracePreClustAll{clust_iii}(cell_iii,:)); + [~,maxNormFlightClustAll{clust_iii}(cell_iii,1)] = max(normTraceFlightClustAll{clust_iii}(cell_iii,:)); + [~,maxNormPostClustAll{clust_iii}(cell_iii,1)] = max(normTracePostClustAll{clust_iii}(cell_iii,:)); end %sort each cell by the timing of its peak firing [BnormFlightAll{clust_iii},InormFlightAll{clust_iii}] = sort(maxNormFlightAll{clust_iii}); [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{1}); %sort by cluster 1 [BnormPreAll{clust_iii},InormPreAll{clust_iii}] = sort(maxNormPreAll{clust_iii}); [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{1}); %sort by cluster 1 - [BnormPosttAll{clust_iii},InormPostAll{clust_iii}] = sort(maxNormPostAll{clust_iii}); - [B1normPosttAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{1}); %sort by cluster 1 + [BnormPostAll{clust_iii},InormPostAll{clust_iii}] = sort(maxNormPostAll{clust_iii}); + [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{1}); %sort by cluster 1 + + [BnormPreClustAll{clust_iii},InormPreClustAll{clust_iii}] = sort(maxNormPreClustAll{clust_iii}); + [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{1}); %sort by cluster 1 + [BnormFlightClustAll{clust_iii},InormFlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{clust_iii}); + [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{1}); %sort by cluster 1 + [BnormPostClustAll{clust_iii},InormPostClustAll{clust_iii}] = sort(maxNormPostClustAll{clust_iii}); + [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{1}); %sort by cluster 1 + + + + end @@ -209,31 +249,45 @@ [~,maxAllFlight] = max(normMeanTraceFlightAll,[],2); [~,maxAllPre] = max(normMeanTracePreAll,[],2); [~,maxAllPost] = max(normMeanTracePostAll,[],2); +for clust_i = 1:nClusters + [~,maxAllPreFlightPost{clust_i}] = max(normMeanTracePreFlightPostAll{clust_iii},[],2); +end + %kPeaks = kmeans(maxAll,nClusters); %take k-means cluster of the peaks of each cell whole time %sort based on each clustered peaks for flight, pre and post rng(2); -for n = 1:size(maxAllFlight,1); +for n = 1:size(maxAllFlight,1) for ii = 1:nClusters if maxAllFlight(n) >= traceFlightIndConcat(ii,1) & maxAllFlight(n) < traceFlightIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster kPeaksFlight(:,n) = 1; end + end end -for n = 1:size(maxAllPre,1); +for n = 1:size(maxAllPre,1) for ii = 1:nClusters if maxAllPre(n) >= tracePreIndConcat(ii,1) & maxAllPre(n) < tracePreIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster kPeaksPre(:,n) = 1; end end end -for n = 1:size(maxAllPost,1); +for n = 1:size(maxAllPost,1) for ii = 1:nClusters if maxAllPost(n) >= tracePostIndConcat(ii,1) & maxAllPost(n) < tracePostIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster kPeaksPost(:,n) = 1; end end end +for clust_i = 1:nClusters + for n = 1:size(maxAllPreFlightPost{clust_i},1) + if maxAllPreFlightPost{clust_i}(n) >= 1 & maxAllPreFlightPost{clust_i}(n) < (length(normTraceFlightAll{clust_iii}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1) %if the peak is within each cluster, sort it into that particular cluster + kPeaksPreFlightPost{clust_i}(:,n) = 1; + end + end + [BkPeaksPreFlightPost{clust_i},IkPeaksPreFlightPost{clust_i}] = sort(kPeaksPreFlightPost{clust_i}); + normMeanTraceSortPreFlightPost{clust_i} = normMeanTracePreFlightPostAll{clust_i}(IkPeaksPreFlightPost{clust_i},:); +end %sort the clusters according to their peak times [BkPeaksFlight,IkPeaksFlight] = sort(kPeaksFlight); @@ -242,6 +296,7 @@ normMeanTraceSortPre = normMeanTracePreAll(IkPeaksPre,:); [BkPeaksPost,IkPeaksPost] = sort(kPeaksPost); normMeanTraceSortPost = normMeanTracePostAll(IkPeaksPost,:); + %for each cluster, find the peaks of the cluster (aMat aka aTemp), tke the max %(maxInd), and sort that max (aSort) from the cluster, add this to the %normMeanTraceSort variable @@ -267,321 +322,100 @@ aSortPost = aTempPost(ImaxPost,:); normMeanTraceSortPost(aMatPost,:) = aSortPost; clear aMatPost aTempPost maxIndPost ImaxPost BaxPost aSortPost + aMatPreFlightPost = find(BkPeaksPreFlightPost{c} == 1); + aTempPreFlightPost = normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:); + [~,maxIndPreFlightPost] = max(aTempPreFlightPost,[],2); + [BmaxPreFlightPost,ImaxPreFlightPost] = sort(maxIndPreFlightPost); + aSortPreFlightPost = aTempPreFlightPost(ImaxPreFlightPost,:); + normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:) = aSortPreFlightPost; + clear aMatPreFlightPost aTempPreFlightPost maxIndPreFlightPost ImaxPreFlightPost BaxPreFlightPost aSortPreFlightPost + + end %divide the normMeanTraceSort overall variable into the respective clusters for c = 1:nClusters normMeanTraceEachFlight{c} = normMeanTraceSortFlight(:,traceFlightIndConcat(c,1):traceFlightIndConcat(c,2)); normMeanTraceEachPre{c} = normMeanTraceSortPre(:,tracePreIndConcat(c,1):tracePreIndConcat(c,2)); normMeanTraceEachPost{c} = normMeanTraceSortPost(:,tracePostIndConcat(c,1):tracePostIndConcat(c,2)); -end - -%% plot clusters normalized and clustered by preferred flight/pre/post (max dff across flights) -snakePlot_prefEachPrePostFlight = figure(); -for p = 1:nClusters - - p1 = subplot(12,clust_i,p); - plot(1:length(smoothSpeedFlight{p}),smoothSpeedFlight{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - %set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(12,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normMeanTraceEachFlight{p},[0.5 5.5]); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - %set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - p3 = subplot(12,clust_i,p+20); - plot(1:length(smoothSpeedPre{p}),smoothSpeedPre{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawPre{p},1) - plot(1:length(smoothSpeedRawPre{p}(cell_ii,:)),smoothSpeedRawPre{p}(cell_ii,:)); - end - sgtitle(['Spatial selectivity sort by flight preference: ' batName ' ' dateSesh ' ' sessionType]); -end - - -%% Plot the clusters normalized and clustered by their preferred flight (max dff across flights) -snakePlot_prefEach = figure(); -for p = 1:nClusters - - p1 = subplot(4,clust_i,p); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - %set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normMeanTraceEachFlight{p},[0.5 5.5]); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - %set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - sgtitle(['Spatial selectivity sort by flight preference: ' batName ' ' dateSesh ' ' sessionType]); -end + normMeanTraceEachPFlightP{c} = normMeanTraceSortPreFlightPost{c}(:,preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium); + normMeanTraceEachPreFP{c} = normMeanTraceSortPreFlightPost{c}(:,1:preFlightPadCalcium); + normMeanTraceEachPFPost{c} = normMeanTraceSortPreFlightPost{c}(:,length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1); -%plot all the flight trajectories concatenated sorted by their preference -snakePlot_prefAll = figure(); -imagesc(normMeanTraceSortFlight); -colormap(hot); -ylabel('cell number'); -set(gca,'yticklabel',{[]}); -title(['Spatial selectivity sort by flight preference: ' batName ' ' dateSesh ' ' sessionType]); -xt = get(gca, 'XTick'); -set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); -xlabel('time (s)'); - - -%% -%plot the cells according to their peak for each cluster with velocity on top -snakePlot_clust = figure(); -for p = 1:clust_i - p1 = subplot(4,clust_i,p); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normTraceFlight{p}(IFlight{p},:)); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - sgtitle(['Spatial selectivity sort by peak: ' batName ' ' dateSesh ' ' sessionType]); - -end - -%plot the cells by cluster sorted by cluster1 order -snakePlot_clustBy1 = figure(); -for p = 1:clust_i - p1 = subplot(4,clust_i,p); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normTraceFlight{p}(I1{p},:)); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - sgtitle(['Spatial selectivity sort by cluster 1: ' batName ' ' dateSesh ' ' sessionType]); - end -%plot half the odd cells sorted and then plot the even cells according to -%the odd sorting -snakePlot_clustOddEven = figure(); -for p = 1:clust_i - p1 = subplot(4,2*clust_i,2*p-1); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,2*clust_i,[2*clust_i+(2*p-1),4*clust_i+(2*p-1),6*clust_i+(2*p-1)]); - imagesc(normTraceOdd{p}(Iodd{p},:)); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - title(['Cluster ' num2str(p) ' Odd']); - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); %ylabel('cell number'); - p3 = subplot(4,2*clust_i,[2*clust_i+(2*p),4*clust_i+(2*p),6*clust_i+(2*p)]); - imagesc(normTraceEven{p}(Iodd{p},:)); - colormap(hot); - title(['Cluster ' num2str(p) ' Even']); - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1),'yticklabel',{[]}); - xlabel('time (s)'); %ylabel('cell number'); - sgtitle(['Spatial selectivity Odd (sorted) vs Even Trials: ' batName ' ' dateSesh ' ' sessionType]); -end - - -%% -%plot the fully normalized cells according to their peak for each cluster with velocity on top -snakePlot_clust_allNorm = figure(); -for p = 1:clust_i - p1 = subplot(4,clust_i,p); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normTraceFlightAll{p}(InormFlightAll{p},:)); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - sgtitle(['Spatial selectivity (norm) sort by peak: ' batName ' ' dateSesh ' ' sessionType]); - -end - -%plot the cells by cluster sorted by cluster1 order -snakePlot_clustBy1_normAll = figure(); -for p = 1:clust_i - p1 = subplot(4,clust_i,p); - plot(1:length(smoothSpeed{p}),smoothSpeed{p},'k'); - hold on - for cell_ii = 1:size(smoothSpeedRawFlight{p},1) - plot(1:length(smoothSpeedRawFlight{p}(cell_ii,:)),smoothSpeedRawFlight{p}(cell_ii,:)); - end - title(['Cluster ' num2str(p)]); - if p == 1 - ylabel('velocity (cm/s)'); - yt = get(gca,'YTick'); - set(gca,'YTick',yt,'YTickLabel',yt*100,'xticklabel',{[]}); - else - set(gca,'xticklabel',{[]},'yticklabel',{[]}); - end - p2 = subplot(4,clust_i,[clust_i+p,2*clust_i+p,3*clust_i+p]); - imagesc(normTraceFlightAll{p}(I1normFlightAll{p},:)); - colormap(hot); - %make labels for first left plot only - if p == 1 - ylabel('cell number'); - else - set(gca,'yticklabel',{[]}); - end - xt = get(gca, 'XTick'); - set(gca,'XTick',xt,'XTickLabel',round(xt/cellData.results.Fs,1)); - xlabel('time (s)'); - %hold off - sgtitle(['Spatial selectivity (norm) sort by cluster 1: ' batName ' ' dateSesh ' ' sessionType]); - -end %% save to snakeTrace variable +snakeTrace.normMeanTraceSortPreFlightPost = normMeanTraceSortPreFlightPost; +snakeTrace.meanTracePreFlightPostAll=meanTracePreFlightPostAll; +snakeTrace.maxAllPreFlightPost=maxAllPreFlightPost; +snakeTrace.normMeanTracePreFlightPostAll=normMeanTracePreFlightPostAll; +snakeTrace.kPeaksPreFlightPost=kPeaksPreFlightPost; +snakeTrace.IkPeaksPreFlightPost=IkPeaksPreFlightPost; +snakeTrace.normMeanTraceEachPFlightP = normMeanTraceEachPFlightP; +snakeTrace.normMeanTraceEachPreFP = normMeanTraceEachPreFP; +snakeTrace.normMeanTraceEachPFPost = normMeanTraceEachPFPost; snakeTrace.meanTraceFlight = meanTraceFlight; snakeTrace.normTraceFlight = normTraceFlight; snakeTrace.maxnormTraceFlight = maxnormTraceFlight; -snakeTrace.sortedTrace = BFlight; -snakeTrace.sortedIndex = IFlight; -snakeTrace.sortedTraceOdd = Bodd; -snakeTrace.sortedIndexOdd = Iodd; -snakeTrace.sortedTraceClustBy1 = B1; -snakeTrace.sortedIndexClustBy1 = I1; +snakeTrace.meanTracePre = meanTracePre; +snakeTrace.normTracePre = normTracePre; +snakeTrace.maxnormTracePre = maxnormTracePre; +snakeTrace.meanTracePost = meanTracePost; +snakeTrace.normTracePost = normTracePost; +snakeTrace.maxnormTracePost = maxnormTracePost; +snakeTrace.BFlight = BFlight; +snakeTrace.IFlight = IFlight; +snakeTrace.BPre = BPre; +snakeTrace.IPre = IPre; +snakeTrace.BPost = BPost; +snakeTrace.IPost = IPost; +snakeTrace.BOdd = Bodd; +snakeTrace.B1Flight = B1Flight; +snakeTrace.I1Flight = I1Flight; +snakeTrace.B1Pre = B1Pre; +snakeTrace.I1Pre = I1Pre; +snakeTrace.B1Post = B1Post; +snakeTrace.I1Post = I1Post; +snakeTrace.Iodd = Iodd; +snakeTrace.Bodd = Bodd; snakeTrace.normTraceEven = normTraceEven; snakeTrace.normTraceOdd = normTraceOdd; -snakeTrace.meanSpeed = meanSpeedFlight; -snakeTrace.smoothSpeed = smoothSpeed; -snakeTrace.snakePlot_clustAll = snakePlot_clust; -snakeTrace.snakePlot_clustOddEven = snakePlot_clustOddEven; -snakeTrace.snakePlot_clustBy1 = snakePlot_clustBy1; +snakeTrace.meanSpeedFlight = meanSpeedFlight; +snakeTrace.smoothSpeedFlight = smoothSpeedFlight; +snakeTrace.meanSpeedPre = meanSpeedPre; +snakeTrace.smoothSpeedPre = smoothSpeedPre; +snakeTrace.meanSpeedPost = meanSpeedPost; +snakeTrace.smoothSpeedPost = smoothSpeedPost; +snakeTrace.smoothSpeedRawPre = smoothSpeedRawPre; +snakeTrace.smoothSpeedRawPost = smoothSpeedRawPost; snakeTrace.smoothSpeedRawFlight = smoothSpeedRawFlight; -snakeTrace.normMeanTraceEach = normMeanTraceEachFlight; -snakeTrace.normMeanTraceSort = normMeanTraceSortFlight; -%snakeTrace.normMeanTraceAllSmooth = normMeanTraceAllSmooth; -snakeTrace.normMeanTraceAll = normMeanTraceFlightAll; -snakeTrace.snakePlot_prefEach = snakePlot_prefEach; -snakeTrace.snakePlot_prefAll = snakePlot_prefAll; -snakeTrace.traceIndConcat = traceFlightIndConcat; -%% save figures and matlab variable +snakeTrace.normMeanTraceEachFlight = normMeanTraceEachFlight; +snakeTrace.normMeanTraceSortFlight = normMeanTraceSortFlight; +snakeTrace.normMeanTraceFlightAll = normMeanTraceFlightAll; +snakeTrace.traceFlightIndConcat = traceFlightIndConcat; +snakeTrace.normMeanTraceEachPre = normMeanTraceEachPre; +snakeTrace.normMeanTraceSortPre = normMeanTraceSortPre; +snakeTrace.normMeanTracePreAll = normMeanTracePreAll; +snakeTrace.tracePreIndConcat = tracePreIndConcat; +snakeTrace.normMeanTraceEachPost = normMeanTraceEachPost; +snakeTrace.normMeanTraceSortPost = normMeanTraceSortPost; +snakeTrace.normMeanTracePostAll = normMeanTracePostAll; +snakeTrace.tracePostIndConcat = tracePostIndConcat; +snakeTrace.nClusters = nClusters; +snakeTrace.batName = batName; +snakeTrace.dateSesh = dateSesh; +snakeTrace.sessionType = sessionType; +snakeTrace.InormFlightAll = InormFlightAll; +snakeTrace.normTraceFlightAll = normTraceFlightAll; +snakeTrace.I1normFlightAll = I1normFlightAll; +snakeTrace.smoothTraceRawPost = smoothTraceRawPost; +snakeTrace.smoothTraceRawPre = smoothTraceRawPre; +snakeTrace.smoothTraceRawFlight = smoothTraceRawFlight; + if saveFlag == 1 - saveas(snakeTrace.snakePlot_clustAll, [pwd '\analysis\snakePlots\' label '_snakePlots_clustAll.svg']); - saveas(snakeTrace.snakePlot_clustOddEven, [pwd '\analysis\snakePlots\' label '_snakePlots_clustOddEven.svg']); - saveas(snakeTrace.snakePlot_clustBy1, [pwd '\analysis\snakePlots\' label '_snakePlots_clustBy1.svg']); - saveas(snakeTrace.snakePlot_prefEach, [pwd '\analysis\snakePlots\' label '_snakePlots_prefEach.svg']); - saveas(snakeTrace.snakePlot_prefAll, [pwd '\analysis\snakePlots\' label '_snakePlots_prefAll.svg']); - saveas(snakeTrace.snakePlot_clustAll, [pwd '\analysis\snakePlots\' label '_snakePlots_clustAll.tif']); - saveas(snakeTrace.snakePlot_clustOddEven, [pwd '\analysis\snakePlots\' label '_snakePlots_clustOddEven.tif']); - saveas(snakeTrace.snakePlot_clustBy1, [pwd '\analysis\snakePlots\' label '_snakePlots_clustBy1.tif']); - saveas(snakeTrace.snakePlot_prefEach, [pwd '\analysis\snakePlots\' label '_snakePlots_prefEach.tif']); - saveas(snakeTrace.snakePlot_prefAll, [pwd '\analysis\snakePlots\' label '_snakePlots_prefAll.tif']); - save([pwd '/analysis/' label '_snakePlotData.mat'],'snakeTrace'); - savefig(snakeTrace.snakePlot_clustAll, [pwd '/analysis/snakePlots/' label '_snakePlots_clustAll.fig']); - savefig(snakeTrace.snakePlot_clustOddEven, [pwd '/analysis/snakePlots/' label '_snakePlots_clustOddEven.fig']); - savefig(snakeTrace.snakePlot_clustBy1, [pwd '/analysis/snakePlots/' label '_snakePlots_clustBy1.fig']); - savefig(snakeTrace.snakePlot_prefEach, [pwd '/analysis/snakePlots/' label '_snakePlots_prefEach.fig']); - savefig(snakeTrace.snakePlot_prefAll, [pwd '/analysis/snakePlots/' label '_snakePlots_prefAll.fig']); + snakeTrace.label = label; + save([pwd '/analysis/' label '_snakePlotData.mat'],'snakeTrace'); +end + +%snakeTrace.normMeanTraceAllSmooth = normMeanTraceAllSmooth; + end \ No newline at end of file diff --git a/snakePlot/ImBat_snakeDataPrePost.m b/snakePlot/ImBat_snakeDataPrePost.m index f4f8ae0..d643438 100644 --- a/snakePlot/ImBat_snakeDataPrePost.m +++ b/snakePlot/ImBat_snakeDataPrePost.m @@ -22,6 +22,8 @@ loadFlag = varargin{i+1}; case 'saveflag' saveFlag = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; end end @@ -32,19 +34,19 @@ cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); alignment = load([pwd '/processed/Alignment.mat']); - load([pwd '/analysis/' label '_flightPaths_6clusters.mat']); + load([pwd '/' analysis_Folder '/' label '_flightPaths_6clusters.mat']); end %padding for during flight snake plot to include some time before and after flight -prePad = 0; %number of seconds to plot before alignment point for during flight -postPad = 0; %number of seconds to plot after alignment point for during flight +prePad = 7; %number of seconds to plot before alignment point for during flight +postPad = 7; %number of seconds to plot after alignment point for during flight prePadCalcium = prePad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postPadCalcium = postPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time prePadSpeed = prePad*120; %add 2 seconds * FS of tracking data (120) postPadSpeed = postPad*120;%add 6 seconds * FS of tracking data (120) %padding for pre and post flight snakePlots -preFlightPad = 10; %number of seconds to include before flight starts -postFlightPad = 10; %of of seconds to include after flight ends +preFlightPad = 7; %number of seconds to include before flight starts +postFlightPad = 7; %of of seconds to include after flight ends preFlightPadCalcium = preFlightPad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction postFlightPadCalcium = postFlightPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time preFlightPadSpeed = preFlightPad*120; %add 2 seconds * FS of tracking data (120) @@ -53,10 +55,22 @@ %meanTrace = cell(1,length(flightPaths.clusterIndex)); meanTracePreFlightPostAll = []; %initialize the variable to concatenate all pre/post/flight traces for uniform zscore +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_gal = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 14 3 16 21 2 1 5 7 8 26 NaN 9 27 6 4; + 5 13 41 23 1 21 3 24 6 22 2 25 16 15 7; + 12 3 34 19 2 14 6 15 9 36 5 10 35 20 1; + 25 26 16 32 1 12 4 19 5 28 15 NaN 34 3 2; + 32 34 29 51 7 10 6 40 16 45 5 8 42 26 43]; + %for each cell in each sort type (pre,during,post) %for each cell -for cell_i = 1:length(cellData.results.C(:,1)) +cellCount = 1; +for cell_i = ROIs_gal(1,:)%1:length(C(:,1)) %for each trial in cluster, calculate the start/stop times and duration of the calcium videos for dur_i = 1:length(flightPaths.flight_starts_idx) %get imaging times of start and stop index converting from tracking to video times @@ -82,27 +96,36 @@ %build the calcium and speed vectors for each flight within each cluster for trace_i = 1:length(flightPaths.flight_starts_idx) try - traceFlight(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (maxDur-dur(trace_i)) + postPadCalcium); + traceFlight(trace_i,:) = cellData.results.C_raw(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (maxDur-dur(trace_i)) + postPadCalcium); speedFlight(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(trace_i) - prePadSpeed:flightPaths.flight_ends_idx(trace_i) + (maxDurSpeed-durSpeed(trace_i)) + postPadSpeed); smoothSpeedRawFlight(trace_i,:) = smooth(speedFlight(trace_i,:),100); - tracePre(trace_i,:) = cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); + tracePre(trace_i,:) = cellData.results.C_raw(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); speedPre(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(trace_i) - preFlightPadSpeed:flightPaths.flight_starts_idx(trace_i)); smoothSpeedRawPre(trace_i,:) = smooth(speedPre(trace_i,:),100); - tracePost(trace_i,:) = cellData.results.C(cell_i,closestIndexEnd(trace_i)+postPadCalcium:closestIndexEnd(trace_i)+postPadCalcium + postFlightPadCalcium); + tracePost(trace_i,:) = cellData.results.C_raw(cell_i,closestIndexEnd(trace_i)+postPadCalcium:closestIndexEnd(trace_i)+postPadCalcium + postFlightPadCalcium); speedPost(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(trace_i)+postPadCalcium:flightPaths.flight_ends_idx(trace_i)+postPadCalcium + postFlightPadSpeed); smoothSpeedRawPost(trace_i,:) = smooth(speedPost(trace_i,:),100); catch - sizeToRecordingEnd = size(cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:end),2); - sizeToTraceEnd = size(traceFlight(trace_i,:),2); - traceFlight(trace_i,:) = (cellData.results.C(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:end + postFlightPadCalcium)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); - speedFlight(trace_i,:) = (flightPaths.batSpeed(closestIndexStart(trace_i) - preFlightPadSpeed:end + postFlightPadSpeed)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); + try + sizeToRecordingEnd = size(cellData.results.C_raw(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:end),2); + sizeToTraceEnd = size(traceFlight(trace_i,:),2); + try + traceFlight(trace_i,:) = (cellData.results.C_raw(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:end + postFlightPadCalcium)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); + speedFlight(trace_i,:) = (flightPaths.batSpeed(closestIndexStart(trace_i) - preFlightPadSpeed:end + postFlightPadSpeed)+(zeros(1,sizeToTraceEnd - sizeToRecordingEnd))); + catch + traceFlight(trace_i,:) = cellData.results.C_raw(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:end+(sizeToTraceEnd - sizeToRecordingEnd)); + speedFlight(trace_i,:) = flightPaths.batSpeed(closestIndexStart(trace_i) - preFlightPadSpeed:end +(sizeToTraceEnd - sizeToRecordingEnd)); + end + catch + + end disp('End of rec') end end %calculate the mean neural activity across all flights in a cluster for each cell - meanTraceFlight(cell_i,:) = mean(traceFlight); - meanTracePre(cell_i,:) = mean(tracePre); - meanTracePost(cell_i,:) = mean(tracePost); + meanTraceFlight(cellCount,:) = mean(traceFlight); + meanTracePre(cellCount,:) = mean(tracePre); + meanTracePost(cellCount,:) = mean(tracePost); meanSpeedFlight = mean(speedFlight); meanSpeedPre = mean(speedPre); meanSpeedPost = mean(speedPost); @@ -110,20 +133,23 @@ %smooth and zscore the neural data. subtract the min of the zscore so the %min is 0 rather than mean 0 - normTraceFlight(cell_i,:) = zscore(smooth(meanTraceFlight(cell_i,:),3)); - normTraceFlight(cell_i,:) = normTraceFlight(cell_i,:) - min(normTraceFlight(cell_i,:)); + normTraceFlight(cellCount,:) = zscore(smooth(meanTraceFlight(cellCount,:),3)); + normTraceFlight(cellCount,:) = normTraceFlight(cellCount,:) - min(normTraceFlight(cellCount,:)); smoothSpeedFlight = smooth(meanSpeedFlight,40); - normTracePre(cell_i,:) = zscore(smooth(meanTracePre(cell_i,:),3)); - normTracePre(cell_i,:) = normTracePre(cell_i,:) - min(normTracePre(cell_i,:)); + normTracePre(cellCount,:) = zscore(smooth(meanTracePre(cellCount,:),3)); + normTracePre(cellCount,:) = normTracePre(cellCount,:) - min(normTracePre(cellCount,:)); smoothSpeedPre = smooth(meanSpeedPre,40); - normTracePost(cell_i,:) = zscore(smooth(meanTracePost(cell_i,:),3)); - normTracePost(cell_i,:) = normTracePost(cell_i,:) - min(normTracePost(cell_i,:)); + normTracePost(cellCount,:) = zscore(smooth(meanTracePost(cellCount,:),3)); + normTracePost(cellCount,:) = normTracePost(cellCount,:) - min(normTracePost(cellCount,:)); smoothSpeedPost = smooth(meanSpeedPost,40); %find time index of max peaks - [~,maxnormTraceFlight(cell_i,1)] = max(normTraceFlight(cell_i,:)); - [~,maxnormTracePre(cell_i,1)] = max(normTracePre(cell_i,:)); - [~,maxnormTracePost(cell_i,1)] = max(normTracePost(cell_i,:)); + [~,maxnormTraceFlight(cellCount,1)] = max(normTraceFlight(cellCount,:)); + [~,maxnormTracePre(cellCount,1)] = max(normTracePre(cellCount,:)); + [~,maxnormTracePost(cellCount,1)] = max(normTracePost(cellCount,:)); + + cellCount = cellCount + 1; end + cellCount = cellCount -1; %sort each cell by the timing of its peak firing [BFlight,IFlight] = sort(maxnormTraceFlight); [BPre,IPre] = sort(maxnormTracePre); @@ -136,7 +162,7 @@ %% this is to smooth, zscore, and sort the entire cell data by their preferred flight according to a homemade k-means (max dff across flights) %zscore the full data set and subtract min to start at 0 -for cell_ii = 1:length(cellData.results.C(:,1)) +for cell_ii = 1:cellCount%length(cellData.results.C(:,1)) normMeanTracePreFlightPostAll(cell_ii,:) = zscore(smooth(meanTracePreFlightPostAll(cell_ii,:),10)); normMeanTracePreFlightPostAll(cell_ii,:) = normMeanTracePreFlightPostAll(cell_ii,:) - min(normMeanTracePreFlightPostAll(cell_ii,:)); end @@ -146,7 +172,7 @@ normTracePreAll = normMeanTracePreFlightPostAll(:,1:preFlightPadCalcium); normTracePostAll = normMeanTracePreFlightPostAll(:,preFlightPadCalcium+maxDur+1+prePadCalcium+postPadCalcium:preFlightPadCalcium++prePadCalcium+postPadCalcium+maxDur+postFlightPadCalcium); %find the order of the maximum for each flight group within the regrouping -for cell_iii = 1:length(cellData.results.C(:,1)) +for cell_iii = 1:cellCount%length(cellData.results.C(:,1)) [~,maxNormFlightAll(cell_iii,1)] = max(normTraceFlightAll(cell_iii,:)); [~,maxNormPreAll(cell_iii,1)] = max(normTracePreAll(cell_iii,:)); [~,maxNormPostAll(cell_iii,1)] = max(normTracePostAll(cell_iii,:)); @@ -233,5 +259,5 @@ if saveFlag == 1 snakeTracePrePost.label = label; - save([pwd '/analysis/' label '_snakePlotData.mat'],'snakeTracePrePost'); + save([pwd '/' analysis_Folder '/' label '_snakePlotDataPrePost.mat'],'snakeTracePrePost'); end \ No newline at end of file diff --git a/snakePlot/ImBat_snakeData_manualStable.m b/snakePlot/ImBat_snakeData_manualStable.m new file mode 100644 index 0000000..7f54512 --- /dev/null +++ b/snakePlot/ImBat_snakeData_manualStable.m @@ -0,0 +1,611 @@ +function [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData_manualStable(cellData,flightPaths,alignment,varargin) + +batName = []; +dateSesh = []; +sessionType = []; +loadFlag = 0; %do you want to load and save the data individually outside of ImBatAnalyze +saveFlag = 0; +%offset = 0.1; % account for slow calcium estimation ~move locations back 0ms in time... This is the knob to turn for 'prospective' coding... +%clusters = [1 2 4 6]; +%nClusters = 4;%length(clusters); %number of flight trajectories to look at and for k means clustering of whole time series by peak + + + +% User inputs overrides +nparams=length(varargin); +for i=1:2:nparams + switch lower(varargin{i}) + case 'batname' + batName=varargin{i+1}; + case 'datesesh' + dateSesh = varargin{i+1}; + case 'sessiontype' + sessionType = varargin{i+1}; + case 'loadflag' + loadFlag = varargin{i+1}; + case 'saveflag' + saveFlag = varargin{i+1}; + case 'nclusters' + nClusters = varargin{i+1}; + case 'preflightpad' + preFlightPad = varargin{i+1}; + case 'postflightpad' + postFlightPad = varargin{i+1}; + case 'analysisfolder' + analysis_Folder = varargin{i+1}; + case 'galdate' + galDate = varargin{i+1}; + end +end +batId = batName; + +%labels for loading and saving data if running independent fromImBat_analyze +if loadFlag == 1 + date = strcat(lower(batName(1:2)),dateSesh); + label = [batName '_' dateSesh '_' sessionType]; + + cellData = load([pwd '/processed/Motion_corrected_Data_DS_results.mat']); + alignment = load([pwd '/processed/Alignment.mat']); + load([pewd '/' analysis_Folder '/' label '_flightPaths.mat']); +end +%padding for during flight snake plot to include some time before and after flight +prePad = 3; %number of seconds to plot before alignment point +postPad = 10; %number of seconds to plot after alignment point +prePadCalcium = prePad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction +postPadCalcium = postPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time +prePadSpeed = prePad*120; %add 2 seconds * FS of tracking data (120) +postPadSpeed = postPad*120;%add 6 seconds * FS of tracking data (120) +%padding for pre and post flight snakePlots +preFlightPad = 7; %number of seconds to include before flight starts +postFlightPad = 7; %of of seconds to include after flight ends +preFlightPadCalcium = preFlightPad*cellData.results.Fs; %number of frames (seconds*freq) to include in the trace extraction +postFlightPadCalcium = postFlightPad*cellData.results.Fs; %add 2 seconds to the end of the plots to include delay in peak time +preFlightPadSpeed = preFlightPad*120; %add 2 seconds * FS of tracking data (120) +postFlightPadSpeed = postFlightPad*120;%add 6 seconds * FS of tracking data (120) +smoothSpeed = 100; %number of tracking frames to smooth the data by using mean smooth +smoothTrace = 2; %number of calcium video frames to smooth the data +%number of clusters to plot data against +if isfield(flightPaths,'nClusters') + nClusters = flightPaths.nClusters; +else + nClusters = length(flightPaths.clusterIndex); +end + +if strcmp(batId,'Gal') +% 15 stable manually selected ROIs across 9 days for Gal +ROIs_manual = [28 20 1 23 12 22 10 8 11 24 NaN 2 21 30 19; + 3 2 10 28 11 1 5 33 8 35 NaN 6 22 32 29; + 4 5 11 24 5 1 16 10 2 18 14 8 25 19 9; + 11 22 4 18 3 1 14 5 19 39 9 17 36 25 8; + 25 6 30 27 3 1 2 9 8 37 NaN 15 31 24 36; + 8 12 35 20 1 10 2 39 9 30 3 14 31 24 11; + 10 7 39 35 3 31 8 22 9 37 5 11 39 17 2; + 9 27 25 45 1 7 8 46 11 33 23 6 42 3 2; + 20 34 29 51 7 10 6 40 16 45 5 8 42 26 43; + 8 2 25 38 16 44 20 7 14 26 3 35 37 24 41; + 1 7 28 NaN 6 17 2 35 16 33 12 11 27 30 34; + 19 4 16 NaN 27 21 3 24 2 29 14 8 26 32 33]; +elseif strcmp(batId,'Gen') +% 20 stable manually selected ROIs across 5 days for Gen +ROIs_manual = [NaN NaN 10 3 16 12 17 18 27 29 8 9 NaN NaN 21 11 31 15 20 25; + 8 17 5 1 2 6 21 10 18 31 NaN 11 51 53 28 4 38 19 23 20; + 50 54 12 3 48 18 27 15 31 34 NaN NaN 28 NaN 29 25 24 22 38 14; + 9 NaN 7 31 2 22 NaN 20 40 25 13 NaN 34 NaN 26 NaN 45 3 24 21; + 10 36 3 11 2 NaN 21 18 20 9 33 NaN NaN NaN 17 NaN 22 7 30 26]; %14 NaN 3 28 2 6 33 26 18 45 NaN NaN 25 NaN 32 NaN 37 8 28 11 +end +% if ~isempty(clustDelete) & clustDelete <6 +% flightPaths.clusterIndex{clustDelete} = []; +% end +%flightPaths.clusterIndex cat(2,flightPaths.clusterIndex{clustComb(1)},flightPaths.clusterIndex{clustComb(2)}); + + %flightPaths.clusterIndex{3} =flightPaths.clusterIndex{6}; +% flightPaths.clusterIndex{3} =[]; +%flightPaths.clusterIndex= flightPaths.clusterIndex(~cellfun('isempty',flightPaths.clusterIndex)); + +%for each C_raw and C matrix +data_i = 1; %start with the cRaw data +for data_i = 1:3 + if data_i ==1 + traceData = cellData.results.C_raw; %assign the data from cnmfe output for C_raw matrix + traceSmooth = 3; %number of imaging frames to smooth the data by using mean smooth + elseif data_i ==2 + traceData = cellData.results.C; %assign the data from cnmfe output for C matrix + traceSmooth = 3; %number of imaging frames to smooth the data by using mean smooth + elseif data_i ==3 + traceData = cellData.results.S; %assign the data from cnmfe output for C matrix + traceSmooth = 1; %number of imaging frames to smooth the data by using mean smooth + end + + %initialize variables + %meanTrace = cell(1,length(flightPaths.clusterIndex)); + meanTraceFlightAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePreAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePostAll = []; %initialize the variable to concatenate all traces for uniform zscore + meanTracePreFlightPostAll = []; %initialize the variable to concatenate all pre/post/flight traces for uniform zscore + traceFlight = cell(1,nClusters); + tracePre = cell(1,nClusters); + tracePost = cell(1,nClusters); + speedFlight = cell(1,nClusters); + speedPre = cell(1,nClusters); + speedPost = cell(1,nClusters); + meanTraceFlight = cell(1,nClusters); + sdTraceFlight = cell(1,nClusters); + meanTraceOdd = cell(1,nClusters); + meanTraceEven = cell(1,nClusters); + meanTracePreFlightPost = cell(1,nClusters); + sdTracePreFlightPost = cell(1,nClusters); + normTraceFlight = cell(1,nClusters); + normTraceOdd= cell(1,nClusters); + normTraceEven = cell(1,nClusters); + tracePreFlightPost = cell(1,nClusters); + smoothTraceRawFlight = cell(1,nClusters); + normTraceRawFlight = cell(1,nClusters); + smoothTraceRawPre = cell(1,nClusters); + normTraceRawPre = cell(1,nClusters); + smoothTraceRawPost = cell(1,nClusters); + normTraceRawPost = cell(1,nClusters); + smoothTraceRawPreFlightPost = cell(1,nClusters); + normTraceRawPreFlightPost = cell(1,nClusters); + speedFlight = cell(1,nClusters); + smoothSpeedRawFlight = cell(1,nClusters); + smoothSpeedRawPre = cell(1,nClusters); + speedPre = cell(1,nClusters); + smoothSpeedRawPost = cell(1,nClusters); + speedPost = cell(1,nClusters); + speedPreFlightPost = cell(1,nClusters); + smoothSpeedRawPreFlightPost = cell(1,nClusters); + normTracePre = cell(1,nClusters); + smoothSpeedPre = cell(1,nClusters); + normTracePost = cell(1,nClusters); + normTracePost = cell(1,nClusters); + smoothSpeedPost = cell(1,nClusters); + semTracePreFlightPost = cell(1,nClusters); + normMeanTraceFlightAll = []; + normMeanTracePreAll= []; + normMeanTracePreAll= []; + normMeanTracePostAll = []; + normMeanTracePreFlightPostAll = cell(1,nClusters); + dur = cell(1,nClusters); + durSpeed = cell(1,nClusters); + %for each cluster type + for clust_i = 1:nClusters %length(flightPaths.clusterIndex) + %for each trial in cluster, calculate the start/stop times and duration of the calcium videos + for dur_i = 1:length(flightPaths.clusterIndex{clust_i}) + %get imaging times of start and stop index converting from tracking to video times + [minValueStart(dur_i),closestIndexStart(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); + [minValueEnd(dur_i),closestIndexEnd(dur_i)] = min(abs(alignment.out.video_times-alignment.out.Location_time(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))))); + %calculate duration of each flight in a particular cluster so + %you can pad all flights to the longest flight in that cluster + dur{clust_i}(dur_i) = closestIndexEnd(dur_i)-closestIndexStart(dur_i); + durSpeed{clust_i}(dur_i)= flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(dur_i))-flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(dur_i)); + end + %calculate max duration for each cluster of trajectories + medDur{clust_i} = round(median(dur{clust_i})); + medDurSpeed{clust_i} = round(median(durSpeed{clust_i})); + %meanTrace{clust_i}=zeros(length(traceData(:,1)),medDur{clust_i}+preWindow+1); + %initialize the vector to store the neural activity of each flight + traceFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),medDur{clust_i}+prePadCalcium+postPadCalcium+1,length(traceData(:,1))); + speedFlight{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),medDurSpeed{clust_i}+prePadSpeed+postPadSpeed+1); + tracePre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadCalcium+1,length(traceData(:,1))); + speedPre{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),preFlightPadSpeed+1); + tracePost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadCalcium+1,length(traceData(:,1))); + speedPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),postFlightPadSpeed+1); + tracePreFlightPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),length(tracePre{clust_i}(1,:,1)) + length(traceFlight{clust_i}(1,:,1)) + length(tracePost{clust_i}(1,:,1))); + speedPreFlightPost{clust_i} = zeros(length(flightPaths.clusterIndex{clust_i}),length(speedPre{clust_i}(1,:)) + length(speedFlight{clust_i}(1,:)) + length(speedPost{clust_i}(1,:))); + %for each cell + cellCount = 1; + for cell_i = ROIs_manual(galDate,:)%1:length(traceData(:,1)) + %build the calcium and speed vectors for each flight within each cluster + for trace_i = 1:length(flightPaths.clusterIndex{clust_i}) + + traceFlightIdx{clust_i}(trace_i) = flightPaths.clusterIndex{clust_i}(trace_i); + try + traceFlight{clust_i}(trace_i,:,cellCount) = traceData(cell_i,closestIndexStart(trace_i) - prePadCalcium:closestIndexEnd(trace_i) + (medDur{clust_i}-dur{clust_i}(trace_i)) + postPadCalcium); + tracePre{clust_i}(trace_i,:,cellCount) = traceData(cell_i,closestIndexStart(trace_i) - preFlightPadCalcium:closestIndexStart(trace_i)); + tracePost{clust_i}(trace_i,:,cellCount) = traceData(cell_i,closestIndexEnd(trace_i):closestIndexEnd(trace_i) + postFlightPadCalcium); + speedFlight{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - prePadSpeed:flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)) + postPadSpeed); + speedPre{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i)) - preFlightPadSpeed:flightPaths.flight_starts_idx(flightPaths.clusterIndex{clust_i}(trace_i))); + speedPost{clust_i}(trace_i,:) = flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)):flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i)) + (medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)) + postFlightPadSpeed); + + catch + % tracePost{clust_i}(trace_i,:,cell_i) = [traceData(cell_i,closestIndexEnd(trace_i):end),zeros(1,size(tracePost{clust_i}(trace_i,:,cell_i),2) - size(traceData(cell_i,closestIndexEnd(trace_i):end),2))]; + % speedPost{clust_i}(trace_i,:) = [flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)):end),zeros(1,size(speedPost{clust_i}(trace_i,:),2)-size(flightPaths.batSpeed(flightPaths.flight_ends_idx(flightPaths.clusterIndex{clust_i}(trace_i))+(medDurSpeed{clust_i}-durSpeed{clust_i}(trace_i)):end,2)))]; + % smoothTraceRawPost{clust_i}(trace_i,:,cell_i) = smooth(tracePost{clust_i}(trace_i,:,cell_i),traceSmooth); + % normTraceRawPost{clust_i}(trace_i,:,cell_i) = zscore(smoothTraceRawPost{clust_i}(trace_i,:,cell_i),0,2); + % normTraceRawPost{clust_i}(trace_i,:,cell_i) = normTraceRawPost{clust_i}(trace_i,:,cell_i) - min(normTraceRawPost{clust_i}(trace_i,:,cell_i)); + % smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),speedSmooth); + %traceFlight{clust_i}(trace_i,:,cellCount) = traceFlight{clust_i}(trace_i,:, + disp('End of rec') + + end + smoothTraceRawFlight{clust_i}(trace_i,:,cellCount) = smooth(traceFlight{clust_i}(trace_i,:,cellCount),traceSmooth); + normTraceRawFlight{clust_i}(trace_i,:,cellCount) = zscore(smoothTraceRawFlight{clust_i}(trace_i,:,cellCount),0,smoothTrace); + normTraceRawFlight{clust_i}(trace_i,:,cellCount) = normTraceRawFlight{clust_i}(trace_i,:,cellCount) - min(normTraceRawFlight{clust_i}(trace_i,:,cellCount)); + smoothSpeedRawFlight{clust_i}(trace_i,:) = smooth(speedFlight{clust_i}(trace_i,:),smoothSpeed); + smoothTraceRawPre{clust_i}(trace_i,:,cellCount) = smooth(tracePre{clust_i}(trace_i,:,cellCount),traceSmooth); + normTraceRawPre{clust_i}(trace_i,:,cellCount) = zscore(smoothTraceRawPre{clust_i}(trace_i,:,cellCount),0,smoothTrace); + normTraceRawPre{clust_i}(trace_i,:,cellCount) = normTraceRawPre{clust_i}(trace_i,:,cellCount) - min(normTraceRawPre{clust_i}(trace_i,:,cellCount)); + smoothSpeedRawPre{clust_i}(trace_i,:) = smooth(speedPre{clust_i}(trace_i,:),smoothSpeed); + smoothTraceRawPost{clust_i}(trace_i,:,cellCount) = smooth(tracePost{clust_i}(trace_i,:,cellCount),traceSmooth); + normTraceRawPost{clust_i}(trace_i,:,cellCount) = zscore(smoothTraceRawPost{clust_i}(trace_i,:,cellCount),0,smoothTrace); + normTraceRawPost{clust_i}(trace_i,:,cellCount) = normTraceRawPost{clust_i}(trace_i,:,cellCount) - min(normTraceRawPost{clust_i}(trace_i,:,cellCount)); + smoothSpeedRawPost{clust_i}(trace_i,:) = smooth(speedPost{clust_i}(trace_i,:),smoothSpeed); + tracePreFlightPost{clust_i}(trace_i,:,cellCount) = cat(2,tracePre{clust_i}(trace_i,:,cellCount),traceFlight{clust_i}(trace_i,:,cellCount),tracePost{clust_i}(trace_i,:,cellCount)); + speedPreFlightPost{clust_i}(trace_i,:) = horzcat(speedPre{clust_i}(trace_i,:),speedFlight{clust_i}(trace_i,:),speedPost{clust_i}(trace_i,:)); + smoothTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount) = smooth(tracePreFlightPost{clust_i}(trace_i,:,cellCount),traceSmooth); + normTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount) = zscore(smoothTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount),0,smoothTrace); + normTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount) = normTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount) - min(normTraceRawPreFlightPost{clust_i}(trace_i,:,cellCount)); + smoothSpeedRawPreFlightPost{clust_i}(trace_i,:) = smooth(speedPreFlightPost{clust_i}(trace_i,:),smoothSpeed); + + + end + + %calculate the mean neural activity across all flights in a cluster for each cell + if length(traceFlight{clust_i}(:,1,cellCount)) <2 + meanTraceFlight{clust_i}(cellCount,:) = traceFlight{clust_i}(:,:,cellCount); + meanTracePre{clust_i}(cellCount,:) = tracePre{clust_i}(:,:,cellCount); + meanTracePost{clust_i}(cellCount,:) = tracePost{clust_i}(:,:,cellCount); + else + meanTraceFlight{clust_i}(cellCount,:) = mean(traceFlight{clust_i}(:,:,cellCount)); + meanTracePre{clust_i}(cellCount,:) = mean(tracePre{clust_i}(:,:,cellCount)); + meanTracePost{clust_i}(cellCount,:) = mean(tracePost{clust_i}(:,:,cellCount)); + + end + sdTraceFlight{clust_i}(cellCount,:) = std(traceFlight{clust_i}(:,:,cellCount)); + meanTraceOdd{clust_i}(cellCount,:) = mean(traceFlight{clust_i}(1:2:end,:,cellCount)); + meanTraceEven{clust_i}(cellCount,:) = mean(traceFlight{clust_i}(2:2:end,:,cellCount)); + meanSpeedFlight{clust_i} = mean(speedFlight{clust_i}); + meanSpeedPre{clust_i} = mean(speedPre{clust_i}); + meanSpeedPost{clust_i} = mean(speedPost{clust_i}); + meanTracePreFlightPost{clust_i}(cellCount,:) = mean(tracePreFlightPost{clust_i}(:,:,cellCount)); + sdTracePreFlightPost{clust_i}(cellCount,:) = std(tracePreFlightPost{clust_i}(:,:,cellCount)); + semTracePreFlightPost{clust_i}(cellCount,:) = std(tracePreFlightPost{clust_i}(:,:,cellCount))/sqrt(length(tracePreFlightPost{clust_i}(:,:,cellCount))); + meanSpeedPreFlightPost{clust_i} = mean(speedPreFlightPost{clust_i}); + + %smooth and zscore the neural data. subtract the min of the zscore so the + %min is 0 rather than mean 0 + normTraceFlight{clust_i}(cellCount,:) = zscore(smooth(meanTraceFlight{clust_i}(cellCount,:),traceSmooth)); + normTraceFlight{clust_i}(cellCount,:) = normTraceFlight{clust_i}(cellCount,:) - min(normTraceFlight{clust_i}(cellCount,:)); + smoothSpeedFlight{clust_i} = smooth(meanSpeedFlight{clust_i},smoothSpeed); + normTraceOdd{clust_i}(cellCount,:) = zscore(smooth(meanTraceOdd{clust_i}(cellCount,:),traceSmooth)); + normTraceOdd{clust_i}(cellCount,:) = normTraceOdd{clust_i}(cellCount,:) - min(normTraceOdd{clust_i}(cellCount,:)); + normTraceEven{clust_i}(cellCount,:) = zscore(smooth(meanTraceEven{clust_i}(cellCount,:),traceSmooth)); + normTraceEven{clust_i}(cellCount,:) = normTraceEven{clust_i}(cellCount,:) - min(normTraceEven{clust_i}(cellCount,:)); + normTracePre{clust_i}(cellCount,:) = zscore(smooth(meanTracePre{clust_i}(cellCount,:),traceSmooth)); + normTracePre{clust_i}(cellCount,:) = normTracePre{clust_i}(cellCount,:) - min(normTracePre{clust_i}(cellCount,:)); + smoothSpeedPre{clust_i} = smooth(meanSpeedPre{clust_i},smoothSpeed); + normTracePost{clust_i}(cellCount,:) = zscore(smooth(meanTracePost{clust_i}(cellCount,:),traceSmooth)); + normTracePost{clust_i}(cellCount,:) = normTracePost{clust_i}(cellCount,:) - min(normTracePost{clust_i}(cellCount,:)); + smoothSpeedPost{clust_i} = smooth(meanSpeedPost{clust_i},smoothSpeed); + %find time index of max peaks + [~,maxnormTraceFlight{clust_i}(cellCount,1)] = max(normTraceFlight{clust_i}(cellCount,:)); + [~,maxnormTracePre{clust_i}(cellCount,1)] = max(normTracePre{clust_i}(cellCount,:)); + [~,maxnormTracePost{clust_i}(cellCount,1)] = max(normTracePost{clust_i}(cellCount,:)); + [~,maxNormTraceOdd{clust_i}(cellCount,1)] = max(normTraceOdd{clust_i}(cellCount,:)); + cellCount = cellCount + 1; %add 1 to the cell index + end + + cellCount = cellCount -1; %subtract the last addition so the rest of the script uses the max Cells correctly + %sort each cell by the timing of its peak firing + [BFlight{clust_i},IFlight{clust_i}] = sort(maxnormTraceFlight{clust_i}); + [BPre{clust_i},IPre{clust_i}] = sort(maxnormTracePre{clust_i}); + [BPost{clust_i},IPost{clust_i}] = sort(maxnormTracePost{clust_i}); + if clust_i == 1 + [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{1}); %sort by cluster 1 + [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{1}); %sort by cluster 1 + [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{1}); %sort by cluster 1 + else + [B1Flight{clust_i},I1Flight{clust_i}] = sort(maxnormTraceFlight{2}); %sort by cluster 2 + [B1Pre{clust_i},I1Pre{clust_i}] = sort(maxnormTracePre{2}); %sort by cluster 2 + [B1Post{clust_i},I1Post{clust_i}] = sort(maxnormTracePost{2}); %sort by cluster 2 + end + [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTraceOdd{clust_i}); + %split dataset into even and odd for comparing 2 halves + % normTraceOdd{clust_i} = normTraceFlight{clust_i}(1:2:end,:); + % normTraceEven{clust_i} = normTraceFlight{clust_i}(2:2:end,:); + % %sort odd clusters in ascending order of the peak of the odds + % if length(normTraceOdd{clust_i}(:,1))>length(normTraceEven{clust_i}(:,1)) %if number of odd elements is greater than even + % [Bodd{clust_i},Iodd{clust_i}] = sort(maxNormTrace{clust_i}(1:2:end-1)); + % else + % [Bodd{clust_i},Iodd{clust_i}] = sort(maxnormTraceFlight{clust_i}(1:2:end)); + % end + + %concatenate all clusters together and then zscore to equalize the + %peaks across all trials + meanTraceFlightAll = [meanTraceFlightAll meanTraceFlight{clust_i}]; %concatenate all traces + meanTracePreAll = [meanTracePreAll meanTracePre{clust_i}]; %concatenate all traces + meanTracePostAll = [meanTracePostAll meanTracePost{clust_i}]; %concatenate all traces + meanTracePreFlightPostAll{clust_i} = [meanTracePre{clust_i} meanTraceFlight{clust_i} meanTracePost{clust_i}]; + + + end + + + %% this is to smooth, zscore, and sort the entire cell data by their preferred flight according to a homemade k-means (max dff across flights) + %zscore the full data set and subtract min to start at 0 + for cell_ii = 1:cellCount + normMeanTraceFlightAll(cell_ii,:) = zscore(smooth(meanTraceFlightAll(cell_ii,:),traceSmooth)); + normMeanTraceFlightAll(cell_ii,:) = normMeanTraceFlightAll(cell_ii,:) - min(normMeanTraceFlightAll(cell_ii,:)); + normMeanTracePreAll(cell_ii,:) = zscore(smooth(meanTracePreAll(cell_ii,:),traceSmooth)); + normMeanTracePreAll(cell_ii,:) = normMeanTracePreAll(cell_ii,:) - min(normMeanTracePreAll(cell_ii,:)); + normMeanTracePostAll(cell_ii,:) = zscore(smooth(meanTracePostAll(cell_ii,:),traceSmooth)); + normMeanTracePostAll(cell_ii,:) = normMeanTracePostAll(cell_ii,:) - min(normMeanTracePostAll(cell_ii,:)); + for clust_i = 1:nClusters + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = zscore(smooth(meanTracePreFlightPostAll{clust_i}(cell_ii,:),traceSmooth)); + normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) = normMeanTracePreFlightPostAll{clust_i}(cell_ii,:) - min(normMeanTracePreFlightPostAll{clust_i}(cell_ii,:)); + end + end + %split the data back into its clusters + traceFlightIndConcat = [1 length(normTraceFlight{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + tracePreIndConcat = [1 length(normTracePre{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + tracePostIndConcat = [1 length(normTracePost{1}(1,:))]; %initialize index variable to hold the indices for start/stop of each cluster + + %find the start and stop indices for 2nd through n cluster + for clust_ii = 2:nClusters + traceFlightIndConcat = vertcat(traceFlightIndConcat,[traceFlightIndConcat(clust_ii-1,2)+1 traceFlightIndConcat(clust_ii-1,2)+length(normTraceFlight{clust_ii}(1,:))]); + tracePreIndConcat = vertcat(tracePreIndConcat,[tracePreIndConcat(clust_ii-1,2)+1 tracePreIndConcat(clust_ii-1,2)+length(normTracePre{clust_ii}(1,:))]); + tracePostIndConcat = vertcat(tracePostIndConcat,[tracePostIndConcat(clust_ii-1,2)+1 tracePostIndConcat(clust_ii-1,2)+length(normTracePost{clust_ii}(1,:))]); + + end + %regroup by each flight cluster + for clust_iii = 1:nClusters + normTraceFlightAll{clust_iii} = normMeanTraceFlightAll(:,traceFlightIndConcat(clust_iii,1):traceFlightIndConcat(clust_iii,2)); + normTracePreAll{clust_iii} = normMeanTracePreAll(:,tracePreIndConcat(clust_iii,1):tracePreIndConcat(clust_iii,2)); + normTracePostAll{clust_iii} = normMeanTracePostAll(:,tracePostIndConcat(clust_iii,1):tracePostIndConcat(clust_iii,2)); + normTracePreClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,1:preFlightPadCalcium); + normTraceFlightClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))); + normTracePostClustAll{clust_iii} = normMeanTracePreFlightPostAll{clust_iii}(:,preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+1:preFlightPadCalcium+length(normTraceFlightAll{clust_iii}(1,:))+postFlightPadCalcium); + %find the order of the maximum for each cluster within the regrouping + for cell_iii = 1:cellCount%length(traceData(:,1)) + [~,maxNormFlightAll{clust_iii}(cell_iii,1)] = max(normTraceFlightAll{clust_iii}(cell_iii,:)); + [~,maxNormPreAll{clust_iii}(cell_iii,1)] = max(normTracePreAll{clust_iii}(cell_iii,:)); + [~,maxNormPostAll{clust_iii}(cell_iii,1)] = max(normTracePostAll{clust_iii}(cell_iii,:)); + [~,maxNormPreClustAll{clust_iii}(cell_iii,1)] = max(normTracePreClustAll{clust_iii}(cell_iii,:)); + [~,maxNormFlightClustAll{clust_iii}(cell_iii,1)] = max(normTraceFlightClustAll{clust_iii}(cell_iii,:)); + [~,maxNormPostClustAll{clust_iii}(cell_iii,1)] = max(normTracePostClustAll{clust_iii}(cell_iii,:)); + end + %sort each cell by the timing of its peak firing + [BnormFlightAll{clust_iii},InormFlightAll{clust_iii}] = sort(maxNormFlightAll{clust_iii}); + [BnormPreAll{clust_iii},InormPreAll{clust_iii}] = sort(maxNormPreAll{clust_iii}); + [BnormPostAll{clust_iii},InormPostAll{clust_iii}] = sort(maxNormPostAll{clust_iii}); + [BnormPreClustAll{clust_iii},InormPreClustAll{clust_iii}] = sort(maxNormPreClustAll{clust_iii}); + [BnormFlightClustAll{clust_iii},InormFlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{clust_iii}); + [BnormPostClustAll{clust_iii},InormPostClustAll{clust_iii}] = sort(maxNormPostClustAll{clust_iii}); + if clust_iii == 1 + [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{1}); %sort by cluster 1 + [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{1}); %sort by cluster 1 + [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{1}); %sort by cluster 1 + [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{1}); %sort by cluster 1 + [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{1}); %sort by cluster 1 + [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{1}); %sort by cluster 1 + else + [B1normPostAll{clust_iii},I1normPostAll{clust_iii}] = sort(maxNormPostAll{2}); %sort by cluster 2 + [B1normPreAll{clust_iii},I1normPreAll{clust_iii}] = sort(maxNormPreAll{2}); %sort by cluster 2 + [B1normFlightAll{clust_iii},I1normFlightAll{clust_iii}] = sort(maxNormFlightAll{2}); %sort by cluster 2 + [B1normPostClustAll{clust_iii},I1normPostClustAll{clust_iii}] = sort(maxNormPostClustAll{2}); %sort by cluster 2 + [B1normPreClustAll{clust_iii},I1normPreClustAll{clust_iii}] = sort(maxNormPreClustAll{2}); %sort by cluster 2 + [B1FlightClustAll{clust_iii},I1FlightClustAll{clust_iii}] = sort(maxNormFlightClustAll{2}); %sort by cluster 2 + end + + + + + end + + + %find max and sort based on the peaks of the cell across the whole + %timeseries + [~,maxAllFlight] = max(normMeanTraceFlightAll,[],2); + [~,maxAllPre] = max(normMeanTracePreAll,[],2); + [~,maxAllPost] = max(normMeanTracePostAll,[],2); + for clust_i = 1:nClusters + [~,maxAllPreFlightPost{clust_i}] = max(normMeanTracePreFlightPostAll{clust_iii},[],2); + end + + + %kPeaks = kmeans(maxAll,nClusters); %take k-means cluster of the peaks of each cell whole time + %sort based on each clustered peaks for flight, pre and post + rng(2); + for n = 1:size(maxAllFlight,1) + for ii = 1:nClusters + if maxAllFlight(n) >= traceFlightIndConcat(ii,1) & maxAllFlight(n) < traceFlightIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksFlight(:,n) = 1; + end + + end + end + for n = 1:size(maxAllPre,1) + for ii = 1:nClusters + if maxAllPre(n) >= tracePreIndConcat(ii,1) & maxAllPre(n) < tracePreIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksPre(:,n) = 1; + end + end + end + for n = 1:size(maxAllPost,1) + for ii = 1:nClusters + if maxAllPost(n) >= tracePostIndConcat(ii,1) & maxAllPost(n) < tracePostIndConcat(ii,2); %if the peak is within each cluster, sort it into that particular cluster + kPeaksPost(:,n) = 1; + end + end + end + for clust_i = 1:nClusters + for n = 1:size(maxAllPreFlightPost{clust_i},1) + if maxAllPreFlightPost{clust_i}(n) >= 1 & maxAllPreFlightPost{clust_i}(n) < (length(normTraceFlightAll{clust_iii}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1) %if the peak is within each cluster, sort it into that particular cluster + kPeaksPreFlightPost{clust_i}(:,n) = 1; + end + end + [BkPeaksPreFlightPost{clust_i},IkPeaksPreFlightPost{clust_i}] = sort(kPeaksPreFlightPost{clust_i}); + normMeanTraceSortPreFlightPost{clust_i} = normMeanTracePreFlightPostAll{clust_i}(IkPeaksPreFlightPost{clust_i},:); + end + + %sort the clusters according to their peak times + [BkPeaksFlight,IkPeaksFlight] = sort(kPeaksFlight); + normMeanTraceSortFlight = normMeanTraceFlightAll(IkPeaksFlight,:); + [BkPeaksPre,IkPeaksPre] = sort(kPeaksPre); + normMeanTraceSortPre = normMeanTracePreAll(IkPeaksPre,:); + [BkPeaksPost,IkPeaksPost] = sort(kPeaksPost); + normMeanTraceSortPost = normMeanTracePostAll(IkPeaksPost,:); + + %for each cluster, find the peaks of the cluster (aMat aka aTemp), tke the max + %(maxInd), and sort that max (aSort) from the cluster, add this to the + %normMeanTraceSort variable + for c = 1:nClusters + aMatFlight = find(BkPeaksFlight == c); + aTempFlight = normMeanTraceSortFlight(aMatFlight,:); + [~,maxIndFlight] = max(aTempFlight,[],2); + [BmaxFlight,ImaxFlight] = sort(maxIndFlight); + aSortFlight = aTempFlight(ImaxFlight,:); + normMeanTraceSortFlight(aMatFlight,:) = aSortFlight; + clear aMatFlight aTempFlight maxIndFlight ImaxFlight BaxFlight aSortFlight + aMatPre = find(BkPeaksPre == c); + aTempPre = normMeanTraceSortPre(aMatPre,:); + [~,maxIndPre] = max(aTempPre,[],2); + [BmaxPre,ImaxPre] = sort(maxIndPre); + aSortPre = aTempPre(ImaxPre,:); + normMeanTraceSortPre(aMatPre,:) = aSortPre; + clear aMatPre aTempPre maxIndPre ImaxPre BaxPre aSortPre + aMatPost = find(BkPeaksPost == c); + aTempPost = normMeanTraceSortPost(aMatPost,:); + [~,maxIndPost] = max(aTempPost,[],2); + [BmaxPost,ImaxPost] = sort(maxIndPost); + aSortPost = aTempPost(ImaxPost,:); + normMeanTraceSortPost(aMatPost,:) = aSortPost; + clear aMatPost aTempPost maxIndPost ImaxPost BaxPost aSortPost + aMatPreFlightPost = find(BkPeaksPreFlightPost{c} == 1); + aTempPreFlightPost = normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:); + [~,maxIndPreFlightPost] = max(aTempPreFlightPost,[],2); + [BmaxPreFlightPost,ImaxPreFlightPost] = sort(maxIndPreFlightPost); + aSortPreFlightPost = aTempPreFlightPost(ImaxPreFlightPost,:); + normMeanTraceSortPreFlightPost{c}(aMatPreFlightPost,:) = aSortPreFlightPost; + clear aMatPreFlightPost aTempPreFlightPost maxIndPreFlightPost ImaxPreFlightPost BaxPreFlightPost aSortPreFlightPost + + + end + %divide the normMeanTraceSort overall variable into the respective clusters + for c = 1:nClusters + normMeanTraceEachFlight{c} = normMeanTraceSortFlight(:,traceFlightIndConcat(c,1):traceFlightIndConcat(c,2)); + normMeanTraceEachPre{c} = normMeanTraceSortPre(:,tracePreIndConcat(c,1):tracePreIndConcat(c,2)); + normMeanTraceEachPost{c} = normMeanTraceSortPost(:,tracePostIndConcat(c,1):tracePostIndConcat(c,2)); + normMeanTraceEachPFlightP{c} = normMeanTraceSortPreFlightPost{c}(:,preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium); + normMeanTraceEachPreFP{c} = normMeanTraceSortPreFlightPost{c}(:,1:preFlightPadCalcium); + normMeanTraceEachPFPost{c} = normMeanTraceSortPreFlightPost{c}(:,length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+1:length(normTraceFlightAll{c}(1,:))+preFlightPadCalcium+postFlightPadCalcium+1); + + end + + %% save to snakeTrace variable + snakeTraceData.batName = batName; + snakeTraceData.dateSesh = dateSesh; + snakeTraceData.sessionType = sessionType; + snakeTraceData.dur = dur; + snakeTraceData.durSpeed = durSpeed; + snakeTraceData.medDur = medDur; + snakeTraceData.medDurSpeed = medDurSpeed; + snakeTraceData.BPre = BPre; + snakeTraceData.IPre = IPre; + snakeTraceData.BFlight = BFlight; + snakeTraceData.IFlight = IFlight; + snakeTraceData.BPost = BPost; + snakeTraceData.IPost = IPost; + snakeTraceData.Bodd = Bodd; + snakeTraceData.Iodd = Iodd; + snakeTraceData.B1Pre = B1Pre; + snakeTraceData.I1Pre = I1Pre; + snakeTraceData.B1Flight = B1Flight; + snakeTraceData.I1Flight = I1Flight; + snakeTraceData.B1Post = B1Post; + snakeTraceData.I1Post = I1Post; + snakeTraceData.InormFlightAll = InormFlightAll; + snakeTraceData.I1normFlightAll = I1normFlightAll; + snakeTraceData.IkPeaksPreFlightPost=IkPeaksPreFlightPost; + snakeTraceData.kPeaksPreFlightPost=kPeaksPreFlightPost; + snakeTraceData.maxAllPreFlightPost=maxAllPreFlightPost; + snakeTraceData.maxnormTracePre = maxnormTracePre; + snakeTraceData.maxnormTraceFlight = maxnormTraceFlight; + snakeTraceData.maxnormTracePost = maxnormTracePost;snakeTraceData.meanTracePre = meanTracePre; + snakeTraceData.meanTraceFlight = meanTraceFlight; + snakeTraceData.meanTracePost = meanTracePost; + snakeTraceData.meanSpeedPre = meanSpeedPre; + snakeTraceData.meanSpeedFlight = meanSpeedFlight; + snakeTraceData.meanSpeedPost = meanSpeedPost; + snakeTraceData.meanSpeedPreFlightPost = meanSpeedPreFlightPost; + snakeTraceData.meanTracePreFlightPost = meanTracePreFlightPost; + snakeTraceData.meanTracePreFlightPostAll=meanTracePreFlightPostAll; + snakeTraceData.meanTraceEven = meanTraceEven; + snakeTraceData.meanTraceOdd = meanTraceOdd; + snakeTraceData.nClusters = nClusters; + snakeTraceData.normTracePre = normTracePre; + snakeTraceData.normTraceFlight = normTraceFlight; + snakeTraceData.normTracePost = normTracePost; + snakeTraceData.normTraceEven = normTraceEven; + snakeTraceData.normTraceOdd = normTraceOdd; + snakeTraceData.normTraceFlightAll = normTraceFlightAll; + snakeTraceData.normTraceRawPre = normTraceRawPre; + snakeTraceData.normTraceRawFlight = normTraceRawFlight; + snakeTraceData.normTraceRawPost = normTraceRawPost; + snakeTraceData.normTraceRawPreFlightPost = normTraceRawPreFlightPost; + snakeTraceData.normMeanTraceSortPreFlightPost = normMeanTraceSortPreFlightPost; + snakeTraceData.normMeanTracePreFlightPostAll=normMeanTracePreFlightPostAll; + snakeTraceData.normMeanTraceEachPFlightP = normMeanTraceEachPFlightP; + snakeTraceData.normMeanTraceEachPreFP = normMeanTraceEachPreFP; + snakeTraceData.normMeanTraceEachPFPost = normMeanTraceEachPFPost; + snakeTraceData.normMeanTraceEachPre = normMeanTraceEachPre; + snakeTraceData.normMeanTraceSortPre = normMeanTraceSortPre; + snakeTraceData.normMeanTracePreAll = normMeanTracePreAll; + snakeTraceData.normMeanTraceEachFlight = normMeanTraceEachFlight; + snakeTraceData.normMeanTraceSortFlight = normMeanTraceSortFlight; + snakeTraceData.normMeanTraceFlightAll = normMeanTraceFlightAll; + snakeTraceData.normMeanTraceEachPost = normMeanTraceEachPost; + snakeTraceData.normMeanTraceSortPost = normMeanTraceSortPost; + snakeTraceData.normMeanTracePostAll = normMeanTracePostAll; + snakeTraceData.preFlightPadCalcium = preFlightPadCalcium; + snakeTraceData.postFlightPadCalcium = postFlightPadCalcium; + snakeTraceData.preFlightPadSpeed = preFlightPadSpeed; + snakeTraceData.postFlightPadSpeed = postFlightPadSpeed; + snakeTraceData.preFlightPad = preFlightPad; + snakeTraceData.postFlightPad = postFlightPad; + snakeTraceData.prePad = prePad; + snakeTraceData.postPad = postPad; + snakeTraceData.sdTracePreFlightPost = sdTracePreFlightPost; + snakeTraceData.semTracePreFlightPost = semTracePreFlightPost; + snakeTraceData.smoothTraceRawPreFlightPost = smoothTraceRawPreFlightPost; + snakeTraceData.smoothSpeedPre = smoothSpeedPre; + snakeTraceData.smoothSpeedFlight = smoothSpeedFlight; + snakeTraceData.smoothSpeedPost = smoothSpeedPost; + snakeTraceData.smoothSpeedRawPre = smoothSpeedRawPre; + snakeTraceData.smoothSpeedRawFlight = smoothSpeedRawFlight; + snakeTraceData.smoothSpeedRawPost = smoothSpeedRawPost; + snakeTraceData.smoothTraceRawPre = smoothTraceRawPre; + snakeTraceData.smoothTraceRawFlight = smoothTraceRawFlight; + snakeTraceData.smoothTraceRawPost = smoothTraceRawPost; + snakeTraceData.smoothSpeedRawPreFlightPost = smoothSpeedRawPreFlightPost; + snakeTraceData.speedPreFlightPost = speedPreFlightPost; + snakeTraceData.traceFlightIndConcat = traceFlightIndConcat; + snakeTraceData.tracePreIndConcat = tracePreIndConcat; + snakeTraceData.tracePostIndConcat = tracePostIndConcat; + snakeTraceData.traceFlightIdx = traceFlightIdx; + snakeTraceData.tracePre = tracePre; + snakeTraceData.traceFlight = traceFlight; + snakeTraceData.tracePost = tracePost; + snakeTraceData.tracePreFlightPost = tracePreFlightPost; + if data_i ==1 + snakeTrace_cRaw = snakeTraceData; + elseif data_i == 2 + snakeTrace_c = snakeTraceData; + elseif data_i == 3 + snakeTrace_s = snakeTraceData; + end +end +if loadFlag ==1 && saveFlag == 1 + snakeTrace_c.label = label; + snakeTrace_cRaw.label = label; + snakeTrace_s.label = label; + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_cRaw.mat'],'snakeTrace_cRaw'); + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_c.mat'],'snakeTrace_c'); + save([pwd '/' analysis_Folder '/' label '_snakeTraceData_s.mat'],'snakeTrace_s'); +elseif loadFlag == 0 && saveFlag ==1 + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_cRaw.mat'],'snakeTrace_cRaw'); + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_c.mat'],'snakeTrace_c'); + save([pwd '/' batName '_' dateSesh '_' sessionType '_snakeTraceData_s.mat'],'snakeTrace_s'); +end + +%snakeTrace.normMeanTraceAllSmooth = normMeanTraceAllSmooth; diff --git a/snakePlot/ImBat_snakeData_wrapperUpdate.m b/snakePlot/ImBat_snakeData_wrapperUpdate.m new file mode 100644 index 0000000..2b45d3f --- /dev/null +++ b/snakePlot/ImBat_snakeData_wrapperUpdate.m @@ -0,0 +1,76 @@ +function ImBat_snakeData_wrapperUpdate +plotFlag = 0; %plot the snakeData too? +saveFlag = 1; %save data? +stableFlag = 0; %do snakeData for only stable ROIs? + +g = dir('G*'); +z = dir('Z*'); +dirTop = vertcat(g,z); %find all folders in top quality directory + +%for each bat/session +for sesh_i = 1:length(dirTop) + + %get meta info for each bat/day + cd([dirTop(sesh_i).name filesep 'extracted']); + dirFly = dir('*fly*extraction*'); + batName = dirFly(1).name(1:3); + dateSesh = dirFly(1).name(5:10); + sessionType = dirFly(1).name(12:16); + fileName = [batName '_' dateSesh '_' sessionType]; + %load cellData, flightpaths,alignment files + cd(dirFly(1).name); + dirAnal = dir('analysis*'); + dirFP = dir([dirAnal(end).folder filesep dirAnal(end).name filesep '*flightPaths.mat']); + load([dirFP.folder filesep dirFP.name]); + dirProc = dir('processed*'); + dirCD = dir([dirProc(end).folder filesep dirProc(end).name filesep 'results.mat']); + dirA = dir([dirProc(end).folder filesep dirProc(end).name filesep 'Alignment.mat']); + cellData = load([dirCD.folder filesep dirCD.name]); + alignment = load([dirA.folder filesep dirA.name]); + + if stableFlag == 0 + [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData(cellData,flightPaths,alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType); + else + [snakeTrace_cRaw,snakeTrace_c,snakeTrace_s] = ImBat_snakeData_manualStable(cellData,flightPaths,alignment,'batname',batName,'datesesh',dateSesh,'sessiontype',sessionType,'galdate',sesh_i); + end + %add the 3 data sets to snakeTrace + snakeTrace.cRaw = snakeTrace_cRaw; + snakeTrace.c = snakeTrace_c; + snakeTrace.s = snakeTrace_s; + if plotFlag == 1 + [snakeTrace_plots] = ImBat_plotSnake(snakeTrace_cRaw); + if saveFlag == 1 + if ~exist([dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots']) + mkdir([dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots']); + end + saveas(snakeTrace_plots.snakePlot_clust, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clust.svg']); + saveas(snakeTrace_plots.snakePlot_clustOddEven, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustOddEven.svg']); + saveas(snakeTrace_plots.snakePlot_clustBy1, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustBy1.svg']); + saveas(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_prefEachPrePostFlight.svg']); + saveas(snakeTrace_plots.snakePlot_clustPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustPrePostFlight.svg']); + saveas(snakeTrace_plots.snakePlot_clust, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustAll.tif']); + saveas(snakeTrace_plots.snakePlot_clustOddEven, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustOddEven.tif']); + saveas(snakeTrace_plots.snakePlot_clustBy1, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustBy1.tif']); + saveas(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_prefEachPrePostFlight.tif']); + saveas(snakeTrace_plots.snakePlot_clustPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustPrePostFlight.tif']); + saveas(snakeTrace_plots.snakePlot_prefAll, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_prefAll.tif']); + saveas(snakeTrace_plots.snakePlot_prefAll, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_prefAll.svg']); + saveas(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustBy1PrePostFlight.tif']); + saveas(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustBy1PrePostFlight.svg']); + savefig(snakeTrace_plots.snakePlot_clust, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustAll.fig']); + savefig(snakeTrace_plots.snakePlot_clustOddEven, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustOddEven.fig']); + savefig(snakeTrace_plots.snakePlot_clustBy1, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_clustBy1.fig']); + savefig(snakeTrace_plots.snakePlot_clustPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustPrePostFlight.fig']); + savefig(snakeTrace_plots.snakePlot_prefEachPrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_prefEachPrePostFlight.fig']); + savefig(snakeTrace_plots.snakePlot_prefAll, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlots_prefAll.fig']); + savefig(snakeTrace_plots.snakePlot_clustBy1PrePostFlight, [dirAnal(end).folder filesep dirAnal(end).name filesep 'snakePlots' filesep fileName '_snakePlot_clustBy1PrePostFlight.fig']); + end + end + if saveFlag == 1 && stableFlag == 1 + save([dirAnal(end).folder filesep dirAnal(end).name filesep fileName '_snakePlotData_stable.mat'],'snakeTrace'); + elseif saveFlag == 1 && stableFlag == 0 + save([dirAnal(end).folder filesep dirAnal(end).name filesep fileName '_snakePlotData.mat'],'snakeTrace'); + end + cd(dirTop(sesh_i).folder); + close all; +end \ No newline at end of file