squant2.cpp 47.2 KB
Newer Older
1
2
3
4
5
6
7
8
//
//  squanty.cpp
//  qparse
// test new architecture Runey
//
//  Created by Florent Jacquemard on 29/03/2019.
//  Copyright © 2019 Florent Jacquemard. All rights reserved.
//
Florent Jacquemard's avatar
Florent Jacquemard committed
9
10
11
/// command line for quantization of input segment according to
/// weighted Symbolic Tree Automaton.

Florent Jacquemard's avatar
Florent Jacquemard committed
12
13
14
/// parsing/enumeration scenari and demos
/// each scenario is defined in a Parser

15
/// workflow inputless:
Florent Jacquemard's avatar
Florent Jacquemard committed
16
/// enumeration of language of a WTA
17
#define QUANT_INPUTLESS                1
Florent Jacquemard's avatar
Florent Jacquemard committed
18
19

/// input segment of musical duration 1 bar, 1 best
20
/// construction of a table indexed by SIP keys
Florent Jacquemard's avatar
Florent Jacquemard committed
21
/// (state, interval, pre/post values)
22
#define QUANT_1BAR_1BEST               2
Florent Jacquemard's avatar
Florent Jacquemard committed
23
24

/// input segment of musical duration 1 bar, K best
25
/// construction of a table indexed by SIP keys
Florent Jacquemard's avatar
Florent Jacquemard committed
26
/// (state, interval, pre/post values)
27
#define QUANT_1BAR_KBEST               3
Florent Jacquemard's avatar
Florent Jacquemard committed
28
29

/// input segment of musical duration several bars, 1 best
30
31
32
33
34
35
/// construction of a table indexed by SI keys (state, interval)
/// runs for sequences of bars constructed as binary trees
#define QUANT_MULTIBAR_1BEST_SI        7

/// input segment of musical duration several bars, 1 best
/// construction of a table indexed by SIP keys
Florent Jacquemard's avatar
Florent Jacquemard committed
36
37
/// (state, interval, pre/post values)
/// runs for sequences of bars constructed as binary trees
38
#define QUANT_MULTIBAR_1BEST_SIP       8
Florent Jacquemard's avatar
Florent Jacquemard committed
39

40
41
42
43
44
45
/// input segment of musical duration several bars, 1 best
/// construction of a table indexed by SIR keys (rests)
/// (state, interval, pre/post values)
/// runs for sequences of bars constructed as binary trees
#define QUANT_MULTIBAR_1BEST_SIR       9

46
47
48
/// idem with SIO keys (refactoring or SIR)
#define QUANT_MULTIBAR_1BEST_SIO       10

Florent Jacquemard's avatar
Florent Jacquemard committed
49
/// input segment of musical duration several bars, 1 best
50
/// construction of a table indexed by SIP keys
Florent Jacquemard's avatar
Florent Jacquemard committed
51
52
/// (state, interval, pre/post values)
/// runs for sequences of bars constructed as lists (flat)
53
#define QUANT_MULTIBAR_1BEST_SIPFLAT   11
Florent Jacquemard's avatar
Florent Jacquemard committed
54
55

/// current scenario
56
#define QUANT_SCENARIO QUANT_MULTIBAR_1BEST_SIO
Florent Jacquemard's avatar
Florent Jacquemard committed
57

58
59
60
61
62
63
64
65
66
67
68
69

#include <stdio.h>
#include <iostream>
#include <time.h>
#include <string>
#include <vector>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>     // handling commandline options
#include <assert.h>

70

71
#include "config.hpp"   // check compile flags
72
73
#include "trace.hpp"
#include "Rational.hpp"
74
#include "util.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
75

Florent Jacquemard's avatar
Florent Jacquemard committed
76
// input segment
77
78
#include "RTU.hpp"
#include "MTU.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
79
80
81
#include "InputSegment.hpp"
#include "InputSegmentSerial.hpp"
#include "InputSegmentMIDI.hpp"
82
#include "InputSegmentMono.hpp"
83
84
#include "Voicing.hpp"
#include "VoicingMono.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
85

Florent Jacquemard's avatar
Florent Jacquemard committed
86
87
// automata and parsing
// switch options for WCFG weight
88
#include "Weight.hpp"
89
#include "WeightDom.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
90
91
92
#include "FloatWeight.hpp"
#include "TropicalWeight.hpp"
#include "ViterbiWeight.hpp"
93
94

#include "Label.hpp"
95
#include "SWTAFileIn.hpp"
96
//#include "Key.hpp"
97
#include "KeyS.hpp"
98
#include "KeySI.hpp"
99
#include "KeySIP.hpp"
100
//#include "KeySIR.hpp"
101
#include "KeySIO.hpp"
102
#include "Runey.hpp"
103
104
#include "RunInner.hpp"
#include "RunTerm.hpp"
105
#include "RunCompare.hpp"
Florent Jacquemard's avatar
doc    
Florent Jacquemard committed
106
#include "RecordOne.hpp"
107
#include "RecordQueue.hpp"
108
109
#include "TableA.hpp"
#include "TableParse.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
110
#include "Quantizer.hpp"
111

Florent Jacquemard's avatar
Florent Jacquemard committed
112
// output
113
#include "LRT.hpp"
赤尾健太's avatar
赤尾健太 committed
114
//#include "ScoringEnv.hpp";
115
#include "TableMonoImporter.hpp"
116
#include "MIDIOutput.hpp"
117
#include "LRTTableIn.hpp"
赤尾健太's avatar
赤尾健太 committed
118
//#include "MEI.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
119
120
121
122
#include "Score.hpp"
#include "Event.hpp"
#include "Measure.hpp"
#include "Note.hpp"
123
#include "PS0.hpp"
124
#include "TableMonoImporter.hpp"
125
#include "SMPrinter.hpp"
126
#include "SMMEI.hpp"
Florent Jacquemard's avatar
Florent Jacquemard committed
127

128
129
130
namespace ScoreModel {};
namespace sm = ScoreModel;

Florent Jacquemard's avatar
Florent Jacquemard committed
131
132
133
134
135
136
137

// ==========================================================================
// Option handling with getop_long (stdlib)

static int verbosity = 0;

/// number of K-best to compute   //was #define TEST_K 1
138
static size_t _nbest = 1;
Florent Jacquemard's avatar
Florent Jacquemard committed
139

Florent Jacquemard's avatar
Florent Jacquemard committed
140
141
142
/// whether the best is the max (true) or the min (false) weight
static int f_max = true;

143
/// input file option is present
Florent Jacquemard's avatar
Florent Jacquemard committed
144
static bool f_input = false;
145
146
/// input file is text
static bool f_in_text = false;
Florent Jacquemard's avatar
Florent Jacquemard committed
147
/// input file is midi
148
149
150
static bool f_in_midi = false;
/// file name for reading input segment
static string _input_file;
Florent Jacquemard's avatar
Florent Jacquemard committed
151
152
153
/// input segment
static InputSegment* _iseg;

154
155
156
/// transform the input midi file into monophonic
static int f_mono = false;

Florent Jacquemard's avatar
Florent Jacquemard committed
157
158
159
160
161
162
/// ignore rests in input midi file
static int f_norest = false;

/// start date option is present
static int f_start = false;
/// argument of start date option
163
static rtu_t d_start;
Florent Jacquemard's avatar
Florent Jacquemard committed
164
165
166
167

/// end date option is present
static int f_end = false;
/// argument of end date option
168
static rtu_t d_end;
Florent Jacquemard's avatar
Florent Jacquemard committed
169
170
171

/// output file option is present
static bool f_output = false;
172
173
174
175
176
/// output file is mei
static bool f_out_mei = false;
/// output file is midi
static bool f_out_midi = false;
/// output file name for writing
Florent Jacquemard's avatar
Florent Jacquemard committed
177
178
179
180
181
182
183
184
185
186
187
188
static string _output_file;

/// config file (aka ini) option is present
static bool f_config = false;
/// text file name for writing
static string _config_file;

/// file name for reading schema
static string _schema_file;
/// schema file is present
static bool f_schema = false;
/// input schema
189
static SWTAFileIn* _schema;
Florent Jacquemard's avatar
Florent Jacquemard committed
190
191
192
193
194
195
196
197
198
199
200
201

/// flag: clean WCFG
static int f_clean = false;

/// flag: number of bars specified (otherwise default = 1)
static int f_bars = false;
/// number of bars in input
static size_t _bars = 1;

/// flag: bar real-time dur specified (otherwise default = 1)
static int f_barsec = false;
///  real-time duration of bar
202
static rtu_t _barsec = 1;
Florent Jacquemard's avatar
Florent Jacquemard committed
203
204
205
206
207
208
209
210
211

/// flag: bar musical-time dur specified (otherwise default = 1)
static int f_barbeat = false;
///  musical-time duration of bar
static size_t _barbeat = 1;

/// flag: time signature specified
static int f_timesig = false;
/// time signature
212
static sm::MeterSig _ts(4,4);
Florent Jacquemard's avatar
Florent Jacquemard committed
213
214
215
216
//static int _ts_num;
//static int _ts_den;

/// flag: pre value
217
/// @todo TBR?
Florent Jacquemard's avatar
Florent Jacquemard committed
218
219
static int f_pre = false;
/// argument of pre option
220
221
/// @todo TBR?
static size_t _pre = 0;
Florent Jacquemard's avatar
Florent Jacquemard committed
222
223
224
225

/// flag: post value
static int f_post = false;
/// argument of post option
226
static size_t _post = 0;
Florent Jacquemard's avatar
Florent Jacquemard committed
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

/// forced weight type for WCFG (given in command line options)
static int f_penalty = false;
static int f_count = false;
static int f_proba = false;
static WeightDom _weight_type = WeightDom::UNDEF;

static struct option long_options[] =
{
    // Options with an abbreviation
    // we dont use flags here, we set them after calling getopt instead
    
    /*  0 */ { "help",        no_argument,       NULL, 'h' },
    /*  1 */ { "version",     no_argument,       NULL, 'V' },
    
    /*  2 */ { "verbosity",   required_argument, NULL, 'v' },
    /*  3 */ { "debug",       no_argument,       NULL, 'd' },
    /*  4 */ { "trace",       no_argument,       NULL, 't' },
    /*  5 */ { "quiet",       no_argument,       NULL, 'q' },
    
    /*  6 */ { "kbest",       required_argument, NULL, 'k' },
    
    /*  7 */ { "input",       required_argument, NULL, 'i' },
    /*  8 */ { "midi",        required_argument, NULL, 'm' },
    /*  9 */ { "schema",      required_argument, NULL, 'a' },
    /* 10 */ { "output",      required_argument, NULL, 'o' },
    /* 11 */ { "config",      required_argument, NULL, 'c' },
    
    // Options with no abbreviation
    
    /* 12 */ { "penalty",     no_argument,       &f_penalty, true},
    /* 13 */ { "counting",    no_argument,       &f_count,   true },
    /* 14 */ { "proba",       no_argument,       &f_proba,   true },
    /* 15 */ { "probability", no_argument,       &f_proba,   true },
    /* 16 */ { "stochastic",  no_argument,       &f_proba,   true },
    /* 17 */ { "clean",       no_argument,       &f_clean,   true },
    /* 18 */ { "norest",      no_argument,       &f_norest,  true },
    /* 19 */ { "start",       required_argument, &f_start,   true },
    /* 20 */ { "end",         required_argument, &f_end,     true },
    /* 21 */ { "bars",        required_argument, &f_bars,    true },
    /* 22 */ { "pre",         required_argument, &f_pre,     true },
    /* 23 */ { "post",        required_argument, &f_post,    true },
    /* 24 */ { "barsec",      required_argument, &f_barsec,  true },
    /* 25 */ { "barbeat",     required_argument, &f_barbeat, true },
    /* 26 */ { "ts",          required_argument, &f_timesig, true },
Florent Jacquemard's avatar
Florent Jacquemard committed
272
273
    /* 27 */ { "min",         no_argument,       &f_max,     false },
    /* 28 */ { "max",         no_argument,       &f_max,     true },
274
    /* 29 */ { "mono",        no_argument,       &f_mono,    true },
Florent Jacquemard's avatar
Florent Jacquemard committed
275
276

    
Florent Jacquemard's avatar
Florent Jacquemard committed
277
278
279
280
    /* last */ { NULL, 0, NULL, 0 }
};


Florent Jacquemard's avatar
Florent Jacquemard committed
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
void usage()
{
    std::cout << "Usage: squant2 [options...]";
    std::cout << std::endl;
    std::cout << "  -help -h";
    std::cout << std::endl;
    std::cout << "  -version -V";
    std::cout << std::endl;
    std::cout << "  -verbosity level -v level : level=0..6  (default is 0)";
    std::cout << std::endl;
    std::cout << "             levels: 0=off, 1=critical, 2=err, 3=warn";
    std::cout << std::endl;
    std::cout << "                     4=info, 5=debug, 6=trace";
    std::cout << std::endl;
    std::cout << "  -trace -t : same as -verbosity 6";
    std::cout << std::endl;
    std::cout << "  -debug -d : same as -verbosity 5";
    std::cout << std::endl;
    std::cout << "  -quiet -q : same as -verbosity 0";
    std::cout << std::endl;
    std::cout << "  --kbest N -k N : compute the N best trees";
    std::cout << std::endl;
    std::cout << "  -max : the best is the max weight";
    std::cout << std::endl;
    std::cout << "  -min : the best is the min weight";
    std::cout << std::endl;
    std::cout << "  -input filename -i filename : \
          filename is either a text file or midifile \
          (characterized by extension .mid or .midi)";
    std::cout << std::endl;
    std::cout << "  -midi midifilename -m midifilename : filename is a midi file";
    std::cout << std::endl;
    std::cout << "  -mono  : convert input midifile to monophonic";
    std::cout << std::endl;
    std::cout << "  -norest  : ignore rests in input midifile and convert to mono";
    std::cout << std::endl;
    std::cout << "  -start D : set start date for input segment";
    std::cout << std::endl;
    std::cout << "  -end D   : set end date for input segment";
    std::cout << std::endl;
    std::cout << "  -schema filename -a filename : filename contains \
          the text description of a WCFG";
    std::cout << std::endl;
    std::cout << "  -clean  : clean input schema";
    std::cout << std::endl;
    std::cout << "  -output filename -o filename : output file \
          .mei for a MEI score output,\
          .midi or .mid for a MIDI file";
    std::cout << std::endl;
    std::cout << "  -config file.ini -c file.ini : configuration file";
    std::cout << std::endl;
    std::cout << "schema weight models (mutually exclusive options):";
    std::cout << std::endl;
    std::cout << "  -counting";
    std::cout << std::endl;
    std::cout << "  -penalty";
    std::cout << std::endl;
    std::cout << "  -probability -stochastic (equivalent)";
    std::cout << std::endl;
    std::cout << "  -pre I : number of notes added (as grace notes)\
          at the begining of the segment to quantize,\
          e.g. originating from another precedent segment";
    std::cout << std::endl;
    std::cout << "  -post I : number of notes that will be aligned to right bound\
          in quantization solutions";
    std::cout << std::endl;
    std::cout << "   -bar I : number of bars in the input segment (default 1)";
    std::cout << std::endl;
    std::cout << "   -barsec D : assumed real-time duration of 1 bar, in seconds (default 1)";
    std::cout << std::endl;
    std::cout << "   -barbeat I : musical-ime duration of 1 bar, in beats (default 1)";
    std::cout << std::endl;
    std::cout << "   -ts \"n/d\" : time signature (default 4/4)";
    std::cout << std::endl;
    std::cout << std::endl;
    std::cout << "-input and -midi are mutualy exclusive";
    std::cout << std::endl;
    std::cout << "-bar and -barsec are mutualy exclusive";
    std::cout << std::endl;
    std::cout << "-probability -stochastic are equivalent";
    std::cout << std::endl;
    std::cout << "-counting -penalty -probability -stochastic are mutually exclusive";
    std::cout << std::endl;
    std::cout << "-trace has priority over -verbosity";
    std::cout << std::endl;
}


void version()
{
    INFO("qparse: version 2");
}

Florent Jacquemard's avatar
Florent Jacquemard committed
374
375
376
377
378
379
380

// ==========================================================================
// Option handling with getop_long (stdlib)

#define check_index_is(NAME) \
assert(0 == strcmp(long_options[option_index].name, NAME))

Florent Jacquemard's avatar
Florent Jacquemard committed
381

Florent Jacquemard's avatar
Florent Jacquemard committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
static void setOptionArgs(int option_index)
{
    TRACE("options: setOptionArgs: {}", option_index);
    string _arg;
    size_t sepindex;
    
    // long options without abbreviation and with argument
    switch(option_index)
    {
        case 19:
            check_index_is("start");
            assert (f_start);
            d_start = strtod(optarg, NULL);
            TRACE("options: setOptionArgs {}: {}", long_options[option_index].name, d_start);
            break;
            
        case 20:
            check_index_is("end");
            assert (f_end);
            d_end = strtod(optarg, NULL);
            TRACE("options: setOptionArgs {}: {}", long_options[option_index].name, d_end);
            break;
            
        case 21:
            check_index_is("bars");
            assert (f_bars);
            _bars = strtol(optarg, NULL, 10);
            TRACE("options: setOptionArgs {}: {}",
                  long_options[option_index].name, _bars);
            break;
            
        case 22:
            check_index_is("pre");
            assert (f_pre);
            _pre = strtol(optarg, NULL, 10);
            TRACE("options: setOptionArgs {}: {}", long_options[option_index].name, _pre);
            break;
            
        case 23:
            check_index_is("post");
            assert (f_post);
            _post = strtol(optarg, NULL, 10);
            TRACE("options: setOptionArgs {}: {}",
                  long_options[option_index].name,
                  _post);
            break;
            
        case 24:
            check_index_is("barsec");
            assert (f_barsec);
            _barsec = strtod(optarg, NULL);
            TRACE("options: setOptionArgs {}: {}",
                  long_options[option_index].name, _barsec);
            break;
            
        case 25:
            check_index_is("barbeat");
            assert (f_barbeat);
            _barbeat = strtol(optarg, NULL, 10);
            TRACE("options: setOptionArgs {}: {}",
                  long_options[option_index].name, _barsec);
            break;
            
        case 26:
            check_index_is("ts");
            assert (f_timesig);
            _arg = string(optarg);
            sepindex = _arg.find_last_of("/");
            // prefix
451
            // prefix, suffix
452
            _ts = sm::MeterSig(std::stoi(_arg.substr(0, sepindex)),
453
                std::stoi(_arg.substr(sepindex + 1, _arg.size() - sepindex)));
Florent Jacquemard's avatar
Florent Jacquemard committed
454
455
456
457
            TRACE("options: setOptionArgs {}: {}",
                  long_options[option_index].name, optarg);
            break;
            
Florent Jacquemard's avatar
Florent Jacquemard committed
458
            
Florent Jacquemard's avatar
Florent Jacquemard committed
459
460
461
462
463
        default:
            ; // ignore
    }
}

Florent Jacquemard's avatar
Florent Jacquemard committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521

/// @param c character of option
/// @return   0 : continue without error
///           1 : stop without error
///         > 1 : stop with error
static int getOption(int c, int option_index)
{
    // end of the options
    assert(c != -1);

    switch (c)
    {
            // long option with flag pointer
        case 0:
            setOptionArgs(option_index);
            break;
            
        case 'h':
            usage();
            return 1;
            
        case 'V':
            version();
            return 1;
            
        case 'v':
            if (optarg)
                //verbosity = strtol(optarg, NULL, 10);
                verbosity = atoi(optarg);
            else
                verbosity = 4;
            TRACE("option {}: {}", long_options[option_index].name,
                  verbosity);
            break;
            
        case 'd':
            verbosity = 5;
            TRACE("option {}: verbosity={}",
                  long_options[option_index].name,
                  verbosity);
            break;
            
        case 't':
            verbosity = 6;
            TRACE("option {}: verbosity={}",
                  long_options[option_index].name,
                  verbosity);
            break;
            
        case 'q':
            verbosity = 0;
            TRACE("option {}: verbosity={}",
                  long_options[option_index].name,
                  verbosity);
            break;
            
        case 'k':
            //k = strtoul(optarg, NULL, 10);
522
            _nbest = atoi(optarg);
Florent Jacquemard's avatar
Florent Jacquemard committed
523
            TRACE("Option {} : {}",
524
525
                  long_options[option_index].name, _nbest);
            if (_nbest == 0)
Florent Jacquemard's avatar
Florent Jacquemard committed
526
            {
527
                ERROR("option error: k={} must be > 0", _nbest);
Florent Jacquemard's avatar
Florent Jacquemard committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
                return 2;
            }
            break;
            
        case 'i':
            f_input = true;
            _input_file = std::string(optarg);
            TRACE("Option {}: {}",
                  long_options[option_index].name, _input_file);
            // distinguish between MIDI and text input
            if (_input_file.size() > 0)
            {
                string suffix = util::suffix(_input_file);
                
                // export only if output file has midi suffix
                if (suffix == "MID" || suffix == "MIDI")
                {
                    INFO("option input: MIDI file import");
                    f_in_midi = true;
                }
                else if (suffix == "TXT")
                {
                    INFO("option input: plaintext file import");
                    f_in_text = true;
                }
                else
                {
                    WARN("option -i input file {}, \
                          no suffix .txt or .midi or .mid found, assume text",
                          _input_file);
                    f_in_text = true;
                }
            }
            else
            {
                ERROR("option -i error: no output file name");
                return 2;
            }
            
            break;
            
        case 'm':
            f_input = true;
            f_in_midi = true;
            _input_file = std::string(optarg);
            TRACE("option {}: {}",
                  long_options[option_index].name, _input_file);
            break;
                
        case 'o':
            f_output = true;
            _output_file = std::string(optarg);
            TRACE("option {}: {}", long_options[option_index].name,
                  _output_file);
            
            if (_output_file.size() > 0) // empty string : no output
            {
                string suffix = util::suffix(_output_file);
                
                // export only if output file has midi suffix
                if (suffix == "MID" || suffix == "MIDI")
                {
                    INFO("option output: MIDI file export");
                    f_out_midi = true;
                }
                else if (suffix == "MEI")
                {
                    INFO("option output: MEI file export");
                    f_out_mei = true;
                }
                else
                {
                    ERROR("option -o error: ouput file {}, \
                           suffix must be .mei or .midi or .mid",
                          _output_file);
                    return 2;
                }
            }
            else
            {
                ERROR("option -o error: no output file name");
                return 2;
            }
            break;
            
        case 'c':
            f_config = true;
            _config_file = std::string(optarg);
            TRACE("Option {}: {}", long_options[option_index].name,
                  _config_file);
            break;
            
        case 'a':
            f_schema = true;
            _schema_file = std::string(optarg);
            TRACE("Option {}: {}",
                  long_options[option_index].name, _schema_file);
            break;
            
        //  missing option argument. Error already signaled by getopt
        case ':':
            ERROR("option error: missing option argument (ignore)");
            break;
            
        // unknown or ambiguous option  Error already signaled by getopt
        case '?':
            ERROR("option error: unkown or ambiguous option argument (ignore)");
            break;
            
            // Do nothing for the options that are not flag-managed but without arguments
        default:
            ERROR("Unknown option {} ignored, use -h for help.", c);
            break;
    }
    
    return 0;
}


Florent Jacquemard's avatar
Florent Jacquemard committed
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
bool checkOptions()
{
    bool error = false;
    
    if (f_penalty || f_count || f_proba)
    {
        if ((f_penalty && f_count) || ((f_penalty || f_count) == f_proba))
        {
            ERROR("options conflict: more than one schema file type");
            error = true;
        }
    }
    else
    {
        TRACE("options: no schema file type");
    }
    
    // set forced weight type value
    if (f_penalty)
    {
        _weight_type = WeightDom::PENALTY;
    }
    else if (f_count)
    {
        _weight_type = WeightDom::COUNTING;
    }
    else if (f_proba)
    {
        _weight_type = WeightDom::STOCHASTIC;
    }
    else
    {
        _weight_type = WeightDom::UNDEF;
    }
    
682
    if (f_in_text == f_in_midi)
Florent Jacquemard's avatar
Florent Jacquemard committed
683
    {
684
685
        TRACE("options: f_input={}, f_in_midi={}", f_input, f_in_midi);
        if (f_in_midi)
Florent Jacquemard's avatar
Florent Jacquemard committed
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
        {
            ERROR("options conflict: 2 input files");
            error = true;
        }
        else
        {
            TRACE("options: no input file");
        }
    }
    
    if (! f_schema)
    {
        ERROR("missing option: schema file");
        error = true;
    }
    
    if (f_start && f_end)
    {
        if (d_end < d_start)
        {
            ERROR("start date must be before end date");
            error = true;
        }
        if (! f_input)
        {
            ERROR("options: set start or end date without input");
            error = true;
        }
    }
    
    if (f_bars && f_barsec)
    {
        ERROR("options bars and barsec are mutually exclusive");
        error = true;
    }
721
722
723
724
725
726
727
728
729

    if (f_out_midi && (! f_barbeat))
    {
        /// @todo adjust according to grammar optional content
        /// SchemaFileIn.readTimesignature or
        /// SchemaFileIn.read_option
        ERROR("options: barbeat must be given for MIDI output");
        error = true;
    }
Florent Jacquemard's avatar
Florent Jacquemard committed
730
731
732
733
734
    
    return error;
}


Florent Jacquemard's avatar
Florent Jacquemard committed
735
void setVerbosityLevel()
Florent Jacquemard's avatar
Florent Jacquemard committed
736
{
Florent Jacquemard's avatar
Florent Jacquemard committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
    switch (verbosity)
    {
        case 0: spd::set_level(spd::level::off); break;
        case 1: spd::set_level(spd::level::critical); break;
        case 2: spd::set_level(spd::level::err); break;
        case 3: spd::set_level(spd::level::warn); break;
        case 4: spd::set_level(spd::level::info); break;
        case 5: spd::set_level(spd::level::debug); break;
        case 6: spd::set_level(spd::level::trace); break;
        default:
        {
            WARN("verbosity level {} too high, set to 6 (trace).", verbosity);
            spd::set_level(spd::level::trace);
        }
    }
Florent Jacquemard's avatar
Florent Jacquemard committed
752
753
}

754

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/// @param init initial key to start parsing.
/// @param n number of best trees to compute.
/// @param f_max whether the best is the max (true) or the min (false) weight
/// @param env parsing environment (input and automaton).
/// @return the parse table computed, containing the k best trees..
/// - K = concrete key class (index rows in the table)
/// - H = KeyHasher (for keys)
template<class K, class H>
parsing::TableA<K>* parse(const K& init,
                          size_t n,
                          bool f_max,
                          parsing::ParsingEnv& env)
{
    assert(env.segment);
    parsing::RunCompare comp = (f_max)?parsing::weightMax:parsing::weightMin;
    parsing::TableA<K>* tab = nullptr;

    // initialize table (empty)
    if (n == 1)     // 1-best
    {
        tab = new parsing::TableParse<K, parsing::RecordOne<K>, H>(env, comp);
    }
    else             // k-best
    {
        assert(n > 1); // cannot be 0
        tab = new parsing::TableParse<K, parsing::RecordQueue<K>, H>(env, comp);
    }
    
    // fill table up to n-best
    assert(tab);
    tab->best(init, n); // const parsing::Run* (not used)

    return tab;
}


/// extract a ScoreModel with 1 unique part from the 1-best tree in given table.
/// @param tab a parse table.
/// @param init initial key at top of the 1-best tree.
/// @param ts metre signature
/// @param scorename name given to the score in the build Score Model
/// @param partname name given to the unique part in the build Score Model
/// @param env scoring environment (input and automaton and voices).
template<class K>
sm::Score* buildSM(parsing::TableA<K>& tab,
                   const K& init,
                   const sm::MeterSig& ts,
                   const string& scorename,
                   const string& partname,
                   sm::ScoringEnv& env)
{
    sm::TableMonoImporter importer(std::string(scorename), ts);
    importer.readPart<K>(std::string("part1"), env, tab, init, 1);
    sm::Score* score = importer.getScore();
    assert(score);
    return score;
}


void spellPitch(sm::Score& score)
{
    for (sm::PartSeq::iterator i = score.begin(); i != score.end(); ++i)
    {
        sm::Part& part = **i;
        INFO("Pitch Spelling part: {}", part.id());
        sm::PS0 ps = sm::PS0(part);
        ps.spell1();
    }
}


void printSM(const sm::Score& score)
{
    sm::Printer sm_pp = sm::Printer(std::cout, false);
    std::cout << std::endl;
    sm_pp.visitScore(&score);
    std::cout << std::endl;
}


/// @param tab a parse table.
/// @param init initial key to start parsing.
/// @param n number of best trees to compute.
template<class K>
void printTrees(parsing::TableA<K>& tab,
                const K& init,
                size_t n)
{
    for (size_t i = 1; i <= _nbest; i++)
    {
        const parsing::Run* best_run = tab.best(init, i);

        if (best_run == NULL) // should no more happen (changed to FAIL)
        {
            //assert(best_tree == NULL);
            INFO("{}-best: NULL", i);
        }
        else if (_nbest == 1)
        {
            //LabeledRhythmTree* best_tree = tab->bestTree(best_run);
            LabeledRhythmTree* best_tree =
                LRTFactory<K>::projection(tab, best_run, 1);
            assert(best_tree);
            INFO("{}-best = {} weight = {}", i,
                 best_tree->to_string(), best_run->weight());
            delete best_tree;
        }
        else
        {
            const parsing::RunRanked<parsing::KeySIP>* best_runr =
                dynamic_cast<const parsing::RunRanked<parsing::KeySIP>*>(best_run);
            assert(best_runr);
            //LabeledRhythmTree* best_tree = tab->bestTree(best_runr);
            LabeledRhythmTree* best_tree =
                LRTFactory<K>::projection(tab, best_runr);
            assert(best_tree);
            INFO("{}-best = {} weight = {}", i,
                 best_tree->to_string(), best_run->weight());
            delete best_tree;
        }
    }

}


size_t writeMEI(const sm::Score& score,
                const string& filename)
{
    string prefix = util::prefix(filename);
    
    if (score.nbParts() == 0)
    {
        ERROR("empty score (0 parts)");
        return 1;
    }

    INFO("Export part 1/{} of the score model into MEI.", score.nbParts());
    sm::MEIExporter sm_export = sm::MEIExporter();
    sm::PartSeq::const_iterator pi = score.cbegin();
    assert(pi != score.cend());
    assert(*pi);
    sm::Part& part1 = *(*pi);
    sm_export.addScore(part1);
    INFO("write to {}", filename);
    sm_export.writeInFile(filename);
    return 0;
}


template<class K>
size_t exportMIDI(parsing::TableA<K>& tab,
                  const K& init,
                  Rational barbeat,
                  const string& input_filename,
                  const string& output_filename,
                  parsing::ParsingEnv& env)
{
    assert(env.segment);
    INFO("quantize segment ({} points) wrt parse tree", env.segment->size()-1);
    // quantize wrt the 1-best for k0
    //_iseg->quantize<parsing::KeySIR>(tab, k0, 1);
    parsing::Quantizer<K> quantizer(tab);
    quantizer.quantize(*(env.segment), init, 1);
    INFO("quantized input segment:");
    env.segment->print(std::cout);
    // qseg->respell(); // not for MIDI out!
    INFO("export to MIDI file {}", output_filename);
    if (output_filename.empty())
        return 2;
    assert(barbeat > Rational(0));
    MIDIExporter midiexport(output_filename, barbeat);
    // track nb = 1
    assert(! input_filename.empty());
    midiexport.export_midifile(*(env.segment), input_filename, 1);
    return 0;
}
Florent Jacquemard's avatar
Florent Jacquemard committed
931

932
933


Florent Jacquemard's avatar
Florent Jacquemard committed
934
935
936



937
938
int main(int argc, char** argv)
{
Florent Jacquemard's avatar
Florent Jacquemard committed
939
940
    //clock_t time_start;     // chrono
    //clock_t time_end;
Florent Jacquemard's avatar
Florent Jacquemard committed
941
942
          

Florent Jacquemard's avatar
Florent Jacquemard committed
943
    // read command line options
Florent Jacquemard's avatar
Florent Jacquemard committed
944
    int c; // character of option
Florent Jacquemard's avatar
Florent Jacquemard committed
945
946
947
948
949
950
951
    
    while(1)
    {
        /* getopt_long stores the option index here. */
        int option_index = 0;
        c = getopt_long_only(argc, argv, "hVv:dtk:i:m:a:",
                             long_options, &option_index);
Florent Jacquemard's avatar
Florent Jacquemard committed
952
                
Florent Jacquemard's avatar
Florent Jacquemard committed
953
954
955
956
        // end of the options
        if (c == -1)
            break;
        
Florent Jacquemard's avatar
Florent Jacquemard committed
957
958
959
960
961
962
963
964
        int ret = getOption(c, option_index);
        
        // if ret ==0 : no problem, continue
        // exit silently
        if (ret == 1)
            return 0;
        // exit with error message
        else if (ret > 1)
Florent Jacquemard's avatar
Florent Jacquemard committed
965
        {
Florent Jacquemard's avatar
Florent Jacquemard committed
966
967
            ERROR("error in options (code {}), exit", ret);
            return ret;
Florent Jacquemard's avatar
Florent Jacquemard committed
968
969
        }
    }
Florent Jacquemard's avatar
Florent Jacquemard committed
970
        
Florent Jacquemard's avatar
Florent Jacquemard committed
971
972
    if (checkOptions())
    {
Florent Jacquemard's avatar
Florent Jacquemard committed
973
        ERROR("option error, exit");
Florent Jacquemard's avatar
Florent Jacquemard committed
974
975
976
977
        std::cerr << "option error. exit";
        return(1);
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
978
979
980
981
982
983
984
985
986

    // set verbosity level. log levels:
    // trace = 0,
    // debug = 1,
    // info = 2,
    // warn = 3,
    // err = 4,
    // critical = 5,
    // off = 6
Florent Jacquemard's avatar
Florent Jacquemard committed
987
    INFO("verbosity level = {}", verbosity);
Florent Jacquemard's avatar
Florent Jacquemard committed
988
989
    spd::set_level(spd::level::debug);     // default
    setVerbosityLevel();
Florent Jacquemard's avatar
Florent Jacquemard committed
990
    
Florent Jacquemard's avatar
Florent Jacquemard committed
991
992

    // display input/output options
Florent Jacquemard's avatar
Florent Jacquemard committed
993
994
995
    if (f_input) { INFO("input file: {}", _input_file); }
    INFO("schema file: {} ({} weight model option)",
         _schema_file,
996
        (f_count?"counting":(f_proba?"stochastic":(f_penalty?"penalty":"???"))));
Florent Jacquemard's avatar
Florent Jacquemard committed
997
998
999
    
    if (f_output) { INFO("output file: {}", _output_file); }
    if (f_config) { INFO("config file: {}", _config_file); }
Florent Jacquemard's avatar
Florent Jacquemard committed
1000

Florent Jacquemard's avatar
Florent Jacquemard committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
    
    // initialize running environment from INI file
    if (f_config)
    {
        INFO("loading config. parameters from ini file {}", _config_file);
        int res = read_config(_config_file);
        if (res == 0)
        {
            INFO("reading config from {} OK", _config_file);
        }
        else if (res == -1)
        {
            ERROR("error opening config file {}", _config_file);
            return 1;
        }
        else
        {
            ERROR("parse error in config file {} line {}", _config_file, res);
            return 2;
        }
    }
1022
        
Florent Jacquemard's avatar
Florent Jacquemard committed
1023
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1024
1025
1026
1027
1028
1029
1030
    // adjust options after reading config file
    // (possible redundancies between config.ini file and options)
    if ((! f_norest) && OPT_NOREST)
    {
        f_norest = true;
    }
    
1031
1032
1033
1034
1035
1036
    if (f_norest && (! f_mono))
    {
        TRACE("option norest: input midi file implicitly assumed mono");
        f_mono = true;
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1037
1038

    // read base schema (global) from file
Florent Jacquemard's avatar
Florent Jacquemard committed
1039
    INFO("Reading schema from {}", _schema_file);
1040
    _schema = new SWTAFileIn(_schema_file, _weight_type);
Florent Jacquemard's avatar
Florent Jacquemard committed
1041
1042
1043
1044
1045
1046
1047
    
    if (_schema == NULL || _schema->empty())
    {
        ERROR("error reading schema {}, abort", _schema_file);
        return(2);
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1048
1049
1050
1051
1052
1053
1054
    if (f_timesig)
    {
        INFO("Time Signature (from command line option) {}/{}",
             _ts.getCount(), _ts.getUnit());
    }
    else
    {
1055
        if (SchemaFileIn::readTimesignature(_schema_file, _ts))
Florent Jacquemard's avatar
Florent Jacquemard committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
        {
            INFO("Time Signature (from file {}) {}/{}",
                 _schema_file, _ts.getCount(), _ts.getUnit());
        }
        else
        {
            INFO("could not find time signature in {}, default to 4/4",
                 _schema_file);
        }
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1067
1068

    // set domain of weights (cost values)
Florent Jacquemard's avatar
Florent Jacquemard committed
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    if (CST_WEIGHT_TYPE == WeightDom::UNDEF)
    {
        ERROR("no weight type found for {}, abort", _schema_file);
        return(3);
    }
    
    switch(CST_WEIGHT_TYPE)
    {
        case WeightDom::UNDEF:
            ERROR("weight type undef after importing automaton. abort.");
            return(4); break;
        case WeightDom::PENALTY:
1081
            INFO("weight model: penalty (alpha = {})", Weight::CST_ALPHA);
Florent Jacquemard's avatar
Florent Jacquemard committed
1082
1083
            break;
        case WeightDom::STOCHASTIC:
1084
            INFO("weight type: stochastic (sigma2 = {})", Weight::CST_SIGMA2);
Florent Jacquemard's avatar
Florent Jacquemard committed
1085
1086
1087
1088
1089
1090
            break;
        case WeightDom::COUNTING:
            ERROR("weight type counting not supported for quantization. abort.");
            return(4);
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1091
1092
1093

    // cleaning of base schema [optional]
    // TBC : remove 0 weighted transitions
Florent Jacquemard's avatar
Florent Jacquemard committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
    if (f_clean)
    {
        INFO("Cleaning schema");
        _schema->clean();
    }
    // TBC normalization flag ?
    if (! _schema->isClean())
    {
        ERROR("schema {} is not clean, abort.", _schema_file);
        set<state_t> empty = _schema->emptyStates();
        for (set<state_t>::iterator i = empty.begin(); i != empty.end(); i++)
        {
            ERROR("empty state : {}", *i);
        }
        
        return 2;
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1112
1113

    // display base schema
1114
    INFO("SWTAFileIn (after casting and cleaning):");
Florent Jacquemard's avatar
Florent Jacquemard committed
1115
1116
1117
1118
1119
1120
    if (verbosity >= 4) // info
    {
        std::cout << *(_schema);
        _schema->print(cout);
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1121
1122

    // read input segment (global) from file
Florent Jacquemard's avatar
Florent Jacquemard committed
1123
1124
1125
1126
    _iseg = NULL;
    
    // the input file is parsed as a midifile
    // if one of the following condition holds:
1127
    // - the option -m was used (flag f_in_midi is set)
Florent Jacquemard's avatar
Florent Jacquemard committed
1128
1129
1130
    // - the file has suffix .mid or .ID or .midi or .MIDI
    // otherwise is it parsed as a plain text file
    // describing monophonic segment.
1131
    if (f_input)
Florent Jacquemard's avatar
Florent Jacquemard committed
1132
    {
1133
1134
        //assert(f_in_midi || f_in_text);
        if (f_in_midi)
Florent Jacquemard's avatar
Florent Jacquemard committed
1135
1136
        {
            // TBC (uses stubs)
1137
            INFO("main: read input segment from MIDI file {}", _input_file);
1138
            // track nb = 1
1139
            InputSegmentMIDI* _iseg0 = new InputSegmentMIDI(_input_file, 1);
1140
1141
            if (f_mono)
            {
1142
1143
                INFO("main: make input segment mono, {} rests",
                     (f_norest == true)?"without":"with");
1144
1145
1146
1147
1148
1149
1150
                _iseg = new InputSegmentMono(*_iseg0, f_norest);
                delete _iseg0;
            }
            else
            {
                _iseg = _iseg0;
            }
Florent Jacquemard's avatar
Florent Jacquemard committed
1151
        }
1152
        else if (f_in_text)
Florent Jacquemard's avatar
Florent Jacquemard committed
1153
        {
1154
            INFO("main: build input segment from text file {}", _input_file);
Florent Jacquemard's avatar
Florent Jacquemard committed
1155
1156
            _iseg = new InputSegmentSerial(_input_file, true);
        }
1157
1158
1159
1160
        else
        {
            ERROR("input file {} of unknown type", _input_file);
        }
Florent Jacquemard's avatar
Florent Jacquemard committed
1161
1162
    }
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1163
    if (f_start || f_end) // change start/end dates of input segment
Florent Jacquemard's avatar
Florent Jacquemard committed
1164
1165
    {
        assert(_iseg);
1166
1167
        rtu_t begin = f_start?d_start:_iseg->rbegin();
        rtu_t end = f_end?d_end:_iseg->rend();
Florent Jacquemard's avatar
Florent Jacquemard committed
1168
1169
1170
1171
1172
1173
1174
        INFO("reset input segment start to {}, end to {}", begin, end);
        InputSegment* save = _iseg;
        // copy and resize
        _iseg = new InputSegment((*save), begin, end);
        //delete save;
    }
    
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
    if (f_bars)
    {
        assert(! f_barsec);
        assert(_iseg);
        assert(_bars > 0);
        _barsec = (_iseg->Interval::rduration()) / _bars;
    }
    
    if (f_barsec)
    {
        assert(! f_bars);
        assert(_iseg);
        assert(_barsec > 0);
        _bars = std::ceil(_iseg->Interval::rduration() / _barsec);
    }
        
Florent Jacquemard's avatar
Florent Jacquemard committed
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
    if (_iseg && _iseg->size() == 0)
    {
        ERROR("empty segment, stopping");
        return(2);
    }
    else if (_iseg && verbosity >= 4) // info
    {
        INFO("segment : {} events", _iseg->size());
        _iseg->print(std::cout);
    }
    
    
1203
#if QUANT_SCENARIO == QUANT_INPUTLESS
1204
    typedef parsing::KeyS KeyS;
1205

1206
1207
1208
    INFO("{}-best computation", _nbest);
    // no input segment
    assert(_schema);
1209
    parsing::ParsingEnv env = parsing::ParsingEnv(_schema, NULL);
Florent Jacquemard's avatar
Florent Jacquemard committed
1210
1211
    state_t init = _schema->initial();
    const KeyS k0 = KeyS(init, env);
1212
1213
1214
1215
1216
1217
    // flag f_max: ordering for enumeration (user option)
    parsing::TableA<parsing::KeyS>* tab =
        parse<parsing::KeyS, parsing::KeySHasher>(k0, _nbest, f_max, env);
    tab->best(k0, _nbest); // fill table up to n-best
        
    for (size_t i = 1; i <= _nbest; i++)
1218
    {
1219
        const parsing::Run* best_run = tab->best(k0, i);
1220
        if (best_run == NULL)
1221
            INFO("{}-BEST RUN: none", i);
1222
        else if (_nbest == 1)
1223
1224
1225
        {
            INFO("{}-BEST RUN = {}", i, *(best_run));
        }
1226
1227
        else
        {
1228
1229
            const parsing::RunRanked<KeyS>* best_runr =
                dynamic_cast<const parsing::RunRanked<KeyS>*>(best_run);
1230
            assert(best_runr);
Florent Jacquemard's avatar
Florent Jacquemard committed
1231
            INFO("{}-BEST RUN = {}", i, *(best_runr));
1232
1233
        }
    }
Florent Jacquemard's avatar
Florent Jacquemard committed
1234

Florent Jacquemard's avatar
doc    
Florent Jacquemard committed
1235
    delete tab;
Florent Jacquemard's avatar
Florent Jacquemard committed
1236

1237
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1238
1239
1240
#elif QUANT_SCENARIO == QUANT_1BAR_1BESTSIP
    ERROR("missing scenario QUANT_1BAR_1BESTSIP");
    
1241
    
Florent Jacquemard's avatar
Florent Jacquemard committed
1242
1243
#elif QUANT_SCENARIO == QUANT_1BAR_KBESTSKIP
    ERROR("missing scenario QUANT_1BAR_KBESTSKIP");
1244
1245
1246

                            
#elif QUANT_SCENARIO == QUANT_MULTIBAR_1BEST_SI
1247
    INFO("parser multibar with Key_SI");
1248
1249
    INFO("compute best tree sequence for {} and input in {}",
         _schema_file, _input_file);
1250
1251

    // check options
1252
1253
1254
1255
1256
1257
    if (!(f_barsec || f_bars))
    {
        ERROR("at least one of the options -bars or -barsec mandatory");
        exit(2);
    }
    
1258
    // prepare parsing environment
1259
1260
    assert(_schema);
    assert(_iseg);
1261
    parsing::ParsingEnv env = parsing::ParsingEnv(_schema, _iseg);
1262
    assert(env.segment);
1263

1264
1265
1266
1267
1268
    INFO("parsing segment [{}-{}], rdur={}",
         env.segment->rbegin(),
         env.segment->rend(),
         env.segment->Interval::rduration());
    INFO("fixed bar duration = {}s ({} bars)", _barsec, _bars);
1269

1270
    INFO("start parsing");
1271
1272
1273
1274
1275
1276
1277
1278
1279
    clock_t time_start = clock();

    // initial augmented state
    const parsing::KeySI k0 = parsing::KeySI(_barsec, env, false);
    // flag f_max: ordering for enumeration (user option)
    parsing::TableA<parsing::KeySI>* tab =
        parse<parsing::KeySI, parsing::KeySIHasher>(k0, _nbest, f_max, env);
    // fill table up to n-best
    const parsing::Run* r0 = tab->best(k0, _nbest);
1280
    INFO("time to parse : {}ms", util::duration(time_start));
1281

1282
    LabeledRhythmTree* t0 = LRTFactory<parsing::KeySI>::best(tab, k0); // was: tab->bestTree(r0);
1283
    assert(t0);
1284

1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
    if (r0 == NULL)
    {
        assert(t0 == NULL);
        INFO("FAILED (no output)");
    }
    else
    {
        INFO("output = {}", t0->to_string());
        INFO("weight = {}", r0->weight());
    }
    
    delete t0;
    
    if (tab)
        delete tab;
    
1301

1302
    
1303
1304
1305
1306
#elif QUANT_SCENARIO == QUANT_MULTIBAR_1BEST_SIP
    INFO("parser multibar with Key_SIP");
    INFO("compute best tree sequence for {} and input in {}",
         _schema_file, _input_file);
1307
    
1308
1309
1310
1311
1312
1313
    // check options
    if (!(f_barsec || f_bars))
    {
        ERROR("at least one of the options -bars or -barsec mandatory");
        exit(2);
    }
1314
    if (! f_timesig)
1315
    {
1316
        WARN("no time signature in commandline, default to {}", _ts);
1317
1318
1319
1320
    }
    
    assert(_schema);
    assert(_iseg);
1321
1322
    parsing::ParsingEnv penv = parsing::ParsingEnv(_schema, _iseg);
    assert(penv.segment);
1323

1324
1325
1326
1327
1328
1329
    INFO("parsing segment [{}-{}], rdur={}",
         penv.segment->rbegin(),
         penv.segment->rend(),
         penv.segment->Interval::rduration());
    INFO("fixed bar duration = {}s ({} bars)", _barsec, _bars);
    INFO("start parsing");
1330

1331
1332
    clock_t time_start = clock();
    
1333
    // initial augmented state
1334
    // state_t init = _schema->initial();
1335
    // pre = 0
1336
    // post = Unknown (partial key)
1337
1338
1339
1340
1341
1342
1343
1344
1345
    const parsing::KeySIP k0 = parsing::KeySIP(_barsec, penv, true, 0);
    // or post = 0 (complete key)
    // const parsing::KeySIP k0 = parsing::KeySIP(_barsec, penv, true, 0, 0);
    // flag f_max: ordering for enumeration (user option)
    parsing::TableA<parsing::KeySIP>* tab =
        parse<parsing::KeySIP, parsing::KeySIPHasher>(k0, _nbest, f_max, penv);
    assert(tab);
    // fill table up to n-best
    tab->best(k0, _nbest); //   const parsing::Run* r0
1346
    INFO("time to parse : {}ms", util::duration(time_start));
Florent Jacquemard's avatar
Florent Jacquemard committed
1347
    
1348
    if (f_output && (_output_file.size() == 0))
1349
    {
Florent Jacquemard's avatar
Florent Jacquemard committed
1350
1351
            ERROR("empty output file name");
            return 1;
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
    }
    /// @todo revise with score builder
    else if (f_output && f_out_mei)
    {
        INFO("Construct the symbolic score model from from the parse table");
        VoicingMono* voicing = NULL; //= new VoicingMono(*(penv.segment));
        // voicing->revoice_all(); // quantize first!
        //assert(voicing->voiced());
        // pack Scoring Environment
        sm::ScoringEnv senv = sm::ScoringEnv(penv, voicing);
        string prefix = util::prefix(_output_file);
        assert(tab);
        sm::Score* score =
            buildSM<parsing::KeySIP>(*tab, k0, _ts, prefix, "part1", senv);
        assert(score);
Florent Jacquemard's avatar
Florent Jacquemard committed
1367

1368
1369
        INFO("Pitch Spelling in score: {}", score->id());
        spellPitch(*score);
Florent Jacquemard's avatar
Florent Jacquemard committed
1370
        
1371
1372
        INFO("Print the score model");
        printSM(*score);
Florent Jacquemard's avatar
Florent Jacquemard committed
1373
        
1374
1375
1376
1377
1378
1379
1380
1381
1382
        INFO("export to MEI file {}", _output_file);
        writeMEI(*score, _output_file);

        if (score) delete score;
        if (voicing) delete voicing;
    }
        
    else if (f_output && f_out_midi)
    {
Florent Jacquemard's avatar
Florent Jacquemard committed
1383
1384
1385
1386
1387
1388
            INFO("export to MIDI file");
            /// @todo MIDI export
    }
    else
    {
        INFO("DEBUG output:");
1389
        printTrees<parsing::KeySIP>(*tab, k0, _nbest);
1390
    }
1391
1392
    
    if (tab) delete tab;
1393

1394

1395
1396
1397
1398
#elif QUANT_SCENARIO == QUANT_MULTIBAR_1BEST_SIR
    INFO("parser multibar with Key_SIR");
    INFO("compute best tree sequence for {} and input in {}",
         _schema_file, _input_file);
1399
    
1400
1401
1402
1403
1404
1405
    // check options
    if (!(f_barsec || f_bars))
    {
        ERROR("at least one of the options -bars or -barsec mandatory");
        exit(2);
    }
1406
1407
1408
1409
1410
1411
    
    if (f_norest)
    {
        ERROR("--norest option should not be used for rest processing with SIR.");
    }
    
1412
    if (! f_timesig)
1413
    {
1414
        WARN("no time signature in commandline, default to {}", _ts);
1415
    }
1416
1417
1418
1419
           
    INFO("{}-best computation", _nbest);

    // prepare parsing environment
1420
1421
    assert(_schema);
    assert(_iseg);
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
    parsing::ParsingEnv penv = parsing::ParsingEnv(_schema, _iseg);
    assert(penv.segment);

    INFO("parsing segment [{}-{}].rdur={}",
         penv.segment->rbegin(),
         penv.segment->rend(),
         penv.segment->Interval::rduration());
    INFO("fixed bar duration = {}s ({} bars)", _barsec, _bars);
    INFO("start parsing");
    clock_t time_start = clock();
    // state_t init = _schema->initial();
    // initial augmented state
    // pre = 0 (default)
    // post = Unknown (partial key) (default)
    const parsing::KeySIR k0 = parsing::KeySIR(_barsec, penv, true);
1437
    // flag f_max: ordering for enumeration (user option)
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
    parsing::TableA<parsing::KeySIR>* tab =
        parse<parsing::KeySIR, parsing::KeySIRHasher>(k0, _nbest, f_max, penv);
    tab->best(k0, _nbest); // fill table up to n-best
    INFO("time to parse : {}ms", util::duration(time_start));

    if (f_output && (_output_file.size() == 0))
    {
        ERROR("empty output file name");
        return 1;
    }
    else if (f_output && f_out_mei)
    {
        INFO("Construct the symbolic score model from the parse table");
        // no need of a voicing in monophonic case
        VoicingMono* voicing = NULL; //= new VoicingMono(*(penv.segment));
        // voicing->revoice_all(); // quantize first!
        // assert(voicing->voiced());
        // pack Scoring Environment
        sm::ScoringEnv senv = sm::ScoringEnv(penv, voicing);
        // construct score model
        string prefix = util::prefix(_output_file); // score name
        assert(tab);
        sm::Score* score =
            buildSM<parsing::KeySIR>(*tab, k0, _ts, prefix, "part1", senv);
        assert(score);
1463
        
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
        INFO("Pitch Spelling in score: {}", score->id());
        spellPitch(*score);
                
        INFO("Print the score model");
        printSM(*score);

        INFO("export to MEI file {}", _output_file);
        writeMEI(*score, _output_file);

        if (score) delete score;
        if (voicing) delete voicing;
1475

1476
1477
    }
    else if (f_output && f_out_midi)
赤尾健太's avatar
赤尾健太 committed
1478
    {
1479
1480
        assert(tab);
        exportMIDI<parsing::KeySIR>(*tab, k0, _barbeat, _input_file, _output_file, penv);
赤尾健太's avatar
赤尾健太 committed
1481
    }
1482
    else // default output
赤尾健太's avatar
赤尾健太 committed
1483
    {
1484
1485
        INFO("DEBUG output:");
        printTrees<parsing::KeySIR>(*tab, k0, _nbest);
赤尾健太's avatar
赤尾健太 committed
1486
1487
    }

1488
1489
    if (tab) delete tab;
       
赤尾健太's avatar
赤尾健太 committed
1490

1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
#elif QUANT_SCENARIO == QUANT_MULTIBAR_1BEST_SIO
    INFO("parser multibar with Key_SIO");
    INFO("compute best tree sequence for {} and input in {}",
         _schema_file, _input_file);
    
    // check options
    if (!(f_barsec || f_bars))
    {
        ERROR("at least one of the options -bars or -barsec mandatory");
        exit(2);
    }
    
    if (f_norest)
    {
        ERROR("--norest option should not be used for rest processing with SIO.");
    }
    
    if (! f_timesig)
    {
        WARN("no time signature in commandline, default to {}", _ts);
    }
           
    INFO("{}-best computation", _nbest);

    // prepare parsing environment
    assert(_schema);
    assert(_iseg);
    parsing::ParsingEnv penv = parsing::ParsingEnv(_schema, _iseg);
    assert(penv.segment);

    INFO("parsing segment [{}-{}].rdur={}",
         penv.segment->rbegin(),
         penv.segment->rend(),
         penv.segment->Interval::rduration());
赤尾健太's avatar
赤尾健太 committed
1525
1526
    INFO("fixed bar duration = {}s ({} bars)", _barsec, _bars);
    INFO("start parsing");
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
    clock_t time_start = clock();
    // state_t init = _schema->initial();
    // initial augmented state
    // pre = 0 (default)
    // post = Unknown (partial key) (default)
    const parsing::KeySIO k0 = parsing::KeySIO(_barsec, penv, true);
    // flag f_max: ordering for enumeration (user option)
    parsing::TableA<parsing::KeySIO>* tab =
        parse<parsing::KeySIO, parsing::KeySIOHasher>(k0, _nbest, f_max, penv);
    tab->best(k0, _nbest); // fill table up to n-best