id
stringlengths
36
36
text
stringlengths
1
1.25M
1ab489cf-7a0a-44a4-b590-b031797ee795
@Override protected void write(char[] arr, int offset, int size) { int tailLen = capacity - putIndex; long address = block.address; if(size <= tailLen) { writeChars(address, putIndex, arr, offset, offset+size); }else { writeChars(address, putIndex, arr, offset, offset+tailLen); writeChars(address, 0, arr, offset+tailLen, offset+size); } }
34494b6d-ae30-4515-ab63-98951a8f2695
@Override protected char read() { return readChar(block.address, takeIndex); }
2ea58785-c469-42e4-86d6-49e3c88b0170
@Override protected void read(char[] arr, int offset, int size) { long address = block.address; if(putIndex <= takeIndex) { int tailLen = capacity - takeIndex; if(size <= tailLen) { readChars(address, takeIndex, arr, offset, offset+size); }else { readChars(address, takeIndex, arr, offset, offset+tailLen); readChars(address, 0, arr, offset+tailLen, offset+size); } }else { readChars(address, takeIndex, arr, offset, offset+size); } }
cc16ae65-2646-4dca-b227-c904f33df565
@Override protected boolean isArrayBacked() { return false; }
f4760802-ef89-41d7-a90b-ca883007bfec
@Override protected char[] backendArray() { throw new UnsupportedOperationException("rolling direct char buffer"); }
120b9460-df34-42e9-a1fb-3a67b7fb7d4e
MemoryBlock(int capacity) { address = allocateMemory(capacity); cleaner = Cleaner.create(this, new Deallocator(address)); }
96282c66-26a6-4a69-8948-02f8afdd8ec5
static MemoryBlock allocate(int capacity) { return new MemoryBlock(capacity); }
72534af1-cab7-46ff-a99c-394792bdc917
static void deallocate(MemoryBlock block) { if(block != null) { block.cleaner.clean(); } }
6c165c69-70b2-4a22-8adc-278bc1b116d7
private Deallocator(long address) { this.address = address; }
05f2d566-a58c-4ea7-8f5c-aba3a4538682
public void run() { if(address == 0) { return; } freeMemory(address); address = 0; }
c3d04566-6595-49c3-9f3b-8045ab6ad3d1
@Override protected void clean() { resetIndex(); capacity = 0; if(block != null) { MemoryBlock.deallocate(block); block = null; } }
7121b427-d677-4161-9c1f-c372477d66b4
RollingHeapCharBuffer(int capacity) { super(); buffer = new char[capacity]; }
1867b797-f921-4b63-b4a8-db58e8f4a870
RollingHeapCharBuffer(char[] array) { super(); buffer = array; }
1034f609-ce1a-498d-9c80-a900a7b0db1d
@Override protected int retCapacity() { return buffer.length; }
c72f746e-d167-45d1-a8ea-be2fbccf2828
@Override protected void ensureCapacity(int incCap) { if(incCap < remained()) { return; } int capacity = capacity(); int newCapacity = 0; if(2*incCap <= capacity) { newCapacity = capacity * 3 / 2 + 1; }else { newCapacity = capacity * 2; } char[] newBuf = new char[newCapacity]; if(size > 0) { if(putIndex > takeIndex) { System.arraycopy(buffer, takeIndex, newBuf, 0, size); }else { int len = buffer.length - takeIndex; System.arraycopy(buffer, takeIndex, newBuf, 0, len); if(size > len) { System.arraycopy(buffer, 0, newBuf, len, putIndex); } } } buffer = newBuf; takeIndex = 0; putIndex = size; }
107873a4-fff3-41cf-9fdf-98ececdfdbef
@Override protected void write(char ch) { buffer[putIndex] = ch; }
0bd4196d-ad98-4c8a-a888-5d70ecb57e82
@Override protected void write(char[] arr, int offset, int size) { int tailLen = buffer.length - putIndex; if(tailLen >= size) { System.arraycopy(arr, offset, buffer, putIndex, size); }else { System.arraycopy(arr, offset, buffer, putIndex, tailLen); System.arraycopy(arr, offset+tailLen, buffer, 0, size-tailLen); } }
0e29d00e-bbd5-4914-a865-2d88b929f8a5
@Override protected char read() { return buffer[takeIndex]; }
bda9ee55-77d1-4dd9-b070-c5a6d42c2100
@Override protected void read(char[] arr, int offset, int size) { if(putIndex <= takeIndex) { int len = buffer.length - takeIndex; if(size <= len) { System.arraycopy(buffer, takeIndex, arr, offset, size); }else { System.arraycopy(buffer, takeIndex, arr, offset, len); System.arraycopy(buffer, 0, arr, offset+len, size-len); } }else { System.arraycopy(buffer, takeIndex, arr, offset, size); } }
fa06d69d-31ff-47bc-b1f3-19cae33d6524
@Override protected boolean isArrayBacked() { return true; }
869dc099-2420-4d79-80c5-e295b1bda959
@Override protected char[] backendArray() { return buffer; }
c8b3cfc0-dc4c-450f-b1dc-766ab92cbf26
@Override protected void clean() { resetIndex(); if(buffer != null) { buffer = null; } }
959903c0-3a7d-48cc-8cf1-9bf1b79ef2d2
public static boolean hasUnsafe() { return UNSAFE != null; }
3b01f496-2d1e-40eb-b7dd-7a61a89f6c2f
public static int memoryPageSize() { if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: memoryPageSize()"); } return UNSAFE.pageSize() / (int)CHAR_ARRAY_SCALE; }
05c49eed-c2c0-4edc-bcee-6bec366a29f2
public static long allocateMemory(long chars) { if(chars < 0) { throw new IllegalArgumentException("illegal argument for allocate memory operaion"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: allcateMemory(long)"); } return UNSAFE.allocateMemory(CHAR_ARRAY_SCALE * chars); }
b3c29246-aa23-46ed-b665-5cf1811ad084
public static void freeMemory(long address) { if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: freeMemory(long)"); } UNSAFE.freeMemory(address); }
0dffbb8c-6bb3-4c3a-8901-c5cebff79930
public static char readChar(long address, int offset) { if(address == 0 || offset < 0) { throw new IllegalArgumentException("illegal argument for read char operaion"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: readChar(long)"); } return UNSAFE.getChar(address+offset*CHAR_ARRAY_SCALE); }
a9e59faa-bd2d-403f-a554-c9d8719e77ee
public static void readChars(long address, int offset, char[] arr) { if(address == 0 || offset < 0 || arr == null) { throw new IllegalArgumentException("illegal argument for read chars opertaion"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: readChars(long, char[])"); } if(arr.length == 0) { return; } copyMemory(address, offset, arr, 0, arr.length); }
8fe101e4-319c-4517-979f-1718b42a5ae3
public static void readChars(long address, int offset, char[] arr, int beginIndex, int endIndex) { if(address == 0 || offset < 0 || arr == null) { throw new IllegalArgumentException("illegal argument for read chars opertaion"); } if(beginIndex < 0 || endIndex > arr.length) { throw new ArrayIndexOutOfBoundsException("out of index for read chars operation"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: readChars(long, char[])"); } if(arr.length == 0 || beginIndex >= endIndex) { return; } copyMemory(address, offset, arr, beginIndex, endIndex - beginIndex); }
b537fb1a-6415-40ae-980e-f0db0acbbc69
public static void writeChar(long address, int offset, char ch) { if(address == 0 || offset < 0) { throw new IllegalArgumentException("illegal argument for write char operaion"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: writeChar(long, char)"); } UNSAFE.putChar(address+offset*CHAR_ARRAY_SCALE, ch); }
9db759bf-4b42-429b-987b-780d1724491f
public static void writeChars(long address, int offset, char[] arr) { if(address == 0 || offset < 0 || arr == null) { throw new IllegalArgumentException("illegal argument for write chars opertaion"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: writeChars(long, char[])"); } if(arr.length == 0) { return; } copyMemory(arr, 0, address, offset, arr.length); }
377af205-f97b-4f4f-aef6-ea673de72015
public static void writeChars(long address, int offset, char[] arr, int beginIndex, int endIndex) { if(address == 0 || offset < 0 || arr == null) { throw new IllegalArgumentException("illegal argument for write chars opertaion"); } if(beginIndex < 0 || endIndex > arr.length) { throw new ArrayIndexOutOfBoundsException("out of index for write chars operation"); } if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: writeChars(long, char[])"); } if(arr.length == 0 || beginIndex >= endIndex) { return; } copyMemory(arr, beginIndex, address, offset, endIndex - beginIndex); }
53ae9fa5-3f3a-4d59-81a0-bea3de58f4c2
public static void copyMemory(long srcMemAddr, int srcOffset, long destMemAddr, int destOffset, long chars) { if(!hasUnsafe()) { throw new UnsupportedOperationException("unsupported opertaion: copyMemory(long, long, long)"); } UNSAFE.copyMemory(srcMemAddr+srcOffset*CHAR_ARRAY_SCALE, destMemAddr+destOffset*CHAR_ARRAY_SCALE, chars*CHAR_ARRAY_SCALE); }
36518aeb-c8a0-47d7-b8fa-a231723a9a20
private static void copyMemory(char[] srcArray, int srcOffset, long destMemAddr, int destOffset, long chars) { UNSAFE.copyMemory(srcArray, CHAR_ARRAY_OFFSET+srcOffset*CHAR_ARRAY_SCALE, null, destMemAddr+destOffset*CHAR_ARRAY_SCALE, chars*CHAR_ARRAY_SCALE); }
e32a00ea-0cda-43e7-9a4e-f6a20af1bda2
private static void copyMemory(long srcMemAddr, int srcOffset, char[] destArray, int destOffset, long chars) { UNSAFE.copyMemory(null, srcMemAddr+srcOffset*CHAR_ARRAY_SCALE, destArray, CHAR_ARRAY_OFFSET+destOffset*CHAR_ARRAY_SCALE, chars*CHAR_ARRAY_SCALE); }
58f4154b-0b9d-4e12-bc25-5fb5b92a1217
public static void main(String[] args) { char[] src = new char[] {'1','2','3'}; long dest = allocateMemory(3); writeChar(dest, 0, 'a'); writeChar(dest, 1, 'a'); writeChar(dest, 2, 'a'); writeChars(dest, 1, src, 1, 3); System.out.println(readChar(dest, 1)); System.out.println(readChar(dest, 2)); writeChar(dest, 1, 'b'); writeChar(dest, 2, 'c'); readChars(dest, 0, src); System.out.println(Arrays.toString(src)); freeMemory(dest); }
d3372f0b-b463-4add-8a0d-e12be9c69029
public static void main(String[] args) throws Exception { // testAccessJavaCharArray(); // testReallocateMemory(); // testCopyJavaMemory(); testPageSize(); }
5d4043e4-9603-4c05-98fa-6010926144f4
public static void testAccessJavaCharArray() throws Exception { char[] chars = new char[] {'1', '2', '3'}; Unsafe unsafe = getUnsafe(); long address = unsafe.arrayBaseOffset(char[].class); int scale = unsafe.arrayIndexScale(char[].class); println("scale = "+scale); println(unsafe.getChar(chars, address)); println(unsafe.getChar(chars, address+scale)); println(unsafe.getChar(chars, address+2*scale)); }
c445e39c-445e-483b-8245-e5412bfdf71c
public static void testReallocateMemory() throws Exception { Unsafe unsafe = getUnsafe(); long addr = unsafe.allocateMemory(2); unsafe.putByte(addr, (byte)1); unsafe.putByte(addr+1, (byte)2); println(unsafe.getByte(addr)); println(unsafe.getByte(addr+1)); long newAddr = unsafe.reallocateMemory(addr, 4); println(unsafe.getByte(newAddr)); println(unsafe.getByte(newAddr+1)); unsafe.freeMemory(newAddr); }
5c2f8543-b2e8-4b2f-93a4-7a66bd61750f
public static void testCopyJavaMemory() throws Exception { Unsafe unsafe = getUnsafe(); char[] src = new char[] {'1', '2', '3'}; long offset = unsafe.arrayBaseOffset(char[].class); long scale = unsafe.arrayIndexScale(char[].class); long dest = unsafe.allocateMemory(3); unsafe.putChar(dest, '4'); unsafe.putChar(dest+scale, '5'); unsafe.putChar(dest+scale*2, '6'); unsafe.copyMemory(src, offset+scale, null, dest+scale, 2*scale); println(unsafe.getChar(dest)); println(unsafe.getChar(dest+scale)); println(unsafe.getChar(dest+scale*2)); unsafe.putChar(dest, 'a'); unsafe.putChar(dest+scale, 'b'); unsafe.putChar(dest+scale*2, 'c'); unsafe.copyMemory(null, dest+scale, src, offset+scale, 2*scale); println(src[0]); println(src[1]); println(src[2]); unsafe.freeMemory(dest); }
9472d7d1-3810-4d2b-8b11-b6bf15f22052
private static void testPageSize() throws Exception { Unsafe unsafe = getUnsafe(); println(unsafe.pageSize()); }
2387d9a8-8a29-47ed-8daf-254e40378b00
private static Unsafe getUnsafe() throws Exception { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (Unsafe) f.get(null); }
e54b8fee-3cf0-4647-9fb8-1a1bc747ac5d
private static <T> void println(T obj) { System.out.println(obj); }
3973655d-950b-4560-bde7-3f4556fc9eb1
public static void main(String[] args) throws Exception { testRollingHeapCharBuffer(); testRollingDirectCharBuffer(); }
5c027fda-9b30-46db-a50a-87454911daae
public static void testRollingHeapCharBuffer() { testOpSeq(RollingCharBuffer.allocate(6)); }
79932c58-8c25-4e7b-925e-1b4c902859ee
public static void testRollingDirectCharBuffer() { testOpSeq(RollingCharBuffer.allocate(6, true)); }
65250a73-3c68-493d-8c17-104333c27003
private static void testOpSeq(RollingCharBuffer buffer) { println("====================="+buffer.getClass().getSimpleName()+"====================="); boolean hasArray = buffer.hasArray(); println(hasArray); buffer.put('1'); buffer.put(new char[]{'2', '3'}); buffer.put(new char[]{'4', '5'}); println(buffer.take()); println(Arrays.toString(buffer.take(2))); buffer.put(new char[]{'6', 'a', 'b'}); if(hasArray) { println(Arrays.toString(buffer.array())); } buffer.put(new char[]{'c', 'd'}); println(buffer.size()); println(buffer.putIndex()); println(buffer.takeIndex()); if(hasArray) { println(Arrays.toString(buffer.array())); } println(Arrays.toString(buffer.takeAll())); println(buffer.size()); println(buffer.putIndex()); println(buffer.takeIndex()); buffer.release(); println("====================="+buffer.getClass().getSimpleName()+"====================="); println(""); }
62fbfead-6986-479e-b634-d8190c5cbb3d
private static <T> void println(T obj) { System.out.println(obj); }
d35deae8-466b-4aa8-8f93-f6fa9c35f6a4
public void setup(Context context) { System.out.println("============== SETUP () ============"); FileSplit fileSplit = (FileSplit)context.getInputSplit(); inpFile = fileSplit.getPath().getName(); }
a5209e50-f154-4e9f-b8bb-c4e8b5bd0f42
public void map(LongWritable key, Text value, Context context) throws IOException { String line = value.toString(); line = line.replaceAll("[^a-zA-Z0-9]+"," "); line = line.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); try { context.write(word, new Text(inpFile)); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("Failed emitting from mapper"); e.printStackTrace(); } } }
0432437f-daf7-4e03-ba2b-6b8f4633fddc
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException { Set<String> fileSet = new HashSet<String>(); int sum = 0, dc = 0; for(Text val:values) { fileSet.add(val.toString()); sum++; } dc = fileSet.size(); /* Dont collect to reduce rather write straight-away to $OUTPUT_FOLDER/Index/TermIndex/ */ Text res = new Text(sum+"\t"+dc); try { context.write(key, res); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("Failed emitting from mapper"); e.printStackTrace(); } }
22335325-7d9c-4abf-a606-bb6ba204ca69
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "TermIndexer Job"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setJarByClass(TermIndexer.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[0]+"/../Index/")); job.waitForCompletion(true); /* JobConf conf = new JobConf(TermIndexer.class); conf.setJobName("TermIndexer"); conf.setMapOutputKeyClass(Text.class); conf.setMapOutputValueClass(Text.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(Text.class); conf.setMapperClass(Map.class); //conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[0]+"/../Index/")); JobClient.runJob(conf); */ }
4bf52eac-e4d2-4132-b5b6-e538347d1db6
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 6) { System.err.println("Usage: wordcount <in> <out> <NoOfClusters K> <CentroidFile> <MaxIterations> <ReducedRank>"); System.exit(2); } conf.set("NoOfClusters", otherArgs[2]); int maxIter = Integer.parseInt(otherArgs[4]); int i=0; for(i=0;i<maxIter;i++) { System.out.println(i + "th ITERATION"); /* Cluster the inputs */ conf.set("CentroidFile", otherArgs[3]+i+"/part-r-00000"); Job job = new Job(conf, "Clustering Job"); job.setJarByClass(LSIndexer.class); job.setMapperClass(ClusteringMapper.class); job.setReducerClass(ClusteringReducer.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); job.setNumReduceTasks(Integer.parseInt(otherArgs[2])); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]+i)); job.waitForCompletion(true); /*Job to make the next centroid file*/ System.out.println("Making the new Centroid FIle"); Job job2 = new Job(conf, "Make Centroid"); job2.setJarByClass(LSIndexer.class); job2.setMapperClass(CombineCentroidsMapper.class); job2.setReducerClass(CombineCentroidsReducer.class); job2.setOutputKeyClass(IntWritable.class); job2.setOutputValueClass(Text.class); job2.setNumReduceTasks(1); FileInputFormat.addInputPath(job2, new Path(otherArgs[1]+i)); int j=i+1; FileOutputFormat.setOutputPath(job2, new Path(otherArgs[3]+j)); job2.waitForCompletion(true); } /* Job to make the final Cluster */ System.out.println("Final MapReduce Job Running"); conf.set("ReducedRank", otherArgs[5]); conf.set("CentroidFile", otherArgs[3]+i+"/part-r-00000"); Job job3 = new Job(conf, "Clustering Job"); job3.setJarByClass(LSIndexer.class); job3.setMapperClass(MakeClusterMapper.class); job3.setReducerClass(MakeClusterReducer.class); job3.setOutputKeyClass(IntWritable.class); job3.setOutputValueClass(Text.class); job3.setNumReduceTasks(Integer.parseInt(otherArgs[2])); FileInputFormat.addInputPath(job3, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job3, new Path(otherArgs[1]+i)); job3.waitForCompletion(true); /*END*/ }
d9464f08-e0ab-4022-839e-3212f7352a07
public void reduce(IntWritable key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { double[] intArray = null; int flag =1; int size = 0; int counter = 0; //key is unique for each reducer hence append C to it //the value key ranges from 0 to K-1 for (Text val : values) { System.out.println(val.toString()); if (flag == 1) { size = val.toString().split("\t").length - 1; intArray = new double[size]; for (int i=0; i < size ; i++) intArray[i] = 0; flag =0; } String[] arr = val.toString().split("\t"); for (int i=0; i<size;i++) intArray[i] += Double.parseDouble(arr[i+1]); counter++; } for (int i=0;i<size;i++) intArray[i] = intArray[i]/counter; String toWrite ="C" + key + "\t"; for (int i=0;i<size;i++) toWrite = toWrite + intArray[i] + "\t"; Text toWriteText = new Text(toWrite); context.write(toWriteText, null); }
7e069b44-618e-48b6-8303-c532bb8b0628
public void setup(Context context) { Configuration conf = context.getConfiguration(); try { FileSystem fs = FileSystem.get(conf); Path infile = new Path(conf.get("CentroidFile")); //give it as an argument if (!fs.exists(infile)) System.out.println("Centroids.txt does not exist"); if (!fs.isFile(infile)) System.out.println("Centroids.txt is not a file"); BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(infile))); String str = conf.get("NoOfClusters"); int K = Integer.parseInt(str); for (int i=0; i<K;i++) Centroids.put(i, br.readLine()); br.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Exception in Creating the FileSystem object in Mapper"); e.printStackTrace(); } }
871215c6-c65f-4652-abc8-f4c7c26938d2
private double EucledianDistance(String s1, String s2) { StringTokenizer itr1 = new StringTokenizer(s1); StringTokenizer itr2 = new StringTokenizer(s2); String id1 = itr1.nextToken("\t");//Do not remove (needed to remove the first id element) String id2 = itr2.nextToken("\t");//Do not remove (needed to remove the first id element) Double sum = 0.0; Double Diff = 0.0; while (itr1.hasMoreTokens() && itr2.hasMoreTokens()) { Diff = (Double.parseDouble(itr1.nextToken("\t")) - Double.parseDouble(itr2.nextToken("\t"))); sum = sum + Math.pow(Diff, 2); } return Math.sqrt(sum); }
6170a51c-c7b6-4e1c-9e05-54e4bcd1b009
public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { int minCentroidID=0; double dist, mindist = -1.0; Iterator<Integer> keyIter = Centroids.keySet().iterator(); while (keyIter.hasNext()) { Integer CentroidID = keyIter.next(); dist = EucledianDistance(Centroids.get(CentroidID), value.toString()); System.out.println("Distance between"+Centroids.get(CentroidID)+"AND"+value.toString()+"is"+ dist); if (dist < mindist || mindist == -1.0) { mindist = dist; minCentroidID = CentroidID; } } IntWritable k = new IntWritable(minCentroidID); context.write(k, value); }
acc8f689-8520-45b5-9017-d089b9500532
public CholeskyDecomposition (Matrix Arg) { // Initialize. double[][] A = Arg.getArray(); n = Arg.getRowDimension(); L = new double[n][n]; isspd = (Arg.getColumnDimension() == n); // Main loop. for (int j = 0; j < n; j++) { double[] Lrowj = L[j]; double d = 0.0; for (int k = 0; k < j; k++) { double[] Lrowk = L[k]; double s = 0.0; for (int i = 0; i < k; i++) { s += Lrowk[i]*Lrowj[i]; } Lrowj[k] = s = (A[j][k] - s)/L[k][k]; d = d + s*s; isspd = isspd & (A[k][j] == A[j][k]); } d = A[j][j] - d; isspd = isspd & (d > 0.0); L[j][j] = Math.sqrt(Math.max(d,0.0)); for (int k = j+1; k < n; k++) { L[j][k] = 0.0; } } }
beccf7a7-b711-4a57-a342-dc5604d800f5
public boolean isSPD () { return isspd; }
8aedf833-a888-45ed-8828-59aeedc8b870
public Matrix getL () { return new Matrix(L,n,n); }
40227f17-5af7-4ec1-80d7-d165ea0b6f95
public Matrix solve (Matrix B) { if (B.getRowDimension() != n) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!isspd) { throw new RuntimeException("Matrix is not symmetric positive definite."); } // Copy right hand side. double[][] X = B.getArrayCopy(); int nx = B.getColumnDimension(); // Solve L*Y = B; for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { for (int i = 0; i < k ; i++) { X[k][j] -= X[i][j]*L[k][i]; } X[k][j] /= L[k][k]; } } // Solve L'*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { for (int i = k+1; i < n ; i++) { X[k][j] -= X[i][j]*L[i][k]; } X[k][j] /= L[k][k]; } } return new Matrix(X,n,nx); }
9f318c4c-df4b-4aaa-b24c-687280a8bde4
public QRDecomposition (Matrix A) { // Initialize. QR = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); Rdiag = new double[n]; // Main loop. for (int k = 0; k < n; k++) { // Compute 2-norm of k-th column without under/overflow. double nrm = 0; for (int i = k; i < m; i++) { nrm = Maths.hypot(nrm,QR[i][k]); } if (nrm != 0.0) { // Form k-th Householder vector. if (QR[k][k] < 0) { nrm = -nrm; } for (int i = k; i < m; i++) { QR[i][k] /= nrm; } QR[k][k] += 1.0; // Apply transformation to remaining columns. for (int j = k+1; j < n; j++) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*QR[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { QR[i][j] += s*QR[i][k]; } } } Rdiag[k] = -nrm; } }
60d3c62f-0e25-4394-980a-a033afaa065d
public boolean isFullRank () { for (int j = 0; j < n; j++) { if (Rdiag[j] == 0) return false; } return true; }
38386247-2902-4beb-81a1-7d8f65836013
public Matrix getH () { Matrix X = new Matrix(m,n); double[][] H = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i >= j) { H[i][j] = QR[i][j]; } else { H[i][j] = 0.0; } } } return X; }
dec8e4ea-0a8b-4d24-9143-1735c328625a
public Matrix getR () { Matrix X = new Matrix(n,n); double[][] R = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i < j) { R[i][j] = QR[i][j]; } else if (i == j) { R[i][j] = Rdiag[i]; } else { R[i][j] = 0.0; } } } return X; }
a8dd944a-b65b-41fe-9127-b129be0dedf3
public Matrix getQ () { Matrix X = new Matrix(m,n); double[][] Q = X.getArray(); for (int k = n-1; k >= 0; k--) { for (int i = 0; i < m; i++) { Q[i][k] = 0.0; } Q[k][k] = 1.0; for (int j = k; j < n; j++) { if (QR[k][k] != 0) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*Q[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { Q[i][j] += s*QR[i][k]; } } } } return X; }
04653fa9-8e49-464e-a67a-aca2e5e7e36e
public Matrix solve (Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isFullRank()) { throw new RuntimeException("Matrix is rank deficient."); } // Copy right hand side int nx = B.getColumnDimension(); double[][] X = B.getArrayCopy(); // Compute Y = transpose(Q)*B for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*X[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { X[i][j] += s*QR[i][k]; } } } // Solve R*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= Rdiag[k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*QR[i][k]; } } } return (new Matrix(X,n,nx).getMatrix(0,n-1,0,nx-1)); }
a8e66b2f-d44c-4631-aca4-5fcc8fb9752a
private void tred2 () { // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int j = 0; j < n; j++) { d[j] = V[n-1][j]; } // Householder reduction to tridiagonal form. for (int i = n-1; i > 0; i--) { // Scale to avoid under/overflow. double scale = 0.0; double h = 0.0; for (int k = 0; k < i; k++) { scale = scale + Math.abs(d[k]); } if (scale == 0.0) { e[i] = d[i-1]; for (int j = 0; j < i; j++) { d[j] = V[i-1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } } else { // Generate Householder vector. for (int k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } double f = d[i-1]; double g = Math.sqrt(h); if (f > 0) { g = -g; } e[i] = scale * g; h = h - f * g; d[i-1] = f - g; for (int j = 0; j < i; j++) { e[j] = 0.0; } // Apply similarity transformation to remaining columns. for (int j = 0; j < i; j++) { f = d[j]; V[j][i] = f; g = e[j] + V[j][j] * f; for (int k = j+1; k <= i-1; k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } e[j] = g; } f = 0.0; for (int j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } double hh = f / (h + h); for (int j = 0; j < i; j++) { e[j] -= hh * d[j]; } for (int j = 0; j < i; j++) { f = d[j]; g = e[j]; for (int k = j; k <= i-1; k++) { V[k][j] -= (f * e[k] + g * d[k]); } d[j] = V[i-1][j]; V[i][j] = 0.0; } } d[i] = h; } // Accumulate transformations. for (int i = 0; i < n-1; i++) { V[n-1][i] = V[i][i]; V[i][i] = 1.0; double h = d[i+1]; if (h != 0.0) { for (int k = 0; k <= i; k++) { d[k] = V[k][i+1] / h; } for (int j = 0; j <= i; j++) { double g = 0.0; for (int k = 0; k <= i; k++) { g += V[k][i+1] * V[k][j]; } for (int k = 0; k <= i; k++) { V[k][j] -= g * d[k]; } } } for (int k = 0; k <= i; k++) { V[k][i+1] = 0.0; } } for (int j = 0; j < n; j++) { d[j] = V[n-1][j]; V[n-1][j] = 0.0; } V[n-1][n-1] = 1.0; e[0] = 0.0; }
42ffc857-75b1-4e12-b605-ef74f8583f9d
private void tql2 () { // This is derived from the Algol procedures tql2, by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int i = 1; i < n; i++) { e[i-1] = e[i]; } e[n-1] = 0.0; double f = 0.0; double tst1 = 0.0; double eps = Math.pow(2.0,-52.0); for (int l = 0; l < n; l++) { // Find small subdiagonal element tst1 = Math.max(tst1,Math.abs(d[l]) + Math.abs(e[l])); int m = l; while (m < n) { if (Math.abs(e[m]) <= eps*tst1) { break; } m++; } // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) { int iter = 0; do { iter = iter + 1; // (Could check iteration count here.) // Compute implicit shift double g = d[l]; double p = (d[l+1] - g) / (2.0 * e[l]); double r = Maths.hypot(p,1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l+1] = e[l] * (p + r); double dl1 = d[l+1]; double h = g - d[l]; for (int i = l+2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; double el1 = e[l+1]; double s = 0.0; double s2 = 0.0; for (int i = m-1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Maths.hypot(p,e[i]); e[i+1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i+1] = h + s * (c * g + s * d[i]); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V[k][i+1]; V[k][i+1] = s * V[k][i] + c * h; V[k][i] = c * V[k][i] - s * h; } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.abs(e[l]) > eps*tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < n-1; i++) { int k = i; double p = d[i]; for (int j = i+1; j < n; j++) { if (d[j] < p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V[j][i]; V[j][i] = V[j][k]; V[j][k] = p; } } } }
d2cc762f-1eac-48c0-8384-a75daf688a8c
private void orthes () { // This is derived from the Algol procedures orthes and ortran, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutines in EISPACK. int low = 0; int high = n-1; for (int m = low+1; m <= high-1; m++) { // Scale column. double scale = 0.0; for (int i = m; i <= high; i++) { scale = scale + Math.abs(H[i][m-1]); } if (scale != 0.0) { // Compute Householder transformation. double h = 0.0; for (int i = high; i >= m; i--) { ort[i] = H[i][m-1]/scale; h += ort[i] * ort[i]; } double g = Math.sqrt(h); if (ort[m] > 0) { g = -g; } h = h - ort[m] * g; ort[m] = ort[m] - g; // Apply Householder similarity transformation // H = (I-u*u'/h)*H*(I-u*u')/h) for (int j = m; j < n; j++) { double f = 0.0; for (int i = high; i >= m; i--) { f += ort[i]*H[i][j]; } f = f/h; for (int i = m; i <= high; i++) { H[i][j] -= f*ort[i]; } } for (int i = 0; i <= high; i++) { double f = 0.0; for (int j = high; j >= m; j--) { f += ort[j]*H[i][j]; } f = f/h; for (int j = m; j <= high; j++) { H[i][j] -= f*ort[j]; } } ort[m] = scale*ort[m]; H[m][m-1] = scale*g; } } // Accumulate transformations (Algol's ortran). for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = (i == j ? 1.0 : 0.0); } } for (int m = high-1; m >= low+1; m--) { if (H[m][m-1] != 0.0) { for (int i = m+1; i <= high; i++) { ort[i] = H[i][m-1]; } for (int j = m; j <= high; j++) { double g = 0.0; for (int i = m; i <= high; i++) { g += ort[i] * V[i][j]; } // Double division avoids possible underflow g = (g / ort[m]) / H[m][m-1]; for (int i = m; i <= high; i++) { V[i][j] += g * ort[i]; } } } } }
24418583-9faf-4cfe-b49f-a74042c1f029
private void cdiv(double xr, double xi, double yr, double yi) { double r,d; if (Math.abs(yr) > Math.abs(yi)) { r = yi/yr; d = yr + r*yi; cdivr = (xr + r*xi)/d; cdivi = (xi - r*xr)/d; } else { r = yr/yi; d = yi + r*yr; cdivr = (r*xr + xi)/d; cdivi = (r*xi - xr)/d; } }
8ed29a83-f691-4705-b37d-df65d8b90f8c
private void hqr2 () { // This is derived from the Algol procedure hqr2, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. // Initialize int nn = this.n; int n = nn-1; int low = 0; int high = nn-1; double eps = Math.pow(2.0,-52.0); double exshift = 0.0; double p=0,q=0,r=0,s=0,z=0,t,w,x,y; // Store roots isolated by balanc and compute matrix norm double norm = 0.0; for (int i = 0; i < nn; i++) { if (i < low | i > high) { d[i] = H[i][i]; e[i] = 0.0; } for (int j = Math.max(i-1,0); j < nn; j++) { norm = norm + Math.abs(H[i][j]); } } // Outer loop over eigenvalue index int iter = 0; while (n >= low) { // Look for single small sub-diagonal element int l = n; while (l > low) { s = Math.abs(H[l-1][l-1]) + Math.abs(H[l][l]); if (s == 0.0) { s = norm; } if (Math.abs(H[l][l-1]) < eps * s) { break; } l--; } // Check for convergence // One root found if (l == n) { H[n][n] = H[n][n] + exshift; d[n] = H[n][n]; e[n] = 0.0; n--; iter = 0; // Two roots found } else if (l == n-1) { w = H[n][n-1] * H[n-1][n]; p = (H[n-1][n-1] - H[n][n]) / 2.0; q = p * p + w; z = Math.sqrt(Math.abs(q)); H[n][n] = H[n][n] + exshift; H[n-1][n-1] = H[n-1][n-1] + exshift; x = H[n][n]; // Real pair if (q >= 0) { if (p >= 0) { z = p + z; } else { z = p - z; } d[n-1] = x + z; d[n] = d[n-1]; if (z != 0.0) { d[n] = x - w / z; } e[n-1] = 0.0; e[n] = 0.0; x = H[n][n-1]; s = Math.abs(x) + Math.abs(z); p = x / s; q = z / s; r = Math.sqrt(p * p+q * q); p = p / r; q = q / r; // Row modification for (int j = n-1; j < nn; j++) { z = H[n-1][j]; H[n-1][j] = q * z + p * H[n][j]; H[n][j] = q * H[n][j] - p * z; } // Column modification for (int i = 0; i <= n; i++) { z = H[i][n-1]; H[i][n-1] = q * z + p * H[i][n]; H[i][n] = q * H[i][n] - p * z; } // Accumulate transformations for (int i = low; i <= high; i++) { z = V[i][n-1]; V[i][n-1] = q * z + p * V[i][n]; V[i][n] = q * V[i][n] - p * z; } // Complex pair } else { d[n-1] = x + p; d[n] = x + p; e[n-1] = z; e[n] = -z; } n = n - 2; iter = 0; // No convergence yet } else { // Form shift x = H[n][n]; y = 0.0; w = 0.0; if (l < n) { y = H[n-1][n-1]; w = H[n][n-1] * H[n-1][n]; } // Wilkinson's original ad hoc shift if (iter == 10) { exshift += x; for (int i = low; i <= n; i++) { H[i][i] -= x; } s = Math.abs(H[n][n-1]) + Math.abs(H[n-1][n-2]); x = y = 0.75 * s; w = -0.4375 * s * s; } // MATLAB's new ad hoc shift if (iter == 30) { s = (y - x) / 2.0; s = s * s + w; if (s > 0) { s = Math.sqrt(s); if (y < x) { s = -s; } s = x - w / ((y - x) / 2.0 + s); for (int i = low; i <= n; i++) { H[i][i] -= s; } exshift += s; x = y = w = 0.964; } } iter = iter + 1; // (Could check iteration count here.) // Look for two consecutive small sub-diagonal elements int m = n-2; while (m >= l) { z = H[m][m]; r = x - z; s = y - z; p = (r * s - w) / H[m+1][m] + H[m][m+1]; q = H[m+1][m+1] - z - r - s; r = H[m+2][m+1]; s = Math.abs(p) + Math.abs(q) + Math.abs(r); p = p / s; q = q / s; r = r / s; if (m == l) { break; } if (Math.abs(H[m][m-1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m-1][m-1]) + Math.abs(z) + Math.abs(H[m+1][m+1])))) { break; } m--; } for (int i = m+2; i <= n; i++) { H[i][i-2] = 0.0; if (i > m+2) { H[i][i-3] = 0.0; } } // Double QR step involving rows l:n and columns m:n for (int k = m; k <= n-1; k++) { boolean notlast = (k != n-1); if (k != m) { p = H[k][k-1]; q = H[k+1][k-1]; r = (notlast ? H[k+2][k-1] : 0.0); x = Math.abs(p) + Math.abs(q) + Math.abs(r); if (x != 0.0) { p = p / x; q = q / x; r = r / x; } } if (x == 0.0) { break; } s = Math.sqrt(p * p + q * q + r * r); if (p < 0) { s = -s; } if (s != 0) { if (k != m) { H[k][k-1] = -s * x; } else if (l != m) { H[k][k-1] = -H[k][k-1]; } p = p + s; x = p / s; y = q / s; z = r / s; q = q / p; r = r / p; // Row modification for (int j = k; j < nn; j++) { p = H[k][j] + q * H[k+1][j]; if (notlast) { p = p + r * H[k+2][j]; H[k+2][j] = H[k+2][j] - p * z; } H[k][j] = H[k][j] - p * x; H[k+1][j] = H[k+1][j] - p * y; } // Column modification for (int i = 0; i <= Math.min(n,k+3); i++) { p = x * H[i][k] + y * H[i][k+1]; if (notlast) { p = p + z * H[i][k+2]; H[i][k+2] = H[i][k+2] - p * r; } H[i][k] = H[i][k] - p; H[i][k+1] = H[i][k+1] - p * q; } // Accumulate transformations for (int i = low; i <= high; i++) { p = x * V[i][k] + y * V[i][k+1]; if (notlast) { p = p + z * V[i][k+2]; V[i][k+2] = V[i][k+2] - p * r; } V[i][k] = V[i][k] - p; V[i][k+1] = V[i][k+1] - p * q; } } // (s != 0) } // k loop } // check convergence } // while (n >= low) // Backsubstitute to find vectors of upper triangular form if (norm == 0.0) { return; } for (n = nn-1; n >= 0; n--) { p = d[n]; q = e[n]; // Real vector if (q == 0) { int l = n; H[n][n] = 1.0; for (int i = n-1; i >= 0; i--) { w = H[i][i] - p; r = 0.0; for (int j = l; j <= n; j++) { r = r + H[i][j] * H[j][n]; } if (e[i] < 0.0) { z = w; s = r; } else { l = i; if (e[i] == 0.0) { if (w != 0.0) { H[i][n] = -r / w; } else { H[i][n] = -r / (eps * norm); } // Solve real equations } else { x = H[i][i+1]; y = H[i+1][i]; q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; t = (x * s - z * r) / q; H[i][n] = t; if (Math.abs(x) > Math.abs(z)) { H[i+1][n] = (-r - w * t) / x; } else { H[i+1][n] = (-s - y * t) / z; } } // Overflow control t = Math.abs(H[i][n]); if ((eps * t) * t > 1) { for (int j = i; j <= n; j++) { H[j][n] = H[j][n] / t; } } } } // Complex vector } else if (q < 0) { int l = n-1; // Last vector component imaginary so matrix is triangular if (Math.abs(H[n][n-1]) > Math.abs(H[n-1][n])) { H[n-1][n-1] = q / H[n][n-1]; H[n-1][n] = -(H[n][n] - p) / H[n][n-1]; } else { cdiv(0.0,-H[n-1][n],H[n-1][n-1]-p,q); H[n-1][n-1] = cdivr; H[n-1][n] = cdivi; } H[n][n-1] = 0.0; H[n][n] = 1.0; for (int i = n-2; i >= 0; i--) { double ra,sa,vr,vi; ra = 0.0; sa = 0.0; for (int j = l; j <= n; j++) { ra = ra + H[i][j] * H[j][n-1]; sa = sa + H[i][j] * H[j][n]; } w = H[i][i] - p; if (e[i] < 0.0) { z = w; r = ra; s = sa; } else { l = i; if (e[i] == 0) { cdiv(-ra,-sa,w,q); H[i][n-1] = cdivr; H[i][n] = cdivi; } else { // Solve complex equations x = H[i][i+1]; y = H[i+1][i]; vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; vi = (d[i] - p) * 2.0 * q; if (vr == 0.0 & vi == 0.0) { vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); } cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi); H[i][n-1] = cdivr; H[i][n] = cdivi; if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { H[i+1][n-1] = (-ra - w * H[i][n-1] + q * H[i][n]) / x; H[i+1][n] = (-sa - w * H[i][n] - q * H[i][n-1]) / x; } else { cdiv(-r-y*H[i][n-1],-s-y*H[i][n],z,q); H[i+1][n-1] = cdivr; H[i+1][n] = cdivi; } } // Overflow control t = Math.max(Math.abs(H[i][n-1]),Math.abs(H[i][n])); if ((eps * t) * t > 1) { for (int j = i; j <= n; j++) { H[j][n-1] = H[j][n-1] / t; H[j][n] = H[j][n] / t; } } } } } } // Vectors of isolated roots for (int i = 0; i < nn; i++) { if (i < low | i > high) { for (int j = i; j < nn; j++) { V[i][j] = H[i][j]; } } } // Back transformation to get eigenvectors of original matrix for (int j = nn-1; j >= low; j--) { for (int i = low; i <= high; i++) { z = 0.0; for (int k = low; k <= Math.min(j,high); k++) { z = z + V[i][k] * H[k][j]; } V[i][j] = z; } } }
ae53e0e9-3910-4ea1-836d-467e4b367fc5
public EigenvalueDecomposition (Matrix Arg) { double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); V = new double[n][n]; d = new double[n]; e = new double[n]; issymmetric = true; for (int j = 0; (j < n) & issymmetric; j++) { for (int i = 0; (i < n) & issymmetric; i++) { issymmetric = (A[i][j] == A[j][i]); } } if (issymmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = A[i][j]; } } // Tridiagonalize. tred2(); // Diagonalize. tql2(); } else { H = new double[n][n]; ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i][j] = A[i][j]; } } // Reduce to Hessenberg form. orthes(); // Reduce Hessenberg to real Schur form. hqr2(); } }
95bcc4ec-e658-4702-bb12-113f42d5290a
public Matrix getV () { return new Matrix(V,n,n); }
9e15abaf-d478-4e58-ab53-a8fed77d5714
public double[] getRealEigenvalues () { return d; }
7a459517-02fd-4d35-b69f-4070d44971ee
public double[] getImagEigenvalues () { return e; }
783986b8-d1dd-4d16-ad6c-53ab249be07e
public Matrix getD () { Matrix X = new Matrix(n,n); double[][] D = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { D[i][j] = 0.0; } D[i][i] = d[i]; if (e[i] > 0) { D[i][i+1] = e[i]; } else if (e[i] < 0) { D[i][i-1] = e[i]; } } return X; }
9e1fe2c6-7389-4658-b58a-0cb66310ec7b
public LUDecomposition (Matrix A) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. LU = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; double[] LUrowi; double[] LUcolj = new double[m]; // Outer loop. for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. for (int i = 0; i < m; i++) { LUcolj[i] = LU[i][j]; } // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = LU[i]; // Most of the time is spent in the following dot product. int kmax = Math.min(i,j); double s = 0.0; for (int k = 0; k < kmax; k++) { s += LUrowi[k]*LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. int p = j; for (int i = j+1; i < m; i++) { if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; } int k = piv[p]; piv[p] = piv[j]; piv[j] = k; pivsign = -pivsign; } // Compute multipliers. if (j < m & LU[j][j] != 0.0) { for (int i = j+1; i < m; i++) { LU[i][j] /= LU[j][j]; } } } }
a77aa531-4fb6-40a0-83c7-52f25bc25106
public boolean isNonsingular () { for (int j = 0; j < n; j++) { if (LU[j][j] == 0) return false; } return true; }
3983d676-00a3-4ff9-8fc6-2dc387faa48b
public Matrix getL () { Matrix X = new Matrix(m,n); double[][] L = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { L[i][j] = LU[i][j]; } else if (i == j) { L[i][j] = 1.0; } else { L[i][j] = 0.0; } } } return X; }
434564fc-2a3a-48e8-85df-5d0ab6422a42
public Matrix getU () { Matrix X = new Matrix(n,n); double[][] U = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i <= j) { U[i][j] = LU[i][j]; } else { U[i][j] = 0.0; } } } return X; }
16c2ab45-6cf3-4927-824c-f552c4013b2f
public int[] getPivot () { int[] p = new int[m]; for (int i = 0; i < m; i++) { p[i] = piv[i]; } return p; }
0716eac4-4749-4638-968e-7e37ec63d0ca
public double[] getDoublePivot () { double[] vals = new double[m]; for (int i = 0; i < m; i++) { vals[i] = (double) piv[i]; } return vals; }
e4fb89b8-cefd-4d75-98a0-2b3c985a5ef7
public double det () { if (m != n) { throw new IllegalArgumentException("Matrix must be square."); } double d = (double) pivsign; for (int j = 0; j < n; j++) { d *= LU[j][j]; } return d; }
c0679dc9-9d68-4334-8e04-3ca1f33a4129
public Matrix solve (Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isNonsingular()) { throw new RuntimeException("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.getColumnDimension(); Matrix Xmat = B.getMatrix(piv,0,nx-1); double[][] X = Xmat.getArray(); // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k+1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return Xmat; }
972522eb-f30f-4b3e-a5af-80b3b498f1be
public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b/a; r = Math.abs(a)*Math.sqrt(1+r*r); } else if (b != 0) { r = a/b; r = Math.abs(b)*Math.sqrt(1+r*r); } else { r = 0.0; } return r; }
4c7e796d-b2f3-4474-beaf-903507fe2e8f
public SingularValueDecomposition (Matrix Arg) { // Derived from LINPACK code. // Initialize. double[][] A = Arg.getArrayCopy(); m = Arg.getRowDimension(); n = Arg.getColumnDimension(); /* Apparently the failing cases are only a proper subset of (m<n), so let's not throw error. Correct fix to come later? if (m<n) { throw new IllegalArgumentException("Jama SVD only works for m >= n"); } */ int nu = Math.min(m,n); s = new double [Math.min(m+1,n)]; U = new double [m][nu]; V = new double [n][n]; double[] e = new double [n]; double[] work = new double [m]; boolean wantu = true; boolean wantv = true; // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. int nct = Math.min(m-1,n); int nrt = Math.max(0,Math.min(n-2,m)); for (int k = 0; k < Math.max(nct,nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k],A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k+1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) { t += A[i][k]*A[i][j]; } t = -t/A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t*A[i][k]; } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A[k][j]; } if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k+1; i < n; i++) { e[k] = Maths.hypot(e[k],e[i]); } if (e[k] != 0.0) { if (e[k+1] < 0.0) { e[k] = -e[k]; } for (int i = k+1; i < n; i++) { e[i] /= e[k]; } e[k+1] += 1.0; } e[k] = -e[k]; if ((k+1 < m) & (e[k] != 0.0)) { // Apply the transformation. for (int i = k+1; i < m; i++) { work[i] = 0.0; } for (int j = k+1; j < n; j++) { for (int i = k+1; i < m; i++) { work[i] += e[j]*A[i][j]; } } for (int j = k+1; j < n; j++) { double t = -e[j]/e[k+1]; for (int i = k+1; i < m; i++) { A[i][j] += t*work[i]; } } } if (wantv) { // Place the transformation in V for subsequent // back multiplication. for (int i = k+1; i < n; i++) { V[i][k] = e[i]; } } } } // Set up the final bidiagonal matrix or order p. int p = Math.min(n,m+1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p-1] = 0.0; } if (nrt+1 < p) { e[nrt] = A[nrt][p-1]; } e[p-1] = 0.0; // If required, generate U. if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct-1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k]*U[i][j]; } t = -t/U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t*U[i][k]; } } for (int i = k; i < m; i++ ) { U[i][k] = -U[i][k]; } U[k][k] = 1.0 + U[k][k]; for (int i = 0; i < k-1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } // If required, generate V. if (wantv) { for (int k = n-1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k+1; i < n; i++) { t += V[i][k]*V[i][j]; } t = -t/V[k+1][k]; for (int i = k+1; i < n; i++) { V[i][j] += t*V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } // Main iteration loop for the singular values. int pp = p-1; int iter = 0; double eps = Math.pow(2.0,-52.0); double tiny = Math.pow(2.0,-966.0); while (p > 0) { int k,kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p-2; k >= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) { e[k] = 0.0; break; } } if (k == p-2) { kase = 4; } else { int ks; for (ks = p-1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k+1 ? Math.abs(e[ks-1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps*t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p-1) { kase = 1; } else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p-2]; e[p-2] = 0.0; for (int j = p-2; j >= k; j--) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; if (j != k) { f = -sn*e[j-1]; e[j-1] = cs*e[j-1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][p-1]; V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1]; V[i][j] = t; } } } } break; // Split at negligible s(k). case 2: { double f = e[k-1]; e[k-1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; f = -sn*e[j]; e[j] = cs*e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][k-1]; U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1]; U[i][j] = t; } } } } break; // Perform one qr step. case 3: { // Calculate the shift. double scale = Math.max(Math.max(Math.max(Math.max( Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])), Math.abs(s[k])),Math.abs(e[k])); double sp = s[p-1]/scale; double spm1 = s[p-2]/scale; double epm1 = e[p-2]/scale; double sk = s[k]/scale; double ek = e[k]/scale; double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; double c = (sp*epm1)*(sp*epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b*b + c); if (b < 0.0) { shift = -shift; } shift = c/(b + shift); } double f = (sk + sp)*(sk - sp) + shift; double g = sk*ek; // Chase zeros. for (int j = k; j < p-1; j++) { double t = Maths.hypot(f,g); double cs = f/t; double sn = g/t; if (j != k) { e[j-1] = t; } f = cs*s[j] + sn*e[j]; e[j] = cs*e[j] - sn*s[j]; g = sn*s[j+1]; s[j+1] = cs*s[j+1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][j+1]; V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1]; V[i][j] = t; } } t = Maths.hypot(f,g); cs = f/t; sn = g/t; s[j] = t; f = cs*e[j] + sn*s[j+1]; s[j+1] = -sn*e[j] + cs*s[j+1]; g = sn*e[j+1]; e[j+1] = cs*e[j+1]; if (wantu && (j < m-1)) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][j+1]; U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1]; U[i][j] = t; } } } e[p-2] = f; iter = iter + 1; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } } // Order the singular values. while (k < pp) { if (s[k] >= s[k+1]) { break; } double t = s[k]; s[k] = s[k+1]; s[k+1] = t; if (wantv && (k < n-1)) { for (int i = 0; i < n; i++) { t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m-1)) { for (int i = 0; i < m; i++) { t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } }
ee50e98d-e8d5-48f0-9461-ea3d2ae7f83d
public Matrix getU () { return new Matrix(U,m,Math.min(m+1,n)); }
52fd3690-e267-4435-9abe-3797e7ca9135
public Matrix getV () { return new Matrix(V,n,n); }
243ac612-8e90-47cf-ba17-b04877041123
public double[] getSingularValues () { return s; }
97968674-e7f6-4d7a-8ac9-16945eea8d33
public Matrix getS () { Matrix X = new Matrix(n,n); double[][] S = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { S[i][j] = 0.0; } S[i][i] = this.s[i]; } return X; }
e4c337b3-9c81-4730-b6f3-26b218f3345a
public double norm2 () { return s[0]; }
8673de25-7522-4230-9c8f-d4a02eb99eac
public double cond () { return s[0]/s[Math.min(m,n)-1]; }
af12e3f1-71e5-402c-bc1c-c709389d6ee1
public int rank () { double eps = Math.pow(2.0,-52.0); double tol = Math.max(m,n)*s[0]*eps; int r = 0; for (int i = 0; i < s.length; i++) { if (s[i] > tol) { r++; } } return r; }
1072d7dd-da80-4220-a8cc-6f87c34c252f
public Matrix (int m, int n) { this.m = m; this.n = n; A = new double[m][n]; }
e0ca8768-c967-4e1f-b303-70b9393c6701
public Matrix (int m, int n, double s) { this.m = m; this.n = n; A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = s; } } }
d2b7337e-c20b-4a95-8fb6-ad68296b3036
public Matrix (double[][] A) { m = A.length; n = A[0].length; for (int i = 0; i < m; i++) { if (A[i].length != n) { throw new IllegalArgumentException("All rows must have the same length."); } } this.A = A; }
968ffc8d-beb9-4a4f-9c55-791516e970f7
public Matrix (double[][] A, int m, int n) { this.A = A; this.m = m; this.n = n; }
c06f15c2-d0f6-43f5-87d1-b7e9836e9ce4
public Matrix (double vals[], int m) { this.m = m; n = (m != 0 ? vals.length/m : 0); if (m*n != vals.length) { throw new IllegalArgumentException("Array length must be a multiple of m."); } A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = vals[i+j*m]; } } }
0b0ca987-6997-4a1b-a344-da35440d4145
public static Matrix constructWithCopy(double[][] A) { int m = A.length; int n = A[0].length; Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { if (A[i].length != n) { throw new IllegalArgumentException ("All rows must have the same length."); } for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return X; }