File Coverage

lib/ClarID/Tools/Command/code.pm
Criterion Covered Total %
statement 527 547 96.3
branch 174 308 56.4
condition 73 157 46.5
subroutine 41 41 100.0
pod 1 2 50.0
total 816 1055 77.3


line stmt bran cond sub pod time code
1             package ClarID::Tools::Command::code;
2 36     36   274 use strict;
  36         100  
  36         1670  
3 36     36   222 use warnings;
  36         66  
  36         2729  
4 36     36   218 use feature qw(say);
  36         68  
  36         5450  
5 36     36   260 use ClarID::Tools;
  36         86  
  36         602  
6 36     36   34549 use ClarID::Tools::Util qw(load_yaml_file load_json_file);
  36         114  
  36         2946  
7 36     36   24158 use Moo;
  36         317470  
  36         208  
8             use MooX::Options
9 36         304 auto_help => 1,
10             version => $ClarID::Tools::VERSION,
11             usage => 'pod',
12 36     36   89799 config_from_hash => {};
  36         181932  
13 36     36   4495240 use Text::CSV_XS;
  36         945111  
  36         2877  
14 36     36   343 use Carp qw(croak);
  36         74  
  36         2609  
15 36     36   24508 use Types::Standard qw(Str Int Enum HashRef Undef ArrayRef);
  36         4594971  
  36         537  
16 36     36   160566 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
  36         1626076  
  36         6041  
17 36     36   24326 use IO::Compress::Gzip qw(gzip $GzipError);
  36         544958  
  36         5632  
18 36     36   382 use JSON::XS qw(decode_json);
  36         81  
  36         2397  
19 36     36   572 use File::Spec::Functions qw(catdir catfile);
  36         82  
  36         2799  
20              
21             # Tell App::Cmd this is a command
22 36     36   248 use App::Cmd::Setup -command;
  36         87  
  36         511  
23 36     36   32018 use namespace::autoclean;
  36         426845  
  36         172  
24              
25             # Set development mode
26 36     36   3223 use constant DEVEL_MODE => 0;
  36         104  
  36         492013  
27              
28             # CLI options
29             # NB: Invalid parameter values (e.g., --format=foo) trigger App::Cmd usage/help
30             # This hides the detailed Types::Standard error
31             # Fix by overriding usage_error/options_usage
32             #
33             # Example (Types::Standard):
34             # perl -Ilib -MClarID::Tools::Command::code -we \
35             # 'ClarID::Tools::Command::code->new(format=>"stube", action=>"encode", entity=>"biosample")'
36             #
37             # Value "stube" did not pass type constraint "Enum["human","stub"]" (in $args->{"format"}) at -e line 1
38             # "Enum["human","stub"]" requires that the value is equal to "human" or "stub"
39             option entity => (
40             is => 'ro',
41             format => 's',
42             isa => Enum [qw/biosample subject biospecimen individual/],
43             coerce => sub {
44             return 'biosample' if $_[0] eq 'biospecimen';
45             return 'subject' if $_[0] eq 'individual';
46             return $_[0];
47             },
48             doc =>
49             'biosample | subject (accepts synonyms: biospecimen -> biosample; individual -> subject)',
50             required => 1,
51             );
52             option format => (
53             is => 'ro',
54             format => 's',
55             isa => Enum [qw/human stub/],
56             doc => 'human | stub',
57             required => 1,
58             );
59             option action => (
60             is => 'ro',
61             format => 's',
62             isa => Enum [qw/encode decode/],
63             doc => 'encode | decode',
64             required => 1,
65             );
66             option codebook => (
67             is => 'ro',
68             format => 's',
69             isa => HashRef,
70             coerce => sub {
71             my $cb = load_yaml_file( $_[0] );
72             _apply_defaults($cb);
73             return $cb;
74             },
75             doc => 'path to codebook.yaml',
76             default =>
77             sub { catfile( $ClarID::Tools::share_dir, 'clarid-codebook.yaml' ) },
78             required => 1,
79             );
80             option infile => (
81             is => 'ro',
82             format => 's',
83             isa => Undef | Str,
84             doc => 'bulk input CSV/TSV',
85             );
86             option outfile => (
87             is => 'ro',
88             format => 's',
89             isa => Undef | Str,
90             doc => 'bulk output file',
91             );
92             option sep => (
93             is => 'ro',
94             format => 's',
95             isa => Str,
96             default => sub { ',' },
97             doc => 'separator',
98             );
99             option icd10_map => (
100             is => 'ro',
101             format => 's',
102             isa => Str,
103             default => sub { catfile( $ClarID::Tools::share_dir, 'icd10.json' ) },
104             doc => 'path to ICD-10 map JSON',
105             );
106             option with_condition_name => (
107             is => 'ro',
108             is_flag => 1,
109             doc => 'append human-readable condition_name on decode',
110             );
111             option subject_id_base62_width => (
112             is => 'ro',
113             format => 'i',
114             default => sub { 3 },
115             doc => 'number of Base-62 characters to use for subject ID stubs',
116             );
117             option subject_id_pad_length => (
118             is => 'ro',
119             format => 'i',
120             default => sub { 5 },
121             doc =>
122             'decimal padding width for subject IDs in biosample/subject human format',
123             );
124             option clar_id => (
125             is => 'ro',
126             format => 's',
127             isa => Undef | Str,
128             doc => 'ID to decode (use --clar_id or --stub_id)',
129             short => 'stub_id',
130             );
131              
132             # Always load the ICD-10 order map at startup (JSON::XS parses ~70K entries in ~100 ms on modern hardware), simplifying stub logic.
133             # This one-time cost (~0.1 s, ~10 MB RAM) is negligible compared to the complexity of conditional or lazy loading.
134             option icd10_order => (
135             is => 'ro',
136             format => 's',
137             isa => HashRef,
138             coerce => \&load_json_file,
139             default => sub { catfile( $ClarID::Tools::share_dir, 'icd10_order.json' ) },
140             doc => 'path to icd10_order.json',
141             );
142              
143             has icd10_by_order => (
144             is => 'ro',
145             isa => ArrayRef,
146             lazy => 1,
147             builder => '_build_icd10_by_order',
148             );
149              
150             option max_conditions => (
151             is => 'ro',
152             format => 'i',
153             isa => Int,
154             default => sub { 10 },
155             doc => 'maximum number of ICD-10 codes allowed',
156             );
157              
158             # biosample fields
159             option project =>
160             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'project key' );
161             option species =>
162             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'species key' );
163             option tissue =>
164             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'tissue key' );
165             option sample_type => (
166             is => 'ro',
167             format => 's',
168             isa => Undef | Str,
169             doc => 'sample_type key'
170             );
171             option assay =>
172             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'assay key' );
173             option timepoint =>
174             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'timepoint' );
175             option duration => (
176             is => 'ro',
177             format => 's',
178             isa => Undef | Str,
179             doc => 'duration: P or P0N (Not Available)'
180             );
181             option batch =>
182             ( is => 'ro', format => 's', isa => Undef | Int, doc => 'batch' );
183             option replicate => (
184             is => 'ro',
185             format => 'i',
186             isa => Undef | Int,
187             doc => 'replicate number'
188             );
189              
190             # subject fields
191             option study =>
192             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'study' );
193             option type => ( is => 'ro', format => 's', isa => Undef | Str, doc => 'type' );
194             option sex => ( is => 'ro', format => 's', isa => Undef | Str, doc => 'sex' );
195             option age_group =>
196             ( is => 'ro', format => 's', isa => Undef | Str, doc => 'age_group' );
197              
198             # Biosample + subject
199             option subject_id =>
200             ( is => 'ro', format => 'i', isa => Undef | Int, doc => 'subject_id' );
201             option condition => (
202             is => 'ro',
203             format => 's',
204             isa => Undef | Str,
205             doc => 'comma-separated ICD-10 codes (e.g. C22.0,C18.1)'
206             );
207              
208             # declare once, reuse everywhere:
209             my %FIELDS = (
210             biosample => {
211             encode => [
212             qw(
213             project species subject_id tissue sample_type assay
214             condition timepoint duration batch replicate
215             )
216             ],
217             decode => [
218             qw(
219             project species subject_id tissue sample_type assay
220             condition timepoint duration batch replicate
221             )
222             ],
223             },
224             subject => {
225             encode => [
226             qw(
227             study subject_id type condition sex age_group
228             )
229             ],
230             decode => [
231             qw(
232             study subject_id type condition sex age_group
233             )
234             ],
235             },
236             );
237              
238             sub _encode_fields {
239 45     45   101 my $self = shift;
240 45         322 my $e = $self->entity;
241 45 50       158 Carp::croak "Unknown entity '$e'" unless exists $FIELDS{$e};
242 45         77 return @{ $FIELDS{$e}{encode} };
  45         296  
243             }
244              
245             sub _decode_fields {
246 32     32   88 my $self = shift;
247 32         161 my $e = $self->entity;
248 32 50       120 Carp::croak "Unknown entity '$e'" unless exists $FIELDS{$e};
249 32         69 return @{ $FIELDS{$e}{decode} };
  32         488  
250             }
251              
252             # Validate required options
253             sub BUILD {
254 36     36 0 1463 my $self = shift;
255              
256             # If we're in bulk mode, skip ALL of the single-record checks,
257             # including the CLI --condition parsing.
258 36 100       414 return if defined $self->infile;
259              
260             # Only from here on is single-record mode…
261              
262             # 1) Ensure --with-condition-name only on decode
263 27 50 66     190 if ( $self->with_condition_name && $self->action ne 'decode' ) {
264 0         0 croak "--with-condition-name only makes sense when --action decode";
265             }
266              
267             # 2) Single-record encode: parse & validate the CLI --condition
268 27 100       330 if ( $self->action eq 'encode' ) {
    50          
269              
270             # split into individual codes (profiled on Aug-09-25)
271 16   50     218 my @conds = split /\s*,\s*/, ( $self->condition // '' );
272 16 50       79 croak "--condition must not be empty" unless @conds;
273              
274             # enforce max
275 16 50       108 if ( @conds > $self->max_conditions ) {
276 0         0 croak sprintf
277             "You passed %d conditions but max is %d",
278             scalar(@conds), $self->max_conditions;
279             }
280              
281             # pull regex from your codebook
282             my $pat_cfg =
283             $self->codebook->{entities}{ $self->entity }{condition_pattern}
284 16 50       246 or croak "No condition_pattern defined in your codebook";
285             my $re = $pat_cfg->{regex}
286 16 50       72 or croak "condition_pattern has no regex";
287              
288             # validate each
289 16         50 for my $c (@conds) {
290 19 50       1154 croak "Invalid condition '$c'"
291             unless $c =~ /^$re$/;
292             }
293              
294             # stash for the encoder
295 16         89 $self->{_conds} = \@conds;
296              
297             # 3) Now enforce the usual “required field” checks
298 16         92 for my $field ( $self->_encode_fields ) {
299 156 100 100     487 next if $field eq 'batch' && !defined $self->batch;
300 154 100 100     670 next if $field eq 'replicate' && !defined $self->replicate;
301 152 50       815 croak "--$field is required for single-record encode"
302             unless defined $self->$field;
303             }
304             }
305             elsif ( $self->action eq 'decode' ) {
306              
307             # 4) Single-record decode needs a clar_id
308 11 50       216 croak "--clar_id is required for decode"
309             unless defined $self->clar_id;
310             }
311             }
312              
313             # lazy load
314             sub _build_icd10_by_order {
315 5     5   77 my $self = shift;
316              
317             # force-load the order hash if not done yet
318 5         21 my $ord_hash = $self->icd10_order;
319 5         23 my @by;
320 5         286760 $by[ $ord_hash->{$_} ] = $_ for keys %$ord_hash;
321 5         27858 return \@by;
322             }
323              
324             # Main dispatch
325             sub execute {
326 36     36 1 565 my $self = shift;
327              
328             # lazy load ICD-10 map if requested
329 36         82 my $code2name;
330 36 100 100     346 if ( $self->action eq 'decode' && $self->with_condition_name ) {
331 4 50       179 croak "ICD-10 map not found at '" . $self->icd10_map . "'"
332             unless -e $self->icd10_map;
333 4 50       255 open my $jh, '<', $self->icd10_map or croak $!;
334 4         24 local $/;
335 4         25712 my $jtxt = <$jh>;
336 4         76 close $jh;
337 4         199146 $code2name = decode_json($jtxt);
338             }
339              
340             # bulk vs single-record
341 36         127 my ( $in_fh, $out_fh );
342 36 100       386 if ( defined( my $infile = $self->infile ) ) {
343              
344             # Input handle (auto‐gunzip for .gz)
345 9 50       53 if ( $infile =~ /\.gz$/ ) {
346 0 0       0 $in_fh = IO::Uncompress::Gunzip->new($infile)
347             or croak "gunzip failed on '$infile': $GunzipError";
348             }
349             else {
350 9 50       742 open my $fh_in, '<', $infile
351             or croak "Could not open '$infile': $!";
352 9         51 $in_fh = $fh_in;
353             }
354              
355             # Output handle (auto‐gzip for .gz, else file or STDOUT)
356 9 50       100 if ( defined $self->outfile ) {
357 0 0       0 if ( $self->outfile =~ /\.gz$/ ) {
358 0 0       0 $out_fh = IO::Compress::Gzip->new( $self->outfile )
359             or croak "gzip failed on '$self->outfile': $GzipError";
360             }
361             else {
362 0 0       0 open my $fh_out, '>', $self->outfile
363             or croak "Could not open '$self->outfile' for writing: $!";
364 0         0 $out_fh = $fh_out;
365             }
366             }
367             else {
368 9         46 $out_fh = *STDOUT;
369             }
370              
371             # Delegate to bulk processor
372 9         122 return $self->_run_bulk( $in_fh, $self->sep, $out_fh, $code2name );
373             }
374              
375             # single-record mode — unwrap either top-level or entities-wrapped codebook
376 27         169 my $full = $self->codebook;
377              
378             # if the YAML has an "entities:" wrapper, drill into it; otherwise assume old style
379             my $root =
380             exists $full->{entities}
381             ? $full->{entities}
382 27 50       139 : $full;
383 27 50       357 my $cb = $root->{ $self->entity }
384             or croak "No codebook for '" . $self->entity . "' in your YAML";
385 27 100       169 if ( $self->action eq 'encode' ) {
386 16         76 my @vals = map { $self->$_ } $self->_encode_fields;
  156         431  
387 16         174 my $meth = sprintf '_encode_%s_%s', $self->format, $self->entity;
388 16         103 say $self->$meth( $cb, @vals );
389             }
390             else {
391 11         145 my $meth = sprintf '_decode_%s_%s', $self->format, $self->entity;
392 11         129 my $res = $self->$meth( $cb, $self->clar_id );
393              
394             # Print each field in order
395 10         63 say "$_: $res->{$_}" for $self->_decode_fields;
396              
397             # Optionally append human-readable condition_name
398 10 100       122 if ( $self->with_condition_name ) {
399              
400             # split whatever separator you're using in $res->{condition}
401 2         16 my @keys = split /[+;]/, $res->{condition};
402              
403             # normalize to dot‐free lookup key and fetch each name
404             my @names = map {
405 2         17 ( my $clean = $_ ) =~ s/\W//g;
  4         24  
406 4   50     27 $code2name->{$clean} // ''
407             } @keys;
408              
409             # join multiple names with semicolons
410 2         39448 say "condition_name: " . join( ';', @names );
411             }
412             }
413             }
414              
415             # Bulk processing for single or multiple records
416             sub _run_bulk {
417 9     9   44 my ( $self, $in_fh, $sep, $out_fh, $code2name ) = @_;
418 9   50     33 $sep ||= ',';
419              
420             # set up CSV parser
421 9         169 my $csv = Text::CSV_XS->new( { sep_char => $sep } );
422              
423             # read header row and set column names
424 9 50       3111 my $hdr = $csv->getline($in_fh)
425             or croak "Failed to read header";
426 9         210 $csv->column_names(@$hdr);
427              
428             # unwrap entity wrapper in the codebook for bulk mode
429 9         544 my $full = $self->codebook;
430 9 50       52 my $root = exists $full->{entities} ? $full->{entities} : $full;
431 9 50       103 my $cb = $root->{ $self->entity }
432             or croak "No codebook for '" . $self->entity . "'";
433              
434             # write output header
435 9 100       56 if ( $self->action eq 'encode' ) {
436 4 100       78 my $label = $self->format eq 'stub' ? 'stub_id' : 'clar_id';
437 4         94 say $out_fh join( $sep, ( @$hdr, $label ) );
438             }
439             else {
440 5         58 my @cols = ( @$hdr, $self->_decode_fields );
441 5 100       47 push @cols, 'condition_name' if $self->with_condition_name;
442 5         102 say $out_fh join( $sep, @cols );
443             }
444              
445             # process each row
446 9         79 while ( my $row = $csv->getline_hr($in_fh) ) {
447              
448 30 100       1111 if ( $self->action eq 'encode' ) {
449              
450             # ——— per-row multi‐condition support (CSV uses ';') ———
451 13   50     94 my @conds = split /\s*;\s*/, $row->{condition} // '';
452 13 50       32 croak "Missing or empty condition in row" unless @conds;
453 13 50       54 if ( @conds > $self->max_conditions ) {
454 0         0 croak sprintf
455             "You passed %d conditions but max is %d",
456             scalar(@conds), $self->max_conditions;
457             }
458              
459             # validate each against the codebook regex
460             my $pat_cfg = $cb->{condition_pattern}
461 13 50       46 or croak "No condition_pattern in codebook";
462             my $re = $pat_cfg->{regex}
463 13 50       58 or croak "condition_pattern has no regex";
464 13         31 for my $c (@conds) {
465 16 50       399 croak "Invalid condition '$c'"
466             unless $c =~ /^$re$/;
467             }
468              
469             # stash for the encoder
470 13         45 $self->{_conds} = \@conds;
471              
472 13         72 my @args = map { $row->{$_} } $self->_encode_fields;
  103         214  
473 13         119 my $meth = sprintf '_encode_%s_%s', $self->format, $self->entity;
474 13         63 my $out = $self->$meth( $cb, @args );
475 13   50     55 say $out_fh join( $sep, ( map { $row->{$_} // '' } @$hdr ), $out );
  116         438  
476             }
477             else {
478             # enforce column based on --format
479 17         27 my ( $meth, $id_col );
480 17 100       62 if ( $self->format eq 'human' ) {
481 13         44 $meth = sprintf '_decode_human_%s', $self->entity;
482 13         19 $id_col = 'clar_id';
483             }
484             else { # format eq 'stub'
485 4         23 $meth = sprintf '_decode_stub_%s', $self->entity;
486 4         8 $id_col = 'stub_id';
487             }
488              
489             croak "Missing $id_col in input row"
490 17 50       39 unless defined $row->{$id_col};
491              
492 17         70 my $res = $self->$meth( $cb, $row->{$id_col} );
493              
494 17   50     45 my @out = map { $res->{$_} // '' } $self->_decode_fields;
  147         285  
495 17 100 66     99 if ( $self->with_condition_name && $code2name ) {
496 5         19 my @codes = split /[+;]/, $res->{condition};
497             my @names = map {
498 5         10 ( my $c = $_ ) =~ s/\W//g;
  8         29  
499 8   100     50 $code2name->{$c} // ''
500             } @codes;
501 5         15 push @out, join( ';', @names );
502             }
503              
504 17   50     75 say $out_fh join( $sep, ( map { $row->{$_} // '' } @$hdr ), @out );
  45         264  
505             }
506             }
507              
508 9         42372 return;
509             }
510              
511             sub _validate_field {
512 120     120   317 my ( $fmap, $f, $v ) = @_;
513 120 50 33     653 croak "Invalid $f '$v'" unless defined $v && exists $fmap->{$v};
514             }
515              
516             # Cache compiled regex + placeholder counts per pattern config
517             sub _prep_pattern {
518 60     60   158 my ( $pcfg, $mode ) = @_;
519 60   66     2412 $pcfg->{_re} ||= qr/^(?:$pcfg->{regex})$/;
520              
521             my $fmt =
522             $mode eq 'human'
523             ? ( $pcfg->{code_format} // '%s' )
524 60 100 50     257 : ( $pcfg->{stub_format} // '%s' );
      50        
525              
526 60 100       145 my $need_key = $mode eq 'human' ? '_need_human' : '_need_stub';
527 60   66     204 $pcfg->{$need_key} //= do {
528 47         131 ( my $t = $fmt ) =~ s/%%//g; # ignore literal %%
529 47         262 scalar( () = $t =~ /%/g ) # count % directives
530             };
531              
532 60         260 return ( $pcfg->{_re}, $fmt, $pcfg->{$need_key} );
533             }
534              
535             # Generic parser (grab captures; safe for alternation like P0N)
536             sub _parse_field {
537 47     47   157 my ( $val, $map, $pcfg, $mode, $field ) = @_;
538              
539 47 50       112 croak "Missing value for $field" unless defined $val;
540 47 50 33     249 croak "No pattern for $field" unless $pcfg && $pcfg->{regex};
541              
542 47         117 my ( $re, $fmt, $need ) = _prep_pattern( $pcfg, $mode );
543 47 100       11346 croak "Invalid $field '$val'" unless $val =~ $re;
544              
545 46         319 my @caps = grep { defined } ( $val =~ $re ); # drop undef from alternation
  94         228  
546 46 50       131 splice @caps, $need if @caps > $need; # never pass extra args
547              
548 46 50       313 return $need ? sprintf( $fmt, @caps ? @caps : ($val) ) : $fmt;
    50          
549             }
550              
551             # Static-or-pattern parser (uses codebook map first, then pattern)
552             sub _parse_from_codebook {
553 13     13   75 my ( $val, $map, $pcfg, $mode ) = @_;
554              
555             # 1) static map entry (e.g., tokens)
556 13 0 33     71 if ( $map && ref $map eq 'HASH' && exists $map->{$val} ) {
      33        
557 0 0       0 my $k = $mode eq 'human' ? 'code' : 'stub_code';
558 0 0       0 return $map->{$val}{$k} if defined $map->{$val}{$k};
559             }
560              
561             # 2) require a value
562 13 50       58 croak "Missing value for field" unless defined $val;
563              
564             # 3) pattern path (captures-aware) or raw fallback
565 13 50 33     150 if ( $pcfg && $pcfg->{regex} ) {
566 13         56 my ( $re, $fmt, $need ) = _prep_pattern( $pcfg, $mode );
567 13 50       138 croak "Invalid value '$val' for field" unless $val =~ $re;
568              
569 13         76 my @caps = grep { defined } ( $val =~ $re );
  13         60  
570 13 50       42 splice @caps, $need if @caps > $need;
571              
572             # for stub mode, if no captures, normalize raw by stripping non-word
573 13 0 33     59 if ( !@caps && $need == 1 && $mode eq 'stub' ) {
      33        
574 0         0 ( my $raw = $val ) =~ s/\W//g;
575 0         0 return sprintf( $fmt, $raw );
576             }
577              
578 13 50       127 return @caps ? sprintf( $fmt, @caps ) : sprintf( $fmt, $val );
579             }
580              
581 0         0 return $val;
582             }
583              
584             #----------------------------------------------------------------
585             # Human biosample encoder
586             #----------------------------------------------------------------
587             # Human biosample encoder
588             sub _encode_human_biosample {
589             my (
590 9     9   57 $self, $cb, $pr_raw, $sp, $sid, $ti, $st,
591             $as, $co, $tp, $du, $ba, $re
592             ) = @_;
593              
594             # normalize project key
595 9         23 my $pr = $pr_raw;
596 9 50       50 unless ( exists $cb->{project}{$pr} ) {
597 0         0 ( my $alt = $pr_raw ) =~ tr/-/_/;
598 0 0       0 $pr = $alt if exists $cb->{project}{$alt};
599             }
600 9 50       150 croak "Invalid project '$pr_raw'" unless exists $cb->{project}{$pr};
601              
602             # basic field validation
603 9         63 _validate_field( $cb->{project}, 'project', $pr );
604 9         32 _validate_field( $cb->{species}, 'species', $sp );
605 9         61 _validate_field( $cb->{tissue}, 'tissue', $ti );
606 9         34 _validate_field( $cb->{sample_type}, 'sample_type', $st );
607 9         32 _validate_field( $cb->{assay}, 'assay', $as );
608              
609             # subject_id
610 9         37 my $pad = $self->subject_id_pad_length;
611 9 50 33     181 croak "Invalid pad length '$pad'" unless $pad =~ /^\d+$/ && $pad > 0;
612 9         57 my $max = 10**$pad - 1;
613 9 50 33     157 croak "Bad subject_id '$sid' (0-$max)"
      33        
614             unless $sid =~ /^\d+$/ && $sid >= 0 && $sid <= $max;
615              
616             # ------ multi‐condition support ------
617 9         21 my @conds = @{ delete $self->{_conds} }; # pull in the validated list
  9         46  
618             my @human = map {
619 9         30 _parse_from_codebook( $_, $cb->{condition}, $cb->{condition_pattern},
620 13         87 'human' )
621             } @conds;
622 9         38 my $cond_code = join '+', @human;
623              
624             # -------------------------------------
625             # timepoint (strict codebook lookup)
626 9         38 _validate_field( $cb->{timepoint}, 'timepoint', $tp );
627 9         28 my $pt_code = $cb->{timepoint}{$tp}{code};
628              
629             # duration (pattern-drivem only)
630             my $dur_code =
631 9         55 _parse_field( $du, undef, $cb->{duration_pattern}, 'human', 'duration' );
632              
633             # batch (pattern-driven only)
634             my $batch_code =
635             defined $ba
636 8 100       111 ? _parse_field( $ba, undef, $cb->{batch_pattern}, 'human', 'batch' )
637             : ();
638              
639             # replicate (pattern-driven only)
640             my $rep_code =
641             defined $re
642 8 100       54 ? _parse_field( $re, undef, $cb->{replicate_pattern}, 'human',
643             'replicate' )
644             : ();
645              
646             # assemble
647             my @parts = (
648             $cb->{project}{$pr}{code}, $cb->{species}{$sp}{code},
649             sprintf( "%0${pad}d", $sid ), $cb->{tissue}{$ti}{code},
650             $cb->{sample_type}{$st}{code}, $cb->{assay}{$as}{code},
651 8         152 $cond_code, $pt_code,
652             $dur_code,
653             );
654 8 100       79 push @parts, $batch_code if defined $batch_code;
655 8 100       194 push @parts, $rep_code if defined $rep_code;
656              
657 8         182 return join( '-', @parts );
658             }
659              
660             # Human biosample decoder
661             sub _decode_human_biosample {
662 13     13   33 my ( $self, $cb, $id ) = @_;
663 13         111 my @p = split /-/, $id;
664 13 50       38 croak "Bad biosample ID" unless @p >= 9;
665 13         61 my ( $prc, $sc, $sid, $tc, $stc, $ac, $cn, $ptc, $du, @rest ) = @p;
666              
667             my ($project) =
668 13         22 grep { $cb->{project}{$_}{code} eq $prc } keys %{ $cb->{project} };
  65         187  
  13         59  
669 13 50       61 croak "Unknown project code '$prc'" unless defined $project;
670             my ($species) =
671 13         22 grep { $cb->{species}{$_}{code} eq $sc } keys %{ $cb->{species} };
  312         545  
  13         119  
672 13 50       41 croak "Unknown species code '$sc'" unless defined $species;
673             my ($tissue) =
674 13         21 grep { $cb->{tissue}{$_}{code} eq $tc } keys %{ $cb->{tissue} };
  273         484  
  13         72  
675 13 50       46 croak "Unknown tissue code '$tc'" unless defined $tissue;
676 78         159 my ($stype) = grep { $cb->{sample_type}{$_}{code} eq $stc }
677 13         20 keys %{ $cb->{sample_type} };
  13         42  
678 13 50       54 croak "Unknown sample_type code '$stc'" unless defined $stype;
679 13         25 my ($assay) = grep { $cb->{assay}{$_}{code} eq $ac } keys %{ $cb->{assay} };
  273         450  
  13         76  
680 13 50       60 croak "Unknown assay code '$ac'" unless defined $assay;
681              
682             # parse subject_id using dynamic pad length
683 13         42 my $pad = $self->subject_id_pad_length;
684 13 50 33     113 croak "Invalid pad length '$pad'" unless $pad =~ /^\d+$/ && $pad > 0;
685 13 50       466 croak "Bad subject_id in ID '$sid'"
686             unless $sid =~ /^\d{$pad}$/;
687 13         45 my $subject_id = int($sid);
688              
689             # Extract batch and replicate (just the integer)
690 13         26 my ( $batch, $replicate );
691 13 100       98 if (@rest) {
692              
693             # last element R## -> replicate
694 11 50       50 if ( $rest[-1] =~ /^R(\d{2})$/ ) {
695 11         28 $replicate = int $1;
696 11         18 pop @rest;
697             }
698              
699             # now maybe B## -> batch
700 11 50 33     55 if ( @rest && $rest[-1] =~ /^B(\d{2})$/ ) {
701 11         19 $batch = int $1;
702 11         14 pop @rest;
703             }
704             }
705              
706             # timepoint decode (strict codebook reverse lookup)
707             my ($timepoint) =
708 13         25 grep { $cb->{timepoint}{$_}{code} eq $ptc } keys %{ $cb->{timepoint} };
  91         166  
  13         86  
709 13 50       37 croak "Unknown timepoint code '$ptc'" unless defined $timepoint;
710              
711             # condition decode (allow multiple codes separated by '+')
712 13         29 my @parts = split /\+/, $cn;
713 13         22 my @norm;
714 13         37 for my $code (@parts) {
715              
716             # if it exists verbatim, use it
717 17 50       52 if ( exists $cb->{condition}{$code} ) {
718 0         0 push @norm, $code;
719             }
720             else {
721             # insert dot after 3rd char if missing
722 17 50 66     70 if ( $code !~ /\./ && length($code) > 3 ) {
723 0         0 $code = substr( $code, 0, 3 ) . '.' . substr( $code, 3 );
724             }
725 17         136 push @norm, $code;
726             }
727             }
728              
729             # join with semicolons for human readability
730 13         33 my $condition = join ';', @norm;
731              
732             # ensure we don't get warnings when printing
733 13 100       49 $batch = '' unless defined $batch;
734 13 100       35 $replicate = '' unless defined $replicate;
735              
736             return {
737 13         131 project => $project,
738             species => $species,
739             subject_id => $subject_id,
740             tissue => $tissue,
741             sample_type => $stype,
742             assay => $assay,
743             condition => $condition,
744             timepoint => $timepoint,
745             duration => $du,
746             batch => $batch,
747             replicate => $replicate,
748             };
749             }
750              
751             #----------------------------------------------------------------
752             # Stub biosample encoder
753             #----------------------------------------------------------------
754             sub _encode_stub_biosample {
755 8     8   41 my ( $self, $cb, $pr, $sp, $sid, $ti, $st, $as, $co, $tp, $du, $ba, $re ) =
756             @_;
757              
758             # 1) static validations
759 8         36 _validate_field( $cb->{project}, 'project', $pr );
760 8         29 _validate_field( $cb->{species}, 'species', $sp );
761 8         23 _validate_field( $cb->{tissue}, 'tissue', $ti );
762 8         22 _validate_field( $cb->{sample_type}, 'sample_type', $st );
763 8         23 _validate_field( $cb->{assay}, 'assay', $as );
764              
765             # 2) subject_id -> stub
766 8         31 my $w = $self->subject_id_base62_width;
767 8 50 33     93 croak "Invalid stub width '$w'" unless $w =~ /^\d+$/ && $w > 0;
768 8 50 33     100 croak "Bad subject_id '$sid' (0–" . ( 62**$w - 1 ) . ")"
      33        
769             unless defined $sid && $sid =~ /^\d+$/ && $sid <= 62**$w - 1;
770 8         35 my $sid_stub = $self->_subject_id_to_stub( $sid, $w );
771              
772             # 3) pull in previously-parsed conditions (bulk) or split the raw string
773 8         22 my $conds_aref = delete $self->{_conds};
774 8 0       35 my @conds =
    50          
775             $conds_aref
776             ? @$conds_aref
777             : split /\s*[+,;]\s*/, ( defined $co ? $co : '' );
778 8 50       20 croak "No conditions provided" unless @conds;
779 8 50       42 croak sprintf "You passed %d conditions but max is %d",
780             scalar(@conds), $self->max_conditions
781             if @conds > $self->max_conditions;
782              
783             # 4) map each ICD-10 -> 3-char stub
784             my @stubs = map {
785 8         28 ( my $c = $_ ) =~ s/\.//g; # strip dots
  8         33  
786             croak "Unknown ICD-10 '$_'"
787 8 50       37 unless exists $self->icd10_order->{$c};
788 8         27 $self->_subject_id_to_stub( $self->icd10_order->{$c}, 3 )
789             } @conds;
790 8         25 my $cond_stub = join '', @stubs;
791 8         29 my $count_prefix = sprintf( "%02d", scalar @stubs ); # << count added
792              
793             # 5) timepoint stub (strict codebook lookup)
794 8         30 _validate_field( $cb->{timepoint}, 'timepoint', $tp );
795 8         19 my $tp_stub = $cb->{timepoint}{$tp}{stub_code};
796              
797             # 6) duration stub (pattern-driven only)
798             my $du_stub =
799 8         34 _parse_field( $du, undef, $cb->{duration_pattern}, 'stub', 'duration' );
800              
801             # 7) batch & replicate (optional)
802             my $ba_stub =
803             defined $ba
804 8 50       39 ? _parse_field( $ba, undef, $cb->{batch_pattern}, 'stub', 'batch' )
805             : '';
806             my $re_stub =
807             defined $re
808 8 50       38 ? _parse_field( $re, undef, $cb->{replicate_pattern}, 'stub',
809             'replicate' )
810             : '';
811              
812             # 8) assemble and return
813             return join '', (
814             $cb->{project}{$pr}{stub_code}, $cb->{species}{$sp}{stub_code},
815             $sid_stub, $cb->{tissue}{$ti}{stub_code},
816             $cb->{sample_type}{$st}{stub_code}, $cb->{assay}{$as}{stub_code},
817 8         311 $cond_stub, $count_prefix, # << here
818             $tp_stub, $du_stub,
819             $ba_stub, $re_stub,
820             );
821             }
822              
823             # Stub biosample decoder
824             sub _decode_stub_biosample {
825 3     3   12 my ( $self, $cb, $id ) = @_;
826 3 50 33     20 croak "Bad stub ID" unless defined $id && length $id;
827              
828             # Use codebook-driven tail peel for replicate & batch
829 3   50     17 my $repl_fmt = $cb->{replicate_pattern}{stub_format} // '%02d';
830 3   50     13 my $batch_fmt = $cb->{batch_pattern}{stub_format} // '%02d';
831              
832             # 1) strip off replicate using stub_format (e.g. 'R%02d' or '%02d')
833 3         18 my $replicate = _strip_tail_using_fmt( \$id, $repl_fmt );
834              
835             # 2) strip off batch using stub_format
836 3         12 my $batch = _strip_tail_using_fmt( \$id, $batch_fmt );
837              
838             # Legacy fallback for old (unprefixed) stubs: peel bare 2 digits if still present
839 3 50 33     16 if ( !defined $replicate && $id =~ s/(\d{2})$// ) { $replicate = 0 + $1 }
  0         0  
840 3 50 33     16 if ( !defined $batch && $id =~ s/(\d{2})$// ) { $batch = 0 + $1 }
  0         0  
841              
842             # 3) strip off duration: allow D/W/M/Y or 0N
843 3 50       32 croak "Bad stub ID (duration)" unless $id =~ s/(\d+)([DWMYN])$//;
844 3         16 my ( $d_num, $d_unit ) = ( $1, $2 );
845 3 100 100     12743 croak "Invalid duration unit 'N' with non-zero"
846             if $d_unit eq 'N' && $d_num != 0;
847 2         6 my $duration = 'P' . $d_num . $d_unit;
848              
849             # 4) strip off timepoint (variable-length stub_code from codebook)
850             my %tp_by =
851 2         20 map { $cb->{timepoint}{$_}{stub_code} => $_ } keys %{ $cb->{timepoint} };
  14         47  
  2         14  
852 2         26 my $timepoint;
853 2         16 for my $stub ( sort { length($b) <=> length($a) } keys %tp_by ) {
  24         37  
854 6 100       91 if ( $id =~ s/\Q$stub\E$// ) { $timepoint = $tp_by{$stub}; last }
  2         7  
  2         5  
855             }
856 2 50       8 croak "Unknown timepoint stub at end of ID" unless defined $timepoint;
857              
858             # 4b) peel 2-digit condition COUNT (immediately before timepoint)
859 2 50       33 croak "Missing condition count" unless $id =~ s/(\d{2})$//;
860 2         9 my $cond_count = int $1;
861 2 50       43 croak "Invalid condition count '$cond_count'" unless $cond_count > 0;
862              
863             # now $id is the head: project + species + sid + tissue + sample_type + assay + COND_SEGMENT
864 2         6 my $head = $id;
865              
866             # 5) project (match longest stub_code at start)
867 10         42 my %proj_by = map { $cb->{project}{$_}{stub_code} => $_ }
868 2         3 keys %{ $cb->{project} };
  2         10  
869 2         5 my ($project);
870 2         9 for my $stub ( sort { length($b) <=> length($a) } keys %proj_by ) {
  15         27  
871 4 100       72 if ( $head =~ s/^\Q$stub\E// ) { $project = $proj_by{$stub}; last }
  2         8  
  2         5  
872             }
873 2 50       6 croak "Unknown project stub" unless defined $project;
874              
875             # 6) species (always 2 chars)
876 2         6 my $spec_stub = substr( $head, 0, 2 );
877 2         7 substr( $head, 0, 2 ) = '';
878 48         128 my %sp_by = map { $cb->{species}{$_}{stub_code} => $_ }
879 2         5 keys %{ $cb->{species} };
  2         19  
880 2 50       14 croak "Unknown species stub '$spec_stub'" unless exists $sp_by{$spec_stub};
881 2         5 my $species = $sp_by{$spec_stub};
882              
883             # 7) subject_id (base-62 width)
884 2         10 my $w = $self->subject_id_base62_width;
885 2 50 33     20 croak "Bad stub width" unless $w =~ /^\d+$/ && $w > 0;
886 2         5 my $sid_stub = substr( $head, 0, $w );
887 2         5 substr( $head, 0, $w ) = '';
888 2         8 my $subject_id = $self->_stub_to_subject_id($sid_stub);
889              
890             # 8) tissue (match longest)
891 42         85 my %ti_by = map { $cb->{tissue}{$_}{stub_code} => $_ }
892 2         10 keys %{ $cb->{tissue} };
  2         24  
893 2         7 my $tissue;
894 2         10 for my $stub ( sort { length($b) <=> length($a) } keys %ti_by ) {
  116         107  
895 22 100       237 if ( $head =~ s/^\Q$stub\E// ) { $tissue = $ti_by{$stub}; last }
  2         7  
  2         4  
896             }
897 2 50       12 croak "Unknown tissue stub '$head'" unless defined $tissue;
898              
899             # 9) sample_type (match longest)
900 12         29 my %st_by = map { $cb->{sample_type}{$_}{stub_code} => $_ }
901 2         59 keys %{ $cb->{sample_type} };
  2         18  
902 2         3 my $stype;
903 2         8 for my $stub ( sort { length($b) <=> length($a) } keys %st_by ) {
  18         27  
904 6 100       78 if ( $head =~ s/^\Q$stub\E// ) { $stype = $st_by{$stub}; last }
  2         4  
  2         4  
905             }
906 2 50       6 croak "Unknown sample_type stub" unless defined $stype;
907              
908             # 10) assay (match longest)
909 42         81 my %as_by = map { $cb->{assay}{$_}{stub_code} => $_ }
910 2         2 keys %{ $cb->{assay} };
  2         14  
911 2         6 my $assay;
912 2         8 for my $stub ( sort { length($b) <=> length($a) } keys %as_by ) {
  88         81  
913 22 100       112 if ( $head =~ s/^\Q$stub\E// ) { $assay = $as_by{$stub}; last }
  2         4  
  2         3  
914             }
915 2 50       7 croak "Unknown assay stub" unless defined $assay;
916              
917             # 11) remaining $head must be exactly cond_count * 3 chars (ICD ordinals stubs)
918 2 50       6 croak "Bad condition stub length" unless length($head) % 3 == 0;
919 2         9 my @c_stubs = $head =~ /(.{3})/g;
920 2 50       6 croak "Condition count mismatch (have "
921             . scalar(@c_stubs)
922             . ", expected $cond_count)"
923             unless @c_stubs == $cond_count;
924              
925             my @conds = map {
926 2         10 my $ord = $self->_stub_to_subject_id($_);
  2         7  
927             croak "Invalid condition ordinal '$ord'"
928 2 50 33     15 unless $ord >= 1 && $ord < @{ $self->icd10_by_order };
  2         55  
929 2         176 _format_icd10( $self->icd10_by_order->[$ord] );
930             } @c_stubs;
931              
932 2         9 my $condition = join ';', @conds;
933              
934 2         6 if (DEVEL_MODE) {
935             say "DEBUG biosample cond_count = $cond_count";
936             say "DEBUG biosample cond_stubs = [" . join( ',', @c_stubs ) . "]";
937             }
938              
939             return {
940 2   50     134 project => $project,
      50        
941             species => $species,
942             subject_id => $subject_id,
943             tissue => $tissue,
944             sample_type => $stype,
945             assay => $assay,
946             condition => $condition, # ';' joined
947             timepoint => $timepoint,
948             duration => $duration,
949             batch => $batch // '',
950             replicate => $replicate // '',
951             };
952             }
953              
954             # Human-mode subject encoder
955             sub _encode_human_subject {
956             my (
957 6     6   27 $self, $cb,
958             $study, # study
959             $sid, # subject_id
960             $ty, # type
961             $co, # raw condition string
962             $sx, # sex
963             $ag # age_group
964             ) = @_;
965              
966             # 1) Validate type, sex & age_group
967 6         28 _validate_field( $cb->{type}, 'type', $ty );
968 6         21 _validate_field( $cb->{sex}, 'sex', $sx );
969 6         21 _validate_field( $cb->{age_group}, 'age_group', $ag );
970              
971             # 2) Pad subject_id
972 6         35 my $pad = $self->subject_id_pad_length;
973 6 50 33     80 croak "Invalid pad length '$pad'"
974             unless $pad =~ /^\d+$/ && $pad > 0;
975 6         20 my $max = 10**$pad - 1;
976 6 50 33     60 croak "Bad subject_id '$sid' (must be 0-$max)"
      33        
977             unless defined $sid && $sid =~ /^\d+$/ && $sid <= $max;
978 6         21 $study =~ tr/-/_/; # normalize study key
979              
980             # 3) Split & validate multiple ICD-10 codes
981 6 50       66 my @conds = split /\s*[+,;]\s*/, ( defined $co ? $co : '' );
982 6 50       58 croak "No conditions provided" unless @conds;
983 6         19 for my $c (@conds) {
984             my $pat_cfg = $cb->{condition_pattern}
985 7 50       28 or croak "No condition_pattern in codebook";
986 7 50       195 croak "Invalid condition '$c'"
987             unless $c =~ /^$pat_cfg->{regex}$/;
988             }
989              
990             # 4) Re-join with '+' for the final code
991 6         23 my $cond_code = join '+', @conds;
992              
993             # 5) Assemble the ID
994             return join( '-',
995             $study,
996             sprintf( "%0${pad}d", $sid ),
997             $cb->{type}{$ty}{code},
998             $cond_code,
999             $cb->{sex}{$sx}{code},
1000             $cb->{age_group}{$ag}{code},
1001 6         102 );
1002             }
1003              
1004             # Human-mode subject decoder
1005             sub _decode_human_subject {
1006 6     6   13 my ( $self, $cb, $id ) = @_;
1007              
1008 6         48 my @p = split /-/, $id;
1009 6 50       21 croak "Bad subject ID" unless @p == 6;
1010 6         18 my ( $study, $sid, $type_c, $co, $sex_c, $ag_code ) = @p;
1011              
1012 72         132 my ($ag_key) = grep { $cb->{age_group}{$_}{code} eq $ag_code }
1013 6         8 keys %{ $cb->{age_group} };
  6         43  
1014 6 50       23 croak "Unknown age_group code '$ag_code'" unless defined $ag_key;
1015              
1016             return {
1017 6         50 study => $study,
1018             type => $type_c,
1019             sex => $sex_c,
1020             age_group => $ag_key,
1021             condition => $co,
1022             subject_id => int($sid),
1023             };
1024             }
1025              
1026             # Stub-mode subject encoder (with 2-digit condition count prefix)
1027             # Stub-mode subject **encoder**, with COUNT just before sex
1028             sub _encode_stub_subject {
1029             my (
1030 6     6   25 $self, $cb,
1031             $study, # study key
1032             $subject_id, # integer
1033             $type, # type key
1034             $condition, # comma-separated ICD list
1035             $sex, # sex key
1036             $age_group # age_group key
1037             ) = @_;
1038              
1039             # study stub
1040 6   33     84 my $study_stub = $cb->{study}{$study}{stub_code} // $study;
1041              
1042             # validate & get stubs for type/sex/age_group
1043 6 50       27 croak "Unknown type '$type'" unless exists $cb->{type}{$type};
1044 6 50       18 croak "Unknown sex '$sex'" unless exists $cb->{sex}{$sex};
1045             croak "Unknown age_group '$age_group'"
1046 6 50       64 unless exists $cb->{age_group}{$age_group};
1047 6         19 my $type_stub = $cb->{type}{$type}{stub_code};
1048 6         54 my $sex_stub = $cb->{sex}{$sex}{stub_code};
1049 6         28 my $age_group_stub = $cb->{age_group}{$age_group}{stub_code};
1050              
1051             # subject_id -> base-62
1052 6         23 my $w = $self->subject_id_base62_width;
1053 6 50 33     71 croak "Invalid stub width '$w'" unless $w =~ /^\d+$/ && $w > 0;
1054 6         24 my $sid_stub = $self->_subject_id_to_stub( $subject_id, $w );
1055              
1056             # split and encode ICDs
1057 6         28 my @conds = split /\s*,\s*/, $condition;
1058 6 50       42 croak "No conditions provided" unless @conds;
1059 6 50       17 croak "Too many conditions" if @conds > 99;
1060             my @cond_stubs = map {
1061 6         17 ( my $c = $_ ) =~ s/\.//g;
  7         31  
1062 7 50       38 croak "Unknown ICD-10 '$_'" unless exists $self->icd10_order->{$c};
1063 7         25 $self->_subject_id_to_stub( $self->icd10_order->{$c}, 3 )
1064             } @conds;
1065              
1066             # build count + conds string
1067 6         25 my $count_prefix = sprintf( "%02d", scalar @cond_stubs );
1068 6         21 my $conds_part = join "", @cond_stubs;
1069              
1070             # final: STUDY + SID + TYPE + CONDS + COUNT + SEX + AGE
1071 6         62 return join "",
1072             (
1073             $study_stub, $sid_stub, $type_stub, $conds_part,
1074             $count_prefix, $sex_stub, $age_group_stub,
1075             );
1076             }
1077              
1078             # Stub-mode subject **decoder**, reading backwards with COUNT before sex
1079             sub _decode_stub_subject {
1080 6     6   23 my ( $self, $cb, $stub ) = @_;
1081              
1082             # 1) sanity on base-62 width
1083 6         27 my $w = $self->subject_id_base62_width;
1084 6 50 33     132 croak "Invalid stub length '$w'"
      33        
1085             unless defined $w && $w =~ /^\d+$/ && $w > 0;
1086              
1087             # 2) reverse the entire stub
1088 6         51 my $rev = reverse $stub;
1089              
1090             # 3) pull off age_group (2 chars) + sex (1 char)
1091 6         22 my $rev_age = substr( $rev, 0, 2 );
1092 6         62 my $rev_sex = substr( $rev, 2, 1 );
1093 6         17 my $rest = substr( $rev, 3 );
1094              
1095             # 4) next two chars are the **reversed** condition count
1096 6 50       22 croak "Bad condition count in stub" unless length($rest) >= 2;
1097 6         15 my $count_rev = substr( $rest, 0, 2 );
1098              
1099             # restore correct order, parse as integer
1100 6         36 my $cond_count = int reverse $count_rev;
1101 6 50       21 croak "Invalid condition count '$cond_count'" unless $cond_count > 0;
1102 6         19 $rest = substr( $rest, 2 );
1103              
1104             # 5) peel off exactly cond_count * 3 chars for all condition stubs
1105 6         17 my $conds_len = $cond_count * 3;
1106 6 50       29 croak "Bad condition stub length"
1107             unless length($rest) >= $conds_len;
1108 6         34 my $rev_conds_rev = substr( $rest, 0, $conds_len );
1109 6         16 $rest = substr( $rest, $conds_len );
1110              
1111             # 6) next is the type stub (1 char)
1112 6 50       33 croak "Missing type stub" unless length($rest) >= 1;
1113 6         16 my $rev_type = substr( $rest, 0, 1 );
1114 6         18 $rest = substr( $rest, 1 );
1115              
1116             # 7) then the subject_id stub (width $w)
1117 6 50       19 croak "Missing subject_id stub" unless length($rest) >= $w;
1118 6         32 my $rev_id_rev = substr( $rest, 0, $w );
1119 6         13 $rest = substr( $rest, $w );
1120              
1121             # 8) and whatever remains is the study stub
1122 6         14 my $rev_study_rev = $rest;
1123              
1124             # 9) DEBUG dumps
1125 6         11 if (DEVEL_MODE) {
1126             say "DEBUG rev = '$rev'";
1127             say "DEBUG rev_age = '$rev_age'";
1128             say "DEBUG rev_sex = '$rev_sex'";
1129             say "DEBUG count_rev = '"
1130             . ( reverse $count_rev )
1131             . "' -> cond_count=$cond_count";
1132             say "DEBUG rev_conds_rev = '$rev_conds_rev'";
1133             say "DEBUG rev_type = '$rev_type'";
1134             say "DEBUG rev_id_rev = '$rev_id_rev'";
1135             say "DEBUG rev_study_rev = '$rev_study_rev'";
1136             }
1137              
1138             # 10) reverse back simple fields
1139 6         23 my $age_s = reverse $rev_age; # stub for age_group
1140 6         14 my $sex_s = reverse $rev_sex; # stub for sex
1141 6         17 my $type_s = reverse $rev_type; # stub for type
1142 6         12 my $sid_stub = reverse $rev_id_rev; # base62 subject_id
1143 6         17 my $study = reverse $rev_study_rev;
1144              
1145             # 11) decode subject_id
1146 6         43 my $subject_id = $self->_stub_to_subject_id($sid_stub);
1147              
1148             # 12) map back type, sex, and age_group via codebook
1149             my ($type) =
1150 6         15 grep { $cb->{type}{$_}{stub_code} eq $type_s } keys %{ $cb->{type} };
  24         82  
  6         40  
1151 6 50       25 croak "Unknown type stub '$type_s'" unless defined $type;
1152              
1153             my ($sex_key) =
1154 6         44 grep { $cb->{sex}{$_}{stub_code} eq $sex_s } keys %{ $cb->{sex} };
  36         96  
  6         62  
1155 6 50       25 croak "Unknown sex stub '$sex_s'" unless defined $sex_key;
1156              
1157 72         179 my ($age_group_key) = grep { $cb->{age_group}{$_}{stub_code} eq $age_s }
1158 6         13 keys %{ $cb->{age_group} };
  6         57  
1159 6 50       23 croak "Unknown age_group stub '$age_s'" unless defined $age_group_key;
1160              
1161             # 13) split condition segment into reversed 3-char chunks
1162 6         39 my @rev_chunks = $rev_conds_rev =~ /(.{3})/g;
1163 6 50       55 croak "Condition stub parsing mismatch"
1164             unless @rev_chunks == $cond_count;
1165              
1166             # *** restore original left-to-right order ***
1167 6         67 @rev_chunks = reverse @rev_chunks;
1168              
1169             # 14) reverse each back, then decode ordinal -> ICD-10
1170             my @conds = map {
1171 6         17 my $stub3 = reverse $_; # un-reverse it
  7         22  
1172 7         30 my $ord = $self->_stub_to_subject_id($stub3); # base62 -> ordinal
1173             croak "Invalid condition ordinal '$ord'"
1174 7 50 33     33 unless $ord >= 1 && $ord < @{ $self->icd10_by_order };
  7         272  
1175 7         457 _format_icd10( $self->icd10_by_order->[$ord] );
1176             } @rev_chunks;
1177              
1178             # 15) assemble final hash
1179             return {
1180 6         188 study => $study,
1181             subject_id => $subject_id,
1182             type => $type,
1183             condition => join( ';', @conds ),
1184             sex => $sex_key,
1185             age_group => $age_group_key, # <-- now mapped via codebook
1186             };
1187             }
1188              
1189             # ------------------------------------------------------------------------
1190             # Helper functions for subject_id ↔ stub conversion
1191             #
1192             # _subject_id_to_stub($id, $width):
1193             # - Converts a non-negative integer $id into a fixed-width base‑62 string.
1194             # - Pads with '0' on the left to exactly $width characters.
1195             #
1196             # _stub_to_subject_id($stub):
1197             # - Parses a base‑62 string $stub back into the original integer.
1198             # - Validates characters against the 0-9, A-Z, a-z alphabet.
1199             #
1200             # These allow you to shrink a 5‑digit decimal ID into 3 base‑62 chars in stub mode,
1201             # and recover the original integer when decoding.
1202             # ------------------------------------------------------------------------
1203              
1204             # Base‑62 alphabet
1205             my @BASE62 = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
1206             my %BASE62_REV = map { $BASE62[$_] => $_ } 0 .. $#BASE62;
1207              
1208             # ------------------------------------------------------------------------
1209             # Convert a non‑negative integer into a fixed-width base‑62 stub
1210             # $id : integer subject ID (>=0)
1211             # $width : desired stub length (default 3)
1212             # Returns a $width-char string in [0-9A-Za-z], zero-padded on the left.
1213             # ------------------------------------------------------------------------
1214             sub _subject_id_to_stub {
1215 29     29   74 my ( $self, $id, $width ) = @_;
1216 29   50     65 $width ||= 3; # default stub length
1217              
1218 29 50 33     268 croak "Bad subject_id '$id'"
      33        
1219             unless defined $id && $id =~ /^\d+$/ && $id >= 0;
1220              
1221 29 50       117 return '0' x $width if $id == 0; # special‑case zero
1222              
1223 29         54 my $s = '';
1224 29         57 my $num = $id;
1225 29         92 while ( $num > 0 ) {
1226              
1227             # prepend the next base‑62 digit
1228 63         158 $s = $BASE62[ $num % 62 ] . $s;
1229 63         169 $num = int( $num / 62 );
1230             }
1231              
1232             # left‑pad with '0' to exactly $width chars
1233 29         156 return substr( ( '0' x $width ) . $s, -$width );
1234             }
1235              
1236             # Convert a base‑62 string back to an integer
1237             sub _stub_to_subject_id {
1238 17     17   61 my ( $self, $stub ) = @_;
1239 17 50 33     144 croak "Bad stub '$stub'"
1240             unless defined $stub && $stub =~ /^[0-9A-Za-z]+$/;
1241 17         37 my $id = 0;
1242 17         63 for my $char ( split //, $stub ) {
1243 52 50       152 croak "Invalid base62 char '$char'" unless exists $BASE62_REV{$char};
1244 52         104 $id = $id * 62 + $BASE62_REV{$char};
1245             }
1246 17         59 return $id;
1247             }
1248              
1249             # Private helper: if an ICD‑10 code has no dot but is >3 chars,
1250             # stick a dot after the third character.
1251             sub _format_icd10 {
1252 9     9   122 my ($code) = @_;
1253 9 50 33     81 return $code if $code =~ /\./ || length($code) <= 3;
1254 9         75 return substr( $code, 0, 3 ) . '.' . substr( $code, 3 );
1255             }
1256              
1257             sub _apply_defaults {
1258 36     36   112 my ($doc) = @_;
1259 36 50       175 my $ents = $doc->{entities} or return;
1260 36   50     159 my $defaults = delete $ents->{_defaults} || {};
1261              
1262 36         201 for my $entity (qw/biosample subject/) {
1263 72 50       258 next unless my $cat = $ents->{$entity};
1264 72         317 for my $slot ( grep { ref $cat->{$_} eq 'HASH' } keys %$cat ) {
  540         1144  
1265 540         812 my $map = $cat->{$slot};
1266              
1267             # skip the default‐holder itself
1268 540 50       1033 next if $slot eq '_defaults';
1269              
1270             # for each of your two default keys, only add if missing:
1271             # NB: 'age_group' already has its own so it is skipped here
1272 540         1053 for my $k ( keys %$defaults ) {
1273 1080   100     2319 $map->{$k} //= { %{ $defaults->{$k} } };
  828         3828  
1274             }
1275             }
1276             }
1277              
1278             warn
1279 36         190 "! Note: injected global 'Unknown' + 'Not Available' defaults into each category\n"
1280             if DEVEL_MODE;
1281             }
1282              
1283             # Turn a stub_format like 'R%02d' or '%02d' into a tail regex with one capture
1284             sub _fmt_to_tail_regex {
1285 6     6   16 my ($fmt) = @_;
1286 6         16 my $re = quotemeta($fmt); # escape literal chars
1287 6         62 $re =~ s/\\%0?(\d+)d/(\\d{$1})/g; # %02d -> (\d{2}), %3d -> (\d{3})
1288 6         200 return qr/$re$/; # anchor at end
1289             }
1290              
1291             # Try to strip a value from the *end* of a string using stub_format
1292             # Returns the captured integer or undef if no match; modifies $$sref
1293             sub _strip_tail_using_fmt {
1294 6     6   17 my ( $sref, $fmt ) = @_;
1295 6         16 my $re = _fmt_to_tail_regex($fmt);
1296 6 50       61 if ( $$sref =~ s/$re// ) { return 0 + $1 }
  6         30  
1297 0           return undef;
1298             }
1299              
1300             1;
1301