File: name_parser.cpp

package info (click to toggle)
mrtrix3 3.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,712 kB
  • sloc: cpp: 129,776; python: 9,494; sh: 593; makefile: 234; xml: 47
file content (388 lines) | stat: -rw-r--r-- 9,757 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/* Copyright (c) 2008-2022 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Covered Software is provided under this License on an "as is"
 * basis, without warranty of any kind, either expressed, implied, or
 * statutory, including, without limitation, warranties that the
 * Covered Software is free of defects, merchantable, fit for a
 * particular purpose or non-infringing.
 * See the Mozilla Public License v. 2.0 for more details.
 *
 * For more details, see http://www.mrtrix.org/.
 */

#include <algorithm>

#include "file/name_parser.h"

namespace MR
{
  namespace File
  {

    namespace
    {

      inline bool in_seq (const vector<uint32_t>& seq, uint32_t val)
      {
        if (seq.size() == 0)
          return true;
        for (size_t i = 0; i < seq.size(); i++)
          if (seq[i] == val)
            return true;
        return false;
      }


    }






    void NameParser::parse (const std::string& imagename, size_t max_num_sequences)
    {
      specification = imagename;
      if (Path::is_dir (imagename)) {
        array.resize (1);
        array[0].set_str (imagename);
        return;
      }

      folder_name = Path::dirname (specification);


      try {
        std::string::size_type pos;
        std::string basename = Path::basename (specification);
        size_t num = 0;

        while ( (pos = basename.find_last_of (']')) < std::string::npos && num < max_num_sequences) {
          insert_str (basename.substr (pos+1));
          basename = basename.substr (0, pos);
          if ( (pos = basename.find_last_of ('[')) == std::string::npos)
            throw Exception ("malformed image sequence specifier for image \"" + specification + "\"");

          insert_seq (basename.substr (pos+1));
          num++;
          basename = basename.substr (0, pos);
        }

        insert_str (basename);


        for (size_t i = 0; i < array.size(); i++)
          if (array[i].is_sequence())
            if (array[i].sequence().size())
              for (size_t n = 0; n < array[i].sequence().size()-1; n++)
                for (size_t m = n+1; m < array[i].sequence().size(); m++)
                  if (array[i].sequence() [n] == array[i].sequence() [m])
                    throw Exception ("malformed image sequence specifier for image \""
                        + specification + "\" (duplicate indices)");
      }
      catch (...) {
        array.resize (1);
        array[0].set_str (imagename);
        throw;
      }
    }





    std::ostream& operator<< (std::ostream& stream, const NameParser::Item& item)
    {
      if (item.is_string())
        stream << "\"" << item.string() << "\"";
      else {
        if (item.sequence().size())
          stream << item.sequence();
        else
          stream << "[ any ]";
      }
      return stream;
    }





    std::ostream& operator<< (std::ostream& stream, const NameParser& parser)
    {
      stream << "File::NameParser: " << parser.specification << "\n";
      for (size_t i = 0; i < parser.array.size(); i++)
        stream << "  " << i << ": " << parser.array[i] << "\n";
      return stream;
    }










    bool NameParser::match (const std::string& file_name, vector<uint32_t>& indices) const
    {
      uint32_t current = 0;
      size_t num = 0;
      indices.resize (seq_index.size());

      for (size_t i = 0; i < array.size(); i++) {
        if (array[i].is_string()) {
          if (file_name.substr (current, array[i].string().size()) != array[i].string())
            return false;
          current += array[i].string().size();
        }
        else {
          uint32_t x = current;
          while (isdigit (file_name[current]))
            current++;
          if (x == current)
            return false;
          x = to<uint32_t> (file_name.substr (x, current-x));
          if (!in_seq (array[i].sequence(), x))
            return false;
          indices[num] = x;
          num++;
        }
      }
      return true;
    }




    void NameParser::calculate_padding (const vector<uint32_t>& maxvals)
    {
      assert (maxvals.size() == seq_index.size());
      for (size_t n = 0; n < seq_index.size(); n++)
        assert (maxvals[n] > 0);

      for (size_t n = 0; n < seq_index.size(); n++) {
        size_t m = seq_index.size() - 1 - n;
        Item& item (array[seq_index[n]]);
        if (item.sequence().size()) {
          if (maxvals[m])
            if (item.sequence().size() != (size_t) maxvals[m])
              throw Exception ("dimensions requested in image specifier \"" + specification
                               + "\" do not match supplied header information");
        }
        else {
          item.sequence().resize (maxvals[m]);
          for (size_t i = 0; i < item.sequence().size(); i++)
            item.sequence() [i] = i;
        }

        item.calc_padding (maxvals[m]);
      }
    }





    void NameParser::Item::calc_padding (size_t maxval)
    {
      for (size_t i = 0; i < sequence().size(); i++) {
        assert (sequence() [i] >= 0);
        if (maxval < (size_t) sequence() [i]) maxval = sequence() [i];
      }

      seq_length = 1;
      for (size_t num = 10; maxval >= num; num *= 10)
        seq_length += 1;
    }





    std::string NameParser::name (const vector<uint32_t>& indices)
    {
      if (!seq_index.size())
        return Path::join (folder_name, array[0].string());

      assert (indices.size() == seq_index.size());

      std::string str;
      size_t n = seq_index.size()-1;
      for (size_t i = 0; i < array.size(); i++) {
        if (array[i].is_string()) str += array[i].string();
        else {
          str += printf ("%*.*d", array[i].size(), array[i].size(), array[i].sequence() [indices[n]]);
          n--;
        }
      }

      return Path::join (folder_name, str);
    }







    std::string NameParser::get_next_match (vector<uint32_t>& indices, bool return_seq_index)
    {
      if (!folder)
        folder.reset (new Path::Dir (folder_name));

      std::string fname;
      while ( (fname = folder->read_name()).size()) {
        if (match (fname, indices)) {
          if (return_seq_index) {
            for (size_t i = 0; i < ndim(); i++) {
              if (sequence (i).size()) {
                uint32_t n = 0;
                while (indices[i] != sequence (i) [n]) n++;
                indices[i] = n;
              }
            }
          }
          return Path::join (folder_name, fname);
        }
      }

      return "";
    }


    bool ParsedName::operator< (const ParsedName& pn) const
    {
      for (size_t i = 0; i < ndim(); i++)
        if (index (i) != pn.index (i))
          return (index (i) < pn.index (i));
      return false;
    }




    vector<uint32_t> ParsedName::List::parse_scan_check (const std::string& specifier, size_t max_num_sequences)
    {
      NameParser parser;
      parser.parse (specifier);

      scan (parser);
      std::sort (list.begin(), list.end(), compare_ptr_contents());
      vector<uint32_t> dim = count();

      for (size_t n = 0; n < dim.size(); n++)
        if (parser.sequence (n).size())
          if (dim[n] != parser.sequence (n).size())
            throw Exception ("number of files found does not match specification \"" + specifier + "\"");

      return dim;
    }






    void ParsedName::List::scan (NameParser& parser)
    {
      vector<uint32_t> index;
      if (parser.ndim() == 0) {
        list.push_back (std::shared_ptr<ParsedName> (new ParsedName (parser.name (index), index)));
        return;
      }

      std::string entry;

      while ( (entry = parser.get_next_match (index, true)).size())
        list.push_back (std::shared_ptr<ParsedName> (new ParsedName (entry, index)));

      if (!size())
        throw Exception ("no matching files found for image specifier \"" + parser.spec() + "\"");
    }






    vector<uint32_t> ParsedName::List::count () const
    {
      if (! list[0]->ndim()) {
        if (size() == 1) return (vector<uint32_t>());
        else throw Exception ("image number mismatch");
      }

      vector<uint32_t> dim ( list[0]->ndim(), 0);
      size_t current_entry = 0;

      count_dim (dim, current_entry, 0);

      return dim;
    }




    void ParsedName::List::count_dim (vector<uint32_t>& dim, size_t& current_entry, size_t current_dim) const
    {
      uint32_t n;
      bool stop = false;
      std::shared_ptr<const ParsedName> first_entry ( list[current_entry]);

      for (n = 0; current_entry < size(); n++) {
        for (size_t d = 0; d < current_dim; d++)
          if ( list[current_entry]->index (d) != first_entry->index (d))
            stop = true;
        if (stop)
          break;

        if (current_dim < list[0]->ndim()-1)
          count_dim (dim, current_entry, current_dim+1);
        else current_entry++;
      }

      if (dim[current_dim] && dim[current_dim] != n)
        throw Exception ("number mismatch between number of images along different dimensions");

      dim[current_dim] = n;
    }






    std::ostream& operator<< (std::ostream& stream, const ParsedName::List& list)
    {
      stream << "parsed name list, size " << list.size() << ", counts " << list.count() << "\n";
      for (const auto& entry : list.list)
        stream << *entry << "\n";
      return stream;
    }







    std::ostream& operator<< (std::ostream& stream, const ParsedName& pin)
    {
      stream << "[ ";
      for (size_t n = 0; n < pin.ndim(); n++)
        stream << pin.index (n) << " ";
      stream << "] " << pin.name();
      return (stream);
    }




  }
}