% ReadGoogleStates.m
%
%  Reads U.S. states from the Google Covid-19 Activity Tracker data from the
%  main GlobalMobilityReport.mat file 


clear all; close all;
diarychad('ReadGoogleStates');

load GlobalMobilityReport
G=GlobalMobilityReport;
summary(G)
varnames=fieldnames(summary(G))
indx=find(startsWith(G.iso_3166_2_code,'US-'));
G=G(indx,:);

% Find the dates of the data
GoogleDates=datetime(G.date);
T=find(datenum(GoogleDates)==datenum(max(GoogleDates)));
T=T(1);
GoogleDates=GoogleDates(1:T);
NumStates=length(G.date)/T


% Restructure each variables as a matrix with dimension: NumYears x NumCountries
for i=1:length(varnames);
  eval([varnames{i} '=reshape(G.' varnames{i} ',T,NumStates);']);
end;

% Assign names and codes to NumCountries x 1 vectors
StateNames=sub_region_1(1,:)';
StateCodes=iso_3166_2_code(1,:)';
for i=1:NumStates;
  StateCodes{i}=StateCodes{i}(4:5);
end;

% Create three-letter codes that point to the appropriate column for
% each country. E.g. gUS=1 and gCA=6, where the g stands for Google
for i=1:length(StateCodes);
  eval(['s' StateCodes{i} '=i;']);
end;

% Compute monthly averages of the Google Activity Tracker data
for m=2:9; % Months: February to September
  indx=find(GoogleDates.Month==m);
  retail_and_rec(m,:)=mean(retail_and_recreation_percent_change_from_baseline(indx,:));
  grocery(m,:)=mean(grocery_and_pharmacy_percent_change_from_baseline(indx,:));
  parks(m,:)=mean(parks_percent_change_from_baseline(indx,:));
  transit(m,:)=mean(transit_stations_percent_change_from_baseline(indx,:));
  workplace(m,:)=mean(workplaces_percent_change_from_baseline(indx,:));
  residential(m,:)=mean(residential_percent_change_from_baseline(indx,:));
end;

% Average of retail_and_recreation and workplace activity
GoogleStateActivity=.5*(retail_and_rec+workplace);

clear i m indx T G;
StateDates=GoogleDates;
save GoogleStateData;

disp ' '; disp ' ';
disp 'GoogleStateActivity measure:'
disp ' -- average of the Retail_and_Recreation and Workplace variables'
tle='Jan Feb Mar Apr May Jun Jul Aug Sep';
cshow(StateCodes,GoogleStateActivity','%8.1f',tle);

diary off;


