comparison data/fileio/CSVFileReader.cpp @ 148:1a42221a1522

* Reorganising code base. This revision will not compile.
author Chris Cannam
date Mon, 31 Jul 2006 11:49:58 +0000
parents
children 4b2ea82fd0ed
comparison
equal deleted inserted replaced
147:3a13b0d4934e 148:1a42221a1522
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2
3 /*
4 Sonic Visualiser
5 An audio file viewer and annotation editor.
6 Centre for Digital Music, Queen Mary, University of London.
7 This file copyright 2006 Chris Cannam.
8
9 This program is free software; you can redistribute it and/or
10 modify it under the terms of the GNU General Public License as
11 published by the Free Software Foundation; either version 2 of the
12 License, or (at your option) any later version. See the file
13 COPYING included with this distribution for more information.
14 */
15
16 #include "CSVFileReader.h"
17
18 #include "base/Model.h"
19 #include "base/RealTime.h"
20 #include "model/SparseOneDimensionalModel.h"
21 #include "model/SparseTimeValueModel.h"
22 #include "model/DenseThreeDimensionalModel.h"
23
24 #include <QFile>
25 #include <QString>
26 #include <QRegExp>
27 #include <QStringList>
28 #include <QTextStream>
29 #include <QFrame>
30 #include <QGridLayout>
31 #include <QPushButton>
32 #include <QHBoxLayout>
33 #include <QVBoxLayout>
34 #include <QTableWidget>
35 #include <QComboBox>
36 #include <QLabel>
37
38 #include <iostream>
39
40 CSVFileReader::CSVFileReader(QString path, size_t mainModelSampleRate) :
41 m_file(0),
42 m_mainModelSampleRate(mainModelSampleRate)
43 {
44 m_file = new QFile(path);
45 bool good = false;
46
47 if (!m_file->exists()) {
48 m_error = QFile::tr("File \"%1\" does not exist").arg(path);
49 } else if (!m_file->open(QIODevice::ReadOnly | QIODevice::Text)) {
50 m_error = QFile::tr("Failed to open file \"%1\"").arg(path);
51 } else {
52 good = true;
53 }
54
55 if (!good) {
56 delete m_file;
57 m_file = 0;
58 }
59 }
60
61 CSVFileReader::~CSVFileReader()
62 {
63 std::cerr << "CSVFileReader::~CSVFileReader: file is " << m_file << std::endl;
64
65 if (m_file) {
66 std::cerr << "CSVFileReader::CSVFileReader: Closing file" << std::endl;
67 m_file->close();
68 }
69 delete m_file;
70 }
71
72 bool
73 CSVFileReader::isOK() const
74 {
75 return (m_file != 0);
76 }
77
78 QString
79 CSVFileReader::getError() const
80 {
81 return m_error;
82 }
83
84 Model *
85 CSVFileReader::load() const
86 {
87 if (!m_file) return 0;
88
89 CSVFormatDialog *dialog = new CSVFormatDialog
90 (0, m_file, m_mainModelSampleRate);
91
92 if (dialog->exec() == QDialog::Rejected) {
93 delete dialog;
94 return 0;
95 }
96
97 CSVFormatDialog::ModelType modelType = dialog->getModelType();
98 CSVFormatDialog::TimingType timingType = dialog->getTimingType();
99 CSVFormatDialog::TimeUnits timeUnits = dialog->getTimeUnits();
100 QString separator = dialog->getSeparator();
101 size_t sampleRate = dialog->getSampleRate();
102 size_t windowSize = dialog->getWindowSize();
103
104 delete dialog;
105
106 if (timingType == CSVFormatDialog::ExplicitTiming) {
107 windowSize = 1;
108 if (timeUnits == CSVFormatDialog::TimeSeconds) {
109 sampleRate = m_mainModelSampleRate;
110 }
111 }
112
113 SparseOneDimensionalModel *model1 = 0;
114 SparseTimeValueModel *model2 = 0;
115 DenseThreeDimensionalModel *model3 = 0;
116 Model *model = 0;
117
118 QTextStream in(m_file);
119 in.seek(0);
120
121 unsigned int warnings = 0, warnLimit = 10;
122 unsigned int lineno = 0;
123
124 float min = 0.0, max = 0.0;
125
126 size_t frameNo = 0;
127
128 while (!in.atEnd()) {
129
130 QString line = in.readLine().trimmed();
131 if (line.startsWith("#")) continue;
132
133 QStringList list = line.split(separator);
134
135 if (!model) {
136
137 switch (modelType) {
138
139 case CSVFormatDialog::OneDimensionalModel:
140 model1 = new SparseOneDimensionalModel(sampleRate, windowSize);
141 model = model1;
142 break;
143
144 case CSVFormatDialog::TwoDimensionalModel:
145 model2 = new SparseTimeValueModel(sampleRate, windowSize,
146 0.0, 0.0,
147 false);
148 model = model2;
149 break;
150
151 case CSVFormatDialog::ThreeDimensionalModel:
152 model3 = new DenseThreeDimensionalModel(sampleRate, windowSize,
153 list.size());
154 model = model3;
155 break;
156 }
157 }
158
159 QStringList tidyList;
160 QRegExp nonNumericRx("[^0-9.,+-]");
161
162 for (int i = 0; i < list.size(); ++i) {
163
164 QString s(list[i].trimmed());
165
166 if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) {
167 s = s.mid(1, s.length() - 2);
168 } else if (s.length() >= 2 && s.startsWith("'") && s.endsWith("'")) {
169 s = s.mid(1, s.length() - 2);
170 }
171
172 if (i == 0 && timingType == CSVFormatDialog::ExplicitTiming) {
173
174 bool ok = false;
175 QString numeric = s;
176 numeric.remove(nonNumericRx);
177
178 if (timeUnits == CSVFormatDialog::TimeSeconds) {
179
180 double time = numeric.toDouble(&ok);
181 frameNo = int(time * sampleRate + 0.00001);
182
183 } else {
184
185 frameNo = numeric.toInt(&ok);
186
187 if (timeUnits == CSVFormatDialog::TimeWindows) {
188 frameNo *= windowSize;
189 }
190 }
191
192 if (!ok) {
193 if (warnings < warnLimit) {
194 std::cerr << "WARNING: CSVFileReader::load: "
195 << "Bad time format (\"" << s.toStdString()
196 << "\") in data line "
197 << lineno << ":" << std::endl;
198 std::cerr << line.toStdString() << std::endl;
199 } else if (warnings == warnLimit) {
200 std::cerr << "WARNING: Too many warnings" << std::endl;
201 }
202 ++warnings;
203 }
204 } else {
205 tidyList.push_back(s);
206 }
207 }
208
209 if (modelType == CSVFormatDialog::OneDimensionalModel) {
210
211 SparseOneDimensionalModel::Point point
212 (frameNo,
213 tidyList.size() > 0 ? tidyList[tidyList.size()-1] :
214 QString("%1").arg(lineno));
215
216 model1->addPoint(point);
217
218 } else if (modelType == CSVFormatDialog::TwoDimensionalModel) {
219
220 SparseTimeValueModel::Point point
221 (frameNo,
222 tidyList.size() > 0 ? tidyList[0].toFloat() : 0.0,
223 tidyList.size() > 1 ? tidyList[1] : QString("%1").arg(lineno));
224
225 model2->addPoint(point);
226
227 } else if (modelType == CSVFormatDialog::ThreeDimensionalModel) {
228
229 DenseThreeDimensionalModel::BinValueSet values;
230
231 for (int i = 0; i < tidyList.size(); ++i) {
232
233 bool ok = false;
234 float value = list[i].toFloat(&ok);
235 values.push_back(value);
236
237 if ((lineno == 0 && i == 0) || value < min) min = value;
238 if ((lineno == 0 && i == 0) || value > max) max = value;
239
240 if (!ok) {
241 if (warnings < warnLimit) {
242 std::cerr << "WARNING: CSVFileReader::load: "
243 << "Non-numeric value in data line " << lineno
244 << ":" << std::endl;
245 std::cerr << line.toStdString() << std::endl;
246 ++warnings;
247 } else if (warnings == warnLimit) {
248 std::cerr << "WARNING: Too many warnings" << std::endl;
249 }
250 }
251 }
252
253 std::cerr << "Setting bin values for count " << lineno << ", frame "
254 << frameNo << ", time " << RealTime::frame2RealTime(frameNo, sampleRate) << std::endl;
255
256 model3->setBinValues(frameNo, values);
257 }
258
259 ++lineno;
260 if (timingType == CSVFormatDialog::ImplicitTiming ||
261 list.size() == 0) {
262 frameNo += windowSize;
263 }
264 }
265
266 if (modelType == CSVFormatDialog::ThreeDimensionalModel) {
267 model3->setMinimumLevel(min);
268 model3->setMaximumLevel(max);
269 }
270
271 return model;
272 }
273
274
275 CSVFormatDialog::CSVFormatDialog(QWidget *parent, QFile *file,
276 size_t defaultSampleRate) :
277 QDialog(parent),
278 m_modelType(OneDimensionalModel),
279 m_timingType(ExplicitTiming),
280 m_timeUnits(TimeAudioFrames),
281 m_separator("")
282 {
283 setModal(true);
284 setWindowTitle(tr("Select Data Format"));
285
286 (void)guessFormat(file);
287
288 QGridLayout *layout = new QGridLayout;
289
290 layout->addWidget(new QLabel(tr("\nPlease select the correct data format for this file.\n")),
291 0, 0, 1, 4);
292
293 layout->addWidget(new QLabel(tr("Each row specifies:")), 1, 0);
294
295 m_modelTypeCombo = new QComboBox;
296 m_modelTypeCombo->addItem(tr("A point in time"));
297 m_modelTypeCombo->addItem(tr("A value at a time"));
298 m_modelTypeCombo->addItem(tr("A set of values"));
299 layout->addWidget(m_modelTypeCombo, 1, 1, 1, 2);
300 connect(m_modelTypeCombo, SIGNAL(activated(int)),
301 this, SLOT(modelTypeChanged(int)));
302 m_modelTypeCombo->setCurrentIndex(int(m_modelType));
303
304 layout->addWidget(new QLabel(tr("The first column contains:")), 2, 0);
305
306 m_timingTypeCombo = new QComboBox;
307 m_timingTypeCombo->addItem(tr("Time, in seconds"));
308 m_timingTypeCombo->addItem(tr("Time, in audio sample frames"));
309 m_timingTypeCombo->addItem(tr("Data (rows are consecutive in time)"));
310 layout->addWidget(m_timingTypeCombo, 2, 1, 1, 2);
311 connect(m_timingTypeCombo, SIGNAL(activated(int)),
312 this, SLOT(timingTypeChanged(int)));
313 m_timingTypeCombo->setCurrentIndex(m_timingType == ExplicitTiming ?
314 m_timeUnits == TimeSeconds ? 0 : 1 : 2);
315
316 m_sampleRateLabel = new QLabel(tr("Audio sample rate (Hz):"));
317 layout->addWidget(m_sampleRateLabel, 3, 0);
318
319 size_t sampleRates[] = {
320 8000, 11025, 12000, 22050, 24000, 32000,
321 44100, 48000, 88200, 96000, 176400, 192000
322 };
323
324 m_sampleRateCombo = new QComboBox;
325 m_sampleRate = defaultSampleRate;
326 for (size_t i = 0; i < sizeof(sampleRates) / sizeof(sampleRates[0]); ++i) {
327 m_sampleRateCombo->addItem(QString("%1").arg(sampleRates[i]));
328 if (sampleRates[i] == m_sampleRate) m_sampleRateCombo->setCurrentIndex(i);
329 }
330 m_sampleRateCombo->setEditable(true);
331
332 layout->addWidget(m_sampleRateCombo, 3, 1);
333 connect(m_sampleRateCombo, SIGNAL(activated(QString)),
334 this, SLOT(sampleRateChanged(QString)));
335 connect(m_sampleRateCombo, SIGNAL(editTextChanged(QString)),
336 this, SLOT(sampleRateChanged(QString)));
337
338 m_windowSizeLabel = new QLabel(tr("Frame increment between rows:"));
339 layout->addWidget(m_windowSizeLabel, 4, 0);
340
341 m_windowSizeCombo = new QComboBox;
342 m_windowSize = 1024;
343 for (int i = 0; i <= 16; ++i) {
344 int value = 1 << i;
345 m_windowSizeCombo->addItem(QString("%1").arg(value));
346 if (value == m_windowSize) m_windowSizeCombo->setCurrentIndex(i);
347 }
348 m_windowSizeCombo->setEditable(true);
349
350 layout->addWidget(m_windowSizeCombo, 4, 1);
351 connect(m_windowSizeCombo, SIGNAL(activated(QString)),
352 this, SLOT(windowSizeChanged(QString)));
353 connect(m_windowSizeCombo, SIGNAL(editTextChanged(QString)),
354 this, SLOT(windowSizeChanged(QString)));
355
356 layout->addWidget(new QLabel(tr("\nExample data from file:")), 5, 0, 1, 4);
357
358 m_exampleWidget = new QTableWidget
359 (std::min(10, m_example.size()), m_maxExampleCols);
360
361 layout->addWidget(m_exampleWidget, 6, 0, 1, 4);
362 layout->setColumnStretch(3, 10);
363 layout->setRowStretch(4, 10);
364
365 QPushButton *ok = new QPushButton(tr("OK"));
366 connect(ok, SIGNAL(clicked()), this, SLOT(accept()));
367 ok->setDefault(true);
368
369 QPushButton *cancel = new QPushButton(tr("Cancel"));
370 connect(cancel, SIGNAL(clicked()), this, SLOT(reject()));
371
372 QHBoxLayout *buttonLayout = new QHBoxLayout;
373 buttonLayout->addStretch(1);
374 buttonLayout->addWidget(ok);
375 buttonLayout->addWidget(cancel);
376
377 QVBoxLayout *mainLayout = new QVBoxLayout;
378 mainLayout->addLayout(layout);
379 mainLayout->addLayout(buttonLayout);
380
381 setLayout(mainLayout);
382
383 timingTypeChanged(m_timingTypeCombo->currentIndex());
384 }
385
386 CSVFormatDialog::~CSVFormatDialog()
387 {
388 }
389
390 void
391 CSVFormatDialog::populateExample()
392 {
393 m_exampleWidget->setColumnCount
394 (m_timingType == ExplicitTiming ?
395 m_maxExampleCols - 1 : m_maxExampleCols);
396
397 m_exampleWidget->setHorizontalHeaderLabels(QStringList());
398
399 for (int i = 0; i < m_example.size(); ++i) {
400 for (int j = 0; j < m_example[i].size(); ++j) {
401
402 QTableWidgetItem *item = new QTableWidgetItem(m_example[i][j]);
403
404 if (j == 0) {
405 if (m_timingType == ExplicitTiming) {
406 m_exampleWidget->setVerticalHeaderItem(i, item);
407 continue;
408 } else {
409 QTableWidgetItem *header =
410 new QTableWidgetItem(QString("%1").arg(i));
411 header->setFlags(Qt::ItemIsEnabled);
412 m_exampleWidget->setVerticalHeaderItem(i, header);
413 }
414 }
415 int index = j;
416 if (m_timingType == ExplicitTiming) --index;
417 item->setFlags(Qt::ItemIsEnabled);
418 m_exampleWidget->setItem(i, index, item);
419 }
420 }
421 }
422
423 void
424 CSVFormatDialog::modelTypeChanged(int type)
425 {
426 m_modelType = (ModelType)type;
427
428 if (m_modelType == ThreeDimensionalModel) {
429 // We can't load 3d models with explicit timing, because the 3d
430 // model is dense so we need a fixed sample increment
431 m_timingTypeCombo->setCurrentIndex(2);
432 timingTypeChanged(2);
433 }
434 }
435
436 void
437 CSVFormatDialog::timingTypeChanged(int type)
438 {
439 switch (type) {
440
441 case 0:
442 m_timingType = ExplicitTiming;
443 m_timeUnits = TimeSeconds;
444 m_sampleRateCombo->setEnabled(false);
445 m_sampleRateLabel->setEnabled(false);
446 m_windowSizeCombo->setEnabled(false);
447 m_windowSizeLabel->setEnabled(false);
448 if (m_modelType == ThreeDimensionalModel) {
449 m_modelTypeCombo->setCurrentIndex(1);
450 modelTypeChanged(1);
451 }
452 break;
453
454 case 1:
455 m_timingType = ExplicitTiming;
456 m_timeUnits = TimeAudioFrames;
457 m_sampleRateCombo->setEnabled(true);
458 m_sampleRateLabel->setEnabled(true);
459 m_windowSizeCombo->setEnabled(false);
460 m_windowSizeLabel->setEnabled(false);
461 if (m_modelType == ThreeDimensionalModel) {
462 m_modelTypeCombo->setCurrentIndex(1);
463 modelTypeChanged(1);
464 }
465 break;
466
467 case 2:
468 m_timingType = ImplicitTiming;
469 m_timeUnits = TimeWindows;
470 m_sampleRateCombo->setEnabled(true);
471 m_sampleRateLabel->setEnabled(true);
472 m_windowSizeCombo->setEnabled(true);
473 m_windowSizeLabel->setEnabled(true);
474 break;
475 }
476
477 populateExample();
478 }
479
480 void
481 CSVFormatDialog::sampleRateChanged(QString rateString)
482 {
483 bool ok = false;
484 int sampleRate = rateString.toInt(&ok);
485 if (ok) m_sampleRate = sampleRate;
486 }
487
488 void
489 CSVFormatDialog::windowSizeChanged(QString sizeString)
490 {
491 bool ok = false;
492 int size = sizeString.toInt(&ok);
493 if (ok) m_windowSize = size;
494 }
495
496 bool
497 CSVFormatDialog::guessFormat(QFile *file)
498 {
499 QTextStream in(file);
500 in.seek(0);
501
502 unsigned int lineno = 0;
503
504 bool nonIncreasingPrimaries = false;
505 bool nonNumericPrimaries = false;
506 bool floatPrimaries = false;
507 bool variableItemCount = false;
508 int itemCount = 1;
509 int earliestNonNumericItem = -1;
510
511 float prevPrimary = 0.0;
512
513 m_maxExampleCols = 0;
514
515 while (!in.atEnd()) {
516
517 QString line = in.readLine().trimmed();
518 if (line.startsWith("#")) continue;
519
520 if (m_separator == "") {
521 //!!! to do: ask the user
522 if (line.split(",").size() >= 2) m_separator = ",";
523 else if (line.split("\t").size() >= 2) m_separator = "\t";
524 else if (line.split("|").size() >= 2) m_separator = "|";
525 else if (line.split("/").size() >= 2) m_separator = "/";
526 else if (line.split(":").size() >= 2) m_separator = ":";
527 else m_separator = " ";
528 }
529
530 QStringList list = line.split(m_separator);
531 QStringList tidyList;
532
533 for (int i = 0; i < list.size(); ++i) {
534
535 QString s(list[i]);
536 bool numeric = false;
537
538 if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) {
539 s = s.mid(1, s.length() - 2);
540 } else if (s.length() >= 2 && s.startsWith("'") && s.endsWith("'")) {
541 s = s.mid(1, s.length() - 2);
542 } else {
543 (void)s.toFloat(&numeric);
544 }
545
546 tidyList.push_back(s);
547
548 if (lineno == 0 || (list.size() < itemCount)) {
549 itemCount = list.size();
550 } else {
551 if (itemCount != list.size()) {
552 variableItemCount = true;
553 }
554 }
555
556 if (i == 0) { // primary
557
558 if (numeric) {
559
560 float primary = s.toFloat();
561
562 if (lineno > 0 && primary <= prevPrimary) {
563 nonIncreasingPrimaries = true;
564 }
565
566 if (s.contains(".") || s.contains(",")) {
567 floatPrimaries = true;
568 }
569
570 prevPrimary = primary;
571
572 } else {
573 nonNumericPrimaries = true;
574 }
575 } else { // secondary
576
577 if (!numeric) {
578 if (earliestNonNumericItem < 0 ||
579 i < earliestNonNumericItem) {
580 earliestNonNumericItem = i;
581 }
582 }
583 }
584 }
585
586 if (lineno < 10) {
587 m_example.push_back(tidyList);
588 if (lineno == 0 || tidyList.size() > m_maxExampleCols) {
589 m_maxExampleCols = tidyList.size();
590 }
591 }
592
593 ++lineno;
594
595 if (lineno == 50) break;
596 }
597
598 if (nonNumericPrimaries || nonIncreasingPrimaries) {
599
600 // Primaries are probably not a series of times
601
602 m_timingType = ImplicitTiming;
603 m_timeUnits = TimeWindows;
604
605 if (nonNumericPrimaries) {
606 m_modelType = OneDimensionalModel;
607 } else if (itemCount == 1 || variableItemCount ||
608 (earliestNonNumericItem != -1)) {
609 m_modelType = TwoDimensionalModel;
610 } else {
611 m_modelType = ThreeDimensionalModel;
612 }
613
614 } else {
615
616 // Increasing numeric primaries -- likely to be time
617
618 m_timingType = ExplicitTiming;
619
620 if (floatPrimaries) {
621 m_timeUnits = TimeSeconds;
622 } else {
623 m_timeUnits = TimeAudioFrames;
624 }
625
626 if (itemCount == 1) {
627 m_modelType = OneDimensionalModel;
628 } else if (variableItemCount || (earliestNonNumericItem != -1)) {
629 if (earliestNonNumericItem != -1 && earliestNonNumericItem < 2) {
630 m_modelType = OneDimensionalModel;
631 } else {
632 m_modelType = TwoDimensionalModel;
633 }
634 } else {
635 m_modelType = ThreeDimensionalModel;
636 }
637 }
638
639 std::cerr << "Estimated model type: " << m_modelType << std::endl;
640 std::cerr << "Estimated timing type: " << m_timingType << std::endl;
641 std::cerr << "Estimated units: " << m_timeUnits << std::endl;
642
643 in.seek(0);
644 return true;
645 }