summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/utilities/FormatUtil.java
blob: c61fdb10eee7b5b63938cd72389cc7267e8c65ca (plain)
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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
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
522
523
524
525
526
527
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
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
682
683
684
685
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
package de.lmu.ifi.dbs.elki.utilities;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2012
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;

/**
 * Utility methods for output formatting of various number objects
 */
public final class FormatUtil {
  /**
   * Dynamic number formatter, but with language constraint.
   */
  public static final NumberFormat NF = NumberFormat.getInstance(Locale.US);

  /**
   * Number Formatter (0 digits) for output purposes.
   */
  public static final NumberFormat NF0 = NumberFormat.getInstance(Locale.US);

  /**
   * Number Formatter (2 digits) for output purposes.
   */
  public static final NumberFormat NF2 = NumberFormat.getInstance(Locale.US);

  /**
   * Number Formatter (4 digits) for output purposes.
   */
  public static final NumberFormat NF4 = NumberFormat.getInstance(Locale.US);

  /**
   * Number Formatter (6 digits) for output purposes.
   */
  public static final NumberFormat NF6 = NumberFormat.getInstance(Locale.US);

  /**
   * Number Formatter (8 digits) for output purposes.
   */
  public static final NumberFormat NF8 = NumberFormat.getInstance(Locale.US);

  static {
    NF.setMinimumFractionDigits(0);
    NF.setMaximumFractionDigits(10);
    NF.setGroupingUsed(false);
    NF0.setMinimumFractionDigits(0);
    NF0.setMaximumFractionDigits(0);
    NF0.setGroupingUsed(false);
    NF2.setMinimumFractionDigits(2);
    NF2.setMaximumFractionDigits(2);
    NF2.setGroupingUsed(false);
    NF4.setMinimumFractionDigits(4);
    NF4.setMaximumFractionDigits(4);
    NF4.setGroupingUsed(false);
    NF6.setMinimumFractionDigits(6);
    NF6.setMaximumFractionDigits(6);
    NF6.setGroupingUsed(false);
    NF8.setMinimumFractionDigits(8);
    NF8.setMaximumFractionDigits(8);
    NF8.setGroupingUsed(false);
  }

  /**
   * Whitespace. The string should cover the commonly used length.
   */
  private static final String WHITESPACE_BUFFER = "                                                                                ";

  /**
   * The system newline setting.
   */
  public static final String NEWLINE = System.getProperty("line.separator");

  /**
   * Non-breaking unicode space character.
   */
  public static final String NONBREAKING_SPACE = "\u00a0";

  /**
   * The time unit sizes: ms, s, m, h, d; all in ms.
   */
  private static final long[] TIME_UNIT_SIZES = new long[] { 1L, 1000L, 60000L, 3600000L, 86400000L };

  /**
   * The strings used in serialization
   */
  private static final String[] TIME_UNIT_NAMES = new String[] { "ms", "s", "m", "h", "d" };

  /**
   * The number of digits used for formatting
   */
  private static final int[] TIME_UNIT_DIGITS = new int[] { 3, 2, 2, 2, 2 };

  /**
   * Formats the double d with the specified fraction digits.
   * 
   * @param d the double array to be formatted
   * @param digits the number of fraction digits
   * @return a String representing the double d
   */
  public static String format(final double d, int digits) {
    final NumberFormat nf = NumberFormat.getInstance(Locale.US);
    nf.setMaximumFractionDigits(digits);
    nf.setMinimumFractionDigits(digits);
    nf.setGroupingUsed(false);
    return nf.format(d);
  }

  /**
   * Formats the double d with the specified number format.
   * 
   * @param d the double array to be formatted
   * @param nf the number format to be used for formatting
   * @return a String representing the double d
   */
  public static String format(final double d, NumberFormat nf) {
    return nf.format(d);
  }

  /**
   * Formats the double d with 2 fraction digits.
   * 
   * @param d the double to be formatted
   * @return a String representing the double d
   */
  public static String format(final double d) {
    return format(d, 2);
  }

  /**
   * Formats the double array d with the specified separator.
   * 
   * @param d the double array to be formatted
   * @param sep the separator between the single values of the double array,
   *        e.g. ','
   * @return a String representing the double array d
   */
  public static String format(double[] d, String sep) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < d.length; i++) {
      if(i > 0) {
        buffer.append(sep).append(d[i]);
      }
      else {
        buffer.append(d[i]);
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the double array d with the specified separator and the specified
   * fraction digits.
   * 
   * @param d the double array to be formatted
   * @param sep the separator between the single values of the double array,
   *        e.g. ','
   * @param digits the number of fraction digits
   * @return a String representing the double array d
   */
  public static String format(double[] d, String sep, int digits) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < d.length; i++) {
      if(i < d.length - 1) {
        buffer.append(format(d[i], digits)).append(sep);
      }
      else {
        buffer.append(format(d[i], digits));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the double array d with the specified number format.
   * 
   * @param d the double array to be formatted
   * @param nf the number format to be used for formatting
   * @return a String representing the double array d
   */
  public static String format(double[] d, NumberFormat nf) {
    return format(d, " ", nf);
  }

  /**
   * Formats the double array d with the specified number format.
   * 
   * @param d the double array to be formatted
   * @param sep the separator between the single values of the double array,
   *        e.g. ','
   * @param nf the number format to be used for formatting
   * @return a String representing the double array d
   */
  public static String format(double[] d, String sep, NumberFormat nf) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < d.length; i++) {
      if(i < d.length - 1) {
        buffer.append(format(d[i], nf)).append(sep);
      }
      else {
        buffer.append(format(d[i], nf));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the double array d with ',' as separator and 2 fraction digits.
   * 
   * @param d the double array to be formatted
   * @return a String representing the double array d
   */
  public static String format(double[] d) {
    return format(d, ", ", 2);
  }

  /**
   * Formats the double array d with ', ' as separator and with the specified
   * fraction digits.
   * 
   * @param d the double array to be formatted
   * @param digits the number of fraction digits
   * @return a String representing the double array d
   */
  public static String format(double[] d, int digits) {
    return format(d, ", ", digits);
  }

  /**
   * Formats the double array d with ',' as separator and 2 fraction digits.
   * 
   * @param d the double array to be formatted
   * @return a String representing the double array d
   */
  public static String format(double[][] d) {
    StringBuffer buffer = new StringBuffer();
    for(double[] array : d) {
      buffer.append(format(array, ", ", 2)).append("\n");
    }
    return buffer.toString();
  }

  /**
   * Formats the array of double arrays d with 'the specified separators and
   * fraction digits.
   * 
   * @param d the double array to be formatted
   * @param sep1 the first separator of the outer array
   * @param sep2 the second separator of the inner array
   * @param digits the number of fraction digits
   * @return a String representing the double array d
   */
  public static String format(double[][] d, String sep1, String sep2, int digits) {
    StringBuffer buffer = new StringBuffer();

    for(int i = 0; i < d.length; i++) {
      if(i < d.length - 1) {
        buffer.append(format(d[i], sep2, digits)).append(sep1);
      }
      else {
        buffer.append(format(d[i], sep2, digits));
      }
    }

    return buffer.toString();
  }

  /**
   * Formats the Double array f with the specified separator and the specified
   * fraction digits.
   * 
   * @param f the Double array to be formatted
   * @param sep the separator between the single values of the Double array,
   *        e.g. ','
   * @param digits the number of fraction digits
   * @return a String representing the Double array f
   */
  public static String format(Double[] f, String sep, int digits) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < f.length; i++) {
      if(i < f.length - 1) {
        buffer.append(format(f[i], digits)).append(sep);
      }
      else {
        buffer.append(format(f[i], digits));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the Double array f with ',' as separator and 2 fraction digits.
   * 
   * @param f the Double array to be formatted
   * @return a String representing the Double array f
   */
  public static String format(Double[] f) {
    return format(f, ", ", 2);
  }

  /**
   * Formats the Double array f with the specified separator and the specified
   * fraction digits.
   * 
   * @param f the Double array to be formatted
   * @param sep the separator between the single values of the Double array,
   *        e.g. ','
   * @param nf the number format
   * @return a String representing the Double array f
   */
  public static String format(Double[] f, String sep, NumberFormat nf) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < f.length; i++) {
      if(i < f.length - 1) {
        buffer.append(format(f[i], nf)).append(sep);
      }
      else {
        buffer.append(format(f[i], nf));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the Double array f with ',' as separator and 2 fraction digits.
   * 
   * @param f the Double array to be formatted
   * @param nf the Number format
   * @return a String representing the Double array f
   */
  public static String format(Double[] f, NumberFormat nf) {
    return format(f, ", ", nf);
  }

  /**
   * Formats the float array f with the specified separator and the specified
   * fraction digits.
   * 
   * @param f the float array to be formatted
   * @param sep the separator between the single values of the float array, e.g.
   *        ','
   * @param digits the number of fraction digits
   * @return a String representing the float array f
   */
  public static String format(float[] f, String sep, int digits) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < f.length; i++) {
      if(i < f.length - 1) {
        buffer.append(format(f[i], digits)).append(sep);
      }
      else {
        buffer.append(format(f[i], digits));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the float array f with ',' as separator and 2 fraction digits.
   * 
   * @param f the float array to be formatted
   * @return a String representing the float array f
   */
  public static String format(float[] f) {
    return format(f, ", ", 2);
  }

  /**
   * Formats the int array a for printing purposes.
   * 
   * @param a the int array to be formatted
   * @param sep the separator between the single values of the float array, e.g.
   *        ','
   * @return a String representing the int array a
   */
  public static String format(int[] a, String sep) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < a.length; i++) {
      if(i < a.length - 1) {
        buffer.append(a[i]).append(sep);
      }
      else {
        buffer.append(a[i]);
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the int array a for printing purposes.
   * 
   * @param a the int array to be formatted
   * @return a String representing the int array a
   */
  public static String format(int[] a) {
    return format(a, ", ");
  }

  /**
   * Formats the Integer array a for printing purposes.
   * 
   * @param a the Integer array to be formatted
   * @param sep the separator between the single values of the float array, e.g.
   *        ','
   * @return a String representing the Integer array a
   */
  public static String format(Integer[] a, String sep) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < a.length; i++) {
      if(i < a.length - 1) {
        buffer.append(a[i]).append(sep);
      }
      else {
        buffer.append(a[i]);
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the Integer array a for printing purposes.
   * 
   * @param a the Integer array to be formatted
   * @return a String representing the Integer array a
   */
  public static String format(Integer[] a) {
    return format(a, ", ");
  }

  /**
   * Formats the long array a for printing purposes.
   * 
   * @param a the long array to be formatted
   * @return a String representing the long array a
   */
  public static String format(long[] a) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < a.length; i++) {
      if(i < a.length - 1) {
        buffer.append(a[i]).append(", ");
      }
      else {
        buffer.append(a[i]);
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the byte array a for printing purposes.
   * 
   * @param a the byte array to be formatted
   * @return a String representing the byte array a
   */
  public static String format(byte[] a) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < a.length; i++) {
      if(i < a.length - 1) {
        buffer.append(a[i]).append(", ");
      }
      else {
        buffer.append(a[i]);
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the boolean array b with ',' as separator.
   * 
   * @param b the boolean array to be formatted
   * @param sep the separator between the single values of the double array,
   *        e.g. ','
   * @return a String representing the boolean array b
   */
  public static String format(boolean[] b, final String sep) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < b.length; i++) {
      if(i < b.length - 1) {
        buffer.append(format(b[i])).append(sep);
      }
      else {
        buffer.append(format(b[i]));
      }
    }
    return buffer.toString();
  }

  /**
   * Formats the boolean b.
   * 
   * @param b the boolean to be formatted
   * @return a String representing of the boolean b
   */
  public static String format(final boolean b) {
    if(b) {
      return "1";
    }
    return "0";
  }

  /**
   * Returns a string representation of the specified bit set.
   * 
   * @param bitSet the bitSet
   * @param dim the overall dimensionality of the bit set
   * @param sep the separator
   * @return a string representation of the specified bit set.
   */
  public static String format(BitSet bitSet, int dim, String sep) {
    StringBuffer msg = new StringBuffer();

    for(int d = 0; d < dim; d++) {
      if(d > 0) {
        msg.append(sep);
      }
      if(bitSet.get(d)) {
        msg.append("1");
      }
      else {
        msg.append("0");
      }
    }

    return msg.toString();
  }

  /**
   * Returns a string representation of the specified bit set.
   * 
   * @param dim the overall dimensionality of the bit set
   * @param bitSet the bitSet
   * @return a string representation of the specified bit set.
   */
  public static String format(int dim, BitSet bitSet) {
    // TODO: removed whitespace - hierarchy reading to be adapted!
    return format(bitSet, dim, ",");
  }

  /**
   * Formats the String collection with the specified separator.
   * 
   * @param d the String collection to format
   * @param sep the separator between the single values of the double array,
   *        e.g. ' '
   * @return a String representing the String Collection d
   */
  public static String format(Collection<String> d, String sep) {
    if(d.size() == 0) {
      return "";
    }
    if(d.size() == 1) {
      return d.iterator().next();
    }
    StringBuffer buffer = new StringBuffer();
    boolean first = true;
    for(String str : d) {
      if(!first) {
        buffer.append(sep);
      }
      buffer.append(str);
      first = false;
    }
    return buffer.toString();
  }

  /**
   * Returns a string representation of this matrix.
   * 
   * @param w column width
   * @param d number of digits after the decimal
   * @return a string representation of this matrix
   */
  // TODO: in use?
  public static String format(Matrix m, int w, int d) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);

    int width = w + 1;
    StringBuffer msg = new StringBuffer();
    msg.append("\n"); // start on new line.
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        String s = format.format(m.get(i, j)); // format the number
        int padding = Math.max(1, width - s.length()); // At _least_ 1
        // space
        for(int k = 0; k < padding; k++) {
          msg.append(' ');
        }
        msg.append(s);
      }
      msg.append("\n");
    }
    // msg.append("\n");

    return msg.toString();
  }

  /**
   * Returns a string representation of this matrix.
   * 
   * @param w column width
   * @param d number of digits after the decimal
   * @return a string representation of this matrix
   */
  // TODO: in use?
  public static String format(Vector v, int w, int d) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);

    int width = w + 1;
    StringBuffer msg = new StringBuffer();
    msg.append("\n"); // start on new line.
    for(int i = 0; i < v.getDimensionality(); i++) {
      String s = format.format(v.get(i)); // format the number
      int padding = Math.max(1, width - s.length()); // At _least_ 1
      // space
      for(int k = 0; k < padding; k++) {
        msg.append(' ');
      }
      msg.append(s);
    }
    // msg.append("\n");

    return msg.toString();
  }

  /**
   * Returns a string representation of this matrix. In each line the specified
   * String <code>pre</code> is prefixed.
   * 
   * @param pre the prefix of each line
   * @return a string representation of this matrix
   */
  public static String format(Matrix m, String pre) {
    StringBuffer output = new StringBuffer();
    output.append(pre).append("[\n").append(pre);
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      output.append(" [");
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        output.append(" ").append(m.get(i, j));
        if(j < m.getColumnDimensionality() - 1) {
          output.append(",");
        }
      }
      output.append(" ]\n").append(pre);
    }
    output.append("]\n").append(pre);

    return (output.toString());
  }

  /**
   * returns String-representation of Matrix.
   * 
   * @param nf NumberFormat to specify output precision
   * @return String representation of this Matrix in precision as specified by
   *         given NumberFormat
   */
  public static String format(Matrix m, NumberFormat nf) {
    int[] colMax = new int[m.getColumnDimensionality()];
    String[][] entries = new String[m.getRowDimensionality()][m.getColumnDimensionality()];
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        entries[i][j] = nf.format(m.get(i, j));
        if(entries[i][j].length() > colMax[j]) {
          colMax[j] = entries[i][j].length();
        }
      }
    }
    StringBuffer output = new StringBuffer();
    output.append("[\n");
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      output.append(" [");
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        output.append(" ");
        int space = colMax[j] - entries[i][j].length();
        for(int s = 0; s < space; s++) {
          output.append(" ");
        }
        output.append(entries[i][j]);
        if(j < m.getColumnDimensionality() - 1) {
          output.append(",");
        }
      }
      output.append(" ]\n");
    }
    output.append("]\n");

    return (output.toString());
  }

  /**
   * returns String-representation of Matrix.
   * 
   * @return String representation of this Matrix
   */
  public static String format(Matrix m) {
    return format(m, FormatUtil.NF8);
  }

  /**
   * returns String-representation of Vector.
   * 
   * @param nf NumberFormat to specify output precision
   * @return String representation of this Matrix in precision as specified by
   *         given NumberFormat
   */
  public static String format(Vector m, NumberFormat nf) {
    return "[" + FormatUtil.format(m.getArrayRef(), nf) + "]";
  }

  /**
   * Returns String-representation of Vector.
   * 
   * @return String representation of this Vector
   */
  public static String format(Vector m) {
    return format(m, FormatUtil.NF8);
  }

  /**
   * Returns a string representation of this matrix. In each line the specified
   * String <code>pre</code> is prefixed.
   * 
   * @param pre the prefix of each line
   * @return a string representation of this matrix
   */
  public static String format(Vector v, String pre) {
    StringBuffer output = new StringBuffer();
    output.append(pre).append("[\n").append(pre);
    for(int j = 0; j < v.getDimensionality(); j++) {
      output.append(" ").append(v.get(j));
      if(j < v.getDimensionality() - 1) {
        output.append(",");
      }
    }
    output.append("]\n").append(pre);

    return (output.toString());
  }

  /**
   * Returns a string representation of this matrix. In each line the specified
   * String <code>pre<\code> is prefixed.
   * 
   * @param nf number format for output accuracy
   * @param pre the prefix of each line
   * @return a string representation of this matrix
   */
  public static String format(Matrix m, String pre, NumberFormat nf) {
    if(nf == null) {
      return FormatUtil.format(m, pre);
    }

    int[] colMax = new int[m.getColumnDimensionality()];
    String[][] entries = new String[m.getRowDimensionality()][m.getColumnDimensionality()];
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        entries[i][j] = nf.format(m.get(i, j));
        if(entries[i][j].length() > colMax[j]) {
          colMax[j] = entries[i][j].length();
        }
      }
    }
    StringBuffer output = new StringBuffer();
    output.append(pre).append("[\n").append(pre);
    for(int i = 0; i < m.getRowDimensionality(); i++) {
      output.append(" [");
      for(int j = 0; j < m.getColumnDimensionality(); j++) {
        output.append(" ");
        int space = colMax[j] - entries[i][j].length();
        for(int s = 0; s < space; s++) {
          output.append(" ");
        }
        output.append(entries[i][j]);
        if(j < m.getColumnDimensionality() - 1) {
          output.append(",");
        }
      }
      output.append(" ]\n").append(pre);
    }
    output.append("]\n").append(pre);

    return (output.toString());
  }

  /**
   * Find the first space before position w or if there is none after w.
   * 
   * @param s String
   * @param width Width
   * @return index of best whitespace or <code>-1</code> if no whitespace was
   *         found.
   */
  public static int findSplitpoint(String s, int width) {
    // the newline (or EOS) is the fallback split position.
    int in = s.indexOf(NEWLINE);
    if(in < 0) {
      in = s.length();
    }
    // Good enough?
    if(in < width) {
      return in;
    }
    // otherwise, search for whitespace
    int iw = s.lastIndexOf(' ', width);
    // good whitespace found?
    if(iw >= 0 && iw < width) {
      return iw;
    }
    // sub-optimal splitpoint - retry AFTER the given position
    int bp = nextPosition(s.indexOf(' ', width), s.indexOf(NEWLINE, width));
    if(bp >= 0) {
      return bp;
    }
    // even worse - can't split!
    return s.length();
  }

  /**
   * Helper that is similar to {@code Math.min(a,b)}, except that negative
   * values are considered "invalid".
   * 
   * @param a String position
   * @param b String position
   * @return {@code Math.min(a,b)} if {@code a >= 0} and {@code b >= 0},
   *         otherwise whichever is positive.
   */
  private static int nextPosition(int a, int b) {
    if(a < 0) {
      return b;
    }
    if(b < 0) {
      return a;
    }
    return Math.min(a, b);
  }

  /**
   * Splits the specified string at the last blank before width. If there is no
   * blank before the given width, it is split at the next.
   * 
   * @param s the string to be split
   * @param width int
   * @return string fragments
   */
  public static List<String> splitAtLastBlank(String s, int width) {
    List<String> chunks = new ArrayList<String>();

    String tmp = s;
    while(tmp.length() > 0) {
      int index = findSplitpoint(tmp, width);
      // store first part
      chunks.add(tmp.substring(0, index));
      // skip whitespace at beginning of line
      while(index < tmp.length() && tmp.charAt(index) == ' ') {
        index += 1;
      }
      // remove a newline
      if(index < tmp.length() && tmp.regionMatches(index, NEWLINE, 0, NEWLINE.length())) {
        index += NEWLINE.length();
      }
      if(index >= tmp.length()) {
        break;
      }
      tmp = tmp.substring(index);
    }

    return chunks;
  }

  /**
   * Returns a string with the specified number of whitespace.
   * 
   * @param n the number of whitespace characters
   * @return a string with the specified number of blanks
   */
  public static String whitespace(int n) {
    if(n < WHITESPACE_BUFFER.length()) {
      return WHITESPACE_BUFFER.substring(0, n);
    }
    char[] buf = new char[n];
    for(int i = 0; i < n; i++) {
      buf[i] = WHITESPACE_BUFFER.charAt(0);
    }
    return new String(buf);
  }

  /**
   * Pad a string to a given length by adding whitespace to the right.
   * 
   * @param o original string
   * @param len destination length
   * @return padded string of at least length len (and o otherwise)
   */
  public static String pad(String o, int len) {
    if(o.length() >= len) {
      return o;
    }
    return o + whitespace(len - o.length());
  }

  /**
   * Pad a string to a given length by adding whitespace to the left.
   * 
   * @param o original string
   * @param len destination length
   * @return padded string of at least length len (and o otherwise)
   */
  public static String padRightAligned(String o, int len) {
    if(o.length() >= len) {
      return o;
    }
    return whitespace(len - o.length()) + o;
  }

  /**
   * Get the width of the terminal window (on Unix xterms), with a default of 78
   * characters.
   * 
   * @return Terminal width
   */
  public static int getConsoleWidth() {
    int termwidth = 78;
    try {
      termwidth = Integer.parseInt(System.getenv("COLUMNS")) - 1;
    }
    catch(Exception e) {
      // Do nothing, stick with default of 78.
    }
    return termwidth;
  }

  /**
   * Formats a time delta in human readable format.
   * 
   * @param time time delta in ms
   * @return Formatted string
   */
  public static String formatTimeDelta(long time, CharSequence sep) {
    final StringBuilder sb = new StringBuilder();
    final Formatter fmt = new Formatter(sb);

    for(int i = TIME_UNIT_SIZES.length - 1; i >= 0; --i) {
      // We do not include ms if we are in the order of minutes.
      if(i == 0 && sb.length() > 4) {
        continue;
      }
      // Separator
      if(sb.length() > 0) {
        sb.append(sep);
      }
      final long acValue = time / TIME_UNIT_SIZES[i];
      time = time % TIME_UNIT_SIZES[i];
      if(!(acValue == 0 && sb.length() == 0)) {
        fmt.format("%0" + TIME_UNIT_DIGITS[i] + "d%s", acValue, TIME_UNIT_NAMES[i]);
      }
    }
    return sb.toString();
  }

  /**
   * Formats the string array d with the specified separator.
   * 
   * @param d the string array to be formatted
   * @param sep the separator between the single values of the double array,
   *        e.g. ','
   * @return a String representing the string array d
   */
  public static String format(String[] d, String sep) {
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < d.length; i++) {
      if(i > 0) {
        buffer.append(sep).append(d[i]);
      }
      else {
        buffer.append(d[i]);
      }
    }
    return buffer.toString();
  }
}