%% step 2 get all errors for 60 rows

close all
clear all
fTable= readtable('T6020231201CosSimilarity500.csv');

index=(fTable.facing_direction==135);
fTable=fTable(index,:);

proj39=proj39collection;
%get familarity scores for viewing and target buildings for independent and self groups
fTable.continuous_unfam_fam=fTable.continuous_unfam_fam-1;
fTable.continuous_unfam_fam_inside=fTable.continuous_unfam_fam_inside-1;
fTable.continuous_unfam_fam_location=fTable.continuous_unfam_fam_location-1;
%self
selfenvrionmentFamilarity=table();
selfenvrionmentFamilarity.participant_number=fTable.participant_number;
selfenvrionmentFamilarity.score=fTable.envrionmentFamilarity;
selfenvrionmentFamilarity.building=fTable.envrionment_building;

selftargetFamilarity=table();
selftargetFamilarity.participant_number=fTable.participant_number;
selftargetFamilarity.score=fTable.targetFamilarity;
selftargetFamilarity.building=fTable.target_building;

unicateM={'building','participant_number'};
%'continuous_unfam_fam' is from independent group about environment
%building (1-5); 'envrionmentFamilarity' is from participants (0-4)
varNames={'score'};
T12selfenvrionmentFamilarity=proj39.pilotTable(selfenvrionmentFamilarity, unicateM, varNames,'mean');

T12selftargetFamilarity=proj39.pilotTable(selftargetFamilarity, unicateM, varNames,'mean');

newvarNames={{'BuInside','Bu','CCInside','CC','CaInside','Ca','HuInside','Hu','PeInside','Pe','RuInside','Ru'}};
T12AselfenvrionmentFamilarity=proj39.reshapetoRepeated(T12selfenvrionmentFamilarity,{'score'},12,newvarNames);
T12AselfenvrionmentFamilarity.building=[];
T12AselfenvrionmentFamilarity.score=[];
T12AselfenvrionmentFamilarity.group=repmat({'self'},size(T12AselfenvrionmentFamilarity(:,1)));%self=0 independent=1

newvarNames={{'Cab','Ed','Li','Su','To'}};
T12AselftargetFamilarity=proj39.reshapetoRepeated(T12selftargetFamilarity,{'score'},5,newvarNames);
T12AselftargetFamilarity.building=[];
T12AselftargetFamilarity.score=[];
T12AselftargetFamilarity.group=repmat({'self'},size(T12AselftargetFamilarity(:,1)));

independentFamilarity=readtable('familarity in Exp 2.csv');

independentFamilarity = renamevars(independentFamilarity,["Hub_out_","Hub_in_","CCIS_out_","CCIS_in_","Cab_out_","Cab_in_","Sub_out_","Sub_in_","Tory_out_","Tory_in_","Butt_out_","Butt_in_","Cam_out_","Cam_in_","Edu_out_","Edu_in_","Lister_out_","Lister_in_","Ruth_out_","Ruth_in_","Pemb_out_","Pemb_in_"], ...
                 ["Hu","HuInside","CC","CCInside","Cab","CabInside","Su","SuInside","To","ToInside","Bu","BuInside","Ca","CaInside","Ed","EdInside","Li","LiInside","Ru","RuInside","Pe","PeInside"]);
independentFamilarity =independentFamilarity(:,:)-1;
independentFamilarity.participant_number=independentFamilarity.participant_number+1;

%VarNames = Daten2.Properties.VariableNames;
independentenvrionmentFamilarity=independentFamilarity(:,independentFamilarity.Properties.VariableNames(["participant_number","BuInside","Bu","CCInside","CC","CaInside","Ca","HuInside","Hu","PeInside","Pe","RuInside","Ru"])); %,"CAB","CABInside","SUB","SUBInside","To","ToInside","Ca","CamInside","Ed","EdInside","Li","Liinside"
independentenvrionmentFamilarity.group=repmat({'Independent'},size(independentenvrionmentFamilarity(:,1)));
independenttargetFamilarity=independentFamilarity(:,independentFamilarity.Properties.VariableNames(["participant_number","Cab","Ed","Su","To","Li"])); %,"CAB","CABInside","SUB","SUBInside","To","ToInside","Ca","CamInside","Ed","EdInside","Li","Liinside"
independenttargetFamilarity.group=repmat({'Independent'},size(independenttargetFamilarity(:,1)));


envrionmentFamilarity=[independentenvrionmentFamilarity;T12AselfenvrionmentFamilarity];
targetFamilarity=[independenttargetFamilarity;T12AselftargetFamilarity];
writetable(envrionmentFamilarity,'envrionmentFamilarity.csv');
writetable(targetFamilarity,'targetFamilarity.csv');

%%
for i=1:size(fTable(:,1))
    %this calucate the bearing of target relative to pPrime and
    %hPrime, and the angular distance between this bearing and participants
    %pointing direction. So this angular error reflects the error after
    %removing the heading and position estimate errors
    
    bearing2estimatedPositionHeading(i) = proj39.getbearingA ([fTable.positionprimeX(i),fTable.positionprimeY(i)], [fTable.TargetX(i),0,fTable.TargetY(i)],fTable.headingprime(i)); %refer to the function of getbearingA
    %bearing(j) = getbearingA (p, target,heading); %refer to the function of getbearingA
    
    %we also need to calcuate the angular position error relative to each
    %target building

    positionAngularError(i) = proj39.getbearingbetween ([fTable.TargetX(i)-fTable.positionprimeX(i),0,fTable.TargetY(i)-fTable.positionprimeY(i)],...
        [fTable.TargetX(i)-fTable.positionX(i),0,fTable.TargetY(i)-fTable.positionY(i)]); %refer to the function of getbearingA
end
    
fTable.bearing2estimatedPositionHeading=bearing2estimatedPositionHeading';
fTable.PointingErrorRemovingPositionHeadingErrors= proj39.convertangleto180(fTable.pointing_angle-fTable.bearing2estimatedPositionHeading);  %angular error reflects the error after removing the heading and position estimate errors
%fTable.PointingErrorRemovingPositionHeadingErrors=PointingErrorRemovingPositionHeadingErrors;
fTable.absPointingErrorRemovingPositionHeadingErrors= abs(fTable.PointingErrorRemovingPositionHeadingErrors); 
%fTable.absPointingErrorRemovingPositionHeadingErrors=absPointingErrorRemovingPositionHeadingErrors;

fTable.headingError=proj39.convertangleto180(fTable.headingprime-fTable.facing_direction);
    %headingError=convertangleto180(headingError);

%fTable.headingError= headingError;
fTable.absheadingError=abs(fTable.headingError);

    % correctX=fTable.positionX;
    % correctY=fTable.positionY;
    % xprime=fTable.positionprimeX;
    % yprime=fTable.positionprimeY;
fTable.distanceError= sqrt((fTable.positionprimeX-fTable.positionX).*(fTable.positionprimeX-fTable.positionX)+(fTable.positionprimeY-fTable.positionY).*(fTable.positionprimeY-fTable.positionY));
fTable.positionAngularError=proj39.convertangleto180(positionAngularError');
fTable.abspositionAngularError=abs(fTable.positionAngularError);

fTable.pointingError=proj39.convertangleto180(fTable.pointing_angle-fTable.correct_angle);
%fTable.pointingError=pointingError;
fTable.predictPointingError=proj39.convertangleto180(fTable.positionAngularError-fTable.headingError+fTable.PointingErrorRemovingPositionHeadingErrors);
fTable.predictPointingErrorWithMotionError=proj39.convertangleto180(fTable.positionAngularError-fTable.headingError);
fTable.abspredictPointingErrorWithMotionError=abs(fTable.predictPointingErrorWithMotionError)

fTable.predictabsPointingError=sqrt(fTable.abspredictPointingErrorWithMotionError.^2+fTable.absPointingErrorRemovingPositionHeadingErrors.^2);

proj39.scatterPlotAngle(fTable.predictPointingError,fTable.pointingError);

proj39.scatterPlotAngle(fTable.predictPointingErrorWithMotionError,fTable.pointingError);

proj39.scatterPlotAngle(fTable.predictabsPointingError,fTable.abs_pointerror);

%% create T1
index=(fTable.participant_number~=0) %& fTable.participant_number~=33);
fTable=fTable(index,:);

Exist_Column = strcmp('responseRT', fTable.Properties.VariableNames)
if sum(Exist_Column)
    fTable = renamevars(fTable, ["responseRT"], ["RT"]); 
end

unicateM={'participant_number'};
%'continuous_unfam_fam' is from independent group about environment
%building (1-5); 'envrionmentFamilarity' is from participants (0-4)
varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam_inside','continuous_unfam_fam_location','envrionmentFamilarity','targetFamilarity','campusExpYears','campusExpHoursPerWeek','STEM','overall_familarity','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError'};
T1=proj39.pilotTable(fTable, unicateM, varNames,'mean');

T1.campusExpYears1=4-T1.campusExpYears;
writetable(T1,'T1_20240208Cos1000.csv');

%% we need to calcuate the similarity between the mental map of indoor environment and outdoor environment
%
%create table with 12 row per subject, inside/indoor_outdoor=2 by environnment (6)
%close all
%clear all
unicateM={'indoor_outdoor','Enviornmentname','participant_number'};
varNames={'positionX', 'positionY', 'positionprimeX', 'positionprimeY', 'facing_direction', 'headingprime','MRT'};%,'rsqprime2c12'};
T=proj39.pilotTable(fTable, unicateM, varNames,'mean');
%

% varNames={'positionAngularError','headingError','pointingError','PointingErrorRemovingPositionHeadingErrors'};
% T1=pilotTable(fTable, unicateM, varNames, 'circMean');

%T=join(T,T1);h
%T12PositionInfo=T(T.participant_number~=21,:);
T12PositionInfo=T;%(T.rsqprime2c12>0.6,:)%(T.participant_number~=21,:);
writetable(T12PositionInfo,'T12PositionInfo20240113.csv');

unicateM=table(T12PositionInfo.indoor_outdoor,T12PositionInfo.Enviornmentname);
[C,ia,ic] = unique(unicateM);
%B=[];
tprime2c=table();
for i=1:length(ia) %((ia) stores unique categoray)
    index=ic==i;%get category i
    key=[C.Var2{i}(1:2),num2str(C.Var1(i))];
    key = erase(key," ");
    %key=key(1:5);
    Pcorrect.(key)=[T12PositionInfo(index,:).('positionX'), T12PositionInfo(index,:).('positionY')];
    Pprime.(key)=[T12PositionInfo(index,:).('positionprimeX'), T12PositionInfo(index,:).('positionprimeY')];

    %P.{[]}
    %B.=[B;mean(Oresp(index,:))];       
end

figure 
fields=fieldnames(Pprime);
c=jet(length(fields)/2);
c=[c;c];
% col=zeros(1,3);
%p=colormap;
%c=p(int16(256/length(fields))*i+1,:);
%r = randi([1 256],12,1)
for i=1:length(fields)  
    %figure
    %c=p(int16(256/length(fields))*i+1,:)
    %p(int16(256/length(fields))*i+1,:);
     %a=find(AxUni==Angle1(i));
    %                 %a=round(Angle1(i)/max(Angle1)*256);
    %c=[p(1,:);p(2,:)];
    %plot([x1(i),x2(i)],[y1(i),y2(i)]);               
    % plot(x1(i),y1(i),'o');
    % plot(x2(i),y2(i),'x');
    %plot([x1(i),x2(i)],[y1(i),y2(i)]);
    %colororder(c);
   
    %c={'g','r','b','k'};
    thiscolor=c(i,:);
    P1=Pcorrect.(fields{i});
    P2=Pprime.(fields{i});
    %scatter(P2(:,1),P2(:,2),['.',c{1}]);
    %scatter(P2(:,1),P2(:,2),'.','ColorVariable',c{1})
    %plot(P2(:,1),P2(:,2),'.','Color',c{1})
    plot(P2(:,1),P2(:,2),'.','Color',thiscolor)
    hold on
    %ellipsePandE20210716(1, 0.95,P2,['+',c{1}])
    output.(fields{i})=ellipsePandE20231125(2, 0.95,P2,'+',thiscolor);
    hold on
    plot(P1(1,1),P1(1,2),'o','Color',thiscolor);
    hold on
    text(P1(1,1),P1(1,2),fields{i},'Color','b');
    Mu=output.(fields{i}).Mu;
    text(Mu(1),Mu(1,2),[fields{i},char(39)],'Color','k');
    %plot(P1(1,1),P1(1,2),['o',c{1}]);
    
    %do hythothesis test between prime and correct positions using
    %HotelingT
    %M=[P2,P1];

end

fTablebuildingCoorinate=readtable('buildingCoorinateCameronoutside.csv');

tTarget=fTablebuildingCoorinate(end-4:end,:);
for i=1:5 %((ia) stores unique categoray)
    %index=ic==i;%get category i
    %key=[C.Var2{i}(1:2),num2str(C.Var1(i))];
    %key = erase(key," ");
    %key=key(1:5);
    %Pcorrect.(key)=[T12PositionInfo(index,:).('positionX'), T12PositionInfo(index,:).('positionY')];
    %Pprime.(key)=[T12PositionInfo(index,:).('positionprimeX'), T12PositionInfo(index,:).('positionprimeY')];
    %P.{[]}
    %B.=[B;mean(Oresp(index,:))];
    x=tTarget(i,:).X;
    y=tTarget(i,:).Y;
    name=tTarget(i,:).location;
   % name=name(1:3);
    plot(x,y,'*','Color','k');
    text(x,y,name);
end



%% below are analyses using bidimensional regression
unicateM={'indoor_outdoor','Enviornmentname'};
varNames={'positionX', 'positionY', 'positionprimeX', 'positionprimeY', 'facing_direction', 'headingprime'};
T12mean=proj39.pilotTable(T12PositionInfo, unicateM, varNames,'mean');
indexIn=T12mean.indoor_outdoor==0;
T6inmean=T12mean(indexIn,:);
T6outmean=T12mean(~indexIn,:);
tinprimemean2outprimemean=bi_regressV3Table(T6inmean.positionprimeX,T6inmean.positionprimeY,T6outmean.positionprimeX,T6outmean.positionprimeY,...
        {'dinprime2outprime','angleinprime2outprime','scaleinprime2outprime','rsqinprime2outprime'})
tinprimemean2outc=bi_regressV3Table(T6inmean.positionprimeX,T6inmean.positionprimeY,T6outmean.positionX,T6outmean.positionY,...
        {'dinprime2outc','angleinprime2outc','scaleinprime2outc','rsqinprime2outc'})



unicateM=table(T12PositionInfo.participant_number);
[C,ia,ic] = unique(unicateM);
%B=[];
T1bdregression=table();
T6vin2out=table();
T6vc2prime=table();
for i=1:length(ia) %((ia) stores unique categoray)
    index=ic==i;%get category i
    T12oneparicipant=T12PositionInfo(index,:);
    indexIn=T12oneparicipant.indoor_outdoor==0;
    T6in=T12oneparicipant(indexIn,:);
    T6out=T12oneparicipant(~indexIn,:);

    Tvin2outc=TvectorTwolocation ([T6in.positionX,T6in.positionY],[T6out.positionX,T6out.positionY],{'vin2outcX','vin2outcY'});
    Tvin2outprime=TvectorTwolocation ([T6in.positionprimeX,T6in.positionprimeY],[T6out.positionprimeX,T6out.positionprimeY],{'vin2outprimeX','vin2outprimeY'});

    Tvinc2inprime=TvectorTwolocation ([T6in.positionX,T6in.positionY],[T6in.positionprimeX,T6in.positionprimeY],{'vinc2inprimeX','vinc2inprimeY'});
    Tvoutc2outprime=TvectorTwolocation ([T6out.positionX,T6out.positionY],[T6out.positionprimeX,T6out.positionprimeY],{'voutc2outprimeX','voutc2outprimeY'});
    

    tprime2c12=bi_regressV3Table( T12oneparicipant.positionprimeX, T12oneparicipant.positionprimeY, T12oneparicipant.positionX, T12oneparicipant.positionY,...
        {'dprime2c12','angleprime2c12','scaleprime2c12','rsqprime2c12'});
    % X=T6in.positionX;
    % Y=T6in.positionY;
    % A=T6out.positionX;
    % B=T6out.positionY;
    X1=0;
    Y1=0;
    % res=bi_regressV3(T6in.positionX,T6in.positionY,T6out.positionX,T6out.positionY,X1,Y1);
    % tinc2outc=array2table(res.regression(3:end),"VariableNames",{'dxinc2outc','dyinc2outc','angleinc2outc','scaleinc2outc','rsqinc2outc'});
    tinc2outc=bi_regressV3Table(T6in.positionX,T6in.positionY,T6out.positionX,T6out.positionY,...
        {'dinc2outc','angleinc2outc','scaleinc2outc','rsqinc2outc'})
    %Toneparticipant=table();
    tinprime2outprime=bi_regressV3Table(T6in.positionprimeX,T6in.positionprimeY,T6out.positionprimeX,T6out.positionprimeY,...
        {'dinprime2outprime','angleinprime2outprime','scaleinprime2outprime','rsqinprime2outprime'})
    %toutc2outprime=bi_regressV3Table(T6out.positionX,T6out.positionY,T6out.positionprimeX,T6out.positionprimeY,{'doutc2outprime','angleoutc2outprime','scaleoutc2outprime','rsqoutc2outprime'})
    toutprime2outc=bi_regressV3Table(T6out.positionprimeX,T6out.positionprimeY,T6out.positionX,T6out.positionY,...
        {'doutprime2outc','angleoutprime2outc','scaleoutprime2outc','rsqoutprime2outc'})
    tinprime2inc=bi_regressV3Table(T6in.positionprimeX,T6in.positionprimeY,T6in.positionX,T6in.positionY, ...
        {'dinprime2inc','angleinprime2inc','scaleinprime2inc','rsqinprime2inc'})

    tinprime2inprimemean=bi_regressV3Table(T6in.positionprimeX,T6in.positionprimeY,T6inmean.positionX,T6inmean.positionY, ...
        {'dinprime2inprimemean','angleinprime2inprimemean','scaleinprime2inprimemean','rsqinprime2inprimemean'})

    toutprime2outprimemean=bi_regressV3Table(T6out.positionprimeX,T6out.positionprimeY,T6outmean.positionX,T6outmean.positionY, ...
        {'doutprime2outprimemean','angleoutprime2outprimemean','scaleoutprime2outprimemean','rsqoutprime2outprimemean'})

     tinprime2outprimemean=bi_regressV3Table(T6in.positionprimeX,T6in.positionprimeY,T6outmean.positionX,T6outmean.positionY, ...
        {'dinprime2outprimemean','angleinprime2outprimemean','scaleinprime2outprimemean','rsqinprime2outprimemean'})
    %T6inmean


    TparticipantNo=T6in(1, T.Properties.VariableNames('participant_number'));
    Toneparticipant=[TparticipantNo, tprime2c12,tinc2outc, tinprime2outprime,tinprime2inc,toutprime2outc,tinprime2inprimemean,toutprime2outprimemean,tinprime2outprimemean];
    T1bdregression=[T1bdregression;Toneparticipant];

    Toneparticipant6vin2out=[T6in(:, T.Properties.VariableNames({'Enviornmentname','participant_number'})),Tvin2outc,Tvin2outprime];
    T6vin2out=[T6vin2out;Toneparticipant6vin2out];
   
    Toneparticipant6vc2prime=[T6in(:, T.Properties.VariableNames({'Enviornmentname','participant_number'})),Tvinc2inprime,Tvoutc2outprime];
    T6vc2prime=[T6vc2prime;Toneparticipant6vc2prime];

    % 
    % key=[C.Var2{i}(1:2),num2str(C.Var1(i))];
    % key = erase(key," ");
    % %key=key(1:5);
    % Pcorrect.(key)=[T12PositionInfo(index,:).('positionX'), T12PositionInfo(index,:).('positionY')];
    % Pprime.(key)=[T12PositionInfo(index,:).('positionprimeX'), T12PositionInfo(index,:).('positionprimeY')];
    % %P.{[]}
    % %B.=[B;mean(Oresp(index,:))];       


    %tprime2c=[T12oneparicipant(1,  T12oneparicipant.Properties.VariableNames({participant_number'})),tprime2conepartipant];

end

tinprimemean2outc
tinprimemean2outprimemean
inc2outc=[mean(T1bdregression.dinc2outc),mean(T1bdregression.angleinc2outc),mean(T1bdregression.scaleinc2outc),mean(T1bdregression.rsqinc2outc)]
inprime2outprime=[mean(T1bdregression.dinprime2outprime),mean(T1bdregression.angleinprime2outprime),mean(T1bdregression.scaleinprime2outprime),mean(T1bdregression.rsqinprime2outprime)]
inprime2inc=[mean(T1bdregression.dinprime2inc),mean(T1bdregression.angleinprime2inc),mean(T1bdregression.scaleinprime2inc),mean(T1bdregression.rsqinprime2inc)]
outprime2outc=[mean(T1bdregression.doutprime2outc),mean(T1bdregression.angleoutprime2outc),mean(T1bdregression.scaleoutprime2outc),mean(T1bdregression.rsqoutprime2outc)]
inprime2inprimemean=[mean(T1bdregression.dinprime2inprimemean),mean(T1bdregression.angleinprime2inprimemean),mean(T1bdregression.scaleinprime2inprimemean),mean(T1bdregression.rsqinprime2inprimemean)]
outprime2outprimemean=[mean(T1bdregression.doutprime2outprimemean),mean(T1bdregression.angleoutprime2outprimemean),mean(T1bdregression.scaleoutprime2outprimemean),mean(T1bdregression.rsqoutprime2outprimemean)]
inprime2outprimemean=[mean(T1bdregression.dinprime2outprimemean),mean(T1bdregression.angleinprime2outprimemean),mean(T1bdregression.scaleinprime2outprimemean),mean(T1bdregression.rsqinprime2outprimemean)]

%writetable(T1bdregression,'T1bdregression.csv');

writetable(T6vin2out,'T6vin2out20240113.csv');
writetable(T6vc2prime,'T6vc2prime20240113.csv');
%T6vc2prime
%T2=readtable('T220231122Cos1000.csv');
%%
%fTable= readtable('T6020231122CosSimilarity1000.csv');
%fTable= readtable('T602023112leastSquarederror1000.csv');
%fTable= convertvars(fTable,{'indoor_outdoor'},'categorical');
index=(fTable.participant_number~=0) %& fTable.participant_number~=33);
fTable=fTable(index,:);
%  create table with 2 row per subject, inside/indoor_outdoor=2
unicateM={'indoor_outdoor','participant_number'};
%varNames={'RT','abs_pointerror','PTT','MRT','overall_familarity','continuous_unfam_fam','euclidian_distance','campus_experience','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError'};
varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam_inside','continuous_unfam_fam_location','envrionmentFamilarity','targetFamilarity','campusExpYears','campusExpHoursPerWeek','STEM','overall_familarity','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError'};


T=proj39.pilotTable(fTable, unicateM, varNames,'mean');
%[mdregression2,tb1]=myregression (T, {'abs_pointerror','PTT','indoor_outdoor','MRT','campus_experience','envrionmentFamilarity'});
T2=T;
T2=[T2,array2table([T1bdregression.rsqinprime2inc;T1bdregression.rsqoutprime2outc],"VariableNames",{'rsqprimetoc'})];
writetable(T2,'T220231122Cos1000.csv');

newvarNames={{'abs_pointerror0','abs_pointerror1'},{'absheadingError0','absheadingError1'},{'distanceError0','distanceError1'},{'leastErrSquared0','leastErrSquared1'},{'absPointingErrorRemovingPositionHeadingErrors0','absPointingErrorRemovingPositionHeadingErrors1'},{'RT0','RT1'},{'abspositionAngularError0','abspositionAngularError1'}};


T2A=proj39.reshapetoRepeated(T2,{'abs_pointerror','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','RT','abspositionAngularError'},2,newvarNames);
writetable(T2A,'T2A20231127Cos1000.csv')

% we also need to get the difference vector between estimated indoor to outdoor enviornments (same environment) and
% check if this vector is different from the difference vector between
% correct indoor and outdoor environments. e.g. positionprime 

T2A=readtable('T2A20231127Cos1000.csv');
T2A.abs_pointerror0_1=T2A.abs_pointerror0-T2A.abs_pointerror1;
T2A.absheadingError0_1=T2A.absheadingError0-T2A.absheadingError1;
T2A.abspositionAngularError0_1=T2A.abspositionAngularError0-T2A.abspositionAngularError1;
T2A.absPointingErrorRemovingPositionHeadingErrors0_1=T2A.absPointingErrorRemovingPositionHeadingErrors0-T2A.absPointingErrorRemovingPositionHeadingErrors1;

T2AwithBiregression=join(T1bdregression ...
    ,T2A);
writetable(T2AwithBiregression,'T2AwithBiregression.csv');

fTable=join(fTable,T1bdregression(:,T1bdregression.Properties.VariableNames({'participant_number','rsqprime2c12'})));


%%
%fTable= readtable('T6020231122CosSimilarity1000.csv');
%fTable= readtable('T602023112leastSquarederror1000.csv');
%fTable= convertvars(fTable,{'indoor_outdoor'},'categorical');
index=(fTable.participant_number~=0) %& fTable.participant_number~=33);
fTable=fTable(index,:);
%  create table with 2 row per subject, inside/indoor_outdoor=2

unicateM={'indoor_outdoor','Enviornmentname','participant_number'};
% varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam','euclidian_distance','campus_experience','absheadingError',...
%     'distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError'};
% T=pilotTable(fTable, unicateM, varNames,'mean');
% 
% 
% 
% unicateM={'indoor_outdoor','participant_number'};
%varNames={'RT','abs_pointerror','PTT','MRT','overall_familarity','continuous_unfam_fam','euclidian_distance','campus_experience','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError','headingError'};
varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam','continuous_unfam_fam_inside','continuous_unfam_fam_location','euclidian_distance','envrionmentFamilarity','targetFamilarity','campusExpYears','campusExpHoursPerWeek','campus_experience','overall_familarity','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError','headingError'};
T=proj39.pilotTable(fTable, unicateM, varNames,'mean');
%[mdregression2,tb1]=myregression (T, {'abs_pointerror','PTT','indoor_outdoor','MRT','campus_experience','envrionmentFamilarity'});
T12=T;
%T12=[T2,array2table([T1bdregression.rsqinprime2inc;T1bdregression.rsqoutprime2outc],"VariableNames",{'rsqprimetoc'})];
%writetable(T12,'T12_20231201CosSimilarity500.csv');

% unicateM1={'Enviornmentname'};
% varNames={'envrionmentFamilarity'};
% tbCate=table();
% for i=1:size(unicateM1,2)
%     tbCate.(unicateM1{i})=T12.(unicateM1{i});
% end
%  A=[];
% for i=1:size(varNames,2)
%     A=[A,T12.(varNames{i})];    
% end
[meanM,buildingNames]=proj39.getMeanORP1(T12.('envrionmentFamilarity'),T12.('Enviornmentname'));
for i=1:length(meanM)
    index=strcmp(T12.Enviornmentname,buildingNames{i});
    T12.envrionmentFamilarityMean(index)=meanM(i);
end


varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam','continuous_unfam_fam_inside','continuous_unfam_fam_location','euclidian_distance','envrionmentFamilarity','targetFamilarity','campusExpYears','campusExpHoursPerWeek','campus_experience','overall_familarity','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError','headingError'};
T12grantMean=proj39.pilotTable(fTable, {'indoor_outdoor','Enviornmentname'}, varNames,'mean');
T12grantMeanInside=T12grantMean(T12grantMean.indoor_outdoor==0,:);
T12grantMeanOutside=T12grantMean(T12grantMean.indoor_outdoor==1,:);
T12grantMeanD=table();
T12grantMeanD.RT0_1=T12grantMeanInside.RT-T12grantMeanOutside.RT;
T12grantMeanD.abs_pointerror0_1=T12grantMeanInside.abs_pointerror-T12grantMeanOutside.abs_pointerror;
T12grantMeanD.absheadingError0_1=T12grantMeanInside.absheadingError-T12grantMeanOutside.absheadingError;
T12grantMeanD.abspositionAngularError0_1=T12grantMeanInside.abspositionAngularError-T12grantMeanOutside.abspositionAngularError;
T12grantMeanD.familarity0_1=T12grantMeanInside.continuous_unfam_fam_inside-T12grantMeanInside.continuous_unfam_fam_location;

writetable(T12grantMean,'T12grantMean20240412.csv');
writetable(T12grantMeanD,'T12grantMeanD20240412.csv');

% if strcmp(method,'mean')
%     [meanM,unicateM]=self.getMeanORP1(A,tbCate);
% elseif strcmp(method,'circMean')


T12.envrionmentFamilarity
writetable(T12,'T12_20240207CosSimilarity500.csv');

newvarNames={{'E1abs_pointerror0','E2abs_pointerror0','E3abs_pointerror0','E4abs_pointerror0','E5abs_pointerror0','E6abs_pointerror0' ...
    'E1abs_pointerror1','E2abs_pointerror1','E3abs_pointerror1','E4abs_pointerror1','E5abs_pointerror1','E6abs_pointerror1'},...
   {'E1absheadingError0','E2absheadingError0','E3absheadingError0','E4absheadingError0','E5absheadingError0','E6absheadingError0' ...
    'E1absheadingError1','E2absheadingError1','E3absheadingError1','E4absheadingError1','E5absheadingError1','E6absheadingError1'},...
   {'E1distanceError0','E2distanceError0','E3distanceError0','E4distanceError0','E5distanceError0','E6distanceError0' ...
    'E1distanceError1','E2distanceError1','E3distanceError1','E4distanceError1','E5distanceError1','E6distanceError1'},...
   {'E1leastErrSquared0','E2leastErrSquared0','E3leastErrSquared0','E4leastErrSquared0','E5leastErrSquared0','E6leastErrSquared0' ...
    'E1leastErrSquared1','E2leastErrSquared1','E3leastErrSquared1','E4leastErrSquared1','E5leastErrSquared1','E6leastErrSquared1'},...
    {'E1RT0','E2RT0','E3RT0','E4RT0','E5RT0','E6RT0' ...
    'E1RT1','E2RT1','E3RT1','E4RT1','E5RT1','E6RT1'}...
    {'E1abspositionAngularError0','E2abspositionAngularError0','E3abspositionAngularError0','E4abspositionAngularError0','E5abspositionAngularError0','E6abspositionAngularError0' ...
    'E1abspositionAngularError1','E2abspositionAngularError1','E3abspositionAngularError1','E4abspositionAngularError1','E5abspositionAngularError1','E6abspositionAngularError1'},...
     {'E1headingError0','E2headingError0','E3headingError0','E4headingError0','E5headingError0','E6headingError0' ...
    'E1headingError1','E2headingError1','E3headingError1','E4headingError1','E5headingError1','E6headingError1'},...
    {'E1absPointingErrorRemovingPositionHeadingErrors0','E2absPointingErrorRemovingPositionHeadingErrors0','E3absPointingErrorRemovingPositionHeadingErrors0','E4absPointingErrorRemovingPositionHeadingErrors0','E5absPointingErrorRemovingPositionHeadingErrors0','E6absPointingErrorRemovingPositionHeadingErrors0' ...
    'E1absPointingErrorRemovingPositionHeadingErrors1','E2absPointingErrorRemovingPositionHeadingErrors1','E3absPointingErrorRemovingPositionHeadingErrors1','E4absPointingErrorRemovingPositionHeadingErrors1','E5absPointingErrorRemovingPositionHeadingErrors1','E6absPointingErrorRemovingPositionHeadingErrors1'},...
    {'E1envrionmentFamilarity0','E2envrionmentFamilarity0','E3envrionmentFamilarity0','E4envrionmentFamilarity0','E5envrionmentFamilarity0','E6envrionmentFamilarity0' ...
    'E1envrionmentFamilarity1','E2henvrionmentFamilarity1','E3envrionmentFamilarity1','E4envrionmentFamilarity1','E5envrionmentFamilarity1','E6envrionmentFamilarity1'}};

T12A=proj39.reshapetoRepeated(T12,{'abs_pointerror','absheadingError','distanceError','leastErrSquared','RT','abspositionAngularError','headingError','absPointingErrorRemovingPositionHeadingErrors','envrionmentFamilarity'},12,newvarNames);

T12AwithBiregression=join(T1bdregression ...
    ,T12A);
writetable(T12AwithBiregression,'T12A_20240207withBiregression.csv');


%newvarNames={{'abs_pointerror0','abs_pointerror1'},{'absheadingError0','absheadingError1'},{'distanceError0','distanceError1'},{'leastErrSquared0','leastErrSquared1'},{'absPointingErrorRemovingPositionHeadingErrors0','absPointingErrorRemovingPositionHeadingErrors1'},{'RT0','RT1'},{'abspositionAngularError0','abspositionAngularError1'}};
%T2A=proj39.reshapetoRepeated(T2,{'abs_pointerror','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','RT','abspositionAngularError'},2,newvarNames);
%writetable(T2A,'T2A20231127Cos1000.csv')

% we also need to get the difference vector between estimated indoor to outdoor enviornments (same environment) and
% check if this vector is different from the difference vector between
% correct indoor and outdoor environments. e.g. positionprime 

% T2A=readtable('T2A20231127Cos1000.csv');
% T2AwithBiregression=join(T1bdregression ...
%     ,T2A);
% %writetable(T2AwithBiregression,'T2AwithBiregression.csv');
% 
% fTable=join(fTable,T1bdregression(:,T1bdregression.Properties.VariableNames({'participant_number','rsqprime2c12'})));


%%

unicateM=table(T6vin2out.Enviornmentname);
[C,ia,ic] = unique(unicateM);
%B=[];
for i=1:length(ia) %((ia) stores unique categoray)
    index=ic==i;%get category i
    key=[C.Var1{i}(1:2)];
    key = erase(key," ");
    %key=key(1:5);
    Vcorrect.(key)=[T6vin2out(index,:).('vin2outcX'), T6vin2out(index,:).('vin2outcY')];
    Vprime.(key)=[T6vin2out(index,:).('vin2outprimeX'), T6vin2out(index,:).('vin2outprimeY')];
    Vinc2prime.(key)=[T6vc2prime(index,:).('vinc2inprimeX'),T6vc2prime(index,:).('vinc2inprimeY')];
    Voutc2prime.(key)=[T6vc2prime(index,:).('voutc2outprimeX'),T6vc2prime(index,:).('voutc2outprimeY')];
    %P.{[]}
    %B.=[B;mean(Oresp(index,:))];       
end

figure
fields=fieldnames(Vprime);
c=jet(length(fields));
% col=zeros(1,3);
p=colormap;
%c=p(int16(256/length(fields))*i+1,:);
%r = randi([1 256],12,1)
for i=1:length(fields)  
    %figure
   
    thiscolor=c(i,:);
    P1=Vcorrect.(fields{i});
    P2=Vprime.(fields{i});
    %scatter(P2(:,1),P2(:,2),['.',c{1}]);
    %scatter(P2(:,1),P2(:,2),'.','ColorVariable',c{1})
    %plot(P2(:,1),P2(:,2),'.','Color',c{1})
    plot(P2(:,1),P2(:,2),'.','Color',thiscolor)
    hold on
    %ellipsePandE20210716(1, 0.95,P2,['+',c{1}])
    output.(fields{i})=ellipsePandE20231125(2, 0.95,P2,'+',thiscolor);
    hold on
    plot(P1(1,1),P1(1,2),'o','Color',thiscolor);
    hold on
    text(P1(1,1),P1(1,2),fields{i},'Color','b');
    Mu=output.(fields{i}).Mu;
    text(Mu(1),Mu(1,2),[fields{i},char(39)],'Color','k');
    %plot(P1(1,1),P1(1,2),['o',c{1}]);
end

figure 
for i=1:length(fields)  
    %figure
   
    thiscolor=c(i,:);
    P1= Vinc2prime.(fields{i});
    P2= Voutc2prime.(fields{i});
    %scatter(P2(:,1),P2(:,2),['.',c{1}]);
    %scatter(P2(:,1),P2(:,2),'.','ColorVariable',c{1})
    %plot(P2(:,1),P2(:,2),'.','Color',c{1})
    plot(P2(:,1),P2(:,2),'.','Color',thiscolor)
    hold on
    %ellipsePandE20210716(1, 0.95,P2,['+',c{1}])
    output.(fields{i})=ellipsePandE20231125(2, 0.95,P2,'+',thiscolor);
    hold on       
    Mu=output.(fields{i}).Mu;
    text(Mu(1),Mu(1,2),[fields{i},'d1'],'Color','k');

    hold on

    output.(fields{i})=ellipsePandE20231125(2, 0.95,P1,'O',thiscolor);
    hold on       
    Mu=output.(fields{i}).Mu;
    text(Mu(1),Mu(1,2),[fields{i},'d0'],'Color','k');

   
end
 text(0,0,'0,0','Color','r');

 xlim([-300,300])
 ylim([-300,300])

%%
% create table with 1 row per subject

% proj39=proj39collection;
% 
% fTable= readtable('T6020231201CosSimilarity500.csv');
% unicateM={'participant_number'};
% varNames={'RT','abs_pointerror','PTT','MRT','continuous_unfam_fam','euclidian_distance','campus_experience','absheadingError','distanceError','leastErrSquared','absPointingErrorRemovingPositionHeadingErrors','abspositionAngularError'};
% T1=proj39.pilotTable(fTable, unicateM, varNames,'mean');
% writetable(T1,'T1_20240208Cos1000.csv');

function T=bi_regressV3Table(X,Y,A,B,VarName)
     meanX=mean(X);
     meanY=mean(Y);
     meanA=mean(A);
     meanB=mean(B);
     res=bi_regressV3(X,Y,A,B,meanX,meanY);
     proj39=proj39collection;
     d=proj39.distance([meanX,meanY],[meanA,meanB])
     
     T=array2table([d,res.regression(5:end)],"VariableNames",VarName);    
end 

function tvA2B=TvectorTwolocation (A,B,VarName)
    vA2B=B-A;
    tvA2B=array2table(vA2B,"VariableNames",VarName);
end