1 This file contains the code
for the subroutines
in
2 Perl
-speaks
-NONMEMs data module
. It is
not functional by itself
.
3 The code should be transferred to the module autogenerated by dia2code
4 using the fill_diacode
.pl script
.
8 start include statements
9 use Digest
::MD5
'md5_hex';
21 use Time
::HiRes
qw(gettimeofday);
22 my @primary_column_names = ('ID', 'DATE', 'DAT1', 'DAT2', 'DAT3' ,'L1', 'L2', 'DV', 'MDV', 'RAW_', 'MRG_', 'RPT_', 'TIME', 'DROP', 'SKIP', 'EVID', 'AMT', 'RATE', 'SS', 'II', 'ADDL', 'CMT', 'PCMT', 'CALL');
25 # }}} include statements
30 # The structure of the data class is subject-centric, recognising that
31 # the subjects included in a study often can be regarded as
32 # independent. A class for the subject level exists within PsN and is
33 # called the individual class. A data object consists of at least one
34 # but probably many individual objects plus optional comments.
44 # my $data_obj = data -> new ( filename => 'test040314.dta' );
46 # $data_obj -> renumber_ascending;
48 # my $subsets_ref = $data_obj -> case_deletion( bins => 10 );
50 # my @subsets = @{$subsets_ref};
60 # <a HREF="model.html">model</a>, <a HREF="output.html">output</a>,
61 # <a HREF="tool/modelfit.html">tool::modelfit</a>,
62 # <a HREF="tool.html">tool</a>
68 # model, output, tool::modelfit, tool
79 # If the column holding the subject identifier is not the
80 # first, it can be specified using the I<idcolumn> attribute
82 # I<ignoresign> determines which rows that are regarded as
83 # comments. Corresponds to the IGNORE= option in the $DATA
84 # record in a NONMEM model file.
86 $this -> {'use_data_table'} = 0;
88 ( $this -> {'directory'},
89 $this -> {'filename'} ) = OSspecific
::absolute_path
( $this -> {'directory'},
90 $this->{'filename'} );
92 debug
-> warn( level
=> 2,
93 message
=> "data -> new: Data object initialized from file: ".
96 # sub register_in_database {
98 # # Backslashes messes up the sql syntax
99 # my $file_str = $this->{'filename'};
100 # my $dir_str = $this->{'directory'};
101 # $file_str =~ s/\\/\//g;
102 # $dir_str =~ s/\\/\//g;
105 # my $md5sum = md5_hex(OSspecific::slurp_file($this-> full_name ));
107 # connect("DBI:mysql:host=".$PsN::config -> {'_'} -> {'database_server'}.
108 # ";databse=".$PsN::config -> {'_'} -> {'project'},
109 # $PsN::config -> {'_'} -> {'user'},
110 # $PsN::config -> {'_'} -> {'password'},
111 # {'RaiseError' => 1});
113 # my $sth = $dbh -> prepare( "SELECT data_id FROM ".$PsN::config -> {'_'} -> {'project'}.
115 # "WHERE filename = '$file_str' AND ".
116 # "directory = '$dir_str' AND ".
117 # "md5sum = '".$md5sum."'" );
118 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
119 # my $select_arr = $sth -> fetchall_arrayref;
120 # if ( scalar @{$select_arr} > 0 ) {
121 # debug -> warn( level => 1,
122 # message => "Found an old entry in the database matching the ".
123 # "current data file" );
124 # if ( scalar @{$select_arr} > 1 ) {
125 # debug -> warn( level => 1,
126 # message => "Found more than one matching entry in database".
127 # ", using the first" );
129 # $this -> {'data_id'} = $select_arr->[0][0];
131 # my ( $date_str, $time_str );
132 # if ( $Config{osname} eq 'MSWin32' ) {
133 # $date_str = `date /T`;
134 # $time_str = ' '.`time /T`;
137 # $date_str = `date`;
141 # my $date_time = $date_str.$time_str;
142 # $sth = $dbh -> prepare("INSERT INTO ".$PsN::config -> {'_'} -> {'project'}.
143 # ".data (filename,date,directory,md5sum) ".
144 # "VALUES ('$file_str', '$date_time', '$dir_str','".
147 # $this -> {'data_id'} = $sth->{'mysql_insertid'};
150 # $dbh -> disconnect;
154 unless ( ( defined $this -> {'header'} and
155 scalar @
{$this -> {'header'}} > 0 ) or
156 ( defined $this -> {'individuals'} and
157 scalar @
{$this -> {'individuals'}} > 0 ) ) {
158 if ( -e
$this -> full_name
) {
159 if ( $this -> {'target'} eq 'mem' ) {
160 # ®ister_in_database( $this ) if ( $PsN::config -> {'_'} -> {'use_database'} and
161 # $this -> {'use_data_table'} );
162 $this -> _read_header
;
163 $this -> _read_individuals
;
164 $this -> {'synced'} = 1;
166 $this -> {'synced'} = 0;
169 debug
-> die(message
=> "No header, individuals, and no file " . $this -> full_name
. " on disk.")
170 unless $this -> {'ignore_missing_files'};
171 $this -> {'synced'} = 0;
174 if ( $this -> {'target'} eq 'mem') {
175 if ( -e
$this -> {'filename'} ) {
176 $this -> _read_header
;
177 # ®ister_in_database if ( $PsN::config -> {'_'} -> {'use_database'} and
178 # $this -> {'use_data_table'} );
179 $this -> _read_individuals
;
180 $this -> {'synced'} = 1;
182 debug
-> die(message
=> "No file:".$this->{'filename'}." on disk" )
183 unless $this -> {'ignore_missing_files'};
184 $this -> {'synced'} = 0;
191 if ( $this -> {'synced'} ) {
193 foreach my $head ( @
{$this -> {'header'}} ) {
194 $this -> {'column_head_indices'} -> {$head} = $i;
198 # $Data::Dumper::Maxdepth = 3;
199 # die Dumper $this -> {'individuals'};
205 # {{{ register_in_database
206 start register_in_database
207 if ( $PsN::config
-> {'_'} -> {'use_database'} ) {
208 # Backslashes messes up the sql syntax
209 my $file_str = $self->{'filename'};
210 my $dir_str = $self->{'directory'};
211 $file_str =~ s/\\/\//g
;
212 $dir_str =~ s/\\/\//g
;
214 my $project = $PsN::config
-> {'_'} -> {'project'};
216 my $md5sum = md5_hex
(OSspecific
::slurp_file
($self-> full_name
));
218 my $dbh = DBI
-> connect("DBI:mysql:host=".$PsN::config
-> {'_'} -> {'database_server'}.
219 ";databse=".$project,
220 $PsN::config
-> {'_'} -> {'user'},
221 $PsN::config
-> {'_'} -> {'password'},
222 {'RaiseError' => 1});
229 my $sth = $dbh -> prepare
( "SELECT data_id FROM ".$project.
231 "WHERE filename = '$file_str' AND ".
232 "directory = '$dir_str' AND ".
233 "md5sum = '".$md5sum."'" );
234 $sth -> execute
or debug
-> die( message
=> $sth->errstr ) ;
235 $select_arr = $sth -> fetchall_arrayref
;
238 if ( scalar @
{$select_arr} > 0 ) {
239 'debug' -> warn( level
=> 1,
240 message
=> "Found an old entry in the database matching the ".
241 "current data file" );
242 if ( scalar @
{$select_arr} > 1 ) {
243 'debug' -> warn( level
=> 1,
244 message
=> "Found more than one data matching entry in database".
245 ", using the first" );
247 $self -> {'data_id'} = $select_arr->[0][0];
249 my $sth = $dbh -> prepare
( "SELECT individual_id FROM ".$project.".data_individual ".
250 "WHERE data_id = '".$self -> {'data_id'}."'" );
251 $sth -> execute
or debug
-> die( message
=> $sth->errstr ) ;
252 my $id_arr = $sth -> fetchall_arrayref
;
253 map( $_ = $_ -> [0], @
{$id_arr} );
254 $self -> {'individual_ids'} = $id_arr;
255 } elsif ( defined $self -> {'individuals'} ) {
256 my ( $date_str, $time_str );
257 if( $Config{osname
} eq 'MSWin32' ){
258 $date_str = `date /T`;
259 $time_str = ' '.`time /T`;
266 my $date_time = $date_str.$time_str;
267 my ( $columns, $values );
268 my $res_str = $resampled ?
'1' : '0';
269 if ( defined $model_id ) {
270 $columns = '(model_id, filename, date, directory, md5sum, resampled)';
271 $values = "('$model_id', '$file_str', '$date_time', '$dir_str','".
272 $md5sum."', '$res_str' )";
274 $columns = '(filename, date, directory, md5sum, resampled)';
275 $values = "('$file_str', '$date_time', '$dir_str','".$md5sum."', '$res_str' )";
277 $sth = $dbh -> prepare
("INSERT INTO ".$PsN::config
-> {'_'} -> {'project'}.
278 ".data $columns VALUES $values");
280 $self -> {'data_id'} = $sth->{'mysql_insertid'};
282 if ( defined $self -> {'data_id'} ) {
284 my $columns = "( id_key, id )";
285 if( $#individual_ids >= 0 ) {
286 $self -> register_di_relation
( individual_ids
=> \
@individual_ids );
288 my $inds = scalar @
{$self -> {'individuals'}};
289 $dbh -> do( "LOCK TABLES ".$PsN::config
-> {'_'} -> {'project'}.
290 ".individual WRITE" );
291 # $sth = $dbh -> prepare( "SELECT MAX(individual_id)".
292 # " FROM ".$PsN::config -> {'_'} -> {'project'}.
294 $dbh -> do( 'USE '.$PsN::config
-> {'_'} -> {'project'} );
295 $sth = $dbh -> prepare
( "SHOW TABLE STATUS LIKE 'individual'" );
296 $sth -> execute
or debug
-> die( message
=> $sth->errstr ) ;
297 my $select_arr = $sth -> fetchall_arrayref
;
298 my $first_id_id = $select_arr -> [0][10] ?
299 $select_arr -> [0][10] : 0;
300 # my $first_id_id = $select_arr -> [0][0] ? ($select_arr -> [0][0] + 1) : 0;
301 my $last_id_id = $first_id_id + $inds - 1;
302 for( my $i = 0; $i < $inds; $i++ ) {
303 if( defined $self -> {'individuals'}[$i] ) {
304 my $id_id = $self -> {'individuals'}[$i] -> idnumber
;
305 $values = $values."," if ( defined $values );
306 $values = $values."( $i, $id_id )";
309 $sth = $dbh -> prepare
( "INSERT INTO ".$PsN::config
-> {'_'} -> {'project'}.
310 ".individual $columns VALUES $values" );
312 $dbh -> do( "UNLOCK TABLES" );
313 @individual_ids = ($first_id_id .. $last_id_id);
314 $self -> register_di_relation
( individual_ids
=> \
@individual_ids );
316 $self -> {'individual_ids'} = \
@individual_ids;
321 $data_id = $self -> {'data_id'}; # return the data_id
323 end register_in_database
324 # }}} register_in_database
326 # {{{ register_di_relation
327 start register_di_relation
328 if ( $PsN::config
-> {'_'} -> {'use_database'} and
329 defined $self -> {'data_id'} and $#individual_ids >= 0 ) {
330 my $dbh = DBI
-> connect("DBI:mysql:host=".$PsN::config
-> {'_'} -> {'database_server'}.
331 ";databse=".$PsN::config
-> {'_'} -> {'project'},
332 $PsN::config
-> {'_'} -> {'user'},
333 $PsN::config
-> {'_'} -> {'password'},
334 {'raiseerror' => 1});
337 my $columns = "( data_id, individual_id )";
338 foreach my $individual_id ( @individual_ids ) {
339 if ( defined $individual_id ) {
340 $values = $values."," if ( defined $values );
341 $values = $values."(".$self -> {'data_id'}.", $individual_id )";
344 $sth = $dbh -> prepare
( "INSERT INTO ".$PsN::config
-> {'_'} -> {'project'}.
345 ".data_individual $columns VALUES $values" );
347 $sth -> finish
if ( defined $sth );
350 end register_di_relation
351 # }}} register_di_relation
357 $full_name = $self -> {'directory'} . $self -> {'filename'};
367 # The bootstrap method draws I<samples> number of boostrap
368 # samples from the data set. The I<subjects> arguments
369 # determines the size of each sample (default equals to the
370 # number of individuals in the original data set). The method
371 # returns references to three arrays: I<boot_samples_ref>,
372 # which holds the bootstrap data sets, I<incl_individuals_ref>
373 # which holds arrays containing the subject identifiers (ID's)
374 # for the included individuals of each bootstrap data set and
375 # I<included_keys_ref> which holds the key or index of the
376 # included individuals. The key or index is an integer
377 # starting at 1 for the first individual in the original data
378 # set and increasing by one for each following.
379 $self -> synchronize
;
380 my @header = @
{$self -> {'header'}};
381 my $individuals = $self -> {'individuals'};
384 my $status_bar = status_bar
-> new
( steps
=> $samples );
385 ui
-> print( category
=> 'bootstrap',
386 message
=> $status_bar -> print_step
,
389 for ( my $i = 1; $i <= $samples; $i++ ) {
390 my $new_name = defined $name_stub ?
$name_stub."_$i.dta" : "bs$i.dta";
391 $new_name = $directory.'/'.$new_name;
392 my ( $boot, $incl_ind_ref, $incl_key_ref ) =
393 $self -> resample
( subjects
=> $subjects,
395 new_name
=> $new_name,
397 stratify_on
=> $stratify_on,
398 model_id
=> $model_ids[$i-1] );
399 push( @included_keys, $incl_key_ref );
400 push( @incl_individuals, $incl_ind_ref );
401 # $boot -> renumber_ascending;
402 push( @boot_samples, $boot );
403 # $boot -> synchronize;
405 if( $status_bar -> tick
() ){
406 ui
-> print( category
=> 'bootstrap',
407 message
=> $status_bar -> print_step
,
411 # print Dumper \@boot_samples;
414 ui
-> print( category
=> 'bootstrap',
415 message
=> ' ... done' );
425 $self -> synchronize
;
426 my ( @header, $individuals, @bs_inds, $key_ref, @id_ids, @bs_id_ids );
427 @id_ids = @
{$self -> {'individual_ids'}} if( defined $self -> {'individual_ids'} );
428 if ( defined $stratify_on ) {
429 unless ( $resume and -e
$new_name ) {
430 @header = @
{$self -> {'header'}};
431 $individuals = $self -> {'individuals'};
433 if( $stratify_on =~ /\D/ ){
434 %strata = %{$self -> factors
( column_head
=> $stratify_on )};
435 if ( $strata{'Non-unique values found'} eq '1' ) {
436 debug
-> die( message
=> "Individuals were found to have multiple values in the $stratify_on column. ".
437 "The column $stratify_on cannot be used for stratification of the resampling." );
440 %strata = %{$self -> factors
( column
=> $stratify_on )};
441 if ( $strata{'Non-unique values found'} eq '1' ) {
442 debug
-> die( message
=> "Individuals were found to have multiple values in column number $stratify_on. ".
443 "Column $stratify_on cannot be used for stratification of the resampling." );
447 while( my ( $factor, $key_list ) = each %strata ) {
448 my $keys = scalar @
{$key_list};
449 for ( my $i = 0; $i < $keys; $i++ ) {
450 my $list_ref = random_uniform_integer
(1,0,$keys-1);
451 push( @bs_inds, $individuals ->
452 [ $key_list -> [$list_ref] ] -> copy
);
453 push( @included_keys, $key_list -> [$list_ref] );
454 push( @incl_individuals, $individuals ->
455 [ $key_list -> [$list_ref] ] -> idnumber
);
456 push( @bs_id_ids, $id_ids[ $key_list -> [$list_ref] ] );
460 $boot = data
-> new
( header
=> \
@header,
461 idcolumn
=> $self -> {'idcolumn'},
462 ignoresign
=> $self -> {'ignoresign'},
463 individuals
=> \
@bs_inds,
464 filename
=> $new_name,
465 ignore_missing_files
=> 1,
467 $boot -> renumber_ascending
;
470 #$boot -> target( $target );
473 unless ( $resume and -e
$new_name ) {
474 @header = @
{$self -> {'header'}};
475 $individuals = $self -> {'individuals'};
476 for ( my $i = 1; $i <= $subjects; $i++ ) {
477 $key_ref = random_uniform_integer
(1,0,scalar @
{$individuals}-1);
478 push( @bs_inds, $individuals -> [ $key_ref ] -> copy
);
479 push( @included_keys, $key_ref );
480 push( @incl_individuals, $individuals -> [ $key_ref ] -> idnumber
);
481 push( @bs_id_ids, $id_ids[ $key_ref ] );
484 # MUST FIX: If a file already exists with the same name,
485 # the created bs data set will be appended to this. IT
486 # MUST BE OVERWRITTEN!
487 $boot = data
-> new
( header
=> \
@header,
488 idcolumn
=> $self -> {'idcolumn'},
489 ignoresign
=> $self -> {'ignoresign'},
490 individuals
=> \
@bs_inds,
491 filename
=> $new_name,
492 ignore_missing_files
=> 1,
494 $boot -> renumber_ascending
;
496 $boot -> target
( $target );
498 # If we are resuming, we still need to generate the
499 # pseudo-random sequence and initiate a data object
500 for ( my $i = 1; $i <= $subjects; $i++ ) {
501 random_uniform_integer
(1,0,scalar @
{$individuals}-1)
503 $boot = data
-> new
( idcolumn
=> $self -> {'idcolumn'},
504 ignoresign
=> $self -> {'ignoresign'},
505 filename
=> $new_name,
506 ignore_missing_files
=> 1,
511 if( $target eq 'disk'){
515 $boot -> register_in_database
( individual_ids
=> \
@bs_id_ids,
517 model_id
=> $model_id );
527 # case_deletion creates subsets of the data. The number of
528 # subsets is specified by the bins argument. The individuals
529 # of each subset is selected randomly or in ascending
530 # numerical order depending on the selection argument that can
531 # be either 'consecutive' or 'random'. case_column must be
532 # specified to give the method something to base the selection
533 # on. Valid case_column values are either the column number
534 # (pure digits) or the name of the column in the (optional)
536 $self -> synchronize
;
537 my @header = @
{$self -> {'header'}};
538 if ( not defined $case_column ) {
539 debug
-> die( message
=> "case_column must be specified" );
541 if ( not $case_column =~ /^\d/ ) {
542 for ( my $i = 0; $i <= $#header; $i++ ) {
543 $case_column = $i+1 if ( $header[$i] eq $case_column );
547 $bins = defined $bins ?
$bins :
548 scalar keys %{$self -> factors
( column
=> $case_column)};
549 my %factors = %{$self -> factors
( column
=> $case_column )};
550 if ( $factors{'Non-unique values found'} eq '1' ) {
551 debug
-> die( message
=> "Individuals were found to have multiple values in column number $case_column. ".
552 "Column $case_column cannot be used for case deletion." );
555 my $maxbins = scalar keys %factors;
556 my @ftrs = sort { $a <=> $b } keys %factors;
557 my $individuals = $self -> {'individuals'};
558 my $maxkey = scalar @
{$individuals} - 1;
560 my ( @tmp_ftrs, @binsize ) =
562 my ( $k, $j, $i ) = ( 0, 0, 0 );
563 # Create the binsizes
564 for ( $j = 0; $j < $maxbins; $j++ ) {
566 $k = 0 if( $k >= $bins );
568 $self -> _fisher_yates_shuffle
( array
=> \
@ftrs ) if( $selection eq 'random' );
569 for ( $k = 0; $k < $bins; $k++ ) {
570 for ( $j = 0; $j < $binsize[ $k ]; $j++ ) {
571 # print "SK: ",$skipped_keys[ $k ]," F: ",$factors{ $ftrs[ $i ] },"\n";
572 push( @
{$skipped_keys[ $k ]}, @
{$factors{ $ftrs[ $i ] }} );
573 push( @
{$skipped_values[ $k ]}, $ftrs[ $i++ ] );
577 for ( $k = 0; $k < $bins; $k++ ) {
580 SELKEYS
: foreach my $key ( 0..$maxkey ) {
581 foreach my $skipped ( @
{$skipped_keys[ $k ]} ) {
582 if ( $key == $skipped ) {
583 push( @
{$skipped_ids[ $k ]}, $individuals ->
584 [ $skipped ] -> idnumber
);
585 push( @del_inds, $individuals -> [ $key ] -> copy
);
589 push( @cd_inds, $individuals -> [ $key ] -> copy
);
591 # Set ignore_missing_files = 1 to make it possible to get the result
593 my $newdata = data
->
594 new
( header
=> \
@header,
595 ignoresign
=> $self -> {'ignoresign'},
596 idcolumn
=> $self -> {'idcolumn'},
597 individuals
=> \
@cd_inds,
599 filename
=> $directory.'/cdd_'.($k+1).'.dta',
600 ignore_missing_files
=> 1 );
601 my $deldata = data
->
602 new
( header
=> \
@header,
603 ignoresign
=> $self -> {'ignoresign'},
604 idcolumn
=> $self -> {'idcolumn'},
605 individuals
=> \
@del_inds,
607 filename
=> $directory.'/rem_'.($k+1).'.dta',
608 ignore_missing_files
=> 1 );
609 push( @subsets, $newdata );
610 push( @remainders, $deldata );
624 # filename: new data file name.
626 # target: keep the copy in memory ('mem') or write it to disk and flush the memory ('disk').
628 ($directory, $filename) = OSspecific
::absolute_path
( $directory, $filename );
630 # Clone self into new data object. Why don't the individuals get cloned too?
631 # strange. need to set synced to 0 AND set the {'individuals'} to undef.
632 cp
($self -> full_name
, $directory.$filename );
633 $new_data = Storable
::dclone
( $self );
634 $new_data -> {'synced'} = 0;
635 $new_data -> {'individuals'} = undef;
636 $new_data -> synchronize
;
638 # Set the new file name for the copy
639 $new_data -> directory
( $directory );
640 $new_data -> filename
( $filename );
646 # {{{ column_to_array
647 start column_to_array
649 $self -> synchronize
;
651 if ( not $column =~ /^\d/ ) {
652 $column = $self -> {'column_head_indices'} -> {$column} - 1;
655 if( $column < 0 or $column > $#{$self -> {'header'}} ){
659 foreach my $individual ( @
{$self -> individuals
} ){
660 foreach my $individual_row( @
{$individual -> subject_data
} ){
661 my @row = split(/,/ , $individual_row);
662 push( @array, $row[$column] );
673 # Returns the number of individuals in the data set.
674 $self -> synchronize
;
675 $num = scalar @
{$self -> {'individuals'}};
684 $self -> synchronize
;
686 my $first_id = $self -> {'individuals'}[0];
688 debug
-> die( message
=> "No individuals defined in data object based on ".
689 $self -> full_name
) unless ( defined $first_id );
691 # Check if $column(-index) is defined and valid, else try to find index
694 my @data_row = split( /,/, $first_id -> subject_data
-> [0] );
695 if( $#columns >= 0 ) {
696 foreach my $column ( @columns ) {
697 unless ( defined $column && defined( $data_row[$column-1] ) ) {
698 debug
-> die( message
=> "Error in data -> factors: ".
699 "invalid column number: \"$column\"\n".
700 "Valid column numbers are 1 to ".
701 scalar @
{$first_id -> subject_data
->[0]}."\n" );
704 } elsif ( $#column_heads >= 0 ) {
705 foreach my $column_head ( @column_heads ) {
706 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
707 debug
-> die( message
=> "Error in data -> factors: unknown column: \"$column_head\" ".
708 "Valid column headers are (in no particular order):\n".
709 join(', ',keys(%{$self -> {'column_head_indices'}})) );
711 my $column = $self -> {'column_head_indices'}{$column_head};
712 push( @columns, $column );
713 debug
-> warn( level
=> 2,
714 message
=> "$column_head is in column number $column" );
718 debug
-> die( message
=> "No column or column_head defined" );
721 if( $global_largest or $global_smallest or
722 $largest_per_individual or $smallest_per_individual ) {
723 if( not scalar @
{$self -> {'individuals'}} == scalar @
{$against_data -> individuals
} ) {
724 debug
-> die( message
=> "Both data object must hold the same number of individuals ".
725 "and observations when calling data -> diff" );
727 for( my $i = 0; $i < scalar @
{$self -> {'individuals'}}; $i++ ) {
728 my %id_diffs = %{$self -> {'individuals'}[$i] ->
729 diff
( against_individual
=> $against_data -> individuals
-> [$i],
730 columns
=> \
@columns,
731 absolute_diff
=> $absolute_diff,
732 diff_as_fraction
=> $diff_as_fraction,
733 largest
=> ( $global_largest or $largest_per_individual ),
734 smallest
=> ( $global_smallest or $smallest_per_individual ) )};
735 if( $global_largest ) {
736 for( my $j = 0; $j <= $#columns; $j++ ) {
737 my $label = defined $column_heads[$j] ?
$column_heads[$j] : $columns[$j];
738 if( not defined $diff_results{$label} or not defined $diff_results{$label}{'diff'} or
739 $id_diffs{$columns[$j]}{'diff'} > $diff_results{$label}{'diff'} ) {
740 $diff_results{$label}{'diff'} = $id_diffs{$columns[$j]}{'diff'};
741 $diff_results{$label}{'self'} = $id_diffs{$columns[$j]}{'self'};
742 $diff_results{$label}{'test'} = $id_diffs{$columns[$j]}{'test'};
748 die "data -> diff is only implemented for finding the largest difference at any observation at this point\n";
757 if ( defined $parm and $parm ne $self -> {'filename'} ) {
758 $self -> {'filename'} = $parm;
759 $self -> {'data_id'} = undef;
770 my %factors = $self -> factors
( 'return_occurences' => 1,
771 'unique_in_individual' => $unique_in_individual,
772 'column_head' => $column_head,
773 'column' => $column);
776 while (my ($factor, $amount) = each %factors) {
777 if ( $factor == $self -> {'missing_data'} && $ignore_missing ) {
783 while (my ($factor, $amount) = each %factors) {
784 if ( $factor == $self -> {'missing_data'} && $ignore_missing ) {
787 $fractions{$factor} = $amount/$sum;
799 # Either column (number, starting at 1) or column_head must be specified.
801 # The default behaviour is to return a hash with the factors as keys
802 # and as values references to arrays with the order numbers (not the ID numbers)
803 # of the individuals that contain this factor
805 # If unique_in_individual is true (1), the returned hash will contain
806 # an element with key 'Non-unique values found' and value 1 if any
807 # individual contain more than one value in the specified column.
809 # Return occurences will calculate the occurence of each
810 # factor value. Several occurences in one individual counts as
811 # one occurence. The elements of the returned hash will have the factors
812 # as keys and the number of occurences as values.
815 $self -> synchronize
;
817 # Check if $column(-index) is defined and valid, else try to find index
819 my $first_id = $self -> {'individuals'}[0];
821 debug
-> die( message
=> "No individuals defined in data object based on ".
822 $self -> full_name
) unless ( defined $first_id );
824 my @data_row = split( /,/, $first_id -> subject_data
-> [0] );
825 unless ( defined $column && defined( $data_row[$column-1] ) ) {
826 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
827 debug
-> die( message
=> "Error in data -> factors: unknown column: \"$column_head\" ".
828 "or invalid column number: \"$column\".\n".
829 "Valid column numbers are 1 to ".scalar @data_row ."\n".
830 "Valid column headers are (in no particular order):\n".
831 join(', ',keys(%{$self -> {'column_head_indices'}})) );
833 $column = $self -> {'column_head_indices'}{$column_head};
834 debug
-> warn( level
=> 2,
835 message
=> "$column_head is in column number $column" );
840 foreach my $individual ( @
{$self -> {'individuals'}} ) {
841 my @ifactors = keys %{$individual -> factors
( column
=> $column )};
842 if ( scalar @ifactors > 1 and $unique_in_individual ) {
843 %factors = ( 'Non-unique values found' => 1 );
846 debug
-> die( message
=> "No value found in column $column in individual ".
847 $individual -> idnumber
) if ( scalar @ifactors == 0 );
849 # Return occurences will calculate the occurence of each
850 # factor value. Several occurences in one individual counts as
853 if ( $return_occurences ) {
854 foreach my $ifactor ( @ifactors ) {
855 $factors{$ifactor}++;
858 foreach my $ifactor ( @ifactors ) {
859 push( @
{$factors{$ifactor}}, $key );
869 # {{{ find_individual
871 # start find_individual
872 # foreach my $tmp_ind ( @{$self -> individuals} ) {
873 # if ( $tmp_ind -> key == $key ) {
874 # $individual = $tmp_ind;
878 # if ( defined $individual ) {
880 # $individual = $individual -> copy;
883 # print "No individual with key $key found in call to ".
884 # "data -> find_individual\n" if ( $self -> debug );
886 # end find_individual
894 my $header = $self -> {'header'};
896 # format the data for NONMEM (simple comma-separated layout)
897 if ( defined $self -> {'comment'} ) {
898 my @comment = @
{$self -> {'comment'}};
904 my $wrap = ( defined $self -> {'wrap_column'} and
905 defined $self -> {'cont_column'} );
907 my @primary_columns = defined $self -> {'primary_columns'} ?
908 @
{$self -> {'primary_columns'}} : ();
909 my @secondary_columns = defined $self -> {'secondary_columns'} ?
910 @
{$self -> {'secondary_columns'}} : ();
911 if ( defined $header and defined $self -> {'ignoresign'} ) {
913 if ( $self -> {'ignoresign'} ne '@' ) {
914 $istr = $self -> {'ignoresign'};
918 for ( my $i = 0; $i <= $#secondary_columns ; $i++ ) {
920 for ( my $j = 0; $j < scalar @
{$secondary_columns[$i]} ; $j++ ) {
921 my $jstr = $j == 0 ?
'' : ',';
922 $sstr = $sstr.$jstr.$secondary_columns[$i][$j][0];
924 push( @h_data, $sstr."\n" );
926 push( @form_data, @h_data );
928 for ( my $i = 0; $i <= $#primary_columns ; $i++ ) {
929 my $jstr = $i == 0 ?
'' : ',';
930 $pstr = $pstr.$jstr.$primary_columns[$i][0];
932 push( @form_data, $pstr."\n" );
934 push( @form_data, $istr.join(',',@
{$self -> {'header'}})."\n" );
938 foreach my $individual ( @
{$self -> {'individuals'}} ) {
939 foreach my $row ( @
{$individual -> subject_data
} ) {
941 for ( my $i = 0; $i <= $#secondary_columns ; $i++ ) {
943 for ( my $j = 0; $j < scalar @
{$secondary_columns[$i]} ; $j++ ) {
944 my $jstr = $j == 0 ?
'' : ',';
945 if ( $secondary_columns[$i][$j][0] eq 'CONT' ) {
946 $sstr = $sstr.$jstr.'1';
948 my @data_row = split( /,/, $row );
949 $sstr = $sstr.$jstr.$data_row[$secondary_columns[$i][$j][1]];
952 push( @r_data, $sstr."\n" );
954 push( @form_data, @r_data );
956 for ( my $i = 0; $i <= $#primary_columns ; $i++ ) {
957 my $jstr = $i == 0 ?
'' : ',';
958 if ( $primary_columns[$i][0] eq 'CONT' ) {
959 $pstr = $pstr.$jstr.'0';
961 my @data_row = split( /,/, $row );
962 $pstr = $pstr.$jstr.$data_row[$primary_columns[$i][1]];
965 push( @form_data, $pstr."\n" );
969 foreach my $individual ( @
{$self -> {'individuals'}} ) {
970 foreach my $row ( @
{$individual -> subject_data
} ) {
971 push( @form_data, $row ."\n" );
984 # This method removes columns that has '=DROP' value in the
985 # model header as given by $INPUT. The model header must be
986 # transfered to this method through the model_header
987 # argument. The model_header argument should be a
988 # two-dimensional array where each position in the first
989 # dimension should be a reference to a 1*2 array holding the
990 # column name and value. Any ignore-sign must be removed.
992 debug
-> die( message
=> 'model header must be defined' )
993 if ( $#model_header < 0 );
994 # Important that the drop_dropped method of the model::problem
995 # class is in sync with this method.
996 $self -> synchronize
;
998 $self -> {'header'} = [];
1001 for( my $i = 0; $i <= $#model_header; $i++ ) {
1002 $self -> {'idcolumn'} = $counter if ( $model_header[$i][0] eq 'ID' );
1003 if( $model_header[$i][1] eq 'DROP' and
1004 not $model_header[$i][0] =~ /DAT(E|1|2|3)/ ) {
1009 push( @
{$self -> {'header'}}, $model_header[$i][0] );
1013 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1014 $individual -> drop_columns
( drop
=> \
@drop );
1017 $self -> {'synced'} = 0;
1018 # $Data::Dumper::Maxdepth = 2;
1020 # die Dumper $self -> {'individuals'};
1029 $self -> synchronize
;
1030 $self -> cont_column
( $cont_column ) if ( defined $cont_column );
1031 $self -> wrap_column
( $wrap_column ) if ( defined $wrap_column );
1032 $self -> prepare_wrap
( model_header
=> \
@model_header );
1033 @secondary_columns = @
{$self -> {'secondary_columns'}}
1034 if ( defined $self -> {'secondary_columns'} );
1035 @primary_columns = @
{$self -> {'primary_columns'}}
1036 if ( defined $self -> {'primary_columns'} );
1044 $self -> {'cont_column'} = undef;
1045 $self -> {'wrap_column'} = undef;
1046 $self -> {'secondary_columns'} = undef;
1047 $self -> {'primary_columns'} = undef;
1056 my $cont_column = $self -> {'cont_column'};
1057 my $wrap_column = $self -> {'wrap_column'};
1058 debug
-> die( message
=> 'cont_column ('.$cont_column.') must be less or equal '.
1059 'to the requested number of columns in each row ('.
1060 ($wrap_column).')' )
1061 if ( $cont_column > $wrap_column );
1063 if ( scalar @model_header > 0 ) {
1064 @header = @model_header;
1066 @header = @
{$self -> {'header'}};
1069 my ( @primary, @secondary, @date_columns );
1071 for ( my $i = 0; $i <= $#header; $i++ ) {
1072 my $name = ref( $header[$i] ) eq 'ARRAY' ?
$header[$i][0] : $header[$i];
1073 my $value = ref( $header[$i] ) eq 'ARRAY' ?
$header[$i][1] : undef;
1074 next if ( $name eq 'ID' );
1076 foreach my $prim ( @primary_column_names ) {
1078 ( $name eq $prim or $value eq $prim ) ) {
1079 push( @primary, [$name, $i, $value] );
1081 my $col = ($#primary+2)>= $cont_column ?
($#primary+3) : ($#primary+2);
1082 push( @date_columns, $col ) if ( $name =~ /DAT(E|1|2|3)/ );
1085 push( @secondary, [$name, $i, $value] ) if ( not $found );
1088 my $prim_num = scalar @primary;
1089 debug
-> die( message
=> 'The number of primary columns (that need to '.
1090 'be part of the row with CONT=0) ('.($prim_num+1).
1091 ') is larger than the required number of columns (wrap_column='.
1092 $wrap_column.') - 1' )
1093 if ( scalar $prim_num > ($wrap_column-2) );
1095 my ( $i, $dum ) = ( 0, 1 );
1097 for ( my $j = 1; $j <= $wrap_column; $j++ ) {
1099 push( @tmp, ['ID', $self -> {'idcolumn'}-1] );
1100 } elsif ( $j == $wrap_column ) {
1101 if ( $j == $cont_column ) {
1102 push( @tmp, ['CONT', undef] );
1105 if ( defined $primary[$i] ) {
1106 $val = $primary[$i];
1107 } elsif ( defined $secondary[0] ) {
1108 $val = shift(@secondary);
1110 $val = ['XX'.$dum++,$self -> {'idcolumn'}-1];
1115 push( @
{$self -> {'primary_columns'}}, @tmp );
1117 if ( $j == $cont_column ) {
1118 push( @tmp, ['CONT', undef] );
1120 if ( $i <= $#primary ) {
1121 push( @tmp, $primary[$i] );
1124 my $val = defined $secondary[0] ?
shift(@secondary) :
1125 ['XX'.$dum++,$self -> {'idcolumn'}-1];
1133 while ( $i <= $#secondary ) {
1135 for ( my $j = 1; $j <= $wrap_column; $j++ ) {
1137 push( @tmp, ['ID', $self -> {'idcolumn'}-1] );
1138 } elsif ( $j == $wrap_column ) {
1139 if ( $j == $cont_column ) {
1140 push( @tmp, ['CONT', undef] );
1142 my $val = defined $secondary[$i] ?
$secondary[$i] :
1143 ['XX'.$dum++,$self -> {'idcolumn'}-1];
1147 unshift( @
{$self -> {'secondary_columns'}}, \
@tmp );
1149 if ( $j == $cont_column ) {
1150 push( @tmp, ['CONT', undef] );
1153 if ( $#date_columns >= 0 ) {
1154 foreach my $col ( @date_columns ) {
1155 # This is a date column which may have to be dropped
1156 # and thus will not appear as a secondary
1157 # column. Nothing should be pushed. The indexes in
1158 # model::problem::pk::_format_record will be ok.
1159 $isdate = 1 if ( $col == $j ) ;
1163 push( @tmp, ['XX'.$dum++,$self -> {'idcolumn'}-1] );
1165 if ( $i <= $#secondary ) {
1166 push( @tmp, $secondary[$i] );
1169 push( @tmp, ['XX'.$dum++,$self -> {'idcolumn'}-1] );
1181 # {{{ have_missing_data
1182 start have_missing_data
1184 # Either I<column> or I<column_head> must be specified.
1186 # This method looks through the data column with index I<column> or
1187 # (optional) header name I<column_head> and returns O if no missing
1188 # data indicator was found or 1 otherwise.
1190 $self -> synchronize
;
1191 my $first_id = $self -> {'individuals'}[0];
1192 debug
-> die( message
=> "No individuals defined in data object based on ".
1193 $self -> full_name
) unless ( defined $first_id );
1194 my @data_row = split( /,/ , $first_id -> subject_data
-> [0] );
1195 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1196 unless(defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})){
1197 die "Error in data -> have_missing_data: unknown column: \"$column_head\" or invalid column number: \"$column\"\n";
1199 $column = $self -> {'column_head_indices'}{$column_head};
1202 $self -> flush
if ( $self -> {'target'} eq 'disk' );
1204 # In case anyone wonders, the ternary statment ( bool ? true :
1205 # false ) below will possibly make a minuscle memory
1206 # optimization. But hey, why not :)
1208 $return_value = defined $self -> {'have_missing_data'} ?
$self -> {'have_missing_data'} -> {$column} : 0;
1210 end have_missing_data
1211 # }}} have_missing_data
1216 #$self -> synchronize;
1217 push( @
{$self -> {'individuals'}}, @
{$mergeobj -> individuals
} );
1226 # Either column or column_head must be specified. Column_head must be a string that
1227 # identifies a column in the (optional ) data file header.
1229 # The if-statement below used to be a cache of allready calculated
1230 # means. But since individuals can be accessed in so many ways, we
1231 # don't know when this cache should be updated. Its easier to
1232 # recalculate the max. Maybe we can include this optimization in the
1233 # future, if it turns out to be a bottleneck
1234 # my $tmp_column = $self -> {'column_head_indices'}{$column_head};
1235 # if ( defined $self -> {'max'}[$tmp_column] ) {
1236 # $return_value = $self -> {'max'}[$tmp_column] ;
1238 $self -> synchronize
;
1239 my $first_id = $self -> {'individuals'}[0];
1240 debug
-> die( message
=> "data -> max: No individuals defined in data object based on " .
1241 $self -> full_name
) unless defined $first_id;
1243 my @data_row = split( /,/ , $first_id -> subject_data
->[0] );
1245 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1246 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
1247 die "Error in data -> max: unknown column: \"$column_head\" or invalid column number: \"$column\"\n";
1249 $column = $self -> {'column_head_indices'}{$column_head};
1252 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1253 my $ifactors = $individual -> factors
( 'column' => $column );
1254 foreach ( keys %{$ifactors} ) {
1255 next if ( $_ == $self -> {'missing_data_token'} );
1256 if ( defined ($return_value) ) {
1257 $return_value = $_ > $return_value ?
$_ : $return_value;
1264 # $self -> {'max'}[$column] = $return_value;
1265 $self -> flush
if ( $self -> {'target'} eq 'disk' );
1277 my $tmp_column = $self -> {'column_head_indices'}{$column_head};
1279 # The if-statement below used to be a cache of allready calculated
1280 # means. But since individuals can be accessed in so many ways, we
1281 # don't know when this cache should be updated. Its easier to
1282 # recalculate the min. Maybe we can include this optimization in the
1283 # future, if it turns out to be a bottleneck
1284 # if ( defined $self -> {'min'}[$tmp_column] ) {
1285 # $return_value = $self -> {'min'}[$tmp_column] ;
1287 $self -> synchronize
;
1288 my $first_id = $self -> {'individuals'}[0];
1289 die "data -> min: No individuals defined in data object based on ",
1290 $self -> full_name
,"\n" unless defined $first_id;
1292 my @data_row = split( /,/ , $first_id -> subject_data
->[0] );
1294 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1295 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
1296 die "Error in data -> min: unknown column: \"$column_head\" or invalid column number: \"$column\"\n";
1298 $column = $self -> {'column_head_indices'}{$column_head};
1301 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1302 my $ifactors = $individual -> factors
( 'column' => $column );
1303 foreach ( keys %{$ifactors} ) {
1304 next if ( $_ == $self -> {'missing_data_token'} );
1305 if ( defined ($return_value) ) {
1306 $return_value = $_ < $return_value ?
$_ : $return_value;
1312 # $self -> {'min'}[$column] = $return_value;
1313 $self -> flush
if ( $self -> {'target'} eq 'disk' );
1325 $self -> synchronize
;
1326 my $first_id = $self -> {'individuals'}[0];
1327 die "data -> median: No individuals defined in data object based on ",
1328 $self -> full_name
,"\n" unless defined $first_id;
1330 my @data_row = split( /,/ , $first_id -> subject_data
->[0] );
1332 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1333 unless(defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})){
1334 die "Error in data -> median: unknown column: \"$column_head\" or invalid column number: \"$column\"\n";
1336 $column = $self -> {'column_head_indices'}{$column_head};
1340 if( defined $self -> {'median'}[$column] ){
1341 return $self -> {'median'}[$column];
1346 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1347 if( $unique_in_individual ){
1348 my $ifactors = $individual -> factors
( 'column' => $column );
1350 foreach ( keys %{$ifactors} ) {
1351 next if ( $_ == $self -> {'missing_data_token'} );
1352 push( @median_array, $_ );
1355 my $ifactors = $individual -> subject_data
;
1357 for(my $i=0; $i<=$#{$ifactors}; $i++ ) {
1358 my @data_row = split( /,/ , $ifactors -> [$i] );
1359 next if ( $data_row[$column-1] == $self -> {'missing_data_token'} );
1360 push(@median_array, $data_row[$column-1]);
1364 @median_array = sort {$a <=> $b} @median_array ;
1366 if( @median_array % 2 ){
1367 $return_value = $median_array[$#median_array / 2];
1369 $return_value = ( $median_array[@median_array / 2] +
1370 $median_array[(@median_array - 2) / 2] ) / 2;
1373 $self -> {'median'}[$column] = $return_value;
1383 # Returns mean value of a column
1384 # If a individual contains more then 1 value (i.e. if an
1385 # individual has different values in different samples a mean
1386 # value of all individuals if calculate first, then the mean
1387 # value of the column If hi_cutoff is defined the mean function
1388 # will cut all value below the cutoff, and set their value to
1389 # 0. It's used to calculate the HI-mean/LOW-mean of a column for
1390 # e.g. Hockey-stick covariates If both hi_cutoff and low_cutoff
1391 # are defined only the hi_cutoff will be used. See L</max>.
1392 my $tmp_column = $self -> {'column_head_indices'}{$column_head};
1393 $self -> synchronize
;
1394 my $first_id = $self -> {'individuals'}[0];
1395 die "data -> mean: No individuals defined in data object based on ",
1396 $self -> full_name
,"\n" unless defined $first_id;
1398 my @data_row = split( /,/, $first_id -> subject_data
->[0] );
1400 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1401 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
1402 die "Error in data -> mean: unknown column: \"$column_head\" or invalid column number: \"$column\"\n";
1404 $column = $self -> {'column_head_indices'}{$column_head};
1408 ## Here the calculation starts
1409 my $num_individuals = 0;
1412 my $all_data_rows=0;
1413 foreach my $individual ( @
{$self ->{'individuals'}} ) {
1415 my $ifactors = $individual -> subject_data
;
1416 my $individual_sum = 0;
1418 for(my $i=0; $i<=$#{$ifactors}; $i++ ) {
1420 # data is stored in strings. We need to split them into an
1423 my @data_row = split( /,/, $ifactors -> [$i] );
1424 if ( $data_row[$column-1] == $self -> {'missing_data_token'} ) {
1425 # print "Skipping row with missing data\n";
1429 if( defined $subset_column and not eval ( $data_row[$subset_column-1].$subset_syntax ) ) {
1430 # print "Skipping row outside subset: syntax: ".($subset_column-1)." $subset_syntax\n";
1434 if (defined $hi_cutoff) {
1435 if ($data_row[$column-1]>$hi_cutoff) {
1436 $individual_sum += $data_row[$column-1]-$hi_cutoff;
1440 if (defined $low_cutoff) {
1441 if ($data_row[$column-1]<$low_cutoff) {
1442 $individual_sum += $low_cutoff - $data_row[$column-1];
1446 $individual_sum += $data_row[$column-1];
1451 if( $global_mean ) {
1452 $sum += $individual_sum;
1453 $num_individuals += $data_rows;
1455 if( $data_rows != 0 ) {
1456 $sum += $individual_sum/$data_rows;
1458 $num_individuals ++;
1460 $all_data_rows += $data_rows;
1462 if( $num_individuals != 0 ) {
1463 $return_value = $sum / $num_individuals;
1465 # print "DR: $all_data_rows\n";
1466 # print "\nNIM: $num_individuals $return_value\n";
1477 # This sub returns standard deviation for a specific column
1478 # If there are more than one sample/individual the value used for that specific
1479 # individual is the mean value of its samples.
1480 # The cut-offs are for hockey stick variables. I.e. If one individual value is
1481 # lower than the hi-cutoff the individual value will be zero.
1482 # HI_cutoff is used to calculate the HI-mean of a column.
1483 # If cut_off is undef it won't be used
1485 my $tmp_column = $self -> {'column_head_indices'}{$column_head};
1486 $self -> synchronize
;
1487 my $first_id = $self -> {'individuals'}[0];
1488 debug
-> die( message
=> "No individuals defined in data object based on ".
1489 $self -> full_name
) unless defined $first_id;
1491 my @data_row = split( /,/ , $first_id -> subject_data
->[0] );
1493 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1494 unless (defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})) {
1495 debug
-> die( message
=> "Unknown column: \"$column_head\" or "
1496 ."invalid column number: \"$column\"" );
1498 $column = $self -> {'column_head_indices'}{$column_head};
1502 ## Here the calculation starts
1503 my $num_individuals = 0;
1506 if (defined $hi_cutoff) {
1507 $mean = $self->mean(column
=> $column,
1508 hi_cutoff
=> $hi_cutoff,
1509 global_mean
=> $global_sd );
1510 } elsif (defined $low_cutoff) {
1511 $mean = $self->mean(column
=> $column,
1512 low_cutoff
=> $low_cutoff,
1513 global_mean
=> $global_sd );
1515 $mean = $self->mean( column
=> $column,
1516 subset_column
=> $subset_column,
1517 subset_syntax
=> $subset_syntax,
1518 global_mean
=> $global_sd );
1521 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1522 my $ifactors = $individual -> subject_data
;
1523 my $individual_sum = 0;
1525 for(my $i=0; $i<=$#{$ifactors}; $i++ ) {
1527 # data is stored in strings. We need to split them into an
1530 my @data_row = split( /,/, $ifactors -> [$i] );
1532 if ( $data_row[$column-1] == $self -> {'missing_data_token'} ) {
1533 # print "Skipping row with missing data\n";
1537 if( defined $subset_column and not eval ( $data_row[$subset_column-1].$subset_syntax ) ) {
1538 # print "Skipping row outside subset: syntax: ".($subset_column-1)." $subset_syntax\n";
1542 if (defined $hi_cutoff) {
1543 if ($data_row[$column-1]>$hi_cutoff) {
1545 $individual_sum += ($data_row[$column-1] - $hi_cutoff - $mean) ** 2;
1547 $individual_sum += $data_row[$column-1]-$hi_cutoff;
1551 if (defined $low_cutoff) {
1552 if ($data_row[$column-1]<$low_cutoff) {
1554 $individual_sum += ($low_cutoff - $data_row[$column-1] - $mean) ** 2;
1556 $individual_sum += $low_cutoff - $data_row[$column-1];
1561 $individual_sum += ($data_row[$column-1] - $mean) ** 2;
1563 $individual_sum += $data_row[$column-1];
1570 $sum += $individual_sum;
1571 $num_individuals += $data_rows;
1573 if( $data_rows != 0 ) {
1574 $sum += ($individual_sum/$data_rows - $mean) ** 2;
1579 if( $num_individuals < 2 ) {
1582 if( $num_individuals != 0 ) {
1583 $return_value = (1/($num_individuals-1)*$sum) ** 0.5;
1596 my $tmp_column = $self -> {'column_head_indices'}{$column_head};
1597 if ( defined $self -> {'range'}[$tmp_column] ) {
1598 $return_value = $self -> {'range'}[$tmp_column];
1600 my $old_target = $self -> {'target'};
1601 $self -> {'target'} = 'mem';
1602 $self -> synchronize
;
1603 $return_value = $self -> max
( column
=> $column,
1604 column_head
=> $column_head ) -
1605 $self -> min
( column
=> $column,
1606 column_head
=> $column_head );
1607 $self -> {'range'}[$column] = $return_value;
1608 if ( $old_target eq 'disk' ) {
1609 $self -> flush
if ( $self -> {'target'} eq 'disk' );
1610 $self -> {'target'} = 'disk';
1620 # Recalculates a column based on expression. Also, see L</max>.
1621 $self -> synchronize
;
1623 # Check if $column(-index) is defined and valid, else try to find index using column_head
1624 my $first_id = $self -> {'individuals'}[0];
1625 die "data -> recalc_column: No individuals defined in data object based on ",
1626 $self -> full_name
,"\n" unless defined $first_id;
1628 my @data_row = split( /,/ , $first_id -> subject_data
->[0] );
1630 unless ( defined $column && defined( $data_row[$column-1] ) ) {
1631 if(defined($column_head) && defined($self -> {'column_head_indices'}{$column_head})){
1632 die "Error in data -> recalc_column: unknown column: \"$column_head\" or column number: \"$column\"\n";
1634 $column = $self -> {'column_head_indices'}{$column_head};
1638 for my $individual ( @
{$self -> {'individuals'}} ) {
1639 $individual -> recalc_column
( column
=> $column,
1640 expression
=> $expression );
1646 # {{{ renumber_ascending
1648 start renumber_ascending
1650 # Renumbers the individuals (changes the subject identifiers) so that
1651 # all have unique integer numbers starting with start_at and
1652 # ascending. The primary use of this
1653 # method is not to order the individuals after their identifiers but to
1654 # ensure that all individuals have unique identifiers.
1656 $self -> synchronize
;
1657 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1658 $individual -> idnumber
( $start_at++ );
1660 $self -> {'synced'} = 0;
1662 end renumber_ascending
1664 # }}} renumber_ascending
1666 # {{{ renumber_descending
1668 start renumber_descending
1670 # See L</renumber_ascending>.
1671 $self -> synchronize
;
1672 foreach my $individual ( @
{$self -> {'individuals'}} ) {
1673 $individual -> idnumber
( $start_at-- );
1675 $self -> {'synced'} = 0;
1677 end renumber_descending
1679 # }}} renumber_descending
1681 # {{{ single_valued_data
1683 start single_valued_data
1687 # ($single_value_data_set, $remainder, $column_indexes) =
1688 # $data_object -> single_valued_data( subset_name => 'subset.dta',
1689 # remainder_name => 'remainder.dta',
1691 # do_not_test_columns => [1..18,24,26];
1693 # my $single_value_column_indexes = $column_indexes -> [0];
1694 # my $all_other_column_indexes = $column_indexes -> [1];
1696 # Analyses the content of each column, based on the
1697 # ID column, and returns two new data objects: One
1698 # that contains all columns that is has only one value per
1699 # individual and one that contains the
1700 # remainding data. This is useful for creating compact 'extra'
1701 # data sets that can be read in via user-defined sub-routines
1702 # when the number of columns needed exceeds the maximum that
1703 # NONMEM allows (e.g. 20 in NONMEM version V).
1705 # The I<do_not_test_columns> argument specifies on which columns
1706 # to skip the single value test
1708 my @multi_value_flags;
1709 my @individuals = @
{$self -> {'individuals'}};
1710 # Initiate the flags:
1711 if ( defined $individuals[0] ) {
1712 my @data = @
{$individuals[0] -> {'subject_data'}};
1713 my @data_row = split( /,/ , $data[0] );
1714 for ( my $i = 0; $i < scalar @data_row; $i++ ) {
1716 foreach my $dntc ( @do_not_test_columns ) {
1717 $dnt_flag = 1 if ( $i == $dntc - 1 );
1719 $multi_value_flags[$i] = $dnt_flag;
1722 die "data -> single_valued_data: No data in ID number 1\n";
1725 for ( my $id = 0; $id <= $#individuals; $id++ ) {
1726 my @data = @
{$individuals[$id] -> {'subject_data'}};
1727 my @data_row = split( /,/, $data[0] );
1728 for ( my $j = 0; $j < scalar @data_row; $j++ ) {
1730 for ( my $i = 0; $i <= $#data; $i++ ) {
1731 my @data_row = split( /,/ , $data[$i] );
1732 $col_unique{$data_row[$j]}++;
1734 my $factors = scalar keys %col_unique;
1735 $multi_value_flags[$j]++ if ( $factors > 1 );
1738 for ( my $i = 0; $i <= $#multi_value_flags; $i++ ) {
1739 if ( $multi_value_flags[$i] ) {
1740 push ( @
{$column_indexes[1]}, $i + 1);
1742 push ( @
{$column_indexes[0]}, $i + 1);
1745 ( $single_value_data_set, $remainder ) =
1746 $self -> subset_vertically
( column_indexes
=> $column_indexes[0],
1747 subset_name
=> $subset_name,
1748 return_remainder
=> 1,
1749 remainder_name
=> $remainder_name,
1751 keep_first_row_only
=> 1);
1753 end single_valued_data
1757 # {{{ subset_vertically
1759 start subset_vertically
1763 # $subset = $data_object -> subset_vertically ( column_indexes => [1,2,6],
1764 # subset_name => 'subset.dta' );
1766 # This basic usage returns a new data object containing
1767 # columns 1,2 and 6 from the original data plus the
1768 # idcolumn. The new data object will be associated with the
1769 # file 'subset.dta'.
1771 # You get the remaining data, i.e. the original data minus
1772 # the created subset by specifying
1774 # ( $subset, $remainder ) =
1775 # $data_object -> subset_vertically ( column_indexes => [1,2,6],
1776 # subset_name => 'subset.dta',
1777 # return_remainder => 1,
1778 # remainder_name => 'remainder.dta' );
1780 # If you would like to flush the created data sets to disk and
1781 # save memory, set the I<target> argument to 'disk'. The
1782 # default value 'mem' will keep the whole data object in RAM.
1784 # The I<keep_first_row_only> argument can be used to reduce
1785 # the size of the subset data obejct by excluding all but the
1786 # first row of data from each individual.
1788 my @individuals = @
{$self -> {'individuals'}};
1789 # Create remainder index array if necessary
1790 my @remainder_indexes;
1791 if ( defined $individuals[0] ) {
1792 my @data = @
{$individuals[0] -> {'subject_data'}};
1793 my $idcolumn = $individuals[0] -> {'idcolumn'};
1794 # print "IC: $idcolumn\n";
1796 foreach my $use_index ( @column_indexes ) {
1797 $id_flag = 1 if ( $use_index == $idcolumn );
1799 if ( $return_remainder ) {
1800 # @remainder_indexes = ( $idcolumn );
1801 for ( my $i = 0; $i < scalar split(/,/,$data[0]); $i++ ) {
1803 foreach my $use_index ( @column_indexes ) {
1804 $rem_flag = 0 if ( $i == $use_index -1 );
1806 # $i == $idcolumn -1 );
1808 push( @remainder_indexes, $i + 1 ) if ( $rem_flag );
1810 unshift( @remainder_indexes, $idcolumn ) if ( $id_flag );
1812 unshift( @column_indexes, $idcolumn ) unless ( $id_flag );
1814 die "data -> single_valued_data: No data in ID number 1\n";
1817 # print "SS: @column_indexes\n";
1818 # print "R : @remainder_indexes\n";
1822 for ( my $id = 0; $id <= $#individuals; $id++ ) {
1823 my $idnumber = $individuals[$id] -> idnumber
;
1824 my $idcolumn = $individuals[$id] -> idcolumn
;
1825 my @data = @
{$individuals[$id] -> {'subject_data'}};
1828 my $use_rows = $keep_first_row_only ?
0 : $#data;
1829 for ( my $i = 0; $i <= $use_rows; $i++ ) {
1831 my @data_row = split( /,/, $data[$i] );
1832 foreach my $use_index ( @column_indexes ) {
1833 push( @new_row, $data_row[$use_index-1] );
1835 # print "@new_row $#new_row\n";
1836 push( @new_data, join( ',', @new_row ) );
1838 for ( my $i = 0; $i <= $#data; $i++ ) {
1839 if ( $return_remainder ) {
1841 my @data_row = split( /,/, $data[$i] );
1842 foreach my $use_index ( @remainder_indexes ) {
1843 push( @new_row_2, $data_row[$use_index-1] );
1845 # print "@new_row_2 $#new_row_2\n";
1846 push( @new_data_2, join( ',' , @new_row_2 ) );
1849 my $new_id = data
::individual
-> new
( idnumber
=> $idnumber,
1850 idcolumn
=> $idcolumn,
1851 subject_data
=> \
@new_data );
1852 push( @new_ids, $new_id );
1853 if ( $return_remainder ) {
1855 $new_id_2 = data
::individual
-> new
( idnumber
=> $idnumber,
1856 idcolumn
=> $idcolumn,
1857 subject_data
=> \
@new_data_2 );
1858 push( @new_ids_2, $new_id_2 );
1861 my @header = @
{$self -> {'header'}};
1863 foreach my $use_index ( @column_indexes ) {
1864 push( @new_header, @header[$use_index-1] );
1867 if( defined $self -> {'comment'} ){
1868 my @comment = @
{$self -> {'comment'}};
1869 $comment = \
@comment;
1871 $subset = data
-> new
( filename
=> $subset_name,
1872 directory
=> $self -> {'directory'},
1873 ignoresign
=> $self -> {'ignoresign'},
1874 header
=> \
@new_header,
1875 comment
=> $comment,
1876 individuals
=> \
@new_ids,
1878 ignore_missing_files
=> 1 );
1879 if ( $return_remainder ) {
1881 foreach my $use_index ( @remainder_indexes ) {
1882 push( @new_header_2, @header[$use_index-1] );
1884 $remainder = data
-> new
( filename
=> $remainder_name,
1885 directory
=> $self -> {'directory'},
1886 ignoresign
=> $self -> {'ignoresign'},
1887 header
=> \
@new_header_2,
1888 comment
=> $comment,
1889 individuals
=> \
@new_ids_2,
1891 ignore_missing_files
=> 1 );
1894 end subset_vertically
1902 # if ( defined $expression and defined $bins ) {
1903 # die "data -> subset: expression and bins may not both be specified\n";
1905 # if ( not ( defined $expression or defined $bins ) ) {
1906 # die "data -> subset: expression or bins must be specified\n";
1908 $self -> synchronize
;
1909 my @header = @
{$self -> {'header'}};
1910 my @comment = defined $self -> {'comment'} ? @
{$self -> {'comment'}} : ();
1914 my @ids = @
{$self -> {'individuals'}};
1915 if ( defined $stratify_on ) {
1916 my $work_data = $self -> copy
( filename
=> 'work_data.dta',
1918 my %strata = %{$work_data -> factors
( column
=> $stratify_on )};
1919 # $Data::Dumper::Maxdepth = 1;
1920 # print Dumper \%strata;
1922 while ( my ( $factor, $keys ) = each %strata ) {
1923 foreach my $key ( @
{$keys} ) {
1925 while ( defined $rnd_ids{$factor}{$rnd_num} ) {
1928 $rnd_ids{$factor}{$rnd_num} = $ids[$key];
1932 while ( my ( $factor, $rnd_nums ) = each %rnd_ids ) {
1933 my @sort_rnd_nums = sort { $a <=> $b } keys %{$rnd_nums};
1934 for ( my $i = 0; $i <= $#sort_rnd_nums; $i ) {
1935 for ( my $j = 0; $j < $bins; $j++ ) {
1937 push( @subset_ids, [$rnd_ids{$factor}{$sort_rnd_nums[$i]} -> copy
] );
1938 push( @incl_ids, [$rnd_ids{$factor}{$sort_rnd_nums[$i]} -> idnumber
] );
1940 push( @
{$subset_ids[$j]}, $rnd_ids{$factor}{$sort_rnd_nums[$i]} -> copy
);
1941 push( @
{$incl_ids[$j]}, $rnd_ids{$factor}{$sort_rnd_nums[$i]} -> idnumber
);
1944 last if $i > $#sort_rnd_nums;
1949 for ( my $j = 0; $j < $bins; $j++ ) {
1950 my $sdata = data
-> new
( header
=> \
@header,
1951 comment
=> \
@comment,
1952 ignoresign
=> $self -> {'ignoresign'},
1953 individuals
=> $subset_ids[$j],
1954 ignore_missing_files
=> 1,
1956 idcolumn
=> $self -> {'idcolumn'},
1957 filename
=> "subset_$j.dta" );
1959 push( @subsets, $sdata );
1962 for ( my $i = 0; $i <= $#ids; $i++ ) {
1964 while ( defined $rnd_ids{$rnd_num} ) {
1967 $rnd_ids{$rnd_num} = $ids[$i];
1969 my @keys = sort { $a <=> $b } keys %rnd_ids;
1971 for ( my $i = 0; $i <= $#keys; $i ) {
1972 for ( my $j = 0; $j < $bins; $j++ ) {
1974 push( @subset_ids, [$rnd_ids{$keys[$i]} -> copy
] );
1975 push( @incl_ids, [$rnd_ids{$keys[$i]} -> idnumber
] );
1977 push( @
{$subset_ids[$j]}, $rnd_ids{$keys[$i]} -> copy
);
1978 push( @
{$incl_ids[$j]}, $rnd_ids{$keys[$i]} -> idnumber
);
1981 last if $i > $#keys;
1985 for ( my $j = 0; $j < $bins; $j++ ) {
1986 my $sdata = data
-> new
( header
=> \
@header,
1987 comment
=> \
@comment,
1988 ignoresign
=> $self -> {'ignoresign'},
1989 individuals
=> $subset_ids[$j],
1990 ignore_missing_files
=> 1,
1992 idcolumn
=> $self -> {'idcolumn'},
1993 filename
=> "subset_$j.dta" );
1995 push( @subsets, $sdata );
2007 $self -> synchronize
;
2008 my @header = @
{$self -> {'header'}};
2009 my @comment = defined $self -> {'comment'} ? @
{$self -> {'comment'}} : ();
2010 my @subset_inds = ();
2012 foreach my $individual ( @
{$self -> {'individuals'}} ) {
2013 if ( $individual -> evaluate_expression
( column
=> $based_on,
2014 expression
=> $expression ) ) {
2015 push( @subset_inds, $individual -> copy
);
2016 push( @incl_individuals, $individual -> idnumber
);
2017 push( @included_keys, $key );
2021 $subset = data
-> new
( header
=> \
@header,
2022 comment
=> \
@comment,
2023 ignoresign
=> $self -> {'ignoresign'},
2024 individuals
=> \
@subset_inds,
2025 idcolumn
=> $self -> {'idcolumn'},
2026 filename
=> "subset.dta" );
2036 if ( $parm eq 'disk' and $self -> {'target'} eq 'mem' ) {
2037 $self -> {'target'} = 'disk';
2039 } elsif ( $parm eq 'mem' and $self -> {'target'} eq 'disk' ) {
2040 $self -> {'target'} = 'mem';
2041 $self -> synchronize
;
2052 die "ERROR: data -> _write: No filename set in data object.\n"
2053 if( $filename eq '' );
2055 # $Data::Dumper::Maxdepth = 2;
2056 # die Dumper $self -> {'individuals'};
2058 if( not defined $self -> {'individuals'} ){
2060 # If we don't have any individuals and write to a new
2061 # filename, we must first read individuals from the old
2062 # file. A call to synchronize will do that. There is no risk
2063 # of a infinite loop here since synchronize allways writes to
2066 unless( $filename eq $self -> full_name
){
2067 $self -> synchronize
;
2071 open(FILE
,">$filename") ||
2072 die "Could not create $filename\n";
2073 my $data_ref = $self -> format_data
;
2074 my @data = @
{$data_ref};
2080 # if ( $PsN::config -> {'_'} -> {'use_database'} and
2081 # $self -> {'use_data_table'} ) {
2082 # # Backslashes messes up the sql syntax
2083 # my $file_str = $self->{'filename'};
2084 # my $dir_str = $self->{'directory'};
2085 # $file_str =~ s/\\/\//g;
2086 # $dir_str =~ s/\\/\//g;
2089 # my $md5sum = md5_hex(OSspecific::slurp_file($self-> full_name ));
2090 # my ( $date_str, $time_str );
2091 # if ( $Config{osname} eq 'MSWin32' ) {
2092 # $date_str = `date /T`;
2093 # $time_str = ' '.`time /T`;
2096 # $date_str = `date`;
2100 # my $date_time = $date_str.$time_str;
2101 # my $dbh = DBI -> connect("DBI:mysql:host=".$PsN::config -> {'_'} -> {'database_server'}.
2102 # ";databse=".$PsN::config -> {'_'} -> {'project'},
2103 # $PsN::config -> {'_'} -> {'user'},
2104 # $PsN::config -> {'_'} -> {'password'},
2106 # 'RaiseError' => 1});
2108 # if ( defined $self -> {'data_id'} ) {
2109 # $sth = $dbh -> prepare( "UPDATE ".$PsN::config -> {'_'} -> {'project'}.
2111 # "SET filename='$file_str',date='$date_time',".
2112 # "directory='$dir_str',md5sum='$md5sum' ".
2113 # "WHERE data_id='".$self -> {'data_id'}."'" );
2114 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
2116 # $sth = $dbh -> prepare("INSERT INTO ".$PsN::config -> {'_'} -> {'project'}.
2117 # ".data (filename,date,directory,md5sum) ".
2118 # "VALUES ('$file_str', '$date_time', '$dir_str','".
2121 # $self -> {'data_id'} = $sth->{'mysql_insertid'};
2124 # $dbh -> disconnect;
2134 # synchronizes the object with the file on disk and empties
2135 # most of the objects attributes to save memory.
2136 if( defined $self -> {'individuals'} and
2137 ( !$self -> {'synced'} or $force ) ) {
2140 # $self -> {'header'} = undef;
2141 $self -> {'comment'} = undef;
2142 $self -> {'individuals'} = undef;
2143 $self -> {'synced'} = 0;
2144 $self -> {'column_head_indices'} = undef;
2145 $self -> {'have_missing_data'} = undef;
2154 # synchronizes the object with the file on disk
2155 unless( $self -> {'synced'} ){
2156 if( defined $self -> {'individuals'} and
2157 scalar @
{$self -> {'individuals'}} > 0 ){
2158 # We should not read new data from file if we
2159 # have an individuals defined?
2160 # Perhaps there should be an attribute
2161 # 'from_file' that overrides this and reads in
2162 # the data from the file specified in filename
2163 # and overwrites whatever the object already
2165 # if( -e $self -> {'filename'} ){
2166 # $self -> _read_header;
2167 # $self -> _read_individuals;
2171 if( -e
$self -> full_name
){
2172 unless( defined $self -> {'header'} and scalar @
{$self -> {'header'}} > 0 ){
2173 $self -> _read_header
;
2175 $self -> _read_individuals
;
2177 debug
-> die( message
=> "Fatal error: datafile: " . $self -> full_name
. " does not exist." );
2183 foreach my $head ( @
{$self -> {'header'}} ){
2184 $self -> {'column_head_indices'} -> {$head} = $i;
2187 $self -> {'synced'} = 1;
2193 # {{{ _fisher_yates_shuffle
2195 start _fisher_yates_shuffle
2197 my $arr_ref = $parm{'array'};
2198 debug
-> warn( level
=> 1,
2199 message
=> "Array of zero length received" )
2200 if ( scalar @
{$arr_ref} < 1 );
2202 for ($i = @
$arr_ref; --$i; ) {
2203 my $j = random_uniform_integer
(1,0,$i);
2204 # my $j = int rand ($i+1);
2205 # print "$j $j_new\n";
2206 @
$arr_ref[$i,$j] = @
$arr_ref[$j,$i];
2209 end _fisher_yates_shuffle
2211 # }}} _fisher_yates_shuffle
2217 my $filename = $self -> full_name
;
2218 my $ignoresign = $self -> ignoresign
;
2219 my ( @data, @new_record, $row, $tmp_row, @header, $hdrstring );
2221 open(DATAFILE
,"$filename") ||
2222 die "Could not open $filename for reading";
2224 while (<DATAFILE
>) {
2226 # @new_record = split(/\,|\s+/,$_);
2227 if ( ! (/^\s*\d+|^\s*\./) ) {
2228 $data[$row] = $tmp_row;
2231 # We have reached the first data-row, return.
2232 $columns = scalar split(/\,\s*|\s+/);
2238 if ( defined $self -> {'cont_column'} and not $self -> {'table_file'} ) {
2239 my $data_len = $#data;
2240 for ( my $i = $data_len; $i >= 0; $i-- ) {
2241 my @arr = split(/\,\s*|\s+/,$data[$i]);
2242 if ( $arr[$self -> {'cont_column'}-1] eq 'CONT' ) {
2243 my $start = $i == $data_len ?
0 : 1;
2244 for ( my $j = $start; $j <= $#arr; $j++ ) {
2245 if ( $j != ($self -> {'cont_column'}-1) ) {
2246 push( @header, $arr[$j] );
2252 $header[0] =~ s/$ignoresign//
2253 if ( defined $self->ignoresign );
2254 shift( @header ) if ( $header[0] eq "" );
2256 chomp( $hdrstring = pop(@data));
2257 @header = split(/\,\s*|\s+/,$hdrstring);
2258 $header[0] =~ s/$ignoresign//
2259 if ( defined $self->ignoresign );
2260 shift( @header ) if ( $header[0] eq "" );
2261 if( $self -> {'table_file'} ) {
2263 for( my $i = 1; $i <= scalar @header; $i++ ) {
2264 if( $header[$i-1] eq 'CONT' ) {
2265 if ( defined $self -> {'cont_column'} and not $i == $self -> {'cont_column'} ) {
2266 debug
-> warn( level
=> 1,
2267 message
=> "The supplied columns for the CONT data item (".
2268 $self -> {'cont_column'}.") does not match the column where the CONT ".
2269 "header was found ($i), using $i" );
2271 $self -> {'cont_column'} = $i;
2273 push( @new_header, $header[$i-1] );
2276 @header = @new_header;
2277 for( my $i = 1; $i <= scalar @header; $i++ ) {
2278 if( $header[$i-1] eq 'ID' ) {
2279 if ( defined $self -> {'idcolumn'} and not $i == $self -> {'idcolumn'} ) {
2280 debug
-> warn( level
=> 1,
2281 message
=> "The supplied columns for the ID data item (".
2282 $self -> {'idcolumn'}.") does not match the column where the CONT ".
2283 "header was found ($i), using $i" );
2285 $self -> {'idcolumn'} = $i;
2291 # I'm not certain on how to deal with this conflict. I'm leaving it commented because I believe this code should not be here.
2293 #<<<<<<< data_subs.pm
2294 # $header[0] =~ s/$ignoresign//
2295 # if ( defined $self->ignoresign );
2296 # shift( @header ) if ( $header[0] eq "" );
2300 # It is ok with data sets without a header.
2301 # unless( scalar @header > 0 ){ debug -> die( message => 'Datafile ' . $self -> full_name . ' is empty.' ); }
2303 $self -> {'header'} = \
@header;
2304 $self -> {'comment'} = \
@data;
2305 # if ( $PsN::config -> {'_'} -> {'use_database'} and
2306 # $self -> {'use_data_table'} ) {
2307 # my $dbh = DBI -> connect("DBI:mysql:host=".$PsN::config -> {'_'} -> {'database_server'}.
2308 # ";databse=".$PsN::config -> {'_'} -> {'project'},
2309 # $PsN::config -> {'_'} -> {'user'},
2310 # $PsN::config -> {'_'} -> {'password'},
2311 # {'RaiseError' => 1});
2312 # if ( scalar @header < 1 ) {
2313 # for ( my $i = 1; $i <= $columns; $i++ ) {
2314 # push( @header, $i );
2317 # for ( my $i = 0; $i <= $#header; $i++ ) {
2318 # my $sth = $dbh -> prepare("INSERT INTO ".$PsN::config -> {'_'} -> {'project'}.
2320 # "(name,number,data_id) ".
2321 # "VALUES ('".$header[$i]."', '".($i+1).
2322 # "', '".$self -> {'data_id'}."' )");
2324 # push( @{$self -> {'data_column_ids'}}, $sth->{'mysql_insertid'} );
2327 # $dbh -> disconnect;
2334 # {{{ _read_individuals
2336 start _read_individuals
2338 my $idcol = $self -> idcolumn
;
2339 my $filename = $self -> full_name
;
2340 debug
-> warn( level
=> 1,
2341 message
=> "Building array of individuals from file " . $self -> {'filename'} );
2342 open(DATAFILE
,"$filename") ||
2343 die "Could not open $filename for reading";
2344 my ( @new_row, $new_ID, $old_ID, @init_data );
2347 while (sysread DATAFILE
, $buffer, 4096) {
2348 $lines += ($buffer =~ tr/\n//);
2350 seek( DATAFILE
, 0,0 );
2353 my $status_bar = status_bar
-> new
( steps
=> $lines );
2355 ui
-> print( category
=> 'scm',
2356 message
=> "Reading data file: ".$self -> filename
);
2357 ui
-> print( category
=> 'scm',
2358 message
=> $status_bar -> print_step
(),
2361 my ( $sth, $dbh, $first_row_id, $first_value_id );
2363 # if ( $PsN::config -> {'_'} -> {'use_database'} and
2364 # $self -> {'use_data_table'} ) {
2365 # $dbh = DBI -> connect("DBI:mysql:host=".$PsN::config -> {'_'} -> {'database_server'}.
2366 # ";databse=".$PsN::config -> {'_'} -> {'project'},
2367 # $PsN::config -> {'_'} -> {'user'},
2368 # $PsN::config -> {'_'} -> {'password'},
2369 # {'RaiseError' => 1});
2370 # my $sth = $dbh -> prepare( "SELECT data_row_id FROM ".$PsN::config -> {'_'} -> {'project'}.
2372 # "WHERE data_id='".$self -> {'data_id'}."'" );
2373 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
2374 # my $select_arr = $sth -> fetchall_arrayref;
2375 # if ( scalar @{$select_arr} > 0 ) {
2376 # for ( my $i = 0; $i < scalar @{$select_arr}; $i++ ) {
2377 # push( @{$self -> {'data_row_ids'}}, $select_arr->[$i][0] );
2379 # $sth = $dbh -> prepare( "SELECT data_value_id FROM ".$PsN::config -> {'_'} -> {'project'}.
2381 # "WHERE data_id='".$self -> {'data_id'}."'" );
2382 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
2383 # my $select_val = $sth -> fetchall_arrayref;
2384 # for ( my $i = 0; $i < scalar @{$select_val}; $i++ ) {
2385 # push( @{$self -> {'data_value_ids'}}, $select_val->[$i][0] );
2388 # $dbh -> disconnect;
2390 # $dbh -> do( "LOCK TABLES ".$PsN::config -> {'_'} -> {'project'}.
2391 # ".data_row WRITE, ".$PsN::config -> {'_'} -> {'project'}.
2392 # ".data_value WRITE" );
2393 # $sth = $dbh -> prepare( "SELECT MAX(data_row_id) FROM ".$PsN::config -> {'_'} -> {'project'}.
2395 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
2396 # my $select_arr = $sth -> fetchall_arrayref;
2397 # $first_row_id = defined $select_arr -> [0][0] ? $select_arr -> [0][0] : 0;
2398 # $sth = $dbh -> prepare( "SELECT MAX(data_value_id) FROM ".$PsN::config -> {'_'} -> {'project'}.
2400 # $sth -> execute or debug -> die( message => $sth->errstr ) ;
2401 # my $select_arr = $sth -> fetchall_arrayref;
2402 # $first_value_id = defined $select_arr -> [0][0] ? $select_arr -> [0][0] : 0;
2409 my $row_counter = 0;
2411 ROW
: while ( <DATAFILE
> ) {
2413 my @new_row = split(/\,\s*|\s+/);
2414 # This regexp check is not time consuming.
2415 if ( /^\s*\d+|^\s*\./ ) {
2416 if ( defined $self -> {'cont_column'} ) {
2417 if ( $new_row[$self -> {'cont_column'} - 1] == 1 ) {
2418 if ( not $self -> {'table_file'} ) { # Skip the CONT=1 rows if this is a table file
2419 for ( my $i = $#new_row; $i > 0; $i-- ) {
2420 if ( $i != ($self -> {'cont_column'} - 1) ) {
2421 unshift( @
{$full_row}, $new_row[$i] );
2427 for ( my $i = $#new_row; $i >= 0; $i-- ) {
2428 # if ( $i != ($self -> {'cont_column'} - 1) or $self -> {'table_file'} ) {
2429 if ( $i != ($self -> {'cont_column'} - 1) ) {
2430 unshift( @
{$full_row}, $new_row[$i] );
2435 @
{$full_row} = @new_row;
2437 $new_ID = $full_row -> [$idcol-1]; # index starts at 0
2438 $old_ID = $new_ID if ( not defined $old_ID );
2440 # Check if column miss data at some row (This adds about 30% of init time)
2441 my $mdt = $self -> {'missing_data_token'};
2442 for( my $i = 0; $i <= $#{$full_row}; $i++ ){
2443 $self -> {'have_missing_data'} -> {$i+1} = 1
2444 if( $full_row -> [$i] == $mdt ); # == is slower but safer than eq
2446 # if ( $PsN::config -> {'_'} -> {'use_database'} and
2447 # $self -> {'use_data_table'} and $insert ) {
2449 # $insert_rows = $insert_rows."," if ( defined $insert_rows );
2450 # $insert_rows = $insert_rows.
2451 # "('$row_counter', '".$self -> {'data_id'}."' )";
2452 # for ( my $j = 0; $j <= $#{$full_row}; $j++ ) {
2453 # $insert_values = $insert_values."," if ( defined $insert_values );
2454 # $insert_values = $insert_values.
2455 # "('".$full_row -> [$j]."', '".
2456 # ($first_row_id+$row_counter)."', '".
2457 # $self -> {'data_column_ids'}->[$j].
2458 # "', '".$self -> {'data_id'}."' )";
2462 if ( $new_ID != $old_ID ) {
2463 my @subject_data = @init_data;
2464 my $id = data
::individual
-> new
( idcolumn
=> $idcol,
2465 subject_data
=> \
@subject_data,
2466 data_id
=> $self -> {'data_id'} );
2467 push( @
{$self -> {'individuals'}}, $id );
2468 @init_data =(join( ",", @
{$full_row}));
2470 push( @init_data, join( ",", @
{$full_row}) );
2475 if ( $status_bar -> tick
() ) {
2476 ui
-> print( category
=> 'scm',
2477 message
=> $status_bar -> print_step
(),
2483 # if ( $PsN::config -> {'_'} -> {'use_database'} and
2484 # $self -> {'use_data_table'} and $insert ) {
2485 # $dbh -> do("INSERT INTO ".$PsN::config -> {'_'} -> {'project'}.
2487 # "(number,data_id) ".
2488 # "VALUES ".$insert_rows);
2489 # push( @{$self -> {'data_row_ids'}}, ($first_row_id..$first_row_id+$row_counter) );
2490 # $dbh -> do( "INSERT INTO ".$PsN::config -> {'_'} -> {'project'}.
2492 # "(value,data_row_id,data_column_id,data_id) ".
2493 # "VALUES ".$insert_values );
2494 # push( @{$self -> {'data_value_ids'}},
2495 # ($first_value_id..$first_value_id+($row_counter*
2496 # scalar @{$self->{'data_column_ids'}})));
2497 # $dbh -> do( "UNLOCK TABLES" );
2498 # $dbh -> disconnect;
2501 if ( $#init_data >= 0 ) {
2502 push( @
{$self -> {'individuals'}},
2503 data
::individual
-> new
( idcolumn
=> $idcol,
2504 subject_data
=> \
@init_data ) );
2506 ui
-> print( category
=> 'scm',
2507 message
=> " ... done" );
2509 # $self -> _write( filename => 'test.dta' );
2511 end _read_individuals
2513 # }}} _read_individuals