1 8 package org.lsmp.djep.vectorJep.values; 9 import org.lsmp.djep.vectorJep.*; 10 11 17 public class Tensor extends Number implements MatrixValueI { 18 private Object values[]=null; 19 private Dimensions dims; 20 22 private Tensor() {} 23 24 25 public Tensor(Dimensions dims) 26 { 27 values = new Object [dims.numEles()]; 28 this.dims = dims; 29 } 30 31 32 public Tensor(Tensor t) 33 { 34 values = new Object [t.getDim().numEles()]; 35 this.dims = t.getDim(); 36 } 37 38 39 public Tensor(int len,Dimensions dims) 40 { 41 values = new Object [len*dims.numEles()]; 42 this.dims = Dimensions.valueOf(len,dims); 43 } 44 45 public Dimensions getDim() { return dims; } 46 public int getNumEles() { return values.length; } 47 public void setEle(int i,Object value) { values[i]=value; } 48 public Object getEle(int i) { return values[i]; } 49 50 public void setEles(MatrixValueI val) 51 { 52 if(!dims.equals(val.getDim())) return; 53 System.arraycopy(((Tensor) val).values,0,values,0,getNumEles()); 54 } 55 56 59 public static MatrixValueI getInstance(Dimensions dims) 60 { 61 switch(dims.rank()) 62 { 63 case 0: return new Scaler(); 64 case 1: return new MVector(dims.getFirstDim()); 65 case 2: return new Matrix(dims.getFirstDim(),dims.getLastDim()); 66 default: 67 return new Tensor(dims); 68 } 69 } 70 71 public static MatrixValueI getInstance(int rows,Dimensions dims) 72 { 73 switch(dims.rank()) 74 { 75 case 0: return new MVector(rows); 76 case 1: return new Matrix(rows,dims.getFirstDim()); 77 default: 78 return new Tensor(Dimensions.valueOf(rows,dims)); 79 } 80 } 81 82 private int curEle =0; 83 84 protected void bufferAppend(StringBuffer sb,int currank) 85 { 86 sb.append("["); 87 if(currank+1 >= dims.rank()) 88 { 89 for(int i=0;i<dims.getIthDim(currank);++i) 91 { 92 if(i!=0) sb.append(","); 93 sb.append(getEle(curEle++)); 94 } 95 } 96 else 97 { 98 for(int i=0;i<dims.getIthDim(currank);++i) 100 { 101 if(i!=0) sb.append(","); 102 bufferAppend(sb,currank+1); 103 } 104 } 105 sb.append("]"); 106 } 107 110 public String toString() 111 { 112 StringBuffer sb = new StringBuffer (); 113 curEle = 0; 114 bufferAppend(sb,0); 115 return sb.toString(); 116 } 117 118 119 public int intValue() {return ((Number ) values[0]).intValue(); } 120 121 public long longValue() {return ((Number ) values[0]).longValue(); } 122 123 public float floatValue() { return ((Number ) values[0]).floatValue(); } 124 125 public double doubleValue() {return ((Number ) values[0]).doubleValue(); } 126 127 public boolean equals(Object obj) { 128 if(!(obj instanceof Tensor)) return false; 129 Tensor tens = (Tensor) obj; 130 if(!tens.getDim().equals(getDim())) return false; 131 for(int i=0;i<values.length;++i) 132 if(!values[i].equals(tens.values[i])) return false; 133 return true; 134 } 135 136 140 public int hashCode() { 141 int result = 17; 142 for(int i=0;i<values.length;++i) 143 result = 37*result+ values[i].hashCode(); 144 return result; 145 } 146 } 147 | Popular Tags |