blib/lib/EyeTracking/EYD.pm untested

filter: Statementstmt 0.0% 0 / 425 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 66 MC/DCmcdc 0.0% 0 / 38 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 707 CC 82 SCAR 50.9
CC
82
Cov
0%
checkAlignment
420.0
barsEprimeLog
182.0
score_sub
156.0
CRAP 162.2
1 use strict;
2 use warnings;
3 package EyeTracking::EYD;
4 use Data::Dumper;
5 use Number::Range;
6 use List::MoreUtils qw{indexes}; # find record name as index
7  
8 sub new {
9 my $class = shift;
10 my $self = {
11 file => shift,
12 id => shift,
13 errorfile=>shift,
14 };
15 $self->{verbose}=0;
16 #$self->{_startbyte} = 0;
17 #$self->{_endbyte} = 0;
18 #$self->{_recfmt} = 0;
19 #$self->{_records} = ();
20 #$self->{data} = ();
21 bless $self, $class;
22
23 return $self;
24 }
25 # need to remove the filehandle after we're done
26 sub DESTROY{
27 my $self=shift;
28 $self->{errorhandle}->close() if $self->{errorhandle};
29 undef $self;
30 #undef @ideal, @b, @m;
31 #undef @retrived, @a, @n;
32 }
33  
34  
35 sub read {
36 my $self=shift;
37 open my $eydfile, $self->{file};
38  
39 # status code has 3 Booleen values, decode them with a hash instead of math
40 my %TFkey = (
41 '0' => [('FALSE')x3],
42 '16' => [qw/FALSE TRUE FALSE/],
43 '32' => [qw/TRUE FALSE FALSE/],
44 '48' => [qw/TRUE TRUE FALSE/ ] );
45
46
47 # what they say the data type is => what perl knows it as
48 my %Dtype = ('Byte' => 'C', 'VT_UI1'=>'C', 'UInt16' => 'S', 'Int16' => 'S', 'VT_UI2' => 'S', 'VT_I2'=>'S');
49 # anti eyd scans have these: s/VT_UI2/UInt16/;s/VT_I2/Int16/;
50
51 my $endbyte = 1; # will be something much greater
52 my $totalbytes = 0; # not used? -- should use to check
53 my @record; # structure of data
54 my @data; # actual data
55 #my @orgXdat; # xdat before bitmask
56  
57  
58 #####
59 # populate data with each frame of eyd binary info
60 #####
61 $_ = <$eydfile>;
62 if(!m/^\[File/){
63 die "++ eyd file is not an eyd file!" ;
64 }
65
66  
67 while(<$eydfile>){
68  
69 # keep going until we are about to hit binary data
70 last if m/^\[Segment_Data\]/;
71  
72 # set endbyte location, skip if we already know it
73 $endbyte = $1 if /Segment_Directory_Start_Address: (\d\d+)/;
74  
75 # set total bytes
76 $totalbytes = $1 if !$totalbytes && /Total_Bytes_Per_Record: (\d+)/;
77
78 #
79 # only want the table with bytes in the byte column.
80 #
81 my @readData = split/\s+/;
82  
83 # between 3 and 4, and 4th is a digit
84 next if $#readData > 4 || $#readData < 3 || $readData[3] !~ /^\d+$/;
85  
86  
87 # add what we have to the table
88 push @record, [@readData];
89  
90 }
91  
92  
93 print Dumper(@record),"\n" if $self->{verbose}>3;
94  
95 # end of text is start of binary
96 my $start = tell($eydfile);
97  
98 # find where XDAT is, probably always 4
99 my $xdatPos=0;
100 $xdatPos++ while $record[$xdatPos][0] !~ /XDAT/ && $xdatPos <= $#record;
101
102  
103 # HEADER
104 print join("\t", map {$_->[0] } @record),"\n" if $self->{verbose} > 2;
105  
106 # gaze data should be divided by 10
107 # so find which index in data that is
108 my @gazeIdx= indexes {/gaze/} map {$_->[0]} @record;
109  
110  
111 # number of bytes to read
112 # byte position of last record + it's size
113 # -1 b/c we start at 0 not 1 ??
114 # also as $totalbytes from header info, could check these numbers
115 my $recSize = $record[-1]->[1] + $record[-1]->[3] -1;
116  
117 # format of line for upack # e.g. CSSCSSSSSSS
118 # join all data types mapped to either C (byte) or S (U/Int16) via hash
119 my $recFmt = join("",map { $Dtype{$_->[2]} } @record);
120 for(@record) {
121 print STDERR "unknown: ", $_->[2], "\n" if ! exists ($Dtype{$_->[2]});
122 }
123 #
124  
125 # need to know previous occurances for correction calculations
126 my $prvXDAT = 0;
127 my $prvXDATidx = 0;
128  
129  
130 print "@", tell($eydfile), "end is $endbyte\n" if $self->{verbose};
131 while(tell($eydfile) < $endbyte || ( $endbyte==1 && !eof($eydfile) ) ) {
132 my $info;
133  
134 # read in whole record and add to data
135 read($eydfile,$info,$recSize);
136  
137 # get record as an array from binary
138 my @unpacked = unpack($recFmt, $info);
139  
140 # scale the gazes
141 $unpacked[$_] /= 10 for @gazeIdx;
142  
143 # and to master array
144 push @data, [ @unpacked ];
145  
146 print join("\t",@{$data[-1]}),"\n" if $self->{verbose} > 3;
147  
148  
149 # xdat is masked -- according to ASLconvert in the ilab matlab package
150 # deal with this when printing out
151 #push @orgXdat, $data[-1][$xdatPos]; # save origianl for print back
152 ## see /mnt/B/bea_res/Data/Tasks/RingRewardsAnti/Basic/10297/20070523/Raw/EyeData/2623_ringreward_anti_run1.eyd
153 ## for when this is necessary
154 $data[-1][$xdatPos] = ($data[-1][$xdatPos] + 65536) & 255; # add 2^16 mask out 2^8 ??
155 }
156
157 close $eydfile;
158  
159  
160 # give the self some more vars
161 $self->{_startbyte} = $start;
162 $self->{_endbyte} = $endbyte;
163 $self->{_recfmt} = $recFmt;
164 $self->{_records} = \@record;
165 $self->{fields} = [ map {$_->[0]} @{$self->{_records}} ];
166 $self->{data} = \@data;
167
168 #return ($file,$start,$endbyte, $recFmt,\@data);
169 #my %data;
170 #for my $i (0..$#record){
171 # $data{"$record[$i]"} = map {$_->[$i]} @data;
172 #}
173 #return %data
174  
175 }
176  
177  
178 sub printEyeData {
179 my $self = shift;
180  
181 # write to
182 my $filename = shift;
183 open(my $fh, ">".($filename || '-')) or die "cannot open output in printCodes ($filename)\n";
184  
185 # the first element of each list in the _records list is the title
186 my @items = map {$_->[0]} @{$self->{_records}};
187  
188 # we only want a few of them
189 my @HdrIdx = indexes {/XDAT|pupil_diam|gaze/} @items;
190  
191 print $fh join("\t",@items[@HdrIdx]),"\n";
192 # get each instances desired fields as a tab delim. string, then separate those by newlines
193 print $fh join("\n", map {join("\t",@{$_}[@HdrIdx])} @{$self->{data}} );
194  
195 close($fh);
196  
197 }
198  
199  
200  
201  
202 sub printallEyeData {
203 my $self = shift;
204 print join("\t", @{$self->{fields}}),"\n";
205 print join("\n", map {join("\t",@{$_})} @{$self->{data}} );
206 }
207  
208  
209 # "code:" array of hashes
210 #[
211 #{
212 # 'target' => { 'xdat' => 149, 'pos' => 25571 },
213 # 'stop' => { 'xdat' => 250, 'pos' => 25668 },
214 # 'start' => { 'xdat' => 100, 'pos' => 25389 }
215 # 'first' => 25389,
216 # 'last' => 28322,
217 # 'startcode' => 100
218 # 'targetcode' => 149
219 #},
220  
221  
222  
223  
224 sub trialPositions {
225 my $self = shift;
226 my ($startCodes,$targetCodes,$stopCodes) = @_;
227  
228  
229 #### find all trials
230  
231 my ($oldstate,$newstate)=(-1,-1); # none=-1,start=0,target=1,stop=2
232 my %statelook=(0=>'start',1=>'target',2=>'stop');
233 #$self->{codes}; # stores hash array
234 my $curCode=-1;
235 my @ranges=($startCodes, $targetCodes, $stopCodes);
236 my %init=(xdat=>-1, pos=>-1);
237 my %trial=(start=>{%init}, stop=>{%init}, target=>{%init}, first=>-1,last=>-1,startcode=>-1,targetcode=>-1);
238 #my %trial=(start=>{%init}, stop=>{%init}, target=>{%init}, first=>-1,last=>-1);
239  
240 my @xdatidx = indexes {/XDAT/i} @{$self->{fields}};
241 #TODO warn if $#xdatidx>0
242 #
243 my @codes=map {$_->[$xdatidx[0]]} @{$self->{data}};
244 # iterate through all xdats read by ASL eye tracker
245 while (my ($idx, $xdat) = each(@codes) ){
246 #$xdat=50 if $xdat==48;
247 next if $xdat == $curCode;
248 # update current code
249 $curCode=$xdat;
250 # check what range the xdat is in, update state
251 my $inrange=0;
252 while( my ($state,$range) = each @ranges ) {
253 if( $range->inrange($xdat) ) {
254 $oldstate=$newstate;
255 $newstate=$state;
256 $inrange=1;
257 }
258 }
259
260 # warn and skip if xdat is off
261 # we dont have to warn about the last xdat, 65278
262 if( !$inrange ) { $self->writeerror("xdat $xdat at pos $idx is not in a known range!") if $xdat != 65278; next}
263
264 # when the next state comes before the old state and we've recovered at least one code
265 # push what's in this trial to codes, clear row, need to push after finish too -- capture last
266 my $numRecov = scalar(grep {$_->{xdat}!=-1} @trial{qw/start target stop/});
267 if($newstate<=$oldstate && $numRecov>0) {
268 $trial{last}=$idx-1;
269 $trial{startcode}=$trial{start}->{xdat};
270 $trial{targetcode}=$trial{target}->{xdat};
271 $trial{ITI}=$trial{last} - $trial{start}->{pos};
272 push @{$self->{codes}}, {%trial};
273 %trial=(start=>{%init}, stop=>{%init}, target=>{%init}, first=>-1,last=>-1,startcode=>-1,targetcode=>-1);
274 #%trial=(start=>{%init}, stop=>{%init}, target=>{%init}, first=>-1,last=>-1);
275 }
276  
277  
278 # build trial up
279 $trial{ $statelook{$newstate} } = { xdat=>$xdat, pos=>$idx };
280 $trial{first}=$idx if $trial{first}==-1;
281  
282  
283 }
284 # get last trial
285 if (scalar(grep {$_->{xdat}!=-1} @trial{qw/start target stop/}) > 0 ) {
286 $trial{last}=$#{$self->{data}};
287 $trial{startcode}=$trial{start}->{xdat};
288 $trial{targetcode}=$trial{target}->{xdat};
289 $trial{ITI}=$trial{last} - $trial{start}->{pos};
290 push @{$self->{codes}},{%trial};
291 }
292  
293 }
294  
295  
296  
297 sub barsEprimeLog {
298 my $self = shift;
299 my %xDATlookup = (
300 'FIVEpunish007' => 147, 'FIVEpunish108' => 148,
301 'FIVEpunish532' => 149, 'FIVEpunish633' => 150,
302 'FIVEreward007' => 127, 'FIVEreward108' => 128,
303 'FIVEreward532' => 129, 'FIVEreward633' => 130,
304 'neutral007' => 201, 'neutral108' => 202,
305 'neutral532' => 203, 'neutral633' => 204);
306  
307  
308 my ($file) = @_;
309 open my $txtfile, $file or die "error opening eprime log file $file: $!";
310 ## prepare vars
311 my @frames;
312 # want these fields from txt file
313 my @flds=qw/masterlist location Procedure Running Latency Score Correct fixation/;
314 print join(",",@flds),"\n" if $self->{verbose};
315  
316 # Skip the header
317 $_=<$txtfile>;
318 $_=<$txtfile> while( ! m/ Header End /);
319 my @data;
320 my %col;
321 my %prevScored;
322 my $fixation="";
323
324 # run through LogFrame Start/End blocks
325 # collecting all the blocks between procuedures that have location frames (a scorable event)
326  
327 while(<$txtfile>) {
328 @col{@flds}=("NA")x($#flds+1) if/ LogFrame Start /; # initilize to all 0s
329 s/\r//g; # strip windows characters
330 $col{"$1"}="$2" if m/\s+(.*): (.*)$/; # get all pairs
331 if( / LogFrame End /) {
332 print join(",",@col{@flds}),"\n" if $self->{verbose} > 1;
333  
334 # there is a location, we've seen fixations
335 # time to publish what we have
336 # if location and fixation are empty, this is the first, and we should continue
337 # so we can collect the ITI
338 if( $col{location} ne '' and $fixation ne '') {
339 # sum ITI time (including fixations)
340 $prevScored{fixationTxt}=$fixation;
341 $fixation=~s/LongFix/363/g;
342 $fixation=~s/[a-z]*Catch2/182/g;
343 $fixation=~s/[a-z]*Catch1|fix/91/g;
344 $prevScored{duration}=eval("0$fixation"); # 0+363+$col{Procedure}
345  
346 my $Proc=$prevScored{'Procedure'};
347 my $startcode=50; if ($Proc =~ m/punish/) { $startcode=100} elsif($Proc=~ m/neutral/){$startcode=200};
348 my %finalhash;
349 @finalhash{(@flds,'fixationTxt')}=@prevScored{(@flds,'fixationTxt')};
350 #$finalhash{'Procedure'} = $Proc; # this is already ahead, need to pull it back before commiting
351 push @data, {%finalhash, 'startcode'=>$startcode, 'targetcode' =>$xDATlookup{$Proc} };
352 $fixation="";
353  
354 #there are only 42 runs
355 last if $#data>=41
356 }
357  
358 # we have Catch trials and fixations to account for
359 $fixation.="+$col{Procedure}" if $col{Procedure} =~ m/Fix|Catch/i;
360 $fixation="" if $col{Procedure} eq 'NA';
361  
362 # continue if we lack data, especially location (dot never appears, not scorable)
363 next if $col{location} eq '' || $col{Procedure} eq 'NA' || $col{Running} ne 'masterlist';
364  
365 %prevScored=%col;
366 }
367 }
368  
369 close $txtfile;
370 $self->{_idealOrderHash}=\@data;
371 }
372  
373 #
374 # use a parsed eprime file (long form of masterlists)
375 sub barsEprimeTrialOrder {
376 my $self = shift;
377 my @data=();
378 my %xDATlookup = (
379 'FIVEpunish007' => 147, 'FIVEpunish108' => 148,
380 'FIVEpunish532' => 149, 'FIVEpunish633' => 150,
381 'FIVEreward007' => 127, 'FIVEreward108' => 128,
382 'FIVEreward532' => 129, 'FIVEreward633' => 130,
383 'neutral007' => 201, 'neutral108' => 202,
384 'neutral532' => 203, 'neutral633' => 204);
385  
386  
387 my ($file) = @_;
388  
389 #want to mirror relevant bits of actually going through the log file
390 #$VAR42 = {
391 # 'startcode' => 100,
392 # 'targetcode' => 149,
393 # 'location' => '532',
394 # 'fixationTxt' => '+LongFix',
395 # 'fixation' => 363,
396 # 'Procedure' => 'FIVEpunish532',
397 #};
398 open my $txtfile, $file or die "err opening eprime trial order file $file: $!";
399 # file like "~/remotes/B/bea_res/MR_Scanner_Experiments/Scanner Tasks/MRRC tasks/Rewards Scanner Bars/OrderOfEvents-v1.txt"
400 # 1 neutral007
401 # 1 LongFix
402 # 2 FIVEpunish532
403 # 2 LongFix
404 # 3 FIVEreward532
405 # 3 LongFix
406 # 3 fix
407 # 3 fix
408 # 3 punCatch1
409 # 3 fix
410 # 4 neutral532
411 while(<$txtfile>) {
412 # format checks
413 die "eprime run order file has unexpected format ($. = $_)" if length(split(/\s+/)) > 1;
414 next if /^ .*fix$/; # start with fix, no trial number -- i.e. run 3
415  
416 # read
417 my ($trialnum,$event) = split/\s+/;
418 print "$trialnum,$event\n" if $self->{verbose};
419  
420 # add fixations
421 if($event =~ /Fix|catch/i){
422 ${$data[$trialnum-1]}{fixationTxt}='' if !exists(${$data[$trialnum-1]}{fixationTxt});
423 ${$data[$trialnum-1]}{fixationTxt}.= "+$event";
424 }
425  
426 # add event
427 else {
428 ${$data[$trialnum-1]}{Procedure} = $event;
429 #print "\ttarget and start code setting!\n";
430 ${$data[$trialnum-1]}{targetcode}= $xDATlookup{$event};
431 # startcode reward: 50 punish:100 neut: 200
432 $_=$event;
433 ${$data[$trialnum-1]}{startcode}= /reward/? 50 : (/punish/? 100 : 200);
434 ${$data[$trialnum-1]}{location} = $1 if /(\d{3})$/;
435 }
436 }
437  
438 close $txtfile;
439 for (0..$#data){
440 my $fixation=${$data[$_]}{fixationTxt};
441 # longfix is known to only happen once and immediatly after a prep+cue+sac
442 # prep+cue+sac+fix = 91*4
443 $fixation=~s/LongFix/363/g;
444 $fixation=~s/[a-z]*Catch2/182/g;
445 $fixation=~s/[a-z]*Catch1|fix/91/g;
446 ${$data[$_]}{duration}=eval("0$fixation"); # 0+363+....
447 }
448 $self->{_idealOrderHash}=\@data;
449 }
450  
451  
452  
453 #
454 # use a parsed eprime file (long form of masterlists)
455 sub ringsEprimeTrialOrder {
456 my $self = shift;
457 my @data=();
458 my %xDATlookup = (
459 'neutralcatch1' => 121, 'neutralcatch2' => 131,
460 'rewardcatch1' => 141, 'rewardcatch2' => 151,
461  
462 'neutral007' => 161, 'neutral108' => 162,
463 'neutral214' => 163, 'neutral426' => 164,
464 'neutral532' => 165, 'neutral633' => 166,
465  
466 'reward007' => 181, 'reward108' => 182,
467 'reward214' => 183, 'reward426' => 184,
468 'reward532' => 185, 'reward633' => 186
469 );
470 our %startCodesHash = (
471 'neutralcatch1'=> 20,
472 'neutralcatch2'=> 30,
473 'rewardcatch1' => 40,
474 'rewardcatch2' => 50,
475 'neutral' => 60,
476 'reward' => 80
477 );
478  
479  
480  
481 my ($file) = @_;
482  
483 #want to mirror relevant bits of actually going through the log file
484 #$VAR42 = {
485 # 'startcode' => 80,
486 # 'targetcode' => 185,
487 # 'location' => '532',
488 # 'fixationTxt' => '+Fix',
489 # 'fixation' => 91,
490 # 'Procedure' => 'reward532',
491 #};
492 open my $txtfile, $file or die "err opening eprime trial order file $file: $!";
493 # file like "~/remotes/B/bea_res/MR_Scanner_Experiments/Scanner Tasks/MRRC tasks/Rewards Scanner Bars/OrderOfEvents-v1.txt"
494 # 1 neutral007
495 # 1 Fix
496 # 2 reward532
497 # 2 Fix
498 # 3 reward532
499 while(<$txtfile>) {
500 # format checks
501 die "eprime run order file has unexpected format ($. = $_)" if length(split(/\s+/)) > 1;
502 next if /^0? .*fix$/; # start with fix, no trial number -- i.e. run 3
503  
504 # read
505 my ($trialnum,$event) = split/\s+/;
506 print "$trialnum,$event\n" if $self->{verbose} > 1;
507  
508 # add fixations
509 if($event =~ /Fix/i){
510 # fixes do not send an xdat
511 # catch2's do not leave enough space between sending start,target, and stop for anything but the stop xdat to be seen
512 ${$data[$trialnum-1]}{fixationTxt}='' if !exists(${$data[$trialnum-1]}{fixationTxt});
513 ${$data[$trialnum-1]}{fixationTxt}.= "+$event";
514 }
515  
516 # add event
517 else {
518 ${$data[$trialnum-1]}{Procedure} = $event;
519 $event=lc($event);
520 print "Warning: $event is unknown!\n" if ! exists($xDATlookup{$event});
521 #print "\ttarget and start code setting!\n";
522 ${$data[$trialnum-1]}{targetcode}= $xDATlookup{$event};
523 $_=$event;
524 /(neutral|reward)(catch\d)?/i;
525 ${$data[$trialnum-1]}{fixationTxt}.= "+$&";
526 ${$data[$trialnum-1]}{startcode}= $startCodesHash{lc($&)};
527 ${$data[$trialnum-1]}{location} = $1 if /(\d{3})$/;
528 }
529 }
530  
531 close $txtfile;
532 my $i=0;
533 while($i<=$#data){
534 # we take in catch2, but the xdat never has time to send, so it not actually seen
535 # compensate by removing from data list, but appending to fixation of the next guy
536 # we run into problems if catch is the last thing
537 if($i<$#data && ${$data[$i+1]}{Procedure} =~ /catch2/i ) {
538 ${$data[$i]}{fixationTxt} .= ${$data[$i+1]}{fixationTxt};
539 splice(@data,$i+1,1);
540 }
541  
542 my $fixation=${$data[$i]}{fixationTxt};
543 $fixation=~s/fix/90/ig;
544 $fixation=~s/\+(neutral|reward)catch1/+180/ig; # ~3*60
545 $fixation=~s/\+(neutral|reward)catch2/+90/ig; # ~1.5*60
546 $fixation=~s/\+(reward|neutral)/+4.5*60/ig; # ~ 4.5*60
547 ${$data[$i]}{duration}=eval("0$fixation"); # 0+363+....
548  
549 print "$i: $fixation=>",${$data[$i]}{duration}, " ", ${$data[$i]}{fixationTxt}, "\n" if $self->{verbose} > 2;
550  
551 $i++;
552 }
553 $self->{_idealOrderHash}=\@data;
554 }
555  
556  
557  
558 # companion function to write errors
559 # done this way so error writing can be abstracted and
560 # so we dont open a file when we dont have an error to write
561 sub writeerror {
562 my $self = shift;
563 my $msg = shift;
564  
565 if(!$self->{errorhandle}) {
566 open($self->{errorhandle} ,">&", \*STDERR ) or die "cannot open STDERR, something's really wrong!\n";
567 if($self->{errorfile}) {
568 close( $self->{errorhandle} );
569 open($self->{errorhandle} , ">", $self->{errorfile}) or die "cannot open error file for checkAlignment ( $self->{errorfile})\n";
570 }
571 }
572  
573 print { $self->{errorhandle} } "$self->{id} $msg\n";
574 print "\t$msg\n" if $self->{printerrors};
575
576 }
577  
578  
579 sub checkAlignment {
580 use Algorithm::NeedlemanWunsch;
581 my $self = shift;
582  
583 #
584 # score
585 # fit trial xdats to those recorded by eprime
586 # with dynamic programing matching algorithm (needlemanWunsch)
587 #
588 #
589 # make copies of the two hashes
590 our @ideal= @{$self->{_idealOrderHash}};
591 our @retrived= @{$self->{codes}};
592
593 our ($a, $b)=("","");
594 sub score_sub {
595 return -2 if !@_; # gap penalty
596 my $a=$_[0]->{startcode};
597 my $b=$_[1]->{startcode};
598 my $a2=$_[0]->{targetcode};
599 my $b2=$_[1]->{targetcode};
600 #return ($_[0] eq $_[1]) ? 1 : -5; # match, mismatch
601 # if start codes are the same +2, if not but they're in the same block -1, otherwise -2
602 my $score=($a eq $b) ? 2 : (abs($a-$b)<100)? -1: -2;
603 # targets match +2, same for targets
604 $score+=($a2 eq $b2) ? 2 : (abs($a-$b)<100)? -1 : -2;
605  
606 print "$a/$b\t$a2/$b2: $score\n" if $self->{verbose} > 1;
607 return $score;
608 #### previous scoring
609 #### donno what was goign on
610 return ($a eq $b && $a2 eq $b2) ? 4: -5 if ($a*$b<0); # misalign-- taget and stop align=4, dont -5
611 return ($a2 eq $b2) ? 3: -5 if ($a*$b<0); # never seen
612 return ($a eq $b) ? 1 : -5; # mismatch = -5
613 }
614
615 # Magic alignment (make string, pop as matched/gapped, reverse)
616 # n and m collect indexes (-1 is used if somethign is skipped)
617 # a and b are string representations of the alingment
618 #
619 # alignment only made on start codes
620 # TODO: include target codes!
621 #
622 our ($n,$m)=($#ideal,$#retrived);
623 our (@n,@m)=();
624 sub shifta_sub {$b="___:___;$b"; $a=sprintf("%03d:%03d;$a",@{pop(@ideal)}{qw/startcode targetcode/}); push @m,-1;push @n,$n--;}
625 sub shiftb_sub {$a="___:___;$a"; $b=sprintf("%03d:%03d;$b",@{pop(@retrived)}{qw/startcode targetcode/}); push @n,-1;push @m,$m--;}
626 #sub onalign {$a=sprintf('%03d',pop(@ideal)->{startcode}).";$a"; $b=sprintf('%03d',pop(@retrived)->{startcode}).";$b"; push @m,$m--; push @n,$n--;}
627 sub onalign {
628 $a=sprintf("%03d:%03d;$a",@{pop(@ideal)}{qw/startcode targetcode/});
629 $b=sprintf("%03d:%03d;$b",@{pop(@retrived)}{qw/startcode targetcode/});
630 push @m,$m--; push @n,$n--;
631 }
632
633 my $matcher = Algorithm::NeedlemanWunsch->new(\&score_sub);
634 my $score=$matcher->align(\@ideal,\@retrived, { shift_b=>\&shiftb_sub, shift_a=>\&shifta_sub, align=>\&onalign});
635
636 $self->{alignment_eprime} = $a;
637 $self->{alignment_eyd} = $b;
638 print "$score:\nep:$a\ney:$b\n" if $self->{verbose};
639  
640 #looks like:
641 #40:
642 #___;200;100;050;200;200;050;200;100;100;200;050;050;050;100;050;200;100;050;200;100;200;050;200;200;100;100...
643 #-01;200;100;050;200;200;050;200;100;100;200;050;050;050;100;050;200;100;050;200;100;200;050;200;200;100;100...
644  
645  
646  
647 # indexes are end to start, not useful for printing
648 @n=reverse @n;
649 @m=reverse @m;
650 # say "@n\n@m";
651
652
653
654 # eyd codes: start targ stop
655 # eyd time index: start targ stop laststop
656 # eprime run order expected codes: start targ stop
657 my @codeTable=([qw/strt trg stp ITIo ITIe | strtp trgp stpp lastp proc strtep trgep stpep/]);
658 for my $i (0..$#n) {
659 # negative index ($i) means bad alignment
660 if($n[$i] <0 || $m[$i] < 0) {
661 # n is expected, m is observed
662 # if n is negative, expected is behind
663 my $whosbehind=($n[$i] < 0)?"expected":"observed";
664 $self->writeerror("bad alignment: missed trial! (@ trial $i: $whosbehind code is behind )") if $i > 0;
665 next
666 }
667 my $epIdx=$n[$i]; # from eprime inde$m[$i] x
668 my $eyIdx=$m[$i]; # from eyd index
669 my @t=();
670 push @t, map {$_->{xdat} } @{$self->{codes}->[$eyIdx]}{qw/start target stop/};
671 #push @t, @{$self->{_idealOrderHash}->[$epIdx]}{qw/startcode targetcode/}, 250;
672 my $ITIobs = @{$self->{codes}}[$eyIdx]->{last} - @{$self->{codes}}[$eyIdx]->{start}->{pos};
673 my $ITIhyp = @{$self->{_idealOrderHash}->[$epIdx]}{duration};
674 push @t, $ITIobs, $ITIhyp;
675 push @t, "|";
676 push @t, map {$_->{pos} } @{$self->{codes}->[$eyIdx]}{qw/start target stop/};
677 push @t, $self->{codes}->[$eyIdx]->{last};
678 push @t, @{$self->{_idealOrderHash}->[$epIdx]}{fixationTxt};
679 push @t, @{$self->{_idealOrderHash}->[$epIdx]}{qw/startcode targetcode/}, 250;
680 push @codeTable, [@t];
681  
682 #@t=();
683 #push @t, $IT
684  
685 # if the estimate is off by more than a sample between the trials
686 # 2 and 41, complain
687 if(abs($ITIhyp - $ITIobs) > 1 and $i>1 and $i<42 ) {
688 $self->writeerror("ITI error\@trial $i, obs $ITIobs != hyp $ITIhyp");
689 }
690  
691 # output useful for graphviz visualization of corrupt codes
692 # but should be the same info as what is printed by score,a,b above
693 for my $type (qw/startcode targetcode/){
694 my $hypCode = $self->{_idealOrderHash}->[$epIdx]->{$type};
695 my $obsCode = $self->{codes}->[$eyIdx]->{$type};
696 $self->writeerror("$hypCode -> $obsCode #expectted -> obs (\@trial $i)") if $hypCode != $obsCode;
697 }
698 }
699
700 # Print codetable if we ask for it
701 # either by specifiying codeTableFN
702 # or by setting verbose to 1
703  
704 #strt trg stp ITIo ITIe strtp trgp stpp lastp proc
705 print join("\n", map {join("\t",@{$_}[0..10])} @codeTable) if $self->{verbose};
706  
707 if($self->{codeTableFN} and open(my $codeTableFH, '>',$self->{codeTableFN}) ){
708 print $codeTableFH join("\n", map {join("\t",@{$_}[0..10])} @codeTable) ;
709 close $codeTableFH;
710 }
711  
712 $self->{checked} = [ @codeTable[1..$#codeTable] ];
713 # checkedHdr is a hash with header names pointing to an index
714 while( my ($idx,$key) = each @{$codeTable[0]} ) { $self->{checkedHdr}->{$key}=$idx }
715  
716 return $score;
717 }
718  
719 sub printCodes {
720 my $self = shift;
721  
722 # write to
723 my $filename = shift;
724 open(my $fh, ">".($filename || '-')) or die "cannot open output in printCodes ($filename)\n";
725  
726 for my $i (0..$#{$self->{codes}}) {
727 next if $self->{codes}->[$i]->{start}->{xdat} == -1;
728 my @a;
729 push @a, map {$_->{xdat}} @{$self->{codes}->[$i]}{qw/start target stop/};
730 push @a, map {$_->{pos} } @{$self->{codes}->[$i]}{qw/start target stop/};
731 print $fh join("\t",@a), "\n";
732 }
733  
734 close($fh);
735 }
736  
737  
738 1;
739  
740 __END__