Skip to content

Commit f966754

Browse files
ctruedenimagejan
authored andcommitted
DefaultTableDisplay: handle double array as table
In this specific case (double[] and double[][]), it is easy to wrap the data in DoubleColumn objects. Ideally, we want to support all types of primitive 1D and 2D arrays, or even all Collection<N extends Number>, but that will require a little more infrastructural work to accomplish. This approach is good enough for now, for MATLAB matrix support, which always uses doubles.
1 parent 0fe628f commit f966754

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

src/main/java/net/imagej/table/DefaultTableDisplay.java

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,75 @@ public DefaultTableDisplay() {
5050
super((Class) Table.class);
5151
}
5252

53+
// -- Display methods --
54+
55+
@Override
56+
public boolean canDisplay(final Class<?> c) {
57+
if (c == double[].class || c == double[][].class) return true;
58+
return super.canDisplay(c);
59+
}
60+
61+
@Override
62+
public void display(final Object o) {
63+
// wrap 1D array as results table
64+
if (o instanceof double[]) {
65+
display(wrapArrayAsTable(new double[][] { (double[]) o }));
66+
return;
67+
}
68+
// wrap 2D array as results table
69+
if (o instanceof double[][]) {
70+
display(wrapArrayAsTable((double[][]) o));
71+
return;
72+
}
73+
74+
super.display(o);
75+
}
76+
77+
@Override
78+
public boolean isDisplaying(final Object o) {
79+
if (super.isDisplaying(o)) return true;
80+
81+
// check for wrapped arrays
82+
if (o instanceof double[]) {
83+
arrayEqualsTable(new double[][] {(double[]) o});
84+
}
85+
if (o instanceof double[][]) {
86+
arrayEqualsTable((double[][]) o);
87+
}
88+
89+
return false;
90+
}
91+
92+
// -- Helper methods --
93+
94+
private ResultsTable wrapArrayAsTable(final double[][] array) {
95+
final ResultsTable table = new DefaultResultsTable();
96+
int rowCount = 0;
97+
for (int d = 0; d < array.length; d++) {
98+
final DoubleColumn column = new DoubleColumn();
99+
column.setArray(array[d]);
100+
table.add(column);
101+
if (rowCount < array[d].length) rowCount = array[d].length;
102+
}
103+
table.setRowCount(rowCount);
104+
return table;
105+
}
106+
107+
private boolean arrayEqualsTable(final double[][] array) {
108+
for (final Table<?, ?> table : this) {
109+
if (!(table instanceof ResultsTable)) continue;
110+
final ResultsTable resultsTable = (ResultsTable) table;
111+
if (array.length != resultsTable.getColumnCount()) continue;
112+
boolean equal = true;
113+
for (int c = 0; c < array.length; c++) {
114+
if (array[c] != resultsTable.get(c).getArray()) {
115+
equal = false;
116+
break;
117+
}
118+
}
119+
return equal;
120+
}
121+
return false;
122+
}
123+
53124
}

0 commit comments

Comments
 (0)