repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/BluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger;
} /** * Get the current active ble scan time that has been set * * @VisibleForTesting */ int getScanActiveMillis() { return (overrideScanActiveMillis != -1) ? overrideScanActiveMillis : scanActiveMillis; } /** * Get the current idle ble scan time that has been set * * @VisibleForTesting */ int getScanIdleMillis() { return (overrideScanActiveMillis != -1) ? overrideScanIdleMillis : scanIdleMillis; } /** * Update the repeating alarm wake-up based on the period defined for the scanner If there are * no clients, or a batch scan running, it will cancel the alarm. */ protected void updateRepeatingAlarm() { // Apply Scan Mode (Cycle Parameters) setScanMode(getMaxPriorityScanMode()); if (!hasClients()) { // No listeners. Remove the repeating alarm, if there is one. getAlarmManager().cancel(getAlarmIntent());
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/BluetoothLeScannerCompat.java import java.util.ArrayList; import java.util.Collection; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; } /** * Get the current active ble scan time that has been set * * @VisibleForTesting */ int getScanActiveMillis() { return (overrideScanActiveMillis != -1) ? overrideScanActiveMillis : scanActiveMillis; } /** * Get the current idle ble scan time that has been set * * @VisibleForTesting */ int getScanIdleMillis() { return (overrideScanActiveMillis != -1) ? overrideScanIdleMillis : scanIdleMillis; } /** * Update the repeating alarm wake-up based on the period defined for the scanner If there are * no clients, or a batch scan running, it will cancel the alarm. */ protected void updateRepeatingAlarm() { // Apply Scan Mode (Cycle Parameters) setScanMode(getMaxPriorityScanMode()); if (!hasClients()) { // No listeners. Remove the repeating alarm, if there is one. getAlarmManager().cancel(getAlarmIntent());
Logger.logInfo("Scan : No clients left, canceling alarm.");
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/NoBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.reelyactive.blesdk.support.ble; /** * Created by saiimons on 16-03-17. */ public class NoBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<ScanCallback, ScanSettings> callbacksMap = new ConcurrentHashMap<>(); public NoBluetoothLeScannerCompat(Context context, AlarmManager alarmManager) { super(
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/NoBluetoothLeScannerCompat.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.reelyactive.blesdk.support.ble; /** * Created by saiimons on 16-03-17. */ public class NoBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<ScanCallback, ScanSettings> callbacksMap = new ConcurrentHashMap<>(); public NoBluetoothLeScannerCompat(Context context, AlarmManager alarmManager) { super(
new SystemClock(),
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/NoBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.reelyactive.blesdk.support.ble; /** * Created by saiimons on 16-03-17. */ public class NoBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<ScanCallback, ScanSettings> callbacksMap = new ConcurrentHashMap<>(); public NoBluetoothLeScannerCompat(Context context, AlarmManager alarmManager) { super( new SystemClock(), alarmManager, PendingIntent.getBroadcast( context, 0, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0) ); } @Override public boolean startScan(List<ScanFilter> filters, ScanSettings settings, ScanCallback callback) { if (callback != null) { try { callbacksMap.put(callback, settings); updateRepeatingAlarm(); return true; } catch (Exception e) {
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/NoBluetoothLeScannerCompat.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.reelyactive.blesdk.support.ble; /** * Created by saiimons on 16-03-17. */ public class NoBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<ScanCallback, ScanSettings> callbacksMap = new ConcurrentHashMap<>(); public NoBluetoothLeScannerCompat(Context context, AlarmManager alarmManager) { super( new SystemClock(), alarmManager, PendingIntent.getBroadcast( context, 0, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0) ); } @Override public boolean startScan(List<ScanFilter> filters, ScanSettings settings, ScanCallback callback) { if (callback != null) { try { callbacksMap.put(callback, settings); updateRepeatingAlarm(); return true; } catch (Exception e) {
Logger.logError(e.getMessage(), e);
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/ScanWakefulService.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // }
import android.app.IntentService; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger;
package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The com.reelyactive.blesdk.support.ble.ScanWakefulService Class is called with a WakeLock held, and executes a single Bluetooth LE * scan cycle. It then calls the {@link ScanWakefulBroadcastReceiver#completeWakefulIntent} with the * same intent to release the associated WakeLock. */ public class ScanWakefulService extends IntentService { public static final String EXTRA_USE_LOLLIPOP_API = "use_lollipop"; public ScanWakefulService() { super("com.reelyactive.blesdk.support.ble.ScanWakefulService"); } @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } // This method runs in a worker thread. // At this point com.reelyactive.blesdk.support.ble.ScanWakefulBroadcastReceiver is still holding a WakeLock. // We can do whatever we need to do in the code below. // After the call to completeWakefulIntent the WakeLock is released.
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanWakefulService.java import android.app.IntentService; import android.content.Intent; import com.reelyactive.blesdk.support.ble.util.Logger; package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The com.reelyactive.blesdk.support.ble.ScanWakefulService Class is called with a WakeLock held, and executes a single Bluetooth LE * scan cycle. It then calls the {@link ScanWakefulBroadcastReceiver#completeWakefulIntent} with the * same intent to release the associated WakeLock. */ public class ScanWakefulService extends IntentService { public static final String EXTRA_USE_LOLLIPOP_API = "use_lollipop"; public ScanWakefulService() { super("com.reelyactive.blesdk.support.ble.ScanWakefulService"); } @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } // This method runs in a worker thread. // At this point com.reelyactive.blesdk.support.ble.ScanWakefulBroadcastReceiver is still holding a WakeLock. // We can do whatever we need to do in the code below. // After the call to completeWakefulIntent the WakeLock is released.
Logger.logDebug("Running scancycle");
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareActivity.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // }
import com.reelyactive.blesdk.support.ble.ScanResult;
package com.reelyactive.blesdk.application; /** * Implement this interface if you want your current activity to be notified when Reelceiver are detected. */ public interface ReelyAwareActivity { public void onScanStarted(); public void onScanStopped();
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // } // Path: library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareActivity.java import com.reelyactive.blesdk.support.ble.ScanResult; package com.reelyactive.blesdk.application; /** * Implement this interface if you want your current activity to be notified when Reelceiver are detected. */ public interface ReelyAwareActivity { public void onScanStarted(); public void onScanStopped();
public void onEnterRegion(ScanResult beacon);
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} and later. * <p> * This class delivers a callback on found, updated, and lost for devices matching a * {@link ScanFilter} filter during scan cycles. * <p> * A scan cycle comprises a period when the Bluetooth Adapter is active and a period when the * Bluetooth adapter is idle. Having an idle period is energy efficient for long lived scans. * <p> * This class can be accessed on multiple threads: * <ul> * <li> main thread (user) can call any of the BluetoothLeScanner APIs * <li> IntentService worker thread can call {@link #onNewScanCycle()} * <li> AIDL binder thread can call {@link #leScanCallback.onLeScan()} * </ul> * * @see <a href="http://go/ble-glossary">BLE Glossary</a> */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class JbBluetoothLeScannerCompat extends BluetoothLeScannerCompat { // Map of BD_ADDR->com.reelyactive.blesdk.support.ble.ScanResult for replay to new registrations. // Entries are evicted after SCAN_LOST_CYCLES cycles. /* @VisibleForTesting */ final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); /* @VisibleForTesting */ final Map<ScanCallback, ScanClient> serialClients = new ConcurrentHashMap<>(); private final BluetoothAdapter bluetoothAdapter; private BluetoothCrashResolver crashResolver; private Handler mainHandler; /** * The Bluetooth LE callback which will be registered with the OS, * to be fired on device discovery. */ private final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { /** * Callback method called from the OS on each BLE device sighting. * This method is invoked on the AIDL handler thread, so all methods * called here must be synchronized. * * @param device The device discovered * @param rssi The signal strength in dBm it was received at * @param scanRecordBytes The raw byte payload buffer */ @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecordBytes) { long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) {
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} and later. * <p> * This class delivers a callback on found, updated, and lost for devices matching a * {@link ScanFilter} filter during scan cycles. * <p> * A scan cycle comprises a period when the Bluetooth Adapter is active and a period when the * Bluetooth adapter is idle. Having an idle period is energy efficient for long lived scans. * <p> * This class can be accessed on multiple threads: * <ul> * <li> main thread (user) can call any of the BluetoothLeScanner APIs * <li> IntentService worker thread can call {@link #onNewScanCycle()} * <li> AIDL binder thread can call {@link #leScanCallback.onLeScan()} * </ul> * * @see <a href="http://go/ble-glossary">BLE Glossary</a> */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class JbBluetoothLeScannerCompat extends BluetoothLeScannerCompat { // Map of BD_ADDR->com.reelyactive.blesdk.support.ble.ScanResult for replay to new registrations. // Entries are evicted after SCAN_LOST_CYCLES cycles. /* @VisibleForTesting */ final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); /* @VisibleForTesting */ final Map<ScanCallback, ScanClient> serialClients = new ConcurrentHashMap<>(); private final BluetoothAdapter bluetoothAdapter; private BluetoothCrashResolver crashResolver; private Handler mainHandler; /** * The Bluetooth LE callback which will be registered with the OS, * to be fired on device discovery. */ private final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { /** * Callback method called from the OS on each BLE device sighting. * This method is invoked on the AIDL handler thread, so all methods * called here must be synchronized. * * @param device The device discovered * @param rssi The signal strength in dBm it was received at * @param scanRecordBytes The raw byte payload buffer */ @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecordBytes) { long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) {
this(manager, alarmManager, new SystemClock(),
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
@Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecordBytes) { long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) { this(manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast(context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0 /* flags */)); this.crashResolver = new BluetoothCrashResolver(context); this.crashResolver.start(); this.mainHandler = new Handler(Looper.getMainLooper()); } /** * Testing constructor for the scanner. * * @VisibleForTesting */ JbBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager,
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecordBytes) { long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) { this(manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast(context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0 /* flags */)); this.crashResolver = new BluetoothCrashResolver(context); this.crashResolver.start(); this.mainHandler = new Handler(Looper.getMainLooper()); } /** * Testing constructor for the scanner. * * @VisibleForTesting */ JbBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager,
Clock clock, PendingIntent alarmIntent) {
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) { this(manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast(context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0 /* flags */)); this.crashResolver = new BluetoothCrashResolver(context); this.crashResolver.start(); this.mainHandler = new Handler(Looper.getMainLooper()); } /** * Testing constructor for the scanner. * * @VisibleForTesting */ JbBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager, Clock clock, PendingIntent alarmIntent) { super(clock, alarmManager, alarmIntent);
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/JbBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; long currentTimeInNanos = TimeUnit.MILLISECONDS.toNanos(getClock().currentTimeMillis()); ScanResult result = new ScanResult(device, ScanRecord.parseFromBytes(scanRecordBytes), rssi, currentTimeInNanos); onScanResult(device.getAddress(), result); if (crashResolver != null) crashResolver.notifyScannedDevice(device, this); } }; /** * Package constructor, called from {@link BluetoothLeScannerCompatProvider}. */ JbBluetoothLeScannerCompat( Context context, BluetoothManager manager, AlarmManager alarmManager) { this(manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast(context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, false), 0 /* flags */)); this.crashResolver = new BluetoothCrashResolver(context); this.crashResolver.start(); this.mainHandler = new Handler(Looper.getMainLooper()); } /** * Testing constructor for the scanner. * * @VisibleForTesting */ JbBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager, Clock clock, PendingIntent alarmIntent) { super(clock, alarmManager, alarmIntent);
Logger.logDebug("BLE 'JB' hardware access layer activated");
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/advertise/LBleAdvertiser.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // }
import android.annotation.TargetApi; import android.bluetooth.BluetoothManager; import android.bluetooth.le.AdvertiseCallback; import android.bluetooth.le.AdvertiseData; import android.bluetooth.le.AdvertiseSettings; import android.bluetooth.le.BluetoothLeAdvertiser; import android.content.Context; import android.os.Build; import android.os.ParcelUuid; import com.reelyactive.blesdk.support.ble.ScanResult; import java.util.List;
package com.reelyactive.blesdk.advertise; /** * Created by saiimons on 15-03-09. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class LBleAdvertiser extends BleAdvertiser { private final BluetoothLeAdvertiser advertiser; private final Context context; private final AdvertiseCallback callback = new AdvertiseCallback() { @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { super.onStartSuccess(settingsInEffect); } @Override public void onStartFailure(int errorCode) { super.onStartFailure(errorCode); } }; public LBleAdvertiser(Context context, BluetoothManager manager) { this.advertiser = manager.getAdapter().getBluetoothLeAdvertiser(); this.context = context; } @Override
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // } // Path: library/src/main/java/com/reelyactive/blesdk/advertise/LBleAdvertiser.java import android.annotation.TargetApi; import android.bluetooth.BluetoothManager; import android.bluetooth.le.AdvertiseCallback; import android.bluetooth.le.AdvertiseData; import android.bluetooth.le.AdvertiseSettings; import android.bluetooth.le.BluetoothLeAdvertiser; import android.content.Context; import android.os.Build; import android.os.ParcelUuid; import com.reelyactive.blesdk.support.ble.ScanResult; import java.util.List; package com.reelyactive.blesdk.advertise; /** * Created by saiimons on 15-03-09. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class LBleAdvertiser extends BleAdvertiser { private final BluetoothLeAdvertiser advertiser; private final Context context; private final AdvertiseCallback callback = new AdvertiseCallback() { @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { super.onStartSuccess(settingsInEffect); } @Override public void onStartFailure(int errorCode) { super.onStartFailure(errorCode); } }; public LBleAdvertiser(Context context, BluetoothManager manager) { this.advertiser = manager.getAdapter().getBluetoothLeAdvertiser(); this.context = context; } @Override
public void startAdvertising(String uuid, List<ScanResult> closestBeaconId, String fallbackUrl) {
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager,
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager,
new SystemClock(),
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast( context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, true), 0 /* flags */ ) ); } LBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager,
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast( context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, true), 0 /* flags */ ) ); } LBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager,
Clock clock, PendingIntent alarmIntent) {
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // }
import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit;
package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast( context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, true), 0 /* flags */ ) ); } LBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager, Clock clock, PendingIntent alarmIntent) { super(clock, alarmManager, alarmIntent);
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Clock.java // public interface Clock { // // /** // * @return current time in milliseconds // */ // public long currentTimeMillis(); // // /** // * @return time since the device was booted, in nanoseconds // */ // public long elapsedRealtimeNanos(); // // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/SystemClock.java // public class SystemClock implements Clock { // // /** // * @return current time in milliseconds // */ // @Override // public long currentTimeMillis() { // return System.currentTimeMillis(); // } // // /** // * @return time since the device was booted, in nanoseconds // */ // @Override // @TargetApi(VERSION_CODES.JELLY_BEAN_MR1) // public long elapsedRealtimeNanos() { // return android.os.SystemClock.elapsedRealtimeNanos(); // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.reelyactive.blesdk.support.ble.util.Clock; import com.reelyactive.blesdk.support.ble.util.Logger; import com.reelyactive.blesdk.support.ble.util.SystemClock; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; package com.reelyactive.blesdk.support.ble; /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP} * and later. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat { private final Map<String, ScanResult> recentScanResults = new ConcurrentHashMap<>(); private final Map<ScanCallback, ScanClient> callbacksMap = new ConcurrentHashMap<>(); private final android.bluetooth.le.BluetoothLeScanner osScanner; /** * Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}. * <p> * Cannot be called from emulated devices that don't implement a BluetoothAdapter. */ LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) { this( manager, alarmManager, new SystemClock(), PendingIntent.getBroadcast( context, 0 /* requestCode */, new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, true), 0 /* flags */ ) ); } LBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager, Clock clock, PendingIntent alarmIntent) { super(clock, alarmManager, alarmIntent);
Logger.logDebug("BLE 'L' hardware access layer activated");
reelyactive/ble-android-sdk
example_app/src/main/java/com/reelyactive/blescanner/BleScanResultAdapter.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.reelyactive.blesdk.support.ble.ScanResult; import java.util.HashMap;
package com.reelyactive.blescanner; public class BleScanResultAdapter extends BaseAdapter { private final Context mContext;
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // } // Path: example_app/src/main/java/com/reelyactive/blescanner/BleScanResultAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.reelyactive.blesdk.support.ble.ScanResult; import java.util.HashMap; package com.reelyactive.blescanner; public class BleScanResultAdapter extends BaseAdapter { private final Context mContext;
private HashMap<String, ScanResult> items;
reelyactive/ble-android-sdk
example_app/src/main/java/com/reelyactive/blescanner/ReelyAwareScanActivity.java
// Path: library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareActivity.java // public interface ReelyAwareActivity { // public void onScanStarted(); // // public void onScanStopped(); // // public void onEnterRegion(ScanResult beacon); // // public void onLeaveRegion(ScanResult beacon); // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // }
import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ListView; import com.reelyactive.blesdk.application.ReelyAwareActivity; import com.reelyactive.blesdk.support.ble.ScanResult;
Snackbar .make((View) list.getParent(), R.string.location_permission, Snackbar.LENGTH_INDEFINITE) .setAction( R.string.ok, new View.OnClickListener() { @Override public void onClick(View v) { ActivityCompat.requestPermissions(ReelyAwareScanActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); } } ).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); break; } } @Override public void onScanStarted() { } @Override public void onScanStopped() { } @Override
// Path: library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareActivity.java // public interface ReelyAwareActivity { // public void onScanStarted(); // // public void onScanStopped(); // // public void onEnterRegion(ScanResult beacon); // // public void onLeaveRegion(ScanResult beacon); // } // // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanResult.java // public final class ScanResult implements Parcelable { // // Remote bluetooth device. // private BluetoothDevice mDevice; // // // Scan record, including advertising data and scan response data. // @Nullable // private ScanRecord mScanRecord; // // // Received signal strength. // private int mRssi; // // // Device timestamp when the result was last seen. // private long mTimestampNanos; // // /** // * Constructor of scan result. // * // * @param device Remote bluetooth device that is found. // * @param scanRecord Scan record including both advertising data and scan response data. // * @param rssi Received signal strength. // * @param timestampNanos Device timestamp when the scan result was observed. // */ // public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi, // long timestampNanos) { // mDevice = device; // mScanRecord = scanRecord; // mRssi = rssi; // mTimestampNanos = timestampNanos; // } // // private ScanResult(Parcel in) { // readFromParcel(in); // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (mDevice != null) { // dest.writeInt(1); // mDevice.writeToParcel(dest, flags); // } else { // dest.writeInt(0); // } // if (mScanRecord != null) { // dest.writeInt(1); // dest.writeByteArray(mScanRecord.getBytes()); // } else { // dest.writeInt(0); // } // dest.writeInt(mRssi); // dest.writeLong(mTimestampNanos); // } // // private void readFromParcel(Parcel in) { // if (in.readInt() == 1) { // mDevice = BluetoothDevice.CREATOR.createFromParcel(in); // } // if (in.readInt() == 1) { // mScanRecord = ScanRecord.parseFromBytes(in.createByteArray()); // } // mRssi = in.readInt(); // mTimestampNanos = in.readLong(); // } // // @Override // public int describeContents() { // return 0; // } // // /** // * Returns the remote bluetooth device identified by the bluetooth device address. // */ // public BluetoothDevice getDevice() { // return mDevice; // } // // /** // * Returns the scan record, which is a combination of advertisement and scan response. // */ // @Nullable // public ScanRecord getScanRecord() { // return mScanRecord; // } // // /** // * Returns the received signal strength in dBm. The valid range is [-127, 127]. // */ // public int getRssi() { // return mRssi; // } // // /** // * Returns timestamp since boot when the scan record was observed. // */ // public long getTimestampNanos() { // return mTimestampNanos; // } // // @Override // public int hashCode() { // return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // ScanResult other = (ScanResult) obj; // return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi) // && Objects.equals(mScanRecord, other.mScanRecord) // && (mTimestampNanos == other.mTimestampNanos); // } // // @Override // public String toString() { // return "com.reelyactive.blesdk.support.ble.ScanResult{" + "mDevice=" + mDevice + ", mScanRecord=" // + Objects.toString(mScanRecord) + ", mRssi=" + mRssi + ", mTimestampNanos=" // + mTimestampNanos + '}'; // } // // /** // * @hide // */ // public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() { // @Override // public ScanResult createFromParcel(Parcel source) { // return new ScanResult(source); // } // // @Override // public ScanResult[] newArray(int size) { // return new ScanResult[size]; // } // }; // // } // Path: example_app/src/main/java/com/reelyactive/blescanner/ReelyAwareScanActivity.java import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ListView; import com.reelyactive.blesdk.application.ReelyAwareActivity; import com.reelyactive.blesdk.support.ble.ScanResult; Snackbar .make((View) list.getParent(), R.string.location_permission, Snackbar.LENGTH_INDEFINITE) .setAction( R.string.ok, new View.OnClickListener() { @Override public void onClick(View v) { ActivityCompat.requestPermissions(ReelyAwareScanActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION); } } ).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); break; } } @Override public void onScanStarted() { } @Override public void onScanStopped() { } @Override
public void onEnterRegion(ScanResult beacon) {
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/ScanRecord.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // }
import java.util.List; import java.util.Map; import android.os.ParcelUuid; import android.support.annotation.Nullable; import android.util.SparseArray; import com.reelyactive.blesdk.support.ble.util.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap;
byte[] serviceDataUuidBytes = extractBytes(scanRecord, currentPos, serviceUuidLength); ParcelUuid serviceDataUuid = BluetoothUuid.parseUuidFrom( serviceDataUuidBytes); byte[] serviceDataArray = extractBytes(scanRecord, currentPos + serviceUuidLength, dataLength - serviceUuidLength); serviceData.put(serviceDataUuid, serviceDataArray); break; case DATA_TYPE_MANUFACTURER_SPECIFIC_DATA: // The first two bytes of the manufacturer specific data are // manufacturer ids in little endian. int manufacturerId = ((scanRecord[currentPos + 1] & 0xFF) << 8) + (scanRecord[currentPos] & 0xFF); byte[] manufacturerDataBytes = extractBytes(scanRecord, currentPos + 2, dataLength - 2); manufacturerData.put(manufacturerId, manufacturerDataBytes); break; default: // Just ignore, we don't handle such data type. break; } currentPos += dataLength; } if (serviceUuids.isEmpty()) { serviceUuids = null; } return new ScanRecord(serviceUuids, manufacturerData, serviceData, advertiseFlag, txPowerLevel, localName, scanRecord); } catch (Exception e) {
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanRecord.java import java.util.List; import java.util.Map; import android.os.ParcelUuid; import android.support.annotation.Nullable; import android.util.SparseArray; import com.reelyactive.blesdk.support.ble.util.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; byte[] serviceDataUuidBytes = extractBytes(scanRecord, currentPos, serviceUuidLength); ParcelUuid serviceDataUuid = BluetoothUuid.parseUuidFrom( serviceDataUuidBytes); byte[] serviceDataArray = extractBytes(scanRecord, currentPos + serviceUuidLength, dataLength - serviceUuidLength); serviceData.put(serviceDataUuid, serviceDataArray); break; case DATA_TYPE_MANUFACTURER_SPECIFIC_DATA: // The first two bytes of the manufacturer specific data are // manufacturer ids in little endian. int manufacturerId = ((scanRecord[currentPos + 1] & 0xFF) << 8) + (scanRecord[currentPos] & 0xFF); byte[] manufacturerDataBytes = extractBytes(scanRecord, currentPos + 2, dataLength - 2); manufacturerData.put(manufacturerId, manufacturerDataBytes); break; default: // Just ignore, we don't handle such data type. break; } currentPos += dataLength; } if (serviceUuids.isEmpty()) { serviceUuids = null; } return new ScanRecord(serviceUuids, manufacturerData, serviceData, advertiseFlag, txPowerLevel, localName, scanRecord); } catch (Exception e) {
Logger.logError("unable to parse scan record: " + Arrays.toString(scanRecord), e);
reelyactive/ble-android-sdk
library/src/main/java/com/reelyactive/blesdk/support/ble/ScanWakefulBroadcastReceiver.java
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // }
import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; import com.reelyactive.blesdk.support.ble.util.Logger;
package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * com.reelyactive.blesdk.support.ble.ScanWakefulBroadcastReceiver initiates the Bluetooth LE scan by calling * {@link ScanWakefulService} after acquiring a WakeLock. On completion {@link ScanWakefulService} * releases the WakeLock. * <p/> * This WakefulBroadcastReceiver is invoked by a pending intent through the alarm manager. */ public class ScanWakefulBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: library/src/main/java/com/reelyactive/blesdk/support/ble/util/Logger.java // public class Logger { // // public static final String TAG = "BleScanCompatLib"; // // public static void logVerbose(String message) { // if (Log.isLoggable(TAG, Log.VERBOSE)) { // Log.v(TAG, message); // } // } // // public static void logWarning(String message) { // if (Log.isLoggable(TAG, Log.WARN)) { // Log.w(TAG, message); // } // } // // public static void logDebug(String message) { // if (Log.isLoggable(TAG, Log.DEBUG)) { // Log.d(TAG, message); // } // } // // public static void logInfo(String message) { // if (Log.isLoggable(TAG, Log.INFO)) { // Log.i(TAG, message); // } // } // // public static void logError(String message, Exception... e) { // if (Log.isLoggable(TAG, Log.ERROR)) { // if (e == null || e.length == 0) { // Log.e(TAG, message); // } else { // Log.e(TAG, message, e[0]); // } // } // } // } // Path: library/src/main/java/com/reelyactive/blesdk/support/ble/ScanWakefulBroadcastReceiver.java import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; import com.reelyactive.blesdk.support.ble.util.Logger; package com.reelyactive.blesdk.support.ble;/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * com.reelyactive.blesdk.support.ble.ScanWakefulBroadcastReceiver initiates the Bluetooth LE scan by calling * {@link ScanWakefulService} after acquiring a WakeLock. On completion {@link ScanWakefulService} * releases the WakeLock. * <p/> * This WakefulBroadcastReceiver is invoked by a pending intent through the alarm manager. */ public class ScanWakefulBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
Logger.logDebug("Alarm triggered");
mguetlein/CheS-Mapper
src/main/java/org/chesmapper/view/gui/GUIControler.java
// Path: src/main/java/org/chesmapper/view/cluster/Clustering.java // public interface Clustering extends CompoundGroupWithProperties // { // void addListener(PropertyChangeListener propertyChangeListener); // // int getNumClusters(); // // int numClusters(); // // List<Cluster> getClusters(); // // boolean isClusterActive(); // // boolean isClusterWatched(); // // Cluster getCluster(int i); // // int indexOf(Cluster cluster); // // Cluster getActiveCluster(); // // Cluster getWatchedCluster(); // // int getActiveClusterIdx(); // // int getWatchedClusterIdx(); // // boolean isCompoundActive(); // // boolean isCompoundWatched(); // // boolean isCompoundActive(Compound c); // // Compound[] getActiveCompounds(); // // Compound getActiveCompound(); // // int[] getActiveCompoundsJmolIdx(); // // Compound getWatchedCompound(); // // Compound[] getWatchedCompounds(); // // int[] getWatchedCompoundsJmolIdx(); // // Cluster getClusterForCompound(Compound c); // // List<CompoundProperty> selectPropertiesAndFeaturesWithDialog(String title, CompoundProperty preselected, // boolean addSmiles, boolean addEmbeddingStress, boolean addActivityCliffs, boolean addDistanceTo); // // List<CompoundProperty> getPropertiesAndFeatures(); // // List<CompoundProperty> getProperties(); // // List<CompoundProperty> getFeatures(); // // List<Compound> getCompounds(boolean includingMultiClusteredCompounds); // // Cluster getUniqueClusterForCompounds(Compound[] c); // // String getOrigLocalPath(); // // String getOrigSDFile(); // // String getSDFile(); // // boolean isClusterAlgorithmDisjoint(); // // String getClusterAlgorithm(); // // int getClusterIndexForCompound(Compound m); // // List<CompoundData> getCompounds(); // // void chooseClustersToExport(CompoundProperty compoundDescriptor); // // void chooseCompoundsToExport(CompoundProperty compoundDescriptor); // // Double[] getDoubleValues(NumericProperty p); // // String[] getStringValues(NominalProperty p, Compound m); // // String getSummaryStringValue(CompoundProperty p, boolean b); // // int numMissingValues(CompoundProperty p); // // String getName(); // // Double getNormalizedLogDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // Double getNormalizedDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // double getSpecificity(Compound compound, CompoundProperty p); // // double getSpecificity(Cluster cluster, CompoundProperty p); // // double getSpecificity(CompoundSelection sel, CompoundProperty p); // // int getNumCompounds(boolean includingMultiClusteredCompounds); // // int getNumUnfilteredCompounds(boolean includingMultiClusteredCompounds); // // String getEmbedAlgorithm(); // // String getEmbedQuality(); // // List<CompoundProperty> getAdditionalProperties(); // // CorrelationProperty getEmbeddingQualityProperty(); // // EqualPositionProperty getEqualPosProperty(); // // Compound getCompoundWithJmolIndex(int convertRowIndexToModel); // // int numDistinctValues(CompoundProperty p); // // public void addSelectionListener(SelectionListener l); // // public abstract static class SelectionListener // { // public void clusterActiveChanged(Cluster c) // { // } // // public void clusterWatchedChanged(Cluster c) // { // } // // public void compoundActiveChanged(Compound c[]) // { // } // // public void compoundWatchedChanged(Compound c[]) // { // } // } // // boolean isBMBFRealEndpointDataset(boolean b); // // CompoundProperty addDistanceToCompoundFeature(Compound c); // // CompoundProperty addSALIFeatures(CompoundProperty c); // // void predict(); // // void addPredictionFeature(CompoundProperty clazz, PredictionResult p); // // NumericProperty addLogFeature(NumericProperty p); // // public CompoundSelection getCompoundSelection(Compound[] c); // // boolean isRandomEmbedding(); // // CompoundProperty getHighlightProperty(); // // Color getHighlightColorText(); // // Double getFeatureDistance(int origIndex, int origIndex2); // // boolean isSkippingRedundantFeatures(); // // boolean isBigDataMode(); // // void computeAppDomain(); // // boolean doCheSMappingWarningsExist(); // // void showCheSMappingWarnings(); // // }
import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.JPopupMenu; import org.chesmapper.view.cluster.Clustering; import org.mg.javalib.gui.Blockable; import org.mg.javalib.gui.property.Property;
package org.chesmapper.view.gui; public interface GUIControler extends Blockable {
// Path: src/main/java/org/chesmapper/view/cluster/Clustering.java // public interface Clustering extends CompoundGroupWithProperties // { // void addListener(PropertyChangeListener propertyChangeListener); // // int getNumClusters(); // // int numClusters(); // // List<Cluster> getClusters(); // // boolean isClusterActive(); // // boolean isClusterWatched(); // // Cluster getCluster(int i); // // int indexOf(Cluster cluster); // // Cluster getActiveCluster(); // // Cluster getWatchedCluster(); // // int getActiveClusterIdx(); // // int getWatchedClusterIdx(); // // boolean isCompoundActive(); // // boolean isCompoundWatched(); // // boolean isCompoundActive(Compound c); // // Compound[] getActiveCompounds(); // // Compound getActiveCompound(); // // int[] getActiveCompoundsJmolIdx(); // // Compound getWatchedCompound(); // // Compound[] getWatchedCompounds(); // // int[] getWatchedCompoundsJmolIdx(); // // Cluster getClusterForCompound(Compound c); // // List<CompoundProperty> selectPropertiesAndFeaturesWithDialog(String title, CompoundProperty preselected, // boolean addSmiles, boolean addEmbeddingStress, boolean addActivityCliffs, boolean addDistanceTo); // // List<CompoundProperty> getPropertiesAndFeatures(); // // List<CompoundProperty> getProperties(); // // List<CompoundProperty> getFeatures(); // // List<Compound> getCompounds(boolean includingMultiClusteredCompounds); // // Cluster getUniqueClusterForCompounds(Compound[] c); // // String getOrigLocalPath(); // // String getOrigSDFile(); // // String getSDFile(); // // boolean isClusterAlgorithmDisjoint(); // // String getClusterAlgorithm(); // // int getClusterIndexForCompound(Compound m); // // List<CompoundData> getCompounds(); // // void chooseClustersToExport(CompoundProperty compoundDescriptor); // // void chooseCompoundsToExport(CompoundProperty compoundDescriptor); // // Double[] getDoubleValues(NumericProperty p); // // String[] getStringValues(NominalProperty p, Compound m); // // String getSummaryStringValue(CompoundProperty p, boolean b); // // int numMissingValues(CompoundProperty p); // // String getName(); // // Double getNormalizedLogDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // Double getNormalizedDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // double getSpecificity(Compound compound, CompoundProperty p); // // double getSpecificity(Cluster cluster, CompoundProperty p); // // double getSpecificity(CompoundSelection sel, CompoundProperty p); // // int getNumCompounds(boolean includingMultiClusteredCompounds); // // int getNumUnfilteredCompounds(boolean includingMultiClusteredCompounds); // // String getEmbedAlgorithm(); // // String getEmbedQuality(); // // List<CompoundProperty> getAdditionalProperties(); // // CorrelationProperty getEmbeddingQualityProperty(); // // EqualPositionProperty getEqualPosProperty(); // // Compound getCompoundWithJmolIndex(int convertRowIndexToModel); // // int numDistinctValues(CompoundProperty p); // // public void addSelectionListener(SelectionListener l); // // public abstract static class SelectionListener // { // public void clusterActiveChanged(Cluster c) // { // } // // public void clusterWatchedChanged(Cluster c) // { // } // // public void compoundActiveChanged(Compound c[]) // { // } // // public void compoundWatchedChanged(Compound c[]) // { // } // } // // boolean isBMBFRealEndpointDataset(boolean b); // // CompoundProperty addDistanceToCompoundFeature(Compound c); // // CompoundProperty addSALIFeatures(CompoundProperty c); // // void predict(); // // void addPredictionFeature(CompoundProperty clazz, PredictionResult p); // // NumericProperty addLogFeature(NumericProperty p); // // public CompoundSelection getCompoundSelection(Compound[] c); // // boolean isRandomEmbedding(); // // CompoundProperty getHighlightProperty(); // // Color getHighlightColorText(); // // Double getFeatureDistance(int origIndex, int origIndex2); // // boolean isSkippingRedundantFeatures(); // // boolean isBigDataMode(); // // void computeAppDomain(); // // boolean doCheSMappingWarningsExist(); // // void showCheSMappingWarnings(); // // } // Path: src/main/java/org/chesmapper/view/gui/GUIControler.java import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.JPopupMenu; import org.chesmapper.view.cluster.Clustering; import org.mg.javalib.gui.Blockable; import org.mg.javalib.gui.property.Property; package org.chesmapper.view.gui; public interface GUIControler extends Blockable {
public void updateTitle(Clustering c);
mguetlein/CheS-Mapper
src/main/java/org/chesmapper/view/gui/ColorEditor.java
// Path: src/main/java/org/chesmapper/view/cluster/Clustering.java // public interface Clustering extends CompoundGroupWithProperties // { // void addListener(PropertyChangeListener propertyChangeListener); // // int getNumClusters(); // // int numClusters(); // // List<Cluster> getClusters(); // // boolean isClusterActive(); // // boolean isClusterWatched(); // // Cluster getCluster(int i); // // int indexOf(Cluster cluster); // // Cluster getActiveCluster(); // // Cluster getWatchedCluster(); // // int getActiveClusterIdx(); // // int getWatchedClusterIdx(); // // boolean isCompoundActive(); // // boolean isCompoundWatched(); // // boolean isCompoundActive(Compound c); // // Compound[] getActiveCompounds(); // // Compound getActiveCompound(); // // int[] getActiveCompoundsJmolIdx(); // // Compound getWatchedCompound(); // // Compound[] getWatchedCompounds(); // // int[] getWatchedCompoundsJmolIdx(); // // Cluster getClusterForCompound(Compound c); // // List<CompoundProperty> selectPropertiesAndFeaturesWithDialog(String title, CompoundProperty preselected, // boolean addSmiles, boolean addEmbeddingStress, boolean addActivityCliffs, boolean addDistanceTo); // // List<CompoundProperty> getPropertiesAndFeatures(); // // List<CompoundProperty> getProperties(); // // List<CompoundProperty> getFeatures(); // // List<Compound> getCompounds(boolean includingMultiClusteredCompounds); // // Cluster getUniqueClusterForCompounds(Compound[] c); // // String getOrigLocalPath(); // // String getOrigSDFile(); // // String getSDFile(); // // boolean isClusterAlgorithmDisjoint(); // // String getClusterAlgorithm(); // // int getClusterIndexForCompound(Compound m); // // List<CompoundData> getCompounds(); // // void chooseClustersToExport(CompoundProperty compoundDescriptor); // // void chooseCompoundsToExport(CompoundProperty compoundDescriptor); // // Double[] getDoubleValues(NumericProperty p); // // String[] getStringValues(NominalProperty p, Compound m); // // String getSummaryStringValue(CompoundProperty p, boolean b); // // int numMissingValues(CompoundProperty p); // // String getName(); // // Double getNormalizedLogDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // Double getNormalizedDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // double getSpecificity(Compound compound, CompoundProperty p); // // double getSpecificity(Cluster cluster, CompoundProperty p); // // double getSpecificity(CompoundSelection sel, CompoundProperty p); // // int getNumCompounds(boolean includingMultiClusteredCompounds); // // int getNumUnfilteredCompounds(boolean includingMultiClusteredCompounds); // // String getEmbedAlgorithm(); // // String getEmbedQuality(); // // List<CompoundProperty> getAdditionalProperties(); // // CorrelationProperty getEmbeddingQualityProperty(); // // EqualPositionProperty getEqualPosProperty(); // // Compound getCompoundWithJmolIndex(int convertRowIndexToModel); // // int numDistinctValues(CompoundProperty p); // // public void addSelectionListener(SelectionListener l); // // public abstract static class SelectionListener // { // public void clusterActiveChanged(Cluster c) // { // } // // public void clusterWatchedChanged(Cluster c) // { // } // // public void compoundActiveChanged(Compound c[]) // { // } // // public void compoundWatchedChanged(Compound c[]) // { // } // } // // boolean isBMBFRealEndpointDataset(boolean b); // // CompoundProperty addDistanceToCompoundFeature(Compound c); // // CompoundProperty addSALIFeatures(CompoundProperty c); // // void predict(); // // void addPredictionFeature(CompoundProperty clazz, PredictionResult p); // // NumericProperty addLogFeature(NumericProperty p); // // public CompoundSelection getCompoundSelection(Compound[] c); // // boolean isRandomEmbedding(); // // CompoundProperty getHighlightProperty(); // // Color getHighlightColorText(); // // Double getFeatureDistance(int origIndex, int origIndex2); // // boolean isSkippingRedundantFeatures(); // // boolean isBigDataMode(); // // void computeAppDomain(); // // boolean doCheSMappingWarningsExist(); // // void showCheSMappingWarnings(); // // }
import java.awt.BorderLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import org.chesmapper.map.main.Settings; import org.chesmapper.view.cluster.Clustering; import com.jgoodies.forms.factories.ButtonBarFactory;
package org.chesmapper.view.gui; public class ColorEditor extends JDialog { ViewControler viewControler; boolean okPressed = false; ColorEditorPanel panels[];
// Path: src/main/java/org/chesmapper/view/cluster/Clustering.java // public interface Clustering extends CompoundGroupWithProperties // { // void addListener(PropertyChangeListener propertyChangeListener); // // int getNumClusters(); // // int numClusters(); // // List<Cluster> getClusters(); // // boolean isClusterActive(); // // boolean isClusterWatched(); // // Cluster getCluster(int i); // // int indexOf(Cluster cluster); // // Cluster getActiveCluster(); // // Cluster getWatchedCluster(); // // int getActiveClusterIdx(); // // int getWatchedClusterIdx(); // // boolean isCompoundActive(); // // boolean isCompoundWatched(); // // boolean isCompoundActive(Compound c); // // Compound[] getActiveCompounds(); // // Compound getActiveCompound(); // // int[] getActiveCompoundsJmolIdx(); // // Compound getWatchedCompound(); // // Compound[] getWatchedCompounds(); // // int[] getWatchedCompoundsJmolIdx(); // // Cluster getClusterForCompound(Compound c); // // List<CompoundProperty> selectPropertiesAndFeaturesWithDialog(String title, CompoundProperty preselected, // boolean addSmiles, boolean addEmbeddingStress, boolean addActivityCliffs, boolean addDistanceTo); // // List<CompoundProperty> getPropertiesAndFeatures(); // // List<CompoundProperty> getProperties(); // // List<CompoundProperty> getFeatures(); // // List<Compound> getCompounds(boolean includingMultiClusteredCompounds); // // Cluster getUniqueClusterForCompounds(Compound[] c); // // String getOrigLocalPath(); // // String getOrigSDFile(); // // String getSDFile(); // // boolean isClusterAlgorithmDisjoint(); // // String getClusterAlgorithm(); // // int getClusterIndexForCompound(Compound m); // // List<CompoundData> getCompounds(); // // void chooseClustersToExport(CompoundProperty compoundDescriptor); // // void chooseCompoundsToExport(CompoundProperty compoundDescriptor); // // Double[] getDoubleValues(NumericProperty p); // // String[] getStringValues(NominalProperty p, Compound m); // // String getSummaryStringValue(CompoundProperty p, boolean b); // // int numMissingValues(CompoundProperty p); // // String getName(); // // Double getNormalizedLogDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // Double getNormalizedDoubleValue(CompoundPropertyOwner m, NumericProperty p); // // double getSpecificity(Compound compound, CompoundProperty p); // // double getSpecificity(Cluster cluster, CompoundProperty p); // // double getSpecificity(CompoundSelection sel, CompoundProperty p); // // int getNumCompounds(boolean includingMultiClusteredCompounds); // // int getNumUnfilteredCompounds(boolean includingMultiClusteredCompounds); // // String getEmbedAlgorithm(); // // String getEmbedQuality(); // // List<CompoundProperty> getAdditionalProperties(); // // CorrelationProperty getEmbeddingQualityProperty(); // // EqualPositionProperty getEqualPosProperty(); // // Compound getCompoundWithJmolIndex(int convertRowIndexToModel); // // int numDistinctValues(CompoundProperty p); // // public void addSelectionListener(SelectionListener l); // // public abstract static class SelectionListener // { // public void clusterActiveChanged(Cluster c) // { // } // // public void clusterWatchedChanged(Cluster c) // { // } // // public void compoundActiveChanged(Compound c[]) // { // } // // public void compoundWatchedChanged(Compound c[]) // { // } // } // // boolean isBMBFRealEndpointDataset(boolean b); // // CompoundProperty addDistanceToCompoundFeature(Compound c); // // CompoundProperty addSALIFeatures(CompoundProperty c); // // void predict(); // // void addPredictionFeature(CompoundProperty clazz, PredictionResult p); // // NumericProperty addLogFeature(NumericProperty p); // // public CompoundSelection getCompoundSelection(Compound[] c); // // boolean isRandomEmbedding(); // // CompoundProperty getHighlightProperty(); // // Color getHighlightColorText(); // // Double getFeatureDistance(int origIndex, int origIndex2); // // boolean isSkippingRedundantFeatures(); // // boolean isBigDataMode(); // // void computeAppDomain(); // // boolean doCheSMappingWarningsExist(); // // void showCheSMappingWarnings(); // // } // Path: src/main/java/org/chesmapper/view/gui/ColorEditor.java import java.awt.BorderLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import org.chesmapper.map.main.Settings; import org.chesmapper.view.cluster.Clustering; import com.jgoodies.forms.factories.ButtonBarFactory; package org.chesmapper.view.gui; public class ColorEditor extends JDialog { ViewControler viewControler; boolean okPressed = false; ColorEditorPanel panels[];
public ColorEditor(Window owner, String title, ViewControler viewControler, Clustering clustering)
mguetlein/CheS-Mapper
src/test/java/org/chesmapper/test/util/SwingTestUtil.java
// Path: src/main/java/org/chesmapper/view/gui/swing/ComponentFactory.java // public static class ClickableLabel extends JLabel // { // public ClickableLabel(String text, ImageIcon icon, int horizontalAlignment) // { // super(text, icon, horizontalAlignment); // } // // Boolean myEnabled = null; // // public void setEnabled(boolean enabled) // { // myEnabled = enabled; // updateUI(); // } // // public void addActionListener(final ActionListener l) // { // addMouseListener(new MouseAdapter() // { // @Override // public void mousePressed(MouseEvent e) // { // if (myEnabled == null || myEnabled) // l.actionPerformed(new ActionEvent(ClickableLabel.this, 0, "button clicked")); // } // }); // } // }
import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Point; import java.awt.Robot; import java.awt.Window; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.text.JTextComponent; import org.chesmapper.view.gui.swing.ComponentFactory.ClickableLabel; import org.junit.Assert; import org.mg.javalib.gui.BlockableFrame; import org.mg.javalib.gui.Selector; import org.mg.javalib.util.ScreenUtil; import org.mg.javalib.util.SwingUtil; import org.mg.javalib.util.ThreadUtil;
public static JPopupMenu getOnlyPopupMenu(Container owner) { return (JPopupMenu) getOnlyComponent(owner, JPopupMenu.class); } public static Selector<?, ?> getOnlySelector(Container owner) { return (Selector<?, ?>) getOnlyComponent(owner, Selector.class); } public static JSpinner getOnlySpinner(Container owner) { return (JSpinner) getOnlyComponent(owner, JSpinner.class); } public static JCheckBox getOnlyCheckBox(Container owner) { return (JCheckBox) getOnlyComponent(owner, JCheckBox.class); } public static JComboBox<?> getOnlyComboBox(Container owner) { return getOnlyComboBox(owner, false); } public static JComboBox<?> getOnlyComboBox(Container owner, boolean onlyVisible) { return (JComboBox<?>) getOnlyComponent(owner, JComboBox.class, onlyVisible); }
// Path: src/main/java/org/chesmapper/view/gui/swing/ComponentFactory.java // public static class ClickableLabel extends JLabel // { // public ClickableLabel(String text, ImageIcon icon, int horizontalAlignment) // { // super(text, icon, horizontalAlignment); // } // // Boolean myEnabled = null; // // public void setEnabled(boolean enabled) // { // myEnabled = enabled; // updateUI(); // } // // public void addActionListener(final ActionListener l) // { // addMouseListener(new MouseAdapter() // { // @Override // public void mousePressed(MouseEvent e) // { // if (myEnabled == null || myEnabled) // l.actionPerformed(new ActionEvent(ClickableLabel.this, 0, "button clicked")); // } // }); // } // } // Path: src/test/java/org/chesmapper/test/util/SwingTestUtil.java import java.awt.Component; import java.awt.Container; import java.awt.Frame; import java.awt.Point; import java.awt.Robot; import java.awt.Window; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.text.JTextComponent; import org.chesmapper.view.gui.swing.ComponentFactory.ClickableLabel; import org.junit.Assert; import org.mg.javalib.gui.BlockableFrame; import org.mg.javalib.gui.Selector; import org.mg.javalib.util.ScreenUtil; import org.mg.javalib.util.SwingUtil; import org.mg.javalib.util.ThreadUtil; public static JPopupMenu getOnlyPopupMenu(Container owner) { return (JPopupMenu) getOnlyComponent(owner, JPopupMenu.class); } public static Selector<?, ?> getOnlySelector(Container owner) { return (Selector<?, ?>) getOnlyComponent(owner, Selector.class); } public static JSpinner getOnlySpinner(Container owner) { return (JSpinner) getOnlyComponent(owner, JSpinner.class); } public static JCheckBox getOnlyCheckBox(Container owner) { return (JCheckBox) getOnlyComponent(owner, JCheckBox.class); } public static JComboBox<?> getOnlyComboBox(Container owner) { return getOnlyComboBox(owner, false); } public static JComboBox<?> getOnlyComboBox(Container owner, boolean onlyVisible) { return (JComboBox<?>) getOnlyComponent(owner, JComboBox.class, onlyVisible); }
public static ClickableLabel getVisibleClickableLabel(Container owner, final int swingConstantOrientation)
mguetlein/CheS-Mapper
src/main/java/org/chesmapper/view/gui/swing/ComponentFactory.java
// Path: src/main/java/org/chesmapper/view/gui/ViewControler.java // public enum Style // { // wireframe, ballsAndSticks, dots // }
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.BasicComboPopup; import javax.swing.plaf.basic.BasicScrollBarUI; import javax.swing.plaf.basic.BasicSliderUI; import javax.swing.plaf.basic.ComboPopup; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.chesmapper.map.main.ScreenSetup; import org.chesmapper.map.main.Settings; import org.chesmapper.view.gui.LaunchCheSMapper; import org.chesmapper.view.gui.ViewControler.Style; import org.mg.javalib.gui.BorderImageIcon; import org.mg.javalib.gui.DescriptionListCellRenderer; import org.mg.javalib.gui.LinkButton; import org.mg.javalib.gui.SimpleImageIcon; import org.mg.javalib.gui.StringImageIcon; import org.mg.javalib.util.ColorUtil; import org.mg.javalib.util.SwingUtil;
public static JCheckBox createViewCheckBox(String text) { JCheckBox c = new JCheckBox(text) { public void updateUI() { super.updateUI(); setForeground(FOREGROUND); setFont(getFont().deriveFont((float) ScreenSetup.INSTANCE.getFontSize())); } }; c.setFocusable(false); return c; } // public static JRadioButton createViewRadioButton(String text) // { // JRadioButton r = new JRadioButton(text) // { // public void updateUI() // { // super.updateUI(); // setForeground(FOREGROUND); // } // }; // return r; // } public static class StyleButton extends JRadioButton {
// Path: src/main/java/org/chesmapper/view/gui/ViewControler.java // public enum Style // { // wireframe, ballsAndSticks, dots // } // Path: src/main/java/org/chesmapper/view/gui/swing/ComponentFactory.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.BasicComboPopup; import javax.swing.plaf.basic.BasicScrollBarUI; import javax.swing.plaf.basic.BasicSliderUI; import javax.swing.plaf.basic.ComboPopup; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.chesmapper.map.main.ScreenSetup; import org.chesmapper.map.main.Settings; import org.chesmapper.view.gui.LaunchCheSMapper; import org.chesmapper.view.gui.ViewControler.Style; import org.mg.javalib.gui.BorderImageIcon; import org.mg.javalib.gui.DescriptionListCellRenderer; import org.mg.javalib.gui.LinkButton; import org.mg.javalib.gui.SimpleImageIcon; import org.mg.javalib.gui.StringImageIcon; import org.mg.javalib.util.ColorUtil; import org.mg.javalib.util.SwingUtil; public static JCheckBox createViewCheckBox(String text) { JCheckBox c = new JCheckBox(text) { public void updateUI() { super.updateUI(); setForeground(FOREGROUND); setFont(getFont().deriveFont((float) ScreenSetup.INSTANCE.getFontSize())); } }; c.setFocusable(false); return c; } // public static JRadioButton createViewRadioButton(String text) // { // JRadioButton r = new JRadioButton(text) // { // public void updateUI() // { // super.updateUI(); // setForeground(FOREGROUND); // } // }; // return r; // } public static class StyleButton extends JRadioButton {
public Style style;
OfficeDev/O365-Android-Snippets
app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java
// Path: app/src/main/java/com/microsoft/office365/snippetapp/AndroidSnippetsApplication.java // public class AndroidSnippetsApplication extends Application { // // private static AndroidSnippetsApplication mAndroidSnippetsApplication; // // @Override // public void onCreate() { // super.onCreate(); // mAndroidSnippetsApplication = this; // } // // public static AndroidSnippetsApplication getApplication() { // return mAndroidSnippetsApplication; // } // } // // Path: app/src/main/java/com/microsoft/office365/snippetapp/Interfaces/OnUseCaseStatusChangedListener.java // public interface OnUseCaseStatusChangedListener { // // void onUseCaseStatusChanged(); // }
import android.content.res.AssetFileDescriptor; import android.util.Log; import android.view.View; import com.microsoft.fileservices.odata.SharePointClient; import com.microsoft.office365.snippetapp.AndroidSnippetsApplication; import com.microsoft.office365.snippetapp.Interfaces.OnUseCaseStatusChangedListener; import com.microsoft.outlookservices.odata.OutlookClient; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException;
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.office365.snippetapp.helpers; public abstract class BaseUserStory { private boolean mIsExecuting = false; private View mUpdateView; private OutlookClient mO365MailClient; private SharePointClient mO365MyFilesClient; private String mMailResourceId;
// Path: app/src/main/java/com/microsoft/office365/snippetapp/AndroidSnippetsApplication.java // public class AndroidSnippetsApplication extends Application { // // private static AndroidSnippetsApplication mAndroidSnippetsApplication; // // @Override // public void onCreate() { // super.onCreate(); // mAndroidSnippetsApplication = this; // } // // public static AndroidSnippetsApplication getApplication() { // return mAndroidSnippetsApplication; // } // } // // Path: app/src/main/java/com/microsoft/office365/snippetapp/Interfaces/OnUseCaseStatusChangedListener.java // public interface OnUseCaseStatusChangedListener { // // void onUseCaseStatusChanged(); // } // Path: app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java import android.content.res.AssetFileDescriptor; import android.util.Log; import android.view.View; import com.microsoft.fileservices.odata.SharePointClient; import com.microsoft.office365.snippetapp.AndroidSnippetsApplication; import com.microsoft.office365.snippetapp.Interfaces.OnUseCaseStatusChangedListener; import com.microsoft.outlookservices.odata.OutlookClient; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; /* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.office365.snippetapp.helpers; public abstract class BaseUserStory { private boolean mIsExecuting = false; private View mUpdateView; private OutlookClient mO365MailClient; private SharePointClient mO365MyFilesClient; private String mMailResourceId;
private OnUseCaseStatusChangedListener mUseCaseStatusChangedListener;
OfficeDev/O365-Android-Snippets
app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java
// Path: app/src/main/java/com/microsoft/office365/snippetapp/AndroidSnippetsApplication.java // public class AndroidSnippetsApplication extends Application { // // private static AndroidSnippetsApplication mAndroidSnippetsApplication; // // @Override // public void onCreate() { // super.onCreate(); // mAndroidSnippetsApplication = this; // } // // public static AndroidSnippetsApplication getApplication() { // return mAndroidSnippetsApplication; // } // } // // Path: app/src/main/java/com/microsoft/office365/snippetapp/Interfaces/OnUseCaseStatusChangedListener.java // public interface OnUseCaseStatusChangedListener { // // void onUseCaseStatusChanged(); // }
import android.content.res.AssetFileDescriptor; import android.util.Log; import android.view.View; import com.microsoft.fileservices.odata.SharePointClient; import com.microsoft.office365.snippetapp.AndroidSnippetsApplication; import com.microsoft.office365.snippetapp.Interfaces.OnUseCaseStatusChangedListener; import com.microsoft.outlookservices.odata.OutlookClient; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException;
public String getFilesFoldersResourceId() { return mFilesFoldersResourceId; } public void setFilesFoldersResourceId(String filesFoldersResourceId) { this.mFilesFoldersResourceId = filesFoldersResourceId; } public void setUseCaseStatusChangedListener(OnUseCaseStatusChangedListener listener) { mUseCaseStatusChangedListener = listener; } protected abstract String execute(); public abstract String getDescription(); public boolean getGroupingFlag() { return mGroupingFlag; } public void setGroupingFlag(boolean groupingFlag) { mGroupingFlag = groupingFlag; } protected String getId() { return java.util.UUID.randomUUID().toString(); } protected String getStringResource(int resourceToGet) {
// Path: app/src/main/java/com/microsoft/office365/snippetapp/AndroidSnippetsApplication.java // public class AndroidSnippetsApplication extends Application { // // private static AndroidSnippetsApplication mAndroidSnippetsApplication; // // @Override // public void onCreate() { // super.onCreate(); // mAndroidSnippetsApplication = this; // } // // public static AndroidSnippetsApplication getApplication() { // return mAndroidSnippetsApplication; // } // } // // Path: app/src/main/java/com/microsoft/office365/snippetapp/Interfaces/OnUseCaseStatusChangedListener.java // public interface OnUseCaseStatusChangedListener { // // void onUseCaseStatusChanged(); // } // Path: app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java import android.content.res.AssetFileDescriptor; import android.util.Log; import android.view.View; import com.microsoft.fileservices.odata.SharePointClient; import com.microsoft.office365.snippetapp.AndroidSnippetsApplication; import com.microsoft.office365.snippetapp.Interfaces.OnUseCaseStatusChangedListener; import com.microsoft.outlookservices.odata.OutlookClient; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; public String getFilesFoldersResourceId() { return mFilesFoldersResourceId; } public void setFilesFoldersResourceId(String filesFoldersResourceId) { this.mFilesFoldersResourceId = filesFoldersResourceId; } public void setUseCaseStatusChangedListener(OnUseCaseStatusChangedListener listener) { mUseCaseStatusChangedListener = listener; } protected abstract String execute(); public abstract String getDescription(); public boolean getGroupingFlag() { return mGroupingFlag; } public void setGroupingFlag(boolean groupingFlag) { mGroupingFlag = groupingFlag; } protected String getId() { return java.util.UUID.randomUUID().toString(); } protected String getStringResource(int resourceToGet) {
return AndroidSnippetsApplication
OfficeDev/O365-Android-Snippets
app/src/main/java/com/microsoft/office365/snippetapp/OperationListAdapter.java
// Path: app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java // public abstract class BaseUserStory { // // private boolean mIsExecuting = false; // private View mUpdateView; // private OutlookClient mO365MailClient; // private SharePointClient mO365MyFilesClient; // private String mMailResourceId; // private OnUseCaseStatusChangedListener mUseCaseStatusChangedListener; // private String mFilesFoldersResourceId; // boolean mGroupingFlag = false; // // public String getFilesFoldersResourceId() { // return mFilesFoldersResourceId; // } // // public void setFilesFoldersResourceId(String filesFoldersResourceId) { // this.mFilesFoldersResourceId = filesFoldersResourceId; // } // // public void setUseCaseStatusChangedListener(OnUseCaseStatusChangedListener listener) { // mUseCaseStatusChangedListener = listener; // } // // protected abstract String execute(); // // public abstract String getDescription(); // // // public boolean getGroupingFlag() { // return mGroupingFlag; // } // // public void setGroupingFlag(boolean groupingFlag) { // mGroupingFlag = groupingFlag; // } // // protected String getId() { // return java.util.UUID.randomUUID().toString(); // } // // protected String getStringResource(int resourceToGet) { // return AndroidSnippetsApplication // .getApplication() // .getApplicationContext() // .getString(resourceToGet); // } // // protected String FormatException(Exception exception, String storyDescription) { // exception.printStackTrace(); // String formattedException = APIErrorMessageHelper.getErrorMessage(exception.getMessage()); // Log.e(storyDescription, formattedException); // return StoryResultFormatter.wrapResult( // storyDescription + ": " // + formattedException // , false // ); // // } // // public byte[] getDrawableResource(int resourceToGet) { // // //Get the photo from the resource/drawable folder as a raw image // final AssetFileDescriptor raw = AndroidSnippetsApplication // .getApplication() // .getApplicationContext() // .getResources() // .openRawResourceFd(resourceToGet); // // //Load raw image into a buffer // final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // try { // final FileInputStream is = raw.createInputStream(); // int nRead; // // //Read 16kb at a time // final byte[] data = new byte[16384]; // // while ((nRead = is.read(data, 0, data.length)) != -1) { // buffer.write(data, 0, nRead); // } // // buffer.flush(); // // } catch (IOException e) { // e.printStackTrace(); // } // return buffer.toByteArray(); // // } // // public View getUIResultView() { // return mUpdateView; // } // // public void setUIResultView(View view) { // mUpdateView = view; // } // // public String getO365MailResourceId() { // return mMailResourceId; // } // // public void setO365MailResourceId(String resourceId) { // mMailResourceId = resourceId; // } // // public OutlookClient getO365MailClient() { // AuthenticationController // .getInstance() // .setResourceId( // this.getO365MailResourceId()); // // return mO365MailClient; // } // // public void setO365MailClient(OutlookClient client) { // // mO365MailClient = client; // } // // public SharePointClient getO365MyFilesClient() { // return mO365MyFilesClient; // } // // public void setO365MyFilesClient(SharePointClient client) { // mO365MyFilesClient = client; // } // // private void notifyStatusChange() { // if (null != mUseCaseStatusChangedListener) { // mUseCaseStatusChangedListener.onUseCaseStatusChanged(); // } // } // // public final void onPreExecute() { // mIsExecuting = true; // notifyStatusChange(); // } // // public final void onPostExecute() { // mIsExecuting = false; // notifyStatusChange(); // } // // public final boolean isExecuting() { // return mIsExecuting; // } // // @Override // public String toString() { // return this.getDescription(); // } // // // }
import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.microsoft.office365.snippetapp.helpers.BaseUserStory; import java.util.List;
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.office365.snippetapp; class OperationListAdapter extends BaseAdapter { protected LayoutInflater mLayoutInflater;
// Path: app/src/main/java/com/microsoft/office365/snippetapp/helpers/BaseUserStory.java // public abstract class BaseUserStory { // // private boolean mIsExecuting = false; // private View mUpdateView; // private OutlookClient mO365MailClient; // private SharePointClient mO365MyFilesClient; // private String mMailResourceId; // private OnUseCaseStatusChangedListener mUseCaseStatusChangedListener; // private String mFilesFoldersResourceId; // boolean mGroupingFlag = false; // // public String getFilesFoldersResourceId() { // return mFilesFoldersResourceId; // } // // public void setFilesFoldersResourceId(String filesFoldersResourceId) { // this.mFilesFoldersResourceId = filesFoldersResourceId; // } // // public void setUseCaseStatusChangedListener(OnUseCaseStatusChangedListener listener) { // mUseCaseStatusChangedListener = listener; // } // // protected abstract String execute(); // // public abstract String getDescription(); // // // public boolean getGroupingFlag() { // return mGroupingFlag; // } // // public void setGroupingFlag(boolean groupingFlag) { // mGroupingFlag = groupingFlag; // } // // protected String getId() { // return java.util.UUID.randomUUID().toString(); // } // // protected String getStringResource(int resourceToGet) { // return AndroidSnippetsApplication // .getApplication() // .getApplicationContext() // .getString(resourceToGet); // } // // protected String FormatException(Exception exception, String storyDescription) { // exception.printStackTrace(); // String formattedException = APIErrorMessageHelper.getErrorMessage(exception.getMessage()); // Log.e(storyDescription, formattedException); // return StoryResultFormatter.wrapResult( // storyDescription + ": " // + formattedException // , false // ); // // } // // public byte[] getDrawableResource(int resourceToGet) { // // //Get the photo from the resource/drawable folder as a raw image // final AssetFileDescriptor raw = AndroidSnippetsApplication // .getApplication() // .getApplicationContext() // .getResources() // .openRawResourceFd(resourceToGet); // // //Load raw image into a buffer // final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // try { // final FileInputStream is = raw.createInputStream(); // int nRead; // // //Read 16kb at a time // final byte[] data = new byte[16384]; // // while ((nRead = is.read(data, 0, data.length)) != -1) { // buffer.write(data, 0, nRead); // } // // buffer.flush(); // // } catch (IOException e) { // e.printStackTrace(); // } // return buffer.toByteArray(); // // } // // public View getUIResultView() { // return mUpdateView; // } // // public void setUIResultView(View view) { // mUpdateView = view; // } // // public String getO365MailResourceId() { // return mMailResourceId; // } // // public void setO365MailResourceId(String resourceId) { // mMailResourceId = resourceId; // } // // public OutlookClient getO365MailClient() { // AuthenticationController // .getInstance() // .setResourceId( // this.getO365MailResourceId()); // // return mO365MailClient; // } // // public void setO365MailClient(OutlookClient client) { // // mO365MailClient = client; // } // // public SharePointClient getO365MyFilesClient() { // return mO365MyFilesClient; // } // // public void setO365MyFilesClient(SharePointClient client) { // mO365MyFilesClient = client; // } // // private void notifyStatusChange() { // if (null != mUseCaseStatusChangedListener) { // mUseCaseStatusChangedListener.onUseCaseStatusChanged(); // } // } // // public final void onPreExecute() { // mIsExecuting = true; // notifyStatusChange(); // } // // public final void onPostExecute() { // mIsExecuting = false; // notifyStatusChange(); // } // // public final boolean isExecuting() { // return mIsExecuting; // } // // @Override // public String toString() { // return this.getDescription(); // } // // // } // Path: app/src/main/java/com/microsoft/office365/snippetapp/OperationListAdapter.java import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.microsoft.office365.snippetapp.helpers.BaseUserStory; import java.util.List; /* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.office365.snippetapp; class OperationListAdapter extends BaseAdapter { protected LayoutInflater mLayoutInflater;
protected List<BaseUserStory> mBaseStoryList;
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FragmentLengthDistributionByGene.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import org.apache.commons.math3.stat.Frequency; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader;
package edu.unc.genomics.ngs; /** * Calculate the fragment length distribution for fragments overlapping each * gene * * @author timpalpant * */ public class FragmentLengthDistributionByGene extends CommandLineTool { private static final Logger log = Logger.getLogger(FragmentLengthDistributionByGene.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/FragmentLengthDistributionByGene.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import org.apache.commons.math3.stat.Frequency; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; package edu.unc.genomics.ngs; /** * Calculate the fragment length distribution for fragments overlapping each * gene * * @author timpalpant * */ public class FragmentLengthDistributionByGene extends CommandLineTool { private static final Logger log = Logger.getLogger(FragmentLengthDistributionByGene.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (reads)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/nucleosomes/IntervalEntropy.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.ngs; /** * For each interval, compute the mean/min/max/total/coverage of data in a (Big)Wig file over that interval. * @author timpalpant * */ public class IntervalEntropy extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<>(); @Parameter(names = {"-l", "--loci"}, description = "Loci file (Bed)",
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/nucleosomes/IntervalEntropy.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.ngs; /** * For each interval, compute the mean/min/max/total/coverage of data in a (Big)Wig file over that interval. * @author timpalpant * */ public class IntervalEntropy extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<>(); @Parameter(names = {"-l", "--loci"}, description = "Loci file (Bed)",
required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/converters/InterpolateDiscontinuousData.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.ReadablePathValidator;
package edu.unc.genomics.converters; /** * Interpolates missing values (NaN) in a Wig file to create a continuous track * Useful for making microarray data continuous * * @author timpalpant * */ public class InterpolateDiscontinuousData extends WigMathTool { private static final Logger log = Logger.getLogger(InterpolateDiscontinuousData.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/converters/InterpolateDiscontinuousData.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.ReadablePathValidator; package edu.unc.genomics.converters; /** * Interpolates missing values (NaN) in a Wig file to create a continuous track * Useful for making microarray data continuous * * @author timpalpant * */ public class InterpolateDiscontinuousData extends WigMathTool { private static final Logger log = Logger.getLogger(InterpolateDiscontinuousData.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (Wig)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/ZScore.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Z-score the values in a Wig file: calculate normal scores = * (value-mean)/stdev * * @author timpalpant * */ public class ZScore extends WigMathTool { private static final Logger log = Logger.getLogger(ZScore.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/ZScore.java import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Z-score the values in a Wig file: calculate normal scores = * (value-mean)/stdev * * @author timpalpant * */ public class ZScore extends WigMathTool { private static final Logger log = Logger.getLogger(ZScore.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/nucleosomes/DynaPro.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter;
package edu.unc.genomics.nucleosomes; /** * Solve single-particle hard-rod statistical equilibria with the DynaPro * algorithm See Morozov AV, et al. (2009) Using DNA mechanics to predict in * vitro nucleosome positions and formation energies. Nucleic Acids Res 37: * 4707-4722 * * @author timpalpant * */ public class DynaPro extends CommandLineTool { private static final Logger log = Logger.getLogger(DynaPro.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/nucleosomes/DynaPro.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter; package edu.unc.genomics.nucleosomes; /** * Solve single-particle hard-rod statistical equilibria with the DynaPro * algorithm See Morozov AV, et al. (2009) Using DNA mechanics to predict in * vitro nucleosome positions and formation energies. Nucleic Acids Res 37: * 4707-4722 * * @author timpalpant * */ public class DynaPro extends CommandLineTool { private static final Logger log = Logger.getLogger(DynaPro.class);
@Parameter(names = { "-i", "--input" }, description = "Energy landscape", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/nucleosomes/DynaPro.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter;
if (scale != null) { for (int i = 0; i < energy.length; i++) { energy[i] *= scale; } } // Compute the probabilities float[] forward = new float[energy.length]; for (int i = nucleosomeSize; i < energy.length; i++) { double factor = 1 + Math.exp(forward[i - nucleosomeSize] - forward[i - 1] - energy[i - nucleosomeSize]); forward[i] = (float) (forward[i - 1] + Math.log(factor)); } float[] backward = new float[energy.length]; for (int i = energy.length - nucleosomeSize - 1; i > 0; i--) { double factor = 1 + Math.exp(backward[i + nucleosomeSize] - backward[i + 1] - energy[i - 1]); backward[i] = (float) (backward[i + 1] + Math.log(factor)); } float[] p = new float[energy.length]; for (int i = 0; i < energy.length - nucleosomeSize; i++) { p[i] = (float) Math.exp(forward[i] - energy[i] + backward[i + nucleosomeSize] - backward[1]); } // Write the chromosome to output writer.write(new Contig(chr, start, stop, p)); } } catch (WigFileException e) { log.error("Error getting data from Wig file"); e.printStackTrace();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/nucleosomes/DynaPro.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter; if (scale != null) { for (int i = 0; i < energy.length; i++) { energy[i] *= scale; } } // Compute the probabilities float[] forward = new float[energy.length]; for (int i = nucleosomeSize; i < energy.length; i++) { double factor = 1 + Math.exp(forward[i - nucleosomeSize] - forward[i - 1] - energy[i - nucleosomeSize]); forward[i] = (float) (forward[i - 1] + Math.log(factor)); } float[] backward = new float[energy.length]; for (int i = energy.length - nucleosomeSize - 1; i > 0; i--) { double factor = 1 + Math.exp(backward[i + nucleosomeSize] - backward[i + 1] - energy[i - 1]); backward[i] = (float) (backward[i + 1] + Math.log(factor)); } float[] p = new float[energy.length]; for (int i = 0; i < energy.length - nucleosomeSize; i++) { p[i] = (float) Math.exp(forward[i] - energy[i] + backward[i + nucleosomeSize] - backward[1]); } // Write the chromosome to output writer.write(new Contig(chr, start, stop, p)); } } catch (WigFileException e) { log.error("Error getting data from Wig file"); e.printStackTrace();
throw new CommandLineToolException("Error getting data from Wig file");
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/visualization/IntervalAverager.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.visualization; /** * Aggregate and average genomic signal for a set of aligned intervals * * @author timpalpant * */ public class IntervalAverager extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalAverager.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/visualization/IntervalAverager.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.visualization; /** * Aggregate and average genomic signal for a set of aligned intervals * * @author timpalpant * */ public class IntervalAverager extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalAverager.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>();
@Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/visualization/IntervalAverager.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.visualization; /** * Aggregate and average genomic signal for a set of aligned intervals * * @author timpalpant * */ public class IntervalAverager extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalAverager.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class) public Path lociFile; @Parameter(names = { "-o", "--output" }, description = "Output file (matrix2png format)", required = true) public Path outputFile; private List<WigFileReader> wigs = new ArrayList<>(); private int numFiles; private List<BedEntry> loci; @Override public void run() throws IOException { log.debug("Initializing input files"); for (String inputFile : inputFiles) { try { WigFileReader wig = WigFileReader.autodetect(Paths.get(inputFile)); wigs.add(wig); } catch (IOException e) { log.error("IOError initializing input Wig file: " + inputFile); e.printStackTrace();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/visualization/IntervalAverager.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.visualization; /** * Aggregate and average genomic signal for a set of aligned intervals * * @author timpalpant * */ public class IntervalAverager extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalAverager.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class) public Path lociFile; @Parameter(names = { "-o", "--output" }, description = "Output file (matrix2png format)", required = true) public Path outputFile; private List<WigFileReader> wigs = new ArrayList<>(); private int numFiles; private List<BedEntry> loci; @Override public void run() throws IOException { log.debug("Initializing input files"); for (String inputFile : inputFiles) { try { WigFileReader wig = WigFileReader.autodetect(Paths.get(inputFile)); wigs.add(wig); } catch (IOException e) { log.error("IOError initializing input Wig file: " + inputFile); e.printStackTrace();
throw new CommandLineToolException(e.getMessage());
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Scale.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Scale a Wig file by a constant, or normalize to its mean value * * @author timpalpant * */ public class Scale extends WigMathTool { private static final Logger log = Logger.getLogger(Scale.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Scale.java import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Scale a Wig file by a constant, or normalize to its mean value * * @author timpalpant * */ public class Scale extends WigMathTool { private static final Logger log = Logger.getLogger(Scale.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/visualization/MatrixAligner.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.visualization; /** * Align data from a Wig file into a matrix for making a heatmap with matrix2png * * @author timpalpant * */ public class MatrixAligner extends CommandLineTool { private static final Logger log = Logger.getLogger(MatrixAligner.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/visualization/MatrixAligner.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.visualization; /** * Align data from a Wig file into a matrix for making a heatmap with matrix2png * * @author timpalpant * */ public class MatrixAligner extends CommandLineTool { private static final Logger log = Logger.getLogger(MatrixAligner.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (Wig)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/visualization/MatrixAligner.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.visualization; /** * Align data from a Wig file into a matrix for making a heatmap with matrix2png * * @author timpalpant * */ public class MatrixAligner extends CommandLineTool { private static final Logger log = Logger.getLogger(MatrixAligner.class); @Parameter(names = { "-i", "--input" }, description = "Input file (Wig)", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class) public Path lociFile; @Parameter(names = { "-m", "--max" }, description = "Truncate width (base pairs)") public Integer maxWidth; @Parameter(names = { "-o", "--output" }, description = "Output file (matrix2png format)", required = true) public Path outputFile; private List<BedEntry> loci; @Override public void run() throws IOException { log.debug("Loading alignment intervals"); try (BedFileReader bed = new BedFileReader(lociFile)) { loci = bed.loadAll(); } // Compute the matrix dimensions int leftMax = Integer.MIN_VALUE; int rightMax = Integer.MIN_VALUE; for (BedEntry entry : loci) { if (entry.getValue() == null) {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/visualization/MatrixAligner.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.BedEntry; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.visualization; /** * Align data from a Wig file into a matrix for making a heatmap with matrix2png * * @author timpalpant * */ public class MatrixAligner extends CommandLineTool { private static final Logger log = Logger.getLogger(MatrixAligner.class); @Parameter(names = { "-i", "--input" }, description = "Input file (Wig)", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class) public Path lociFile; @Parameter(names = { "-m", "--max" }, description = "Truncate width (base pairs)") public Integer maxWidth; @Parameter(names = { "-o", "--output" }, description = "Output file (matrix2png format)", required = true) public Path outputFile; private List<BedEntry> loci; @Override public void run() throws IOException { log.debug("Loading alignment intervals"); try (BedFileReader bed = new BedFileReader(lociFile)) { loci = bed.loadAll(); } // Compute the matrix dimensions int leftMax = Integer.MIN_VALUE; int rightMax = Integer.MIN_VALUE; for (BedEntry entry : loci) { if (entry.getValue() == null) {
throw new CommandLineToolException("You must specify an alignment point for each interval in column 5");
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/nucleosomes/Phasogram.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.nucleosomes; /** * Make a histogram of phase counts from sequencing data to identify * periodicities. See Valouev A, et al. (2011) Determinants of nucleosome * organization in primary human cells. Nature 474: 516-520 * * @author timpalpant * */ public class Phasogram extends CommandLineTool { private static final Logger log = Logger.getLogger(Phasogram.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/nucleosomes/Phasogram.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.nucleosomes; /** * Make a histogram of phase counts from sequencing data to identify * periodicities. See Valouev A, et al. (2011) Determinants of nucleosome * organization in primary human cells. Nature 474: 516-520 * * @author timpalpant * */ public class Phasogram extends CommandLineTool { private static final Logger log = Logger.getLogger(Phasogram.class);
@Parameter(names = { "-i", "--input" }, description = "Input wig file (read counts)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/nucleosomes/Phasogram.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
@Parameter(names = { "-o", "--output" }, description = "Output file (histogram)", required = true) public Path outputFile; public void run() throws IOException { double[] phaseCounts = new double[maxPhase + 1]; // Process each chromosome in the input file try (WigFileReader reader = WigFileReader.autodetect(inputFile)) { for (String chr : reader.chromosomes()) { log.debug("Processing chromosome " + chr); int start = reader.getChrStart(chr); while (start < reader.getChrStop(chr)) { int stop = Math.min(start + DEFAULT_CHUNK_SIZE - 1, reader.getChrStop(chr)); log.debug("Processing chunk " + chr + ":" + start + "-" + stop); int paddedStop = Math.min(stop + maxPhase, reader.getChrStop(chr)); try { float[] data = reader.query(chr, start, paddedStop).getValues(); for (int i = 0; i < data.length - maxPhase; i++) { if (!Float.isNaN(data[i]) && !Float.isInfinite(data[i])) { for (int j = 0; j <= maxPhase; j++) { if (!Float.isNaN(data[i + j]) && !Float.isInfinite(data[i + j])) { phaseCounts[j] += data[i] * data[i + j]; } } } } } catch (WigFileException e) { log.fatal("Error querying data from Wig file!"); e.printStackTrace();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/nucleosomes/Phasogram.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; @Parameter(names = { "-o", "--output" }, description = "Output file (histogram)", required = true) public Path outputFile; public void run() throws IOException { double[] phaseCounts = new double[maxPhase + 1]; // Process each chromosome in the input file try (WigFileReader reader = WigFileReader.autodetect(inputFile)) { for (String chr : reader.chromosomes()) { log.debug("Processing chromosome " + chr); int start = reader.getChrStart(chr); while (start < reader.getChrStop(chr)) { int stop = Math.min(start + DEFAULT_CHUNK_SIZE - 1, reader.getChrStop(chr)); log.debug("Processing chunk " + chr + ":" + start + "-" + stop); int paddedStop = Math.min(stop + maxPhase, reader.getChrStop(chr)); try { float[] data = reader.query(chr, start, paddedStop).getValues(); for (int i = 0; i < data.length - maxPhase; i++) { if (!Float.isNaN(data[i]) && !Float.isInfinite(data[i])) { for (int j = 0; j <= maxPhase; j++) { if (!Float.isNaN(data[i + j]) && !Float.isInfinite(data[i + j])) { phaseCounts[j] += data[i] * data[i + j]; } } } } } catch (WigFileException e) { log.fatal("Error querying data from Wig file!"); e.printStackTrace();
throw new CommandLineToolException("Error querying data from Wig file!");
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Divide.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Divide two (Big)Wig files base pair by base pair * * @author timpalpant * */ public class Divide extends WigMathTool { private static final Logger log = Logger.getLogger(Divide.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Divide.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Divide two (Big)Wig files base pair by base pair * * @author timpalpant * */ public class Divide extends WigMathTool { private static final Logger log = Logger.getLogger(Divide.class);
@Parameter(names = { "-n", "--numerator" }, description = "Dividend / Numerator (file 1)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Summary.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/ngs/Autocorrelation.java // public class Autocorrelation extends CommandLineTool { // // private static final Logger log = Logger.getLogger(Autocorrelation.class); // // @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) // public Path inputFile; // @Parameter(names = { "-l", "--loci" }, description = "Genomic loci (Bed format)", required = true, validateWith = ReadablePathValidator.class) // public Path lociFile; // @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) // public Path outputFile; // @Parameter(names = { "-m", "--max" }, description = "Autocorrelation limit (bp)") // public int limit = 200; // // @Override // public void run() throws IOException { // try (WigFileReader wig = WigFileReader.autodetect(inputFile); // IntervalFileReader<? extends Interval> loci = IntervalFileReader.autodetect(lociFile); // BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { // log.debug("Computing autocorrelation for each window"); // int skipped = 0; // for (Interval interval : loci) { // float[] data; // try { // data = wig.query(interval).getValues(); // } catch (IOException | WigFileException e) { // log.debug("Skipping interval: " + interval.toString()); // skipped++; // continue; // } // // // Compute the autocorrelation // float[] auto = FFTUtils.autocovariance(data, limit); // // // Write to output // writer.write(interval.toBed()); // for (int i = 0; i < auto.length; i++) { // writer.write("\t" + auto[i]); // } // writer.newLine(); // } // // log.info("Skipped " + skipped + " intervals"); // } // } // // public static void main(String[] args) { // new Autocorrelation().instanceMain(args); // } // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.ngs.Autocorrelation;
package edu.unc.genomics.wigmath; /** * Output a summary of a (Big)Wig file with information about the chromosomes, * contigs, and statistics about the data. * * @author timpalpant * */ public class Summary extends CommandLineTool { private static final Logger log = Logger.getLogger(Autocorrelation.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/ngs/Autocorrelation.java // public class Autocorrelation extends CommandLineTool { // // private static final Logger log = Logger.getLogger(Autocorrelation.class); // // @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) // public Path inputFile; // @Parameter(names = { "-l", "--loci" }, description = "Genomic loci (Bed format)", required = true, validateWith = ReadablePathValidator.class) // public Path lociFile; // @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) // public Path outputFile; // @Parameter(names = { "-m", "--max" }, description = "Autocorrelation limit (bp)") // public int limit = 200; // // @Override // public void run() throws IOException { // try (WigFileReader wig = WigFileReader.autodetect(inputFile); // IntervalFileReader<? extends Interval> loci = IntervalFileReader.autodetect(lociFile); // BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { // log.debug("Computing autocorrelation for each window"); // int skipped = 0; // for (Interval interval : loci) { // float[] data; // try { // data = wig.query(interval).getValues(); // } catch (IOException | WigFileException e) { // log.debug("Skipping interval: " + interval.toString()); // skipped++; // continue; // } // // // Compute the autocorrelation // float[] auto = FFTUtils.autocovariance(data, limit); // // // Write to output // writer.write(interval.toBed()); // for (int i = 0; i < auto.length; i++) { // writer.write("\t" + auto[i]); // } // writer.newLine(); // } // // log.info("Skipped " + skipped + " intervals"); // } // } // // public static void main(String[] args) { // new Autocorrelation().instanceMain(args); // } // } // Path: src/edu/unc/genomics/wigmath/Summary.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.ngs.Autocorrelation; package edu.unc.genomics.wigmath; /** * Output a summary of a (Big)Wig file with information about the chromosomes, * contigs, and statistics about the data. * * @author timpalpant * */ public class Summary extends CommandLineTool { private static final Logger log = Logger.getLogger(Autocorrelation.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/SplitReads.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter;
package edu.unc.genomics.ngs; /** * This tool splits sequencing reads into bins * * @author timpalpant * */ public class SplitReads extends CommandLineTool { private static final Logger log = Logger.getLogger(SplitReads.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/SplitReads.java import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter; package edu.unc.genomics.ngs; /** * This tool splits sequencing reads into bins * * @author timpalpant * */ public class SplitReads extends CommandLineTool { private static final Logger log = Logger.getLogger(SplitReads.class);
@Parameter(names = { "-i", "--input" }, required = true, description = "Input file", validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Subtract.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Subtract two (Big)Wig files * * @author timpalpant * */ public class Subtract extends WigMathTool { private static final Logger log = Logger.getLogger(Subtract.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Subtract.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Subtract two (Big)Wig files * * @author timpalpant * */ public class Subtract extends WigMathTool { private static final Logger log = Logger.getLogger(Subtract.class);
@Parameter(names = { "-m", "--minuend" }, description = "Minuend (top - file 1)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FindAbsoluteMaxima.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayUtils.java // public class ArrayUtils { // // /** // * Get the index of the maximum (largest) value in an array In the event of a // * tie, the first index is returned // * // * @param x // * a vector of values // * @return the index of the largest element in x // */ // public static int maxIndex(float[] x) { // float maxValue = -Float.MAX_VALUE; // int maxIndex = -1; // for (int i = 0; i < x.length; i++) { // if (x[i] > maxValue) { // maxValue = x[i]; // maxIndex = i; // } // } // // return maxIndex; // } // // public static float[] mapToFloat(int[] data) { // float[] ret = new float[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = data[i]; // } // return ret; // } // // public static int[] mapToInt(float[] data) { // int[] ret = new int[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = (int) data[i]; // } // return ret; // } // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayUtils;
package edu.unc.genomics.ngs; /** * For a set of intervals, this tool finds the location of the largest value in * a Wig file for each interval. * * @author timpalpant * */ public class FindAbsoluteMaxima extends CommandLineTool { private static final Logger log = Logger.getLogger(FindAbsoluteMaxima.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayUtils.java // public class ArrayUtils { // // /** // * Get the index of the maximum (largest) value in an array In the event of a // * tie, the first index is returned // * // * @param x // * a vector of values // * @return the index of the largest element in x // */ // public static int maxIndex(float[] x) { // float maxValue = -Float.MAX_VALUE; // int maxIndex = -1; // for (int i = 0; i < x.length; i++) { // if (x[i] > maxValue) { // maxValue = x[i]; // maxIndex = i; // } // } // // return maxIndex; // } // // public static float[] mapToFloat(int[] data) { // float[] ret = new float[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = data[i]; // } // return ret; // } // // public static int[] mapToInt(float[] data) { // int[] ret = new int[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = (int) data[i]; // } // return ret; // } // } // Path: src/edu/unc/genomics/ngs/FindAbsoluteMaxima.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayUtils; package edu.unc.genomics.ngs; /** * For a set of intervals, this tool finds the location of the largest value in * a Wig file for each interval. * * @author timpalpant * */ public class FindAbsoluteMaxima extends CommandLineTool { private static final Logger log = Logger.getLogger(FindAbsoluteMaxima.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>();
@Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FindAbsoluteMaxima.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayUtils.java // public class ArrayUtils { // // /** // * Get the index of the maximum (largest) value in an array In the event of a // * tie, the first index is returned // * // * @param x // * a vector of values // * @return the index of the largest element in x // */ // public static int maxIndex(float[] x) { // float maxValue = -Float.MAX_VALUE; // int maxIndex = -1; // for (int i = 0; i < x.length; i++) { // if (x[i] > maxValue) { // maxValue = x[i]; // maxIndex = i; // } // } // // return maxIndex; // } // // public static float[] mapToFloat(int[] data) { // float[] ret = new float[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = data[i]; // } // return ret; // } // // public static int[] mapToInt(float[] data) { // int[] ret = new int[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = (int) data[i]; // } // return ret; // } // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayUtils;
@Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; private List<WigFileReader> wigs = new ArrayList<>(); @Override public void run() throws IOException { log.debug("Initializing input Wig file(s)"); for (String inputFile : inputFiles) { wigs.add(WigFileReader.autodetect(Paths.get(inputFile))); } log.debug("Initializing output file"); int count = 0, skipped = 0; try (IntervalFileReader<? extends Interval> reader = IntervalFileReader.autodetect(lociFile); BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { writer.write("#Chr\tStart\tStop\tID\tValue\tStrand"); for (String inputFile : inputFiles) { Path p = Paths.get(inputFile); writer.write("\t" + p.getFileName().toString()); } writer.newLine(); log.debug("Iterating over all intervals and finding maxima"); for (Interval interval : reader) { writer.write(interval.toBed()); for (WigFileReader wig : wigs) { try { float[] data = wig.query(interval).getValues(); int dir = interval.isWatson() ? 1 : -1;
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayUtils.java // public class ArrayUtils { // // /** // * Get the index of the maximum (largest) value in an array In the event of a // * tie, the first index is returned // * // * @param x // * a vector of values // * @return the index of the largest element in x // */ // public static int maxIndex(float[] x) { // float maxValue = -Float.MAX_VALUE; // int maxIndex = -1; // for (int i = 0; i < x.length; i++) { // if (x[i] > maxValue) { // maxValue = x[i]; // maxIndex = i; // } // } // // return maxIndex; // } // // public static float[] mapToFloat(int[] data) { // float[] ret = new float[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = data[i]; // } // return ret; // } // // public static int[] mapToInt(float[] data) { // int[] ret = new int[data.length]; // for (int i = 0; i < data.length; i++) { // ret[i] = (int) data[i]; // } // return ret; // } // } // Path: src/edu/unc/genomics/ngs/FindAbsoluteMaxima.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayUtils; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; private List<WigFileReader> wigs = new ArrayList<>(); @Override public void run() throws IOException { log.debug("Initializing input Wig file(s)"); for (String inputFile : inputFiles) { wigs.add(WigFileReader.autodetect(Paths.get(inputFile))); } log.debug("Initializing output file"); int count = 0, skipped = 0; try (IntervalFileReader<? extends Interval> reader = IntervalFileReader.autodetect(lociFile); BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { writer.write("#Chr\tStart\tStop\tID\tValue\tStrand"); for (String inputFile : inputFiles) { Path p = Paths.get(inputFile); writer.write("\t" + p.getFileName().toString()); } writer.newLine(); log.debug("Iterating over all intervals and finding maxima"); for (Interval interval : reader) { writer.write(interval.toBed()); for (WigFileReader wig : wigs) { try { float[] data = wig.query(interval).getValues(); int dir = interval.isWatson() ? 1 : -1;
int maxima = interval.getStart() + dir * ArrayUtils.maxIndex(data);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/IntervalStats.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic;
package edu.unc.genomics.ngs; /** * For each interval, compute the mean/min/max/total/coverage of data in a * (Big)Wig file over that interval. * * @author timpalpant * */ public class IntervalStats extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<>();
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // } // Path: src/edu/unc/genomics/ngs/IntervalStats.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic; package edu.unc.genomics.ngs; /** * For each interval, compute the mean/min/max/total/coverage of data in a * (Big)Wig file over that interval. * * @author timpalpant * */ public class IntervalStats extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<>();
@Parameter(names = { "-l", "--loci" }, description = "Loci file (Bed)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/ExtractRegion.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter;
package edu.unc.genomics.wigmath; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractRegion.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/wigmath/ExtractRegion.java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter; package edu.unc.genomics.wigmath; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractRegion.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (BigWig/Wig)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/ExtractRegion.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter;
package edu.unc.genomics.wigmath; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractRegion.class); @Parameter(names = { "-i", "--input" }, description = "Input file (BigWig/Wig)", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-c", "--chr" }, description = "Chromosome", required = true) public String chr; @Parameter(names = { "-s", "--start" }, description = "Start base pair") public int start = -1; @Parameter(names = { "-e", "--stop" }, description = "Stop base pair") public int stop = -1; @Parameter(names = { "--chunk" }, description = "Size to chunk each chromosome into when processing (bp)") public int chunkSize = DEFAULT_CHUNK_SIZE; @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") public boolean fixedStep = false; @Parameter(names = { "-o", "--output" }, description = "Output file (wig)", required = true) public Path outputFile; @Override public void run() throws IOException { try (WigFileReader reader = WigFileReader.autodetect(inputFile)) { if (!reader.includes(chr)) {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/wigmath/ExtractRegion.java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter; package edu.unc.genomics.wigmath; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractRegion.class); @Parameter(names = { "-i", "--input" }, description = "Input file (BigWig/Wig)", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-c", "--chr" }, description = "Chromosome", required = true) public String chr; @Parameter(names = { "-s", "--start" }, description = "Start base pair") public int start = -1; @Parameter(names = { "-e", "--stop" }, description = "Stop base pair") public int stop = -1; @Parameter(names = { "--chunk" }, description = "Size to chunk each chromosome into when processing (bp)") public int chunkSize = DEFAULT_CHUNK_SIZE; @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") public boolean fixedStep = false; @Parameter(names = { "-o", "--output" }, description = "Output file (wig)", required = true) public Path outputFile; @Override public void run() throws IOException { try (WigFileReader reader = WigFileReader.autodetect(inputFile)) { if (!reader.includes(chr)) {
throw new CommandLineToolException("Wig file does not contain chromosome " + chr);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Average.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Average multiple Wig files base pair by base pair * * @author timpalpant * */ public class Average extends WigMathTool { private static final Logger log = Logger.getLogger(Average.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Average.java import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Average multiple Wig files base pair by base pair * * @author timpalpant * */ public class Average extends WigMathTool { private static final Logger log = Logger.getLogger(Average.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
throw new CommandLineToolException("No reason to average < 2 files.");
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Multiply.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Multiply (Big)Wig files base pair by base pair * * @author timpalpant * */ public class Multiply extends WigMathTool { private static final Logger log = Logger.getLogger(Multiply.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { log.debug("Initializing input files"); for (String inputFile : inputFiles) { try { addInputFile(WigFileReader.autodetect(Paths.get(inputFile))); } catch (IOException e) {
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Multiply.java import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Multiply (Big)Wig files base pair by base pair * * @author timpalpant * */ public class Multiply extends WigMathTool { private static final Logger log = Logger.getLogger(Multiply.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { log.debug("Initializing input files"); for (String inputFile : inputFiles) { try { addInputFile(WigFileReader.autodetect(Paths.get(inputFile))); } catch (IOException e) {
throw new CommandLineToolException(e);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Downsample.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic;
package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // } // Path: src/edu/unc/genomics/wigmath/Downsample.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic; package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Downsample.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic;
package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-w", "--window" }, description = "Window size (bp)") public int windowSize = 100; @Parameter(names = { "-m", "--metric" }, description = "Downsampling metric (coverage/total/mean/min/max)") public String metric = "mean"; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; @Override public void run() throws IOException {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // } // Path: src/edu/unc/genomics/wigmath/Downsample.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic; package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-w", "--window" }, description = "Window size (bp)") public int windowSize = 100; @Parameter(names = { "-m", "--metric" }, description = "Downsampling metric (coverage/total/mean/min/max)") public String metric = "mean"; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; @Override public void run() throws IOException {
WigStatistic dsm = WigStatistic.fromName(metric);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Downsample.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic;
package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-w", "--window" }, description = "Window size (bp)") public int windowSize = 100; @Parameter(names = { "-m", "--metric" }, description = "Downsampling metric (coverage/total/mean/min/max)") public String metric = "mean"; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; @Override public void run() throws IOException { WigStatistic dsm = WigStatistic.fromName(metric); if (dsm == null) { log.error("Unknown downsampling metric: " + metric);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/WigStatistic.java // public enum WigStatistic { // COVERAGE("coverage"), TOTAL("total"), MEAN("mean"), MIN("min"), MAX("max"); // // private String name; // // WigStatistic(final String name) { // this.name = name; // } // // public static WigStatistic fromName(final String name) { // for (WigStatistic dsm : WigStatistic.values()) { // if (dsm.getName().equalsIgnoreCase(name)) { // return dsm; // } // } // // return null; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // } // Path: src/edu/unc/genomics/wigmath/Downsample.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.WigStatistic; package edu.unc.genomics.wigmath; /** * Downsample a high-resolution Wig file into larger windows so that it has * smaller file size * * @author timpalpant * */ public class Downsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Downsample.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-w", "--window" }, description = "Window size (bp)") public int windowSize = 100; @Parameter(names = { "-m", "--metric" }, description = "Downsampling metric (coverage/total/mean/min/max)") public String metric = "mean"; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; @Override public void run() throws IOException { WigStatistic dsm = WigStatistic.fromName(metric); if (dsm == null) { log.error("Unknown downsampling metric: " + metric);
throw new CommandLineToolException("Unknown downsampling metric: " + metric
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/MovingEntropy.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Smooth a (Big)Wig file with a moving average filter * @author timpalpant * */ public class MovingEntropy extends WigMathTool { @Parameter(names = {"-i", "--input"}, description = "Input file",
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/MovingEntropy.java import java.io.IOException; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Smooth a (Big)Wig file with a moving average filter * @author timpalpant * */ public class MovingEntropy extends WigMathTool { @Parameter(names = {"-i", "--input"}, description = "Input file",
required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/converters/FastqIlluminaToSanger.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import net.sf.picard.fastq.FastqReader; import net.sf.picard.fastq.FastqRecord; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator;
package edu.unc.genomics.converters; /** * Converts a FASTQ file with Illumina quality scores (Phred+64) to Sanger * quality scores (Phred+33) * * @author timpalpant * */ public class FastqIlluminaToSanger extends CommandLineTool { private static final Logger log = Logger.getLogger(FastqIlluminaToSanger.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/converters/FastqIlluminaToSanger.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import net.sf.picard.fastq.FastqReader; import net.sf.picard.fastq.FastqRecord; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; package edu.unc.genomics.converters; /** * Converts a FASTQ file with Illumina quality scores (Phred+64) to Sanger * quality scores (Phred+33) * * @author timpalpant * */ public class FastqIlluminaToSanger extends CommandLineTool { private static final Logger log = Logger.getLogger(FastqIlluminaToSanger.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (FASTQ, Illumina)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FindOutlierRegions.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedGraphFileWriter; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.ngs; /** * Finds regions of a Wig file that differ significantly from the mean, such as * CNVs or deletions. * * @author timpalpant * */ public class FindOutlierRegions extends CommandLineTool { private static final Logger log = Logger.getLogger(FindOutlierRegions.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/FindOutlierRegions.java import java.io.IOException; import java.nio.file.Path; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.BedGraphFileWriter; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.ngs; /** * Finds regions of a Wig file that differ significantly from the mean, such as * CNVs or deletions. * * @author timpalpant * */ public class FindOutlierRegions extends CommandLineTool { private static final Logger log = Logger.getLogger(FindOutlierRegions.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/dna/DNAPropertyCalculator.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/Samtools.java // public class Samtools { // // private static final Logger log = Logger.getLogger(Samtools.class); // // /** // * Index a FASTA file with 'samtools faidx' // * // * @param p // * the FASTA file to index // * @throws Exception // * if the index is not created successfully // */ // public static void indexFasta(Path p) throws Exception { // log.debug("Attempting to generate FASTA index by calling 'samtools faidx'"); // // try { // Process proc = new ProcessBuilder("samtools", "faidx", p.toString()).start(); // proc.waitFor(); // } catch (Exception e) { // log.error("Error attempting to call 'samtools faidx'. Is samtools available in the PATH?"); // } finally { // if (!IndexedFastaSequenceFile.canCreateIndexedFastaReader(p.toFile())) { // log.error("Could not create FASTA index for file " + p); // throw new Exception("Could not create FASTA index for file " + p); // } // } // } // }
import java.io.IOException; import java.nio.file.Path; import net.sf.picard.reference.FastaSequenceIndex; import net.sf.picard.reference.FastaSequenceIndexEntry; import net.sf.picard.reference.IndexedFastaSequenceFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.samtools.util.StringUtil; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.genomeview.dnaproperties.DNAProperty; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileWriter; import edu.unc.utils.Samtools;
package edu.unc.genomics.dna; /** * This tool calculates DNA properties from a table lookup and creates a Wig * file with the property for each position * * @author timpalpant * */ public class DNAPropertyCalculator extends CommandLineTool { private static final Logger log = Logger.getLogger(DNAPropertyCalculator.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/Samtools.java // public class Samtools { // // private static final Logger log = Logger.getLogger(Samtools.class); // // /** // * Index a FASTA file with 'samtools faidx' // * // * @param p // * the FASTA file to index // * @throws Exception // * if the index is not created successfully // */ // public static void indexFasta(Path p) throws Exception { // log.debug("Attempting to generate FASTA index by calling 'samtools faidx'"); // // try { // Process proc = new ProcessBuilder("samtools", "faidx", p.toString()).start(); // proc.waitFor(); // } catch (Exception e) { // log.error("Error attempting to call 'samtools faidx'. Is samtools available in the PATH?"); // } finally { // if (!IndexedFastaSequenceFile.canCreateIndexedFastaReader(p.toFile())) { // log.error("Could not create FASTA index for file " + p); // throw new Exception("Could not create FASTA index for file " + p); // } // } // } // } // Path: src/edu/unc/genomics/dna/DNAPropertyCalculator.java import java.io.IOException; import java.nio.file.Path; import net.sf.picard.reference.FastaSequenceIndex; import net.sf.picard.reference.FastaSequenceIndexEntry; import net.sf.picard.reference.IndexedFastaSequenceFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.samtools.util.StringUtil; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.genomeview.dnaproperties.DNAProperty; import com.beust.jcommander.Parameter; import edu.ucsc.genome.TrackHeader; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileWriter; import edu.unc.utils.Samtools; package edu.unc.genomics.dna; /** * This tool calculates DNA properties from a table lookup and creates a Wig * file with the property for each position * * @author timpalpant * */ public class DNAPropertyCalculator extends CommandLineTool { private static final Logger log = Logger.getLogger(DNAPropertyCalculator.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (FASTA)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FilterRegions.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter;
package edu.unc.genomics.ngs; /** * Removes regions of a Wig file * * @author timpalpant * */ public class FilterRegions extends CommandLineTool { private static final Logger log = Logger.getLogger(FilterRegions.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/FilterRegions.java import java.io.IOException; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter; package edu.unc.genomics.ngs; /** * Removes regions of a Wig file * * @author timpalpant * */ public class FilterRegions extends CommandLineTool { private static final Logger log = Logger.getLogger(FilterRegions.class);
@Parameter(names = { "-i", "--input" }, description = "Input (Big)wig", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/FilterRegions.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter;
int stop = reader.getChrStop(chr); log.debug("Processing chromosome " + chr + " region " + bp + "-" + stop); // Process the chromosome in chunks while (bp < stop) { int chunkStart = bp; int chunkStop = Math.min(bp + DEFAULT_CHUNK_SIZE - 1, stop); Interval chunk = new Interval(chr, chunkStart, chunkStop); log.debug("Processing chunk " + chunk); try { Contig contig = reader.query(chunk); Iterator<? extends Interval> it = loci.query(contig); int start = contig.getStart(); // Copy the data up to the excluded point, then skip past the // excluded point while (it.hasNext()) { Interval exclude = it.next(); log.debug("Skipping interval " + exclude); if (exclude.low() - 1 > start) { writer.write(contig.copy(start, exclude.low() - 1)); } start = exclude.high() + 1; } // Copy the remaining data, if there is any if (start <= contig.getStop()) { writer.write(contig.copy(start, contig.getStop())); } } catch (WigFileException e) {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/FilterRegions.java import java.io.IOException; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileWriter; int stop = reader.getChrStop(chr); log.debug("Processing chromosome " + chr + " region " + bp + "-" + stop); // Process the chromosome in chunks while (bp < stop) { int chunkStart = bp; int chunkStop = Math.min(bp + DEFAULT_CHUNK_SIZE - 1, stop); Interval chunk = new Interval(chr, chunkStart, chunkStop); log.debug("Processing chunk " + chunk); try { Contig contig = reader.query(chunk); Iterator<? extends Interval> it = loci.query(contig); int start = contig.getStart(); // Copy the data up to the excluded point, then skip past the // excluded point while (it.hasNext()) { Interval exclude = it.next(); log.debug("Skipping interval " + exclude); if (exclude.low() - 1 > start) { writer.write(contig.copy(start, exclude.low() - 1)); } start = exclude.high() + 1; } // Copy the remaining data, if there is any if (start <= contig.getStop()) { writer.write(contig.copy(start, contig.getStop())); } } catch (WigFileException e) {
throw new CommandLineToolException("Wig file error while processing chunk " + chr + ":" + chunkStart + "-"
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/ReadLengthDistributionMatrix.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader;
package edu.unc.genomics.ngs; /** * Creates a heatmap matrix of sequencing read coverage separated by read length * See Floer M, et al. (2010) A RSC/nucleosome complex determines chromatin * architecture and facilitates activator binding. Cell 141: 407-418 for * examples. * * @author timpalpant * */ public class ReadLengthDistributionMatrix extends CommandLineTool { private static final Logger log = Logger.getLogger(ReadLengthDistributionMatrix.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/ReadLengthDistributionMatrix.java import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; package edu.unc.genomics.ngs; /** * Creates a heatmap matrix of sequencing read coverage separated by read length * See Floer M, et al. (2010) A RSC/nucleosome complex determines chromatin * architecture and facilitates activator binding. Cell 141: 407-418 for * examples. * * @author timpalpant * */ public class ReadLengthDistributionMatrix extends CommandLineTool { private static final Logger log = Logger.getLogger(ReadLengthDistributionMatrix.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (reads)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/Subsample.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.util.Random; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter;
package edu.unc.genomics.ngs; /** * Randomly select N reads out of a total of M * * @author timpalpant * */ public class Subsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Subsample.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/Subsample.java import java.io.IOException; import java.nio.file.Path; import java.util.Random; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter; package edu.unc.genomics.ngs; /** * Randomly select N reads out of a total of M * * @author timpalpant * */ public class Subsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Subsample.class);
@Parameter(names = { "-i", "--input" }, required = true, description = "Input file", validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/Subsample.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.util.Random; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter;
package edu.unc.genomics.ngs; /** * Randomly select N reads out of a total of M * * @author timpalpant * */ public class Subsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Subsample.class); @Parameter(names = { "-i", "--input" }, required = true, description = "Input file", validateWith = ReadablePathValidator.class) public Path input; @Parameter(names = { "-n", "--select" }, required = true, description = "Number of entries to select") public int n; @Parameter(names = { "-o", "--output" }, required = true, description = "Output file") public Path output; @Override public void run() throws IOException { try (IntervalFileReader<? extends Interval> reader = IntervalFileReader.autodetect(input); IntervalFileWriter<Interval> writer = new IntervalFileWriter<>(output)) { int nRemaining = reader.count(); log.info("Input file has " + nRemaining + " entries"); if (n >= reader.count()) {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/Subsample.java import java.io.IOException; import java.nio.file.Path; import java.util.Random; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.IntervalFileWriter; package edu.unc.genomics.ngs; /** * Randomly select N reads out of a total of M * * @author timpalpant * */ public class Subsample extends CommandLineTool { private static final Logger log = Logger.getLogger(Subsample.class); @Parameter(names = { "-i", "--input" }, required = true, description = "Input file", validateWith = ReadablePathValidator.class) public Path input; @Parameter(names = { "-n", "--select" }, required = true, description = "Number of entries to select") public int n; @Parameter(names = { "-o", "--output" }, required = true, description = "Output file") public Path output; @Override public void run() throws IOException { try (IntervalFileReader<? extends Interval> reader = IntervalFileReader.autodetect(input); IntervalFileWriter<Interval> writer = new IntervalFileWriter<>(output)) { int nRemaining = reader.count(); log.info("Input file has " + nRemaining + " entries"); if (n >= reader.count()) {
throw new CommandLineToolException("Cannot select " + n + " entries from a file with " + nRemaining);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/SplitWigIntervals.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter; import edu.unc.genomics.io.WigFileException; import edu.ucsc.genome.TrackHeader;
package edu.unc.genomics.ngs; /** * For each interval, output a new Wig file of data * @author timpalpant * */ public class SplitWigIntervals extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(names = {"-i", "--input"}, description = "Input file (Wig)",
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/SplitWigIntervals.java import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.Contig; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileWriter; import edu.unc.genomics.io.WigFileException; import edu.ucsc.genome.TrackHeader; package edu.unc.genomics.ngs; /** * For each interval, output a new Wig file of data * @author timpalpant * */ public class SplitWigIntervals extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalStats.class); @Parameter(names = {"-i", "--input"}, description = "Input file (Wig)",
required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/GaussianSmooth.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Smooth a Wig file with a Gaussian filter * * @author timpalpant * */ public class GaussianSmooth extends WigMathTool { private static final Logger log = Logger.getLogger(GaussianSmooth.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/GaussianSmooth.java import java.io.IOException; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Contig; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Smooth a Wig file with a Gaussian filter * * @author timpalpant * */ public class GaussianSmooth extends WigMathTool { private static final Logger log = Logger.getLogger(GaussianSmooth.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Shift.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Shift a Wig file to have a specified mean * * @author timpalpant * */ public class Shift extends WigMathTool { private static final Logger log = Logger.getLogger(Shift.class);
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Shift.java import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Shift a Wig file to have a specified mean * * @author timpalpant * */ public class Shift extends WigMathTool { private static final Logger log = Logger.getLogger(Shift.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/ExtractDataFromRegion.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // }
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader;
package edu.unc.genomics.ngs; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractDataFromRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractDataFromRegion.class); @Parameter(description = "Input files (BigWig/Wig)", required = true) public List<String> inputFiles = new ArrayList<String>(); @Parameter(names = { "-c", "--chr" }, description = "Chromosome", required = true) public String chr; @Parameter(names = { "-s", "--start" }, description = "Start base pair", required = true) public int start; @Parameter(names = { "-e", "--stop" }, description = "Stop base pair", required = true) public int stop; @Parameter(names = { "-o", "--output" }, description = "Output file (tabular)", required = true) public Path outputFile; @Override public void run() throws IOException { // Query each wig file and get the data for the region log.debug("Loading data for region from " + inputFiles.size() + " wig files"); Interval region = new Interval(chr, start, stop); float[][] data = new float[inputFiles.size()][region.length()]; for (int i = 0; i < inputFiles.size(); i++) { try (WigFileReader reader = WigFileReader.autodetect(Paths.get(inputFiles.get(i)))) { data[i] = reader.query(region).getValues(); } catch (WigFileException e) {
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // Path: src/edu/unc/genomics/ngs/ExtractDataFromRegion.java import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.io.WigFileReader; package edu.unc.genomics.ngs; /** * Extracts the values from a (Big)Wig file for a given interval * * @author timpalpant * */ public class ExtractDataFromRegion extends CommandLineTool { private static final Logger log = Logger.getLogger(ExtractDataFromRegion.class); @Parameter(description = "Input files (BigWig/Wig)", required = true) public List<String> inputFiles = new ArrayList<String>(); @Parameter(names = { "-c", "--chr" }, description = "Chromosome", required = true) public String chr; @Parameter(names = { "-s", "--start" }, description = "Start base pair", required = true) public int start; @Parameter(names = { "-e", "--stop" }, description = "Stop base pair", required = true) public int stop; @Parameter(names = { "-o", "--output" }, description = "Output file (tabular)", required = true) public Path outputFile; @Override public void run() throws IOException { // Query each wig file and get the data for the region log.debug("Loading data for region from " + inputFiles.size() + " wig files"); Interval region = new Interval(chr, start, stop); float[][] data = new float[inputFiles.size()][region.length()]; for (int i = 0; i < inputFiles.size(); i++) { try (WigFileReader reader = WigFileReader.autodetect(Paths.get(inputFiles.get(i)))) { data[i] = reader.query(region).getValues(); } catch (WigFileException e) {
throw new CommandLineToolException(e);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/WaveletTransform.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayScaler.java // public class ArrayScaler { // // private UnivariateFunction interp; // // /** // * Create a new ArrayScaler // * // * @param x // * the seed array to downsample/upsample // */ // public ArrayScaler(double[] x) { // double[] indices = new double[x.length]; // for (int i = 0; i < indices.length; i++) { // indices[i] = ((double) i) / (x.length - 1); // } // // UnivariateInterpolator interpolator = new SplineInterpolator(); // interp = interpolator.interpolate(indices, x); // } // // /** // * Interpolate to create a new scaled vector of length l // * // * @param l // * the desired vector length // * @return a new vector of length l created by interpolating x // */ // public double[] getScaled(int l) { // double[] stretched = new double[l]; // for (int i = 0; i < l; i++) { // stretched[i] = interp.value(((double) i) / l); // } // return stretched; // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayScaler;
package edu.unc.genomics.ngs; /** * This tool performs a Wavelet scaling analysis on data from a genomic interval * * @author timpalpant * */ public class WaveletTransform extends CommandLineTool { private static final Logger log = Logger.getLogger(WaveletTransform.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/ArrayScaler.java // public class ArrayScaler { // // private UnivariateFunction interp; // // /** // * Create a new ArrayScaler // * // * @param x // * the seed array to downsample/upsample // */ // public ArrayScaler(double[] x) { // double[] indices = new double[x.length]; // for (int i = 0; i < indices.length; i++) { // indices[i] = ((double) i) / (x.length - 1); // } // // UnivariateInterpolator interpolator = new SplineInterpolator(); // interp = interpolator.interpolate(indices, x); // } // // /** // * Interpolate to create a new scaled vector of length l // * // * @param l // * the desired vector length // * @return a new vector of length l created by interpolating x // */ // public double[] getScaled(int l) { // double[] stretched = new double[l]; // for (int i = 0; i < l; i++) { // stretched[i] = interp.value(((double) i) / l); // } // return stretched; // } // } // Path: src/edu/unc/genomics/ngs/WaveletTransform.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.utils.ArrayScaler; package edu.unc.genomics.ngs; /** * This tool performs a Wavelet scaling analysis on data from a genomic interval * * @author timpalpant * */ public class WaveletTransform extends CommandLineTool { private static final Logger log = Logger.getLogger(WaveletTransform.class);
@Parameter(names = { "-i", "--input" }, description = "Input file (Wig)", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/ngs/IntervalLengthDistribution.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.Frequency; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader;
package edu.unc.genomics.ngs; /** * Generate a histogram of interval lengths, such as read lengths or gene * lengths * * @author timpalpant * */ public class IntervalLengthDistribution extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalLengthDistribution.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // Path: src/edu/unc/genomics/ngs/IntervalLengthDistribution.java import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.math3.stat.Frequency; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.IntervalFileReader; package edu.unc.genomics.ngs; /** * Generate a histogram of interval lengths, such as read lengths or gene * lengths * * @author timpalpant * */ public class IntervalLengthDistribution extends CommandLineTool { private static final Logger log = Logger.getLogger(IntervalLengthDistribution.class);
@Parameter(names = { "-i", "--input" }, description = "Interval file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/converters/RomanNumeralize.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/RomanNumeral.java // public class RomanNumeral { // // final static RomanValue[] ROMAN_VALUE_TABLE = { new RomanValue(1000, "M"), new RomanValue(900, "CM"), // new RomanValue(500, "D"), new RomanValue(400, "CD"), new RomanValue(100, "C"), new RomanValue(90, "XC"), // new RomanValue(50, "L"), new RomanValue(40, "XL"), new RomanValue(10, "X"), new RomanValue(9, "IX"), // new RomanValue(5, "V"), new RomanValue(4, "IV"), new RomanValue(1, "I") }; // // /** // * Convert an int to Roman numeral // * // * @param n // * an integer between 1-3999 // * @return n as a Roman numeral // */ // public static String int2roman(int n) { // if (n >= 4000 || n < 1) { // throw new NumberFormatException("Numbers must be in range 1-3999"); // } // // // ... Start with largest value, and work toward smallest. // StringBuilder result = new StringBuilder(10); // for (RomanValue equiv : ROMAN_VALUE_TABLE) { // // ... Remove as many of this value as possible (maybe none). // while (n >= equiv.intVal) { // n -= equiv.intVal; // Subtract value. // result.append(equiv.romVal); // Add roman equivalent. // } // } // // return result.toString(); // } // // private static class RomanValue { // // ... No need to make this fields private because they are // // used only in this private value class. // int intVal; // Integer value. // String romVal; // Equivalent roman numeral. // // RomanValue(int dec, String rom) { // this.intVal = dec; // this.romVal = rom; // } // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.utils.RomanNumeral;
package edu.unc.genomics.converters; /** * Convert instances of "chr12" to "chrXII" in a text file, etc. * * @author timpalpant * */ public class RomanNumeralize extends CommandLineTool { private static final Logger log = Logger.getLogger(RomanNumeralize.class);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/RomanNumeral.java // public class RomanNumeral { // // final static RomanValue[] ROMAN_VALUE_TABLE = { new RomanValue(1000, "M"), new RomanValue(900, "CM"), // new RomanValue(500, "D"), new RomanValue(400, "CD"), new RomanValue(100, "C"), new RomanValue(90, "XC"), // new RomanValue(50, "L"), new RomanValue(40, "XL"), new RomanValue(10, "X"), new RomanValue(9, "IX"), // new RomanValue(5, "V"), new RomanValue(4, "IV"), new RomanValue(1, "I") }; // // /** // * Convert an int to Roman numeral // * // * @param n // * an integer between 1-3999 // * @return n as a Roman numeral // */ // public static String int2roman(int n) { // if (n >= 4000 || n < 1) { // throw new NumberFormatException("Numbers must be in range 1-3999"); // } // // // ... Start with largest value, and work toward smallest. // StringBuilder result = new StringBuilder(10); // for (RomanValue equiv : ROMAN_VALUE_TABLE) { // // ... Remove as many of this value as possible (maybe none). // while (n >= equiv.intVal) { // n -= equiv.intVal; // Subtract value. // result.append(equiv.romVal); // Add roman equivalent. // } // } // // return result.toString(); // } // // private static class RomanValue { // // ... No need to make this fields private because they are // // used only in this private value class. // int intVal; // Integer value. // String romVal; // Equivalent roman numeral. // // RomanValue(int dec, String rom) { // this.intVal = dec; // this.romVal = rom; // } // } // } // Path: src/edu/unc/genomics/converters/RomanNumeralize.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.utils.RomanNumeral; package edu.unc.genomics.converters; /** * Convert instances of "chr12" to "chrXII" in a text file, etc. * * @author timpalpant * */ public class RomanNumeralize extends CommandLineTool { private static final Logger log = Logger.getLogger(RomanNumeralize.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/converters/RomanNumeralize.java
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/RomanNumeral.java // public class RomanNumeral { // // final static RomanValue[] ROMAN_VALUE_TABLE = { new RomanValue(1000, "M"), new RomanValue(900, "CM"), // new RomanValue(500, "D"), new RomanValue(400, "CD"), new RomanValue(100, "C"), new RomanValue(90, "XC"), // new RomanValue(50, "L"), new RomanValue(40, "XL"), new RomanValue(10, "X"), new RomanValue(9, "IX"), // new RomanValue(5, "V"), new RomanValue(4, "IV"), new RomanValue(1, "I") }; // // /** // * Convert an int to Roman numeral // * // * @param n // * an integer between 1-3999 // * @return n as a Roman numeral // */ // public static String int2roman(int n) { // if (n >= 4000 || n < 1) { // throw new NumberFormatException("Numbers must be in range 1-3999"); // } // // // ... Start with largest value, and work toward smallest. // StringBuilder result = new StringBuilder(10); // for (RomanValue equiv : ROMAN_VALUE_TABLE) { // // ... Remove as many of this value as possible (maybe none). // while (n >= equiv.intVal) { // n -= equiv.intVal; // Subtract value. // result.append(equiv.romVal); // Add roman equivalent. // } // } // // return result.toString(); // } // // private static class RomanValue { // // ... No need to make this fields private because they are // // used only in this private value class. // int intVal; // Integer value. // String romVal; // Equivalent roman numeral. // // RomanValue(int dec, String rom) { // this.intVal = dec; // this.romVal = rom; // } // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.utils.RomanNumeral;
package edu.unc.genomics.converters; /** * Convert instances of "chr12" to "chrXII" in a text file, etc. * * @author timpalpant * */ public class RomanNumeralize extends CommandLineTool { private static final Logger log = Logger.getLogger(RomanNumeralize.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; /** * Pattern for finding "chr12" tokens (will find "chr1" through "chr99") */ Pattern p = Pattern.compile("chr[\\d]{1,2}"); @Override public void run() throws IOException { try (BufferedReader reader = Files.newBufferedReader(inputFile, Charset.defaultCharset()); BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { log.debug("Copying input to output and replacing with Roman Numerals"); String line; while ((line = reader.readLine()) != null) { Matcher m = p.matcher(line); StringBuffer converted = new StringBuffer(line.length()); while (m.find()) { String chrNum = line.substring(m.start() + 3, m.end()); int arabic = Integer.parseInt(chrNum);
// Path: src/edu/unc/genomics/CommandLineTool.java // public abstract class CommandLineTool { // // /** // * The default bite-size to use for applications that process files in chunks // * TODO Read from a configuration file // */ // public static final int DEFAULT_CHUNK_SIZE = 10_000_000; // // /** // * Do the main computation of this tool // * // * @throws IOException // */ // public abstract void run() throws IOException; // // /** // * Parse command-line arguments and run the tool Exit on parameter exceptions // * // * @param args // */ // public void instanceMain(String[] args) throws CommandLineToolException { // // Initialize the command-line options parser // JCommander jc = new JCommander(this); // // // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles // jc.addConverterFactory(new PathFactory()); // jc.addConverterFactory(new AssemblyFactory()); // // // Set the program name to be the class name // String[] nameParts = getClass().getName().split("\\."); // String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.'); // jc.setProgramName(shortName); // // try { // jc.parse(args); // } catch (ParameterException e) { // System.err.println(e.getMessage()); // jc.usage(); // System.exit(-1); // } // // ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency(); // try { // SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT); // run(); // } catch (IOException e) { // throw new CommandLineToolException("IO error while running", e); // } finally { // SAMFileReader.setDefaultValidationStringency(stringency); // } // } // } // // Path: src/edu/unc/genomics/ReadablePathValidator.java // public class ReadablePathValidator implements IParameterValidator { // // /* // * (non-Javadoc) // * // * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String, // * java.lang.String) // */ // @Override // public void validate(String name, String value) throws ParameterException { // PathConverter converter = new PathConverter(); // Path p = converter.convert(value); // if (!Files.isReadable(p)) { // throw new ParameterException("Parameter " + name + " should be a readable file"); // } // } // // } // // Path: src/edu/unc/utils/RomanNumeral.java // public class RomanNumeral { // // final static RomanValue[] ROMAN_VALUE_TABLE = { new RomanValue(1000, "M"), new RomanValue(900, "CM"), // new RomanValue(500, "D"), new RomanValue(400, "CD"), new RomanValue(100, "C"), new RomanValue(90, "XC"), // new RomanValue(50, "L"), new RomanValue(40, "XL"), new RomanValue(10, "X"), new RomanValue(9, "IX"), // new RomanValue(5, "V"), new RomanValue(4, "IV"), new RomanValue(1, "I") }; // // /** // * Convert an int to Roman numeral // * // * @param n // * an integer between 1-3999 // * @return n as a Roman numeral // */ // public static String int2roman(int n) { // if (n >= 4000 || n < 1) { // throw new NumberFormatException("Numbers must be in range 1-3999"); // } // // // ... Start with largest value, and work toward smallest. // StringBuilder result = new StringBuilder(10); // for (RomanValue equiv : ROMAN_VALUE_TABLE) { // // ... Remove as many of this value as possible (maybe none). // while (n >= equiv.intVal) { // n -= equiv.intVal; // Subtract value. // result.append(equiv.romVal); // Add roman equivalent. // } // } // // return result.toString(); // } // // private static class RomanValue { // // ... No need to make this fields private because they are // // used only in this private value class. // int intVal; // Integer value. // String romVal; // Equivalent roman numeral. // // RomanValue(int dec, String rom) { // this.intVal = dec; // this.romVal = rom; // } // } // } // Path: src/edu/unc/genomics/converters/RomanNumeralize.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.ReadablePathValidator; import edu.unc.utils.RomanNumeral; package edu.unc.genomics.converters; /** * Convert instances of "chr12" to "chrXII" in a text file, etc. * * @author timpalpant * */ public class RomanNumeralize extends CommandLineTool { private static final Logger log = Logger.getLogger(RomanNumeralize.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-o", "--output" }, description = "Output file", required = true) public Path outputFile; /** * Pattern for finding "chr12" tokens (will find "chr1" through "chr99") */ Pattern p = Pattern.compile("chr[\\d]{1,2}"); @Override public void run() throws IOException { try (BufferedReader reader = Files.newBufferedReader(inputFile, Charset.defaultCharset()); BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) { log.debug("Copying input to output and replacing with Roman Numerals"); String line; while ((line = reader.readLine()) != null) { Matcher m = p.matcher(line); StringBuffer converted = new StringBuffer(line.length()); while (m.find()) { String chrNum = line.substring(m.start() + 3, m.end()); int arabic = Integer.parseInt(chrNum);
String roman = RomanNumeral.int2roman(arabic);
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/StandardDeviation.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * Calculate base pair by base pair variance for a set of Wig files * * @author timpalpant * */ public class StandardDeviation extends WigMathTool { private static final Logger log = Logger.getLogger(StandardDeviation.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/StandardDeviation.java import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * Calculate base pair by base pair variance for a set of Wig files * * @author timpalpant * */ public class StandardDeviation extends WigMathTool { private static final Logger log = Logger.getLogger(StandardDeviation.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
throw new CommandLineToolException("Cannot compute variance with < 2 files.");
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/Add.java
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // }
import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException;
package edu.unc.genomics.wigmath; /** * This tool will add all values in the specified Wig files base pair by base * pair. * * @author timpalpant * */ public class Add extends WigMathTool { private static final Logger log = Logger.getLogger(Add.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
// Path: src/edu/unc/genomics/CommandLineToolException.java // public class CommandLineToolException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 4740440799806133636L; // // /** // * // */ // public CommandLineToolException() { // // TODO Auto-generated constructor stub // } // // /** // * @param message // */ // public CommandLineToolException(String message) { // super(message); // // TODO Auto-generated constructor stub // } // // /** // * @param cause // */ // public CommandLineToolException(Throwable cause) { // super(cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // */ // public CommandLineToolException(String message, Throwable cause) { // super(message, cause); // // TODO Auto-generated constructor stub // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // // TODO Auto-generated constructor stub // } // // } // // Path: src/edu/unc/genomics/WigMathTool.java // public abstract class WigMathTool extends WigAnalysisTool { // // private static final Logger log = Logger.getLogger(WigMathTool.class); // // @Parameter(names = { "-f", "--fixedstep" }, description = "Force fixedStep output") // public boolean fixedStep = false; // @Parameter(names = { "-v", "--variablestep" }, description = "Force variableStep output") // public boolean variableStep = false; // @Parameter(names = { "--step" }, description = "Step size for output Wig files") // public int step = 1; // @Parameter(names = { "-o", "--output" }, required = true, description = "Output Wig file") // public Path outputFile; // // private WigFileWriter writer; // // /** // * Setup the computation, and add all input Wig files // */ // protected abstract void setup(); // // /** // * Do the computation on a chunk and return the results. Must return // * chunk.length() values (one for every base pair in chunk) // * // * @param chunk // * the interval to process // * @return the results of the computation for this chunk // * @throws IOException // * @throws WigFileException // */ // protected abstract float[] compute(Interval chunk) throws IOException, WigFileException; // // /** // * Setup the computation. Should add all input Wig files with addInputFile() // * during setup // * // * @throws IOException // */ // @Override // protected final void prepare() { // // Setup the input files // setup(); // // // Setup the output file // try { // writer = new WigFileWriter(outputFile, TrackHeader.newWiggle()); // } catch (IOException e) { // throw new CommandLineToolException("Error initializing output file " + outputFile, e); // } // } // // /** // * Shutdown the computation and do any cleanup / final processing // * // * @throws IOException // */ // @Override // protected final void shutdown() throws IOException { // writer.close(); // super.shutdown(); // } // // @Override // public final void process(Interval chunk) throws IOException, WigFileException { // float[] result = compute(chunk); // // // Verify that the computation returned the correct number of // // values for the chunk. It must either be 1 value per base pair, // // or one value per step (if the script already computed the reduction). // Contig outputContig = null; // if (result.length != chunk.length()) { // int nValues = (int) Math.ceil(((float) chunk.length()) / step); // if (result.length == nValues) { // already reduced // // assume values have already been condensed to a certain step // outputContig = new Contig(chunk, result, step); // } else { // log.error("Expected result length=" + chunk.length() + ", got=" + result.length); // throw new CommandLineToolException("Result of Wig computation is not the expected length!"); // } // } else { // 1 value per base pair // outputContig = new Contig(chunk, result); // if (step != 1) { // outputContig.setSpan(step); // } // } // // // Write the result of the computation for this chunk to disk // if (fixedStep) { // writer.writeFixedStepContig(outputContig); // } else if (variableStep) { // writer.writeVariableStepContig(outputContig); // } else { // writer.write(outputContig); // } // } // } // Path: src/edu/unc/genomics/wigmath/Add.java import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.WigMathTool; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; package edu.unc.genomics.wigmath; /** * This tool will add all values in the specified Wig files base pair by base * pair. * * @author timpalpant * */ public class Add extends WigMathTool { private static final Logger log = Logger.getLogger(Add.class); @Parameter(description = "Input files", required = true) public List<String> inputFiles = new ArrayList<String>(); @Override public void setup() { if (inputFiles.size() < 2) {
throw new CommandLineToolException("No reason to add < 2 files.");
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_IT_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // }
import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow;
/* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime; public class PrettyTimeI18n_IT_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("it"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_IT_Test.java import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime; public class PrettyTimeI18n_IT_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("it"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
if (!(timeUnit instanceof JustNow)) {
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_uk.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // }
import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle;
/* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime.i18n; /** * Created with IntelliJ IDEA. User: Tumin Alexander Date: 2012-12-13 Time: 03:33 * * reedit to Ukrainian with Eclipse). User: Ihor Lavrynuk Date: 2013-01-06 Time: 15:04 * */ public class Resources_uk extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int slavicPluralForms = 3;
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_uk.java import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime.i18n; /** * Created with IntelliJ IDEA. User: Tumin Alexander Date: 2012-12-13 Time: 03:33 * * reedit to Ukrainian with Eclipse). User: Ihor Lavrynuk Date: 2013-01-06 Time: 15:04 * */ public class Resources_uk extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int slavicPluralForms = 3;
private static class TimeFormatAided implements TimeFormat
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_pl.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // }
import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle;
/* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime.i18n; public class Resources_pl extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int polishPluralForms = 3;
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_pl.java import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime.i18n; public class Resources_pl extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int polishPluralForms = 3;
private static class TimeFormatAided implements TimeFormat
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_EL_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/impl/ResourcesTimeFormat.java // public class ResourcesTimeFormat extends SimpleTimeFormat // { // private final ResourcesTimeUnit unit; // private TimeFormat override; // private String overrideResourceBundle; // If used this bundle will override the included bundle // // public ResourcesTimeFormat(ResourcesTimeUnit unit) // { // this.unit = unit; // } // // public ResourcesTimeFormat(ResourcesTimeUnit unit, String overrideResourceBundle) // { // this.unit = unit; // this.overrideResourceBundle = overrideResourceBundle; // } // // @Override // public ResourcesTimeFormat setLocale(Locale locale) // { // ResourceBundle bundle = null; // if (overrideResourceBundle != null) { // try { // // Attempt to load the bundle that the user passed in, maybe it exists, maybe not // bundle = ResourceBundle.getBundle(overrideResourceBundle, locale); // } // catch (Exception e) { // // Throw away if the bundle doesn't contain this local // } // } // // // If the bundle doesn't exist then load the default included one // if (bundle == null) { // bundle = ResourceBundle.getBundle(unit.getResourceBundleName(), locale); // } // // if (bundle instanceof TimeFormatProvider) { // TimeFormat format = ((TimeFormatProvider) bundle).getFormatFor(unit); // if (format != null) { // this.override = format; // } // } // else { // override = null; // } // // if (override == null) { // setPattern(bundle.getString(unit.getResourceKeyPrefix() + "Pattern")); // setFuturePrefix(bundle.getString(unit.getResourceKeyPrefix() + "FuturePrefix")); // setFutureSuffix(bundle.getString(unit.getResourceKeyPrefix() + "FutureSuffix")); // setPastPrefix(bundle.getString(unit.getResourceKeyPrefix() + "PastPrefix")); // setPastSuffix(bundle.getString(unit.getResourceKeyPrefix() + "PastSuffix")); // // setSingularName(bundle.getString(unit.getResourceKeyPrefix() + "SingularName")); // setPluralName(bundle.getString(unit.getResourceKeyPrefix() + "PluralName")); // // try { // setFuturePluralName(bundle.getString(unit.getResourceKeyPrefix() + "FuturePluralName")); // } // catch (Exception e) { // } // try { // setFutureSingularName((bundle.getString(unit.getResourceKeyPrefix() + "FutureSingularName"))); // } // catch (Exception e) { // } // try { // setPastPluralName((bundle.getString(unit.getResourceKeyPrefix() + "PastPluralName"))); // } // catch (Exception e) { // } // try { // setPastSingularName((bundle.getString(unit.getResourceKeyPrefix() + "PastSingularName"))); // } // catch (Exception e) { // } // // } // // return this; // } // // @Override // public String decorate(Duration duration, String time) // { // return override == null ? super.decorate(duration, time) : override.decorate(duration, time); // } // // @Override // public String decorateUnrounded(Duration duration, String time) // { // return override == null ? super.decorateUnrounded(duration, time) : override.decorateUnrounded(duration, time); // } // // @Override // public String format(Duration duration) // { // return override == null ? super.format(duration) : override.format(duration); // } // // @Override // public String formatUnrounded(Duration duration) // { // return override == null ? super.formatUnrounded(duration) : override.formatUnrounded(duration); // } // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.impl.ResourcesTimeFormat; import org.ocpsoft.prettytime.units.Minute; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale;
Assert.assertEquals("1 μήνας Πριν από", t.format(then)); } @Test public void testNullDate() throws Exception { PrettyTime t = new PrettyTime(); final String format = t.format((Date) null); Assert.assertTrue("πριν από στιγμές".equals(format) || "στιγμές από τώρα".equals(format)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); Assert.assertEquals("στιγμές από τώρα", t.format(new Date())); } @Test public void testCalculatePreciceDuration() throws Exception { PrettyTime t = new PrettyTime(); List<Duration> preciseDuration = t.calculatePreciseDuration( new Date(System.currentTimeMillis() - (2 * 60 * 60 * 1000) - (2 * 60 * 1000))); Assert.assertEquals("2 ώρες 2 λεπτά Πριν από", t.format(preciseDuration)); Assert.assertEquals("2 ώρες 2 λεπτά", t.formatDuration(preciseDuration)); Assert.assertEquals("στιγμές από τώρα", t.format(t.calculatePreciseDuration(new Date()))); } @Test public void testCalculatePreciseDuration2() { PrettyTime prettyTime = new PrettyTime(); prettyTime.clearUnits();
// Path: core/src/main/java/org/ocpsoft/prettytime/impl/ResourcesTimeFormat.java // public class ResourcesTimeFormat extends SimpleTimeFormat // { // private final ResourcesTimeUnit unit; // private TimeFormat override; // private String overrideResourceBundle; // If used this bundle will override the included bundle // // public ResourcesTimeFormat(ResourcesTimeUnit unit) // { // this.unit = unit; // } // // public ResourcesTimeFormat(ResourcesTimeUnit unit, String overrideResourceBundle) // { // this.unit = unit; // this.overrideResourceBundle = overrideResourceBundle; // } // // @Override // public ResourcesTimeFormat setLocale(Locale locale) // { // ResourceBundle bundle = null; // if (overrideResourceBundle != null) { // try { // // Attempt to load the bundle that the user passed in, maybe it exists, maybe not // bundle = ResourceBundle.getBundle(overrideResourceBundle, locale); // } // catch (Exception e) { // // Throw away if the bundle doesn't contain this local // } // } // // // If the bundle doesn't exist then load the default included one // if (bundle == null) { // bundle = ResourceBundle.getBundle(unit.getResourceBundleName(), locale); // } // // if (bundle instanceof TimeFormatProvider) { // TimeFormat format = ((TimeFormatProvider) bundle).getFormatFor(unit); // if (format != null) { // this.override = format; // } // } // else { // override = null; // } // // if (override == null) { // setPattern(bundle.getString(unit.getResourceKeyPrefix() + "Pattern")); // setFuturePrefix(bundle.getString(unit.getResourceKeyPrefix() + "FuturePrefix")); // setFutureSuffix(bundle.getString(unit.getResourceKeyPrefix() + "FutureSuffix")); // setPastPrefix(bundle.getString(unit.getResourceKeyPrefix() + "PastPrefix")); // setPastSuffix(bundle.getString(unit.getResourceKeyPrefix() + "PastSuffix")); // // setSingularName(bundle.getString(unit.getResourceKeyPrefix() + "SingularName")); // setPluralName(bundle.getString(unit.getResourceKeyPrefix() + "PluralName")); // // try { // setFuturePluralName(bundle.getString(unit.getResourceKeyPrefix() + "FuturePluralName")); // } // catch (Exception e) { // } // try { // setFutureSingularName((bundle.getString(unit.getResourceKeyPrefix() + "FutureSingularName"))); // } // catch (Exception e) { // } // try { // setPastPluralName((bundle.getString(unit.getResourceKeyPrefix() + "PastPluralName"))); // } // catch (Exception e) { // } // try { // setPastSingularName((bundle.getString(unit.getResourceKeyPrefix() + "PastSingularName"))); // } // catch (Exception e) { // } // // } // // return this; // } // // @Override // public String decorate(Duration duration, String time) // { // return override == null ? super.decorate(duration, time) : override.decorate(duration, time); // } // // @Override // public String decorateUnrounded(Duration duration, String time) // { // return override == null ? super.decorateUnrounded(duration, time) : override.decorateUnrounded(duration, time); // } // // @Override // public String format(Duration duration) // { // return override == null ? super.format(duration) : override.format(duration); // } // // @Override // public String formatUnrounded(Duration duration) // { // return override == null ? super.formatUnrounded(duration) : override.formatUnrounded(duration); // } // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_EL_Test.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.impl.ResourcesTimeFormat; import org.ocpsoft.prettytime.units.Minute; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; Assert.assertEquals("1 μήνας Πριν από", t.format(then)); } @Test public void testNullDate() throws Exception { PrettyTime t = new PrettyTime(); final String format = t.format((Date) null); Assert.assertTrue("πριν από στιγμές".equals(format) || "στιγμές από τώρα".equals(format)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); Assert.assertEquals("στιγμές από τώρα", t.format(new Date())); } @Test public void testCalculatePreciceDuration() throws Exception { PrettyTime t = new PrettyTime(); List<Duration> preciseDuration = t.calculatePreciseDuration( new Date(System.currentTimeMillis() - (2 * 60 * 60 * 1000) - (2 * 60 * 1000))); Assert.assertEquals("2 ώρες 2 λεπτά Πριν από", t.format(preciseDuration)); Assert.assertEquals("2 ώρες 2 λεπτά", t.formatDuration(preciseDuration)); Assert.assertEquals("στιγμές από τώρα", t.format(t.calculatePreciseDuration(new Date()))); } @Test public void testCalculatePreciseDuration2() { PrettyTime prettyTime = new PrettyTime(); prettyTime.clearUnits();
Minute minutes = new Minute();
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_EL_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/impl/ResourcesTimeFormat.java // public class ResourcesTimeFormat extends SimpleTimeFormat // { // private final ResourcesTimeUnit unit; // private TimeFormat override; // private String overrideResourceBundle; // If used this bundle will override the included bundle // // public ResourcesTimeFormat(ResourcesTimeUnit unit) // { // this.unit = unit; // } // // public ResourcesTimeFormat(ResourcesTimeUnit unit, String overrideResourceBundle) // { // this.unit = unit; // this.overrideResourceBundle = overrideResourceBundle; // } // // @Override // public ResourcesTimeFormat setLocale(Locale locale) // { // ResourceBundle bundle = null; // if (overrideResourceBundle != null) { // try { // // Attempt to load the bundle that the user passed in, maybe it exists, maybe not // bundle = ResourceBundle.getBundle(overrideResourceBundle, locale); // } // catch (Exception e) { // // Throw away if the bundle doesn't contain this local // } // } // // // If the bundle doesn't exist then load the default included one // if (bundle == null) { // bundle = ResourceBundle.getBundle(unit.getResourceBundleName(), locale); // } // // if (bundle instanceof TimeFormatProvider) { // TimeFormat format = ((TimeFormatProvider) bundle).getFormatFor(unit); // if (format != null) { // this.override = format; // } // } // else { // override = null; // } // // if (override == null) { // setPattern(bundle.getString(unit.getResourceKeyPrefix() + "Pattern")); // setFuturePrefix(bundle.getString(unit.getResourceKeyPrefix() + "FuturePrefix")); // setFutureSuffix(bundle.getString(unit.getResourceKeyPrefix() + "FutureSuffix")); // setPastPrefix(bundle.getString(unit.getResourceKeyPrefix() + "PastPrefix")); // setPastSuffix(bundle.getString(unit.getResourceKeyPrefix() + "PastSuffix")); // // setSingularName(bundle.getString(unit.getResourceKeyPrefix() + "SingularName")); // setPluralName(bundle.getString(unit.getResourceKeyPrefix() + "PluralName")); // // try { // setFuturePluralName(bundle.getString(unit.getResourceKeyPrefix() + "FuturePluralName")); // } // catch (Exception e) { // } // try { // setFutureSingularName((bundle.getString(unit.getResourceKeyPrefix() + "FutureSingularName"))); // } // catch (Exception e) { // } // try { // setPastPluralName((bundle.getString(unit.getResourceKeyPrefix() + "PastPluralName"))); // } // catch (Exception e) { // } // try { // setPastSingularName((bundle.getString(unit.getResourceKeyPrefix() + "PastSingularName"))); // } // catch (Exception e) { // } // // } // // return this; // } // // @Override // public String decorate(Duration duration, String time) // { // return override == null ? super.decorate(duration, time) : override.decorate(duration, time); // } // // @Override // public String decorateUnrounded(Duration duration, String time) // { // return override == null ? super.decorateUnrounded(duration, time) : override.decorateUnrounded(duration, time); // } // // @Override // public String format(Duration duration) // { // return override == null ? super.format(duration) : override.format(duration); // } // // @Override // public String formatUnrounded(Duration duration) // { // return override == null ? super.formatUnrounded(duration) : override.formatUnrounded(duration); // } // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.impl.ResourcesTimeFormat; import org.ocpsoft.prettytime.units.Minute; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale;
} @Test public void testNullDate() throws Exception { PrettyTime t = new PrettyTime(); final String format = t.format((Date) null); Assert.assertTrue("πριν από στιγμές".equals(format) || "στιγμές από τώρα".equals(format)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); Assert.assertEquals("στιγμές από τώρα", t.format(new Date())); } @Test public void testCalculatePreciceDuration() throws Exception { PrettyTime t = new PrettyTime(); List<Duration> preciseDuration = t.calculatePreciseDuration( new Date(System.currentTimeMillis() - (2 * 60 * 60 * 1000) - (2 * 60 * 1000))); Assert.assertEquals("2 ώρες 2 λεπτά Πριν από", t.format(preciseDuration)); Assert.assertEquals("2 ώρες 2 λεπτά", t.formatDuration(preciseDuration)); Assert.assertEquals("στιγμές από τώρα", t.format(t.calculatePreciseDuration(new Date()))); } @Test public void testCalculatePreciseDuration2() { PrettyTime prettyTime = new PrettyTime(); prettyTime.clearUnits(); Minute minutes = new Minute();
// Path: core/src/main/java/org/ocpsoft/prettytime/impl/ResourcesTimeFormat.java // public class ResourcesTimeFormat extends SimpleTimeFormat // { // private final ResourcesTimeUnit unit; // private TimeFormat override; // private String overrideResourceBundle; // If used this bundle will override the included bundle // // public ResourcesTimeFormat(ResourcesTimeUnit unit) // { // this.unit = unit; // } // // public ResourcesTimeFormat(ResourcesTimeUnit unit, String overrideResourceBundle) // { // this.unit = unit; // this.overrideResourceBundle = overrideResourceBundle; // } // // @Override // public ResourcesTimeFormat setLocale(Locale locale) // { // ResourceBundle bundle = null; // if (overrideResourceBundle != null) { // try { // // Attempt to load the bundle that the user passed in, maybe it exists, maybe not // bundle = ResourceBundle.getBundle(overrideResourceBundle, locale); // } // catch (Exception e) { // // Throw away if the bundle doesn't contain this local // } // } // // // If the bundle doesn't exist then load the default included one // if (bundle == null) { // bundle = ResourceBundle.getBundle(unit.getResourceBundleName(), locale); // } // // if (bundle instanceof TimeFormatProvider) { // TimeFormat format = ((TimeFormatProvider) bundle).getFormatFor(unit); // if (format != null) { // this.override = format; // } // } // else { // override = null; // } // // if (override == null) { // setPattern(bundle.getString(unit.getResourceKeyPrefix() + "Pattern")); // setFuturePrefix(bundle.getString(unit.getResourceKeyPrefix() + "FuturePrefix")); // setFutureSuffix(bundle.getString(unit.getResourceKeyPrefix() + "FutureSuffix")); // setPastPrefix(bundle.getString(unit.getResourceKeyPrefix() + "PastPrefix")); // setPastSuffix(bundle.getString(unit.getResourceKeyPrefix() + "PastSuffix")); // // setSingularName(bundle.getString(unit.getResourceKeyPrefix() + "SingularName")); // setPluralName(bundle.getString(unit.getResourceKeyPrefix() + "PluralName")); // // try { // setFuturePluralName(bundle.getString(unit.getResourceKeyPrefix() + "FuturePluralName")); // } // catch (Exception e) { // } // try { // setFutureSingularName((bundle.getString(unit.getResourceKeyPrefix() + "FutureSingularName"))); // } // catch (Exception e) { // } // try { // setPastPluralName((bundle.getString(unit.getResourceKeyPrefix() + "PastPluralName"))); // } // catch (Exception e) { // } // try { // setPastSingularName((bundle.getString(unit.getResourceKeyPrefix() + "PastSingularName"))); // } // catch (Exception e) { // } // // } // // return this; // } // // @Override // public String decorate(Duration duration, String time) // { // return override == null ? super.decorate(duration, time) : override.decorate(duration, time); // } // // @Override // public String decorateUnrounded(Duration duration, String time) // { // return override == null ? super.decorateUnrounded(duration, time) : override.decorateUnrounded(duration, time); // } // // @Override // public String format(Duration duration) // { // return override == null ? super.format(duration) : override.format(duration); // } // // @Override // public String formatUnrounded(Duration duration) // { // return override == null ? super.formatUnrounded(duration) : override.formatUnrounded(duration); // } // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_EL_Test.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.impl.ResourcesTimeFormat; import org.ocpsoft.prettytime.units.Minute; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; } @Test public void testNullDate() throws Exception { PrettyTime t = new PrettyTime(); final String format = t.format((Date) null); Assert.assertTrue("πριν από στιγμές".equals(format) || "στιγμές από τώρα".equals(format)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); Assert.assertEquals("στιγμές από τώρα", t.format(new Date())); } @Test public void testCalculatePreciceDuration() throws Exception { PrettyTime t = new PrettyTime(); List<Duration> preciseDuration = t.calculatePreciseDuration( new Date(System.currentTimeMillis() - (2 * 60 * 60 * 1000) - (2 * 60 * 1000))); Assert.assertEquals("2 ώρες 2 λεπτά Πριν από", t.format(preciseDuration)); Assert.assertEquals("2 ώρες 2 λεπτά", t.formatDuration(preciseDuration)); Assert.assertEquals("στιγμές από τώρα", t.format(t.calculatePreciseDuration(new Date()))); } @Test public void testCalculatePreciseDuration2() { PrettyTime prettyTime = new PrettyTime(); prettyTime.clearUnits(); Minute minutes = new Minute();
prettyTime.registerUnit(minutes, new ResourcesTimeFormat(minutes));
ocpsoft/prettytime
nlp/src/main/java/org/ocpsoft/prettytime/nlp/PrettyTimeParser.java
// Path: nlp/src/main/java/org/ocpsoft/prettytime/nlp/parse/DateGroup.java // public interface DateGroup // { // /** // * Get the line in which this {@link DateGroup} was found. // */ // int getLine(); // // /** // * Get the text fragment parsed into this {@link DateGroup}. // */ // String getText(); // // /** // * Get the {@link Date} to which this {@link DateGroup} recurs. // */ // Date getRecursUntil(); // // /** // * Get the starting position of this {@link DateGroup} in the language text. // */ // int getPosition(); // // /** // * Get all {@link Date} instances parsed from the language text. // */ // List<Date> getDates(); // // /** // * Return <code>true</code> if this {@link DateGroup} is a recurring event. // */ // boolean isRecurring(); // // /** // * If this {@link DateGroup} is recurring, return the interval in milliseconds with which this {@link DateGroup} // * recurs, otherwise return -1; // */ // long getRecurInterval(); // }
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import org.ocpsoft.prettytime.nlp.parse.DateGroup; import com.joestelmach.natty.Parser;
else if (number < 100) { int unit = number % 10; key = tensNames[number / 10] + numNames[unit]; } else { int unit = number % 10; int ten = number % 100 - unit; int hundred = (number - ten) / 100; if (hundred < 20) key = numNames[hundred] + " hundred"; else key = tensNames[hundred / 10] + numNames[hundred % 10] + " hundred"; if (ten + unit < 20 && ten + unit > 10) key += numNames[ten + unit]; else key += tensNames[ten / 10] + numNames[unit]; } return key.trim(); } /** * Parse the given language and return a {@link List} with all discovered {@link Date} instances. */ public List<Date> parse(String language) { language = words2numbers(language); List<Date> result = new ArrayList<Date>();
// Path: nlp/src/main/java/org/ocpsoft/prettytime/nlp/parse/DateGroup.java // public interface DateGroup // { // /** // * Get the line in which this {@link DateGroup} was found. // */ // int getLine(); // // /** // * Get the text fragment parsed into this {@link DateGroup}. // */ // String getText(); // // /** // * Get the {@link Date} to which this {@link DateGroup} recurs. // */ // Date getRecursUntil(); // // /** // * Get the starting position of this {@link DateGroup} in the language text. // */ // int getPosition(); // // /** // * Get all {@link Date} instances parsed from the language text. // */ // List<Date> getDates(); // // /** // * Return <code>true</code> if this {@link DateGroup} is a recurring event. // */ // boolean isRecurring(); // // /** // * If this {@link DateGroup} is recurring, return the interval in milliseconds with which this {@link DateGroup} // * recurs, otherwise return -1; // */ // long getRecurInterval(); // } // Path: nlp/src/main/java/org/ocpsoft/prettytime/nlp/PrettyTimeParser.java import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import org.ocpsoft.prettytime.nlp.parse.DateGroup; import com.joestelmach.natty.Parser; else if (number < 100) { int unit = number % 10; key = tensNames[number / 10] + numNames[unit]; } else { int unit = number % 10; int ten = number % 100 - unit; int hundred = (number - ten) / 100; if (hundred < 20) key = numNames[hundred] + " hundred"; else key = tensNames[hundred / 10] + numNames[hundred % 10] + " hundred"; if (ten + unit < 20 && ten + unit > 10) key += numNames[ten + unit]; else key += tensNames[ten / 10] + numNames[unit]; } return key.trim(); } /** * Parse the given language and return a {@link List} with all discovered {@link Date} instances. */ public List<Date> parse(String language) { language = words2numbers(language); List<Date> result = new ArrayList<Date>();
List<com.joestelmach.natty.DateGroup> groups = parser.parse(language);
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // }
import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium;
{ "SecondSingularName", "秒" }, { "SecondPluralName", "秒" }, { "WeekPattern", "%n%u" }, { "WeekFuturePrefix", "今から" }, { "WeekFutureSuffix", "後" }, { "WeekPastPrefix", "" }, { "WeekPastSuffix", "前" }, { "WeekSingularName", "週間" }, { "WeekPluralName", "週間" }, { "YearPattern", "%n%u" }, { "YearFuturePrefix", "今から" }, { "YearFutureSuffix", "後" }, { "YearPastPrefix", "" }, { "YearPastSuffix", "前" }, { "YearSingularName", "年" }, { "YearPluralName", "年" }, { "AbstractTimeUnitPattern", "" }, { "AbstractTimeUnitFuturePrefix", "" }, { "AbstractTimeUnitFutureSuffix", "" }, { "AbstractTimeUnitPastPrefix", "" }, { "AbstractTimeUnitPastSuffix", "" }, { "AbstractTimeUnitSingularName", "" }, { "AbstractTimeUnitPluralName", "" } }; @Override public Object[][] getContents() { return OBJECTS; }
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium; { "SecondSingularName", "秒" }, { "SecondPluralName", "秒" }, { "WeekPattern", "%n%u" }, { "WeekFuturePrefix", "今から" }, { "WeekFutureSuffix", "後" }, { "WeekPastPrefix", "" }, { "WeekPastSuffix", "前" }, { "WeekSingularName", "週間" }, { "WeekPluralName", "週間" }, { "YearPattern", "%n%u" }, { "YearFuturePrefix", "今から" }, { "YearFutureSuffix", "後" }, { "YearPastPrefix", "" }, { "YearPastSuffix", "前" }, { "YearSingularName", "年" }, { "YearPluralName", "年" }, { "AbstractTimeUnitPattern", "" }, { "AbstractTimeUnitFuturePrefix", "" }, { "AbstractTimeUnitFutureSuffix", "" }, { "AbstractTimeUnitPastPrefix", "" }, { "AbstractTimeUnitPastSuffix", "" }, { "AbstractTimeUnitSingularName", "" }, { "AbstractTimeUnitPluralName", "" } }; @Override public Object[][] getContents() { return OBJECTS; }
private final Map<TimeUnit, TimeFormat> formatMap = new ConcurrentHashMap<>();
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // }
import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium;
} try { setPastSingularName((bundle.getString(getUnitName(unit) + "PastSingularName"))); } catch (Exception e) { } } private String getUnitName(TimeUnit unit) { return unit.getClass().getSimpleName(); } @Override public String format(final Duration duration) { return format(duration, true); } @Override public String formatUnrounded(Duration duration) { return format(duration, false); } private String format(final Duration duration, final boolean round) { String sign = getSign(duration); String unit = getGramaticallyCorrectName(duration, round); long quantity = getQuantity(duration, round);
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium; } try { setPastSingularName((bundle.getString(getUnitName(unit) + "PastSingularName"))); } catch (Exception e) { } } private String getUnitName(TimeUnit unit) { return unit.getClass().getSimpleName(); } @Override public String format(final Duration duration) { return format(duration, true); } @Override public String formatUnrounded(Duration duration) { return format(duration, false); } private String format(final Duration duration, final boolean round) { String sign = getSign(duration); String unit = getGramaticallyCorrectName(duration, round); long quantity = getQuantity(duration, round);
if (duration.getUnit() instanceof Decade)
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // }
import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium;
setPastSingularName((bundle.getString(getUnitName(unit) + "PastSingularName"))); } catch (Exception e) { } } private String getUnitName(TimeUnit unit) { return unit.getClass().getSimpleName(); } @Override public String format(final Duration duration) { return format(duration, true); } @Override public String formatUnrounded(Duration duration) { return format(duration, false); } private String format(final Duration duration, final boolean round) { String sign = getSign(duration); String unit = getGramaticallyCorrectName(duration, round); long quantity = getQuantity(duration, round); if (duration.getUnit() instanceof Decade) quantity *= 10;
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Decade.java // public class Decade extends ResourcesTimeUnit // { // // public Decade() // { // setMillisPerUnit(315569259747L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Decade"; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Millennium.java // public class Millennium extends ResourcesTimeUnit // { // // public Millennium() // { // setMillisPerUnit(31556926000000L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Millennium"; // } // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ja.java import java.util.ListResourceBundle; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Decade; import org.ocpsoft.prettytime.units.Millennium; setPastSingularName((bundle.getString(getUnitName(unit) + "PastSingularName"))); } catch (Exception e) { } } private String getUnitName(TimeUnit unit) { return unit.getClass().getSimpleName(); } @Override public String format(final Duration duration) { return format(duration, true); } @Override public String formatUnrounded(Duration duration) { return format(duration, false); } private String format(final Duration duration, final boolean round) { String sign = getSign(duration); String unit = getGramaticallyCorrectName(duration, round); long quantity = getQuantity(duration, round); if (duration.getUnit() instanceof Decade) quantity *= 10;
if (duration.getUnit() instanceof Millennium)
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeAPIManipulationTest.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow;
t.toString(); } @Test public void testApiMisuse16() throws Exception { Assert.assertNull(t.removeUnit((Class<TimeUnit>) null)); } @Test public void testApiMisuse17() throws Exception { Assert.assertNull(t.removeUnit((TimeUnit) null)); } @Test public void testApiMisuse18() throws Exception { Assert.assertNull(t.getUnit(null)); } @Test public void testApiMisuse19() throws Exception { Assert.assertNull(t.getUnit((Class<TimeUnit>) null)); } @Test public void testGetUnit() {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeAPIManipulationTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; t.toString(); } @Test public void testApiMisuse16() throws Exception { Assert.assertNull(t.removeUnit((Class<TimeUnit>) null)); } @Test public void testApiMisuse17() throws Exception { Assert.assertNull(t.removeUnit((TimeUnit) null)); } @Test public void testApiMisuse18() throws Exception { Assert.assertNull(t.getUnit(null)); } @Test public void testApiMisuse19() throws Exception { Assert.assertNull(t.getUnit((Class<TimeUnit>) null)); } @Test public void testGetUnit() {
JustNow unit = t.getUnit(JustNow.class);
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_SK_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Month.java // public class Month extends ResourcesTimeUnit // { // // public Month() // { // setMillisPerUnit(2629743830L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Month"; // } // // }
import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; import org.ocpsoft.prettytime.units.Month;
@Test public void testCeilingInterval() throws Exception { Date then = format.parse("5/20/2009"); Date ref = format.parse("6/17/2009"); PrettyTime t = new PrettyTime(ref); assertEquals("pred 1 mesiacom", t.format(then)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); assertEquals("o chvíľu", t.format(new Date())); } @Test public void testRightNowVariance() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o chvíľu", t.format(new Date(600))); } @Test public void testMinutesFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); for (TimeUnit u : t.getUnits()) {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Month.java // public class Month extends ResourcesTimeUnit // { // // public Month() // { // setMillisPerUnit(2629743830L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Month"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_SK_Test.java import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; import org.ocpsoft.prettytime.units.Month; @Test public void testCeilingInterval() throws Exception { Date then = format.parse("5/20/2009"); Date ref = format.parse("6/17/2009"); PrettyTime t = new PrettyTime(ref); assertEquals("pred 1 mesiacom", t.format(then)); } @Test public void testRightNow() throws Exception { PrettyTime t = new PrettyTime(); assertEquals("o chvíľu", t.format(new Date())); } @Test public void testRightNowVariance() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o chvíľu", t.format(new Date(600))); } @Test public void testMinutesFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); for (TimeUnit u : t.getUnits()) {
if (u instanceof JustNow)
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_SK_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Month.java // public class Month extends ResourcesTimeUnit // { // // public Month() // { // setMillisPerUnit(2629743830L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Month"; // } // // }
import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; import org.ocpsoft.prettytime.units.Month;
assertEquals("o 1 minútu", t.format(new Date(1000 * 60 * 1))); assertEquals("o 3 minúty", t.format(new Date(1000 * 60 * 3))); assertEquals("o 12 minút", t.format(new Date(1000 * 60 * 12))); } @Test public void testHoursFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o 1 hodinu", t.format(new Date(1000 * 60 * 60 * 1))); assertEquals("o 3 hodiny", t.format(new Date(1000 * 60 * 60 * 3))); assertEquals("o 10 hodín", t.format(new Date(1000 * 60 * 60 * 10))); } @Test public void testDaysFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o 1 deň", t.format(new Date(1000 * 60 * 60 * 24 * 1))); assertEquals("o 3 dni", t.format(new Date(1000 * 60 * 60 * 24 * 3))); assertEquals("o 5 dní", t.format(new Date(1000 * 60 * 60 * 24 * 5))); } @Test public void testWeeksFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); for (TimeUnit u : t.getUnits()) {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Month.java // public class Month extends ResourcesTimeUnit // { // // public Month() // { // setMillisPerUnit(2629743830L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Month"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_SK_Test.java import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; import org.ocpsoft.prettytime.units.Month; assertEquals("o 1 minútu", t.format(new Date(1000 * 60 * 1))); assertEquals("o 3 minúty", t.format(new Date(1000 * 60 * 3))); assertEquals("o 12 minút", t.format(new Date(1000 * 60 * 12))); } @Test public void testHoursFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o 1 hodinu", t.format(new Date(1000 * 60 * 60 * 1))); assertEquals("o 3 hodiny", t.format(new Date(1000 * 60 * 60 * 3))); assertEquals("o 10 hodín", t.format(new Date(1000 * 60 * 60 * 10))); } @Test public void testDaysFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); assertEquals("o 1 deň", t.format(new Date(1000 * 60 * 60 * 24 * 1))); assertEquals("o 3 dni", t.format(new Date(1000 * 60 * 60 * 24 * 3))); assertEquals("o 5 dní", t.format(new Date(1000 * 60 * 60 * 24 * 5))); } @Test public void testWeeksFromNow() throws Exception { PrettyTime t = new PrettyTime(new Date(0)); for (TimeUnit u : t.getUnits()) {
if (u instanceof Month)
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ru.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // }
import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle;
package org.ocpsoft.prettytime.i18n; /** * Created with IntelliJ IDEA. User: Tumin Alexander Date: 2012-12-13 Time: 03:33 */ public class Resources_ru extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int russianPluralForms = 3;
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_ru.java import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle; package org.ocpsoft.prettytime.i18n; /** * Created with IntelliJ IDEA. User: Tumin Alexander Date: 2012-12-13 Time: 03:33 */ public class Resources_ru extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; private static final int tolerance = 50; // see http://translate.sourceforge.net/wiki/l10n/pluralforms private static final int russianPluralForms = 3;
private static class TimeFormatAided implements TimeFormat
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/i18n/Resources_xx.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // }
import java.util.ListResourceBundle; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Minute;
package org.ocpsoft.prettytime.i18n; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Resources_xx extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[][] {}; @Override public Object[][] getContents() { return OBJECTS; } @Override
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/i18n/Resources_xx.java import java.util.ListResourceBundle; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Minute; package org.ocpsoft.prettytime.i18n; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Resources_xx extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[][] {}; @Override public Object[][] getContents() { return OBJECTS; } @Override
public TimeFormat getFormatFor(TimeUnit t)
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/i18n/Resources_xx.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // }
import java.util.ListResourceBundle; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Minute;
package org.ocpsoft.prettytime.i18n; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Resources_xx extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[][] {}; @Override public Object[][] getContents() { return OBJECTS; } @Override public TimeFormat getFormatFor(TimeUnit t) {
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // // Path: core/src/main/java/org/ocpsoft/prettytime/units/Minute.java // public class Minute extends ResourcesTimeUnit // { // // public Minute() // { // setMillisPerUnit(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "Minute"; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/i18n/Resources_xx.java import java.util.ListResourceBundle; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.Minute; package org.ocpsoft.prettytime.i18n; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Resources_xx extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[][] {}; @Override public Object[][] getContents() { return OBJECTS; } @Override public TimeFormat getFormatFor(TimeUnit t) {
if (t instanceof Minute)
ocpsoft/prettytime
core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_kk.java
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // }
import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle;
package org.ocpsoft.prettytime.i18n; /** * Created by Azimkhan Yerzhan on 5/8/2017 */ public class Resources_kk extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; @Override protected Object[][] getContents() { return OBJECTS; }
// Path: core/src/main/java/org/ocpsoft/prettytime/TimeFormat.java // public interface TimeFormat // { // /** // * Given a populated {@link Duration} object. Apply formatting (with rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public abstract String format(final Duration duration); // // /** // * Given a populated {@link Duration} object. Apply formatting (without rounding) and output the result. // * // * @param The original {@link Duration} instance from which the time string should be decorated. // */ // public String formatUnrounded(Duration duration); // // /** // * Decorate with past or future prefix/suffix (with rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorate(Duration duration, String time); // // /** // * Decorate with past or future prefix/suffix (without rounding) // * // * @param duration The original {@link Duration} instance from which the time string should be decorated. // * @param time The formatted time string. // */ // public String decorateUnrounded(Duration duration, String time); // // } // Path: core/src/main/java/org/ocpsoft/prettytime/i18n/Resources_kk.java import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import org.ocpsoft.prettytime.impl.TimeFormatProvider; import org.ocpsoft.prettytime.units.*; import java.util.ListResourceBundle; package org.ocpsoft.prettytime.i18n; /** * Created by Azimkhan Yerzhan on 5/8/2017 */ public class Resources_kk extends ListResourceBundle implements TimeFormatProvider { private static final Object[][] OBJECTS = new Object[0][0]; @Override protected Object[][] getContents() { return OBJECTS; }
private static class KkTimeFormat implements TimeFormat
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_ET_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // }
import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow;
package org.ocpsoft.prettytime; public class PrettyTimeI18n_ET_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("et"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_ET_Test.java import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; package org.ocpsoft.prettytime; public class PrettyTimeI18n_ET_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("et"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
if (!(timeUnit instanceof JustNow)) {
ocpsoft/prettytime
core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_FI_Test.java
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // }
import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow;
/* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime; public class PrettyTimeI18n_FI_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("fi"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
// Path: core/src/main/java/org/ocpsoft/prettytime/units/JustNow.java // public class JustNow extends ResourcesTimeUnit // { // // public JustNow() // { // setMaxQuantity(1000L * 60L); // } // // @Override // protected String getResourceKeyPrefix() // { // return "JustNow"; // } // // @Override // public boolean isPrecise() // { // return false; // } // // } // Path: core/src/test/java/org/ocpsoft/prettytime/PrettyTimeI18n_FI_Test.java import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.ocpsoft.prettytime.units.JustNow; /* * Copyright 2012 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ocpsoft.prettytime; public class PrettyTimeI18n_FI_Test { private Locale locale; @Before public void setUp() throws Exception { locale = new Locale("fi"); } private PrettyTime newPrettyTimeWOJustNow(Date ref, Locale locale) { PrettyTime t = new PrettyTime(ref, locale); List<TimeUnit> units = t.getUnits(); List<TimeFormat> formats = new ArrayList<TimeFormat>(); for (TimeUnit timeUnit : units) {
if (!(timeUnit instanceof JustNow)) {
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/ContextTest.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // }
import org.junit.Test; import com.github.davidmoten.rtree.geometry.Geometry;
package com.github.davidmoten.rtree; public class ContextTest { @Test(expected = RuntimeException.class) public void testContextIllegalMinChildren() {
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // Path: src/test/java/com/github/davidmoten/rtree/ContextTest.java import org.junit.Test; import com.github.davidmoten.rtree.geometry.Geometry; package com.github.davidmoten.rtree; public class ContextTest { @Test(expected = RuntimeException.class) public void testContextIllegalMinChildren() {
new Context<Object, Geometry>(0, 4, new SelectorMinimalAreaIncrease(),
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/Node.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/NodeAndEntries.java // public final class NodeAndEntries<T, S extends Geometry> { // // private final Optional<? extends Node<T, S>> node; // private final List<Entry<T, S>> entries; // private final int count; // // /** // * Constructor. // * // * @param node // * absent = whole node was deleted present = either an unchanged // * node because of no removal or the newly created node without // * the deleted entry // * @param entries // * from nodes that dropped below minChildren in size and thus // * their entries are to be redistributed (readded to the tree) // * @param countDeleted // * count of the number of entries removed // */ // public NodeAndEntries(Optional<? extends Node<T, S>> node, List<Entry<T, S>> entries, // int countDeleted) { // this.node = node; // this.entries = entries; // this.count = countDeleted; // } // // public Optional<? extends Node<T, S>> node() { // return node; // } // // public List<Entry<T, S>> entriesToAdd() { // return entries; // } // // public int countDeleted() { // return count; // } // // }
import java.util.List; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.internal.NodeAndEntries; import rx.Subscriber; import rx.functions.Func1;
package com.github.davidmoten.rtree; public interface Node<T, S extends Geometry> extends HasGeometry { List<Node<T, S>> add(Entry<? extends T, ? extends S> entry);
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/NodeAndEntries.java // public final class NodeAndEntries<T, S extends Geometry> { // // private final Optional<? extends Node<T, S>> node; // private final List<Entry<T, S>> entries; // private final int count; // // /** // * Constructor. // * // * @param node // * absent = whole node was deleted present = either an unchanged // * node because of no removal or the newly created node without // * the deleted entry // * @param entries // * from nodes that dropped below minChildren in size and thus // * their entries are to be redistributed (readded to the tree) // * @param countDeleted // * count of the number of entries removed // */ // public NodeAndEntries(Optional<? extends Node<T, S>> node, List<Entry<T, S>> entries, // int countDeleted) { // this.node = node; // this.entries = entries; // this.count = countDeleted; // } // // public Optional<? extends Node<T, S>> node() { // return node; // } // // public List<Entry<T, S>> entriesToAdd() { // return entries; // } // // public int countDeleted() { // return count; // } // // } // Path: src/main/java/com/github/davidmoten/rtree/Node.java import java.util.List; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.internal.NodeAndEntries; import rx.Subscriber; import rx.functions.Func1; package com.github.davidmoten.rtree; public interface Node<T, S extends Geometry> extends HasGeometry { List<Node<T, S>> add(Entry<? extends T, ? extends S> entry);
NodeAndEntries<T, S> delete(Entry<? extends T, ? extends S> entry, boolean all);
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/EntriesTest.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rtree.geometry.Geometries;
package com.github.davidmoten.rtree; public class EntriesTest { @Test public void testValue() {
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // Path: src/test/java/com/github/davidmoten/rtree/EntriesTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rtree.geometry.Geometries; package com.github.davidmoten.rtree; public class EntriesTest { @Test public void testValue() {
assertEquals(1, (int) Entries.entry(1, Geometries.point(0, 0)).value());
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/SplitterRStarTest.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/ListPair.java // public final class ListPair<T extends HasGeometry> { // private final Group<T> group1; // private final Group<T> group2; // // these non-final variable mean that this class is not thread-safe // // because access to them is not synchronized // private double areaSum = -1; // private final double marginSum; // // public ListPair(List<T> list1, List<T> list2) { // this.group1 = new Group<T>(list1); // this.group2 = new Group<T>(list2); // this.marginSum = group1.geometry().mbr().perimeter() + group2.geometry().mbr().perimeter(); // } // // public Group<T> group1() { // return group1; // } // // public Group<T> group2() { // return group2; // } // // public double areaSum() { // if (areaSum == -1) // areaSum = group1.geometry().mbr().area() + group2.geometry().mbr().area(); // return areaSum; // } // // public double marginSum() { // return marginSum; // } // // }
import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.ListPair;
package com.github.davidmoten.rtree; public class SplitterRStarTest { @Test public void testGetPairs() { int minSize = 2; List<HasGeometry> list = Lists.newArrayList();
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/ListPair.java // public final class ListPair<T extends HasGeometry> { // private final Group<T> group1; // private final Group<T> group2; // // these non-final variable mean that this class is not thread-safe // // because access to them is not synchronized // private double areaSum = -1; // private final double marginSum; // // public ListPair(List<T> list1, List<T> list2) { // this.group1 = new Group<T>(list1); // this.group2 = new Group<T>(list2); // this.marginSum = group1.geometry().mbr().perimeter() + group2.geometry().mbr().perimeter(); // } // // public Group<T> group1() { // return group1; // } // // public Group<T> group2() { // return group2; // } // // public double areaSum() { // if (areaSum == -1) // areaSum = group1.geometry().mbr().area() + group2.geometry().mbr().area(); // return areaSum; // } // // public double marginSum() { // return marginSum; // } // // } // Path: src/test/java/com/github/davidmoten/rtree/SplitterRStarTest.java import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.ListPair; package com.github.davidmoten.rtree; public class SplitterRStarTest { @Test public void testGetPairs() { int minSize = 2; List<HasGeometry> list = Lists.newArrayList();
list.add(Geometries.point(1, 1).mbr());
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/SplitterRStarTest.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/ListPair.java // public final class ListPair<T extends HasGeometry> { // private final Group<T> group1; // private final Group<T> group2; // // these non-final variable mean that this class is not thread-safe // // because access to them is not synchronized // private double areaSum = -1; // private final double marginSum; // // public ListPair(List<T> list1, List<T> list2) { // this.group1 = new Group<T>(list1); // this.group2 = new Group<T>(list2); // this.marginSum = group1.geometry().mbr().perimeter() + group2.geometry().mbr().perimeter(); // } // // public Group<T> group1() { // return group1; // } // // public Group<T> group2() { // return group2; // } // // public double areaSum() { // if (areaSum == -1) // areaSum = group1.geometry().mbr().area() + group2.geometry().mbr().area(); // return areaSum; // } // // public double marginSum() { // return marginSum; // } // // }
import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.ListPair;
package com.github.davidmoten.rtree; public class SplitterRStarTest { @Test public void testGetPairs() { int minSize = 2; List<HasGeometry> list = Lists.newArrayList(); list.add(Geometries.point(1, 1).mbr()); list.add(Geometries.point(2, 2).mbr()); list.add(Geometries.point(3, 3).mbr()); list.add(Geometries.point(4, 4).mbr()); list.add(Geometries.point(5, 5).mbr());
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/ListPair.java // public final class ListPair<T extends HasGeometry> { // private final Group<T> group1; // private final Group<T> group2; // // these non-final variable mean that this class is not thread-safe // // because access to them is not synchronized // private double areaSum = -1; // private final double marginSum; // // public ListPair(List<T> list1, List<T> list2) { // this.group1 = new Group<T>(list1); // this.group2 = new Group<T>(list2); // this.marginSum = group1.geometry().mbr().perimeter() + group2.geometry().mbr().perimeter(); // } // // public Group<T> group1() { // return group1; // } // // public Group<T> group2() { // return group2; // } // // public double areaSum() { // if (areaSum == -1) // areaSum = group1.geometry().mbr().area() + group2.geometry().mbr().area(); // return areaSum; // } // // public double marginSum() { // return marginSum; // } // // } // Path: src/test/java/com/github/davidmoten/rtree/SplitterRStarTest.java import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.ListPair; package com.github.davidmoten.rtree; public class SplitterRStarTest { @Test public void testGetPairs() { int minSize = 2; List<HasGeometry> list = Lists.newArrayList(); list.add(Geometries.point(1, 1).mbr()); list.add(Geometries.point(2, 2).mbr()); list.add(Geometries.point(3, 3).mbr()); list.add(Geometries.point(4, 4).mbr()); list.add(Geometries.point(5, 5).mbr());
List<ListPair<HasGeometry>> pairs = SplitterRStar.getPairs(minSize, list);
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/internal/Comparators.java
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // }
import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle;
package com.github.davidmoten.rtree.internal; /** * Utility functions asociated with {@link Comparator}s, especially for use with * {@link Selector}s and {@link Splitter}s. * */ public final class Comparators { private Comparators() { // prevent instantiation } public static <T extends HasGeometry> Comparator<HasGeometry> overlapAreaThenAreaIncreaseThenAreaComparator(
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // } // Path: src/main/java/com/github/davidmoten/rtree/internal/Comparators.java import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle; package com.github.davidmoten.rtree.internal; /** * Utility functions asociated with {@link Comparator}s, especially for use with * {@link Selector}s and {@link Splitter}s. * */ public final class Comparators { private Comparators() { // prevent instantiation } public static <T extends HasGeometry> Comparator<HasGeometry> overlapAreaThenAreaIncreaseThenAreaComparator(
final Rectangle r, final List<T> list) {
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/internal/Comparators.java
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // }
import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle;
for (HasGeometry other : list) { if (other != g) { m += gPlusR.intersectionArea(other.geometry().mbr()); } } return m; } private static double areaIncrease(Rectangle r, HasGeometry g) { Rectangle gPlusR = g.geometry().mbr().add(r); return gPlusR.area() - g.geometry().mbr().area(); } /** * <p> * Returns a comparator that can be used to sort entries returned by search * methods. For example: * </p> * <p> * <code>search(100).toSortedList(ascendingDistance(r))</code> * </p> * * @param <T> * the value type * @param <S> * the entry type * @param r * rectangle to measure distance to * @return a comparator to sort by ascending distance from the rectangle */
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // } // Path: src/main/java/com/github/davidmoten/rtree/internal/Comparators.java import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle; for (HasGeometry other : list) { if (other != g) { m += gPlusR.intersectionArea(other.geometry().mbr()); } } return m; } private static double areaIncrease(Rectangle r, HasGeometry g) { Rectangle gPlusR = g.geometry().mbr().add(r); return gPlusR.area() - g.geometry().mbr().area(); } /** * <p> * Returns a comparator that can be used to sort entries returned by search * methods. For example: * </p> * <p> * <code>search(100).toSortedList(ascendingDistance(r))</code> * </p> * * @param <T> * the value type * @param <S> * the entry type * @param r * rectangle to measure distance to * @return a comparator to sort by ascending distance from the rectangle */
public static <T, S extends Geometry> Comparator<Entry<T, S>> ascendingDistance(
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/internal/Comparators.java
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // }
import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle;
for (HasGeometry other : list) { if (other != g) { m += gPlusR.intersectionArea(other.geometry().mbr()); } } return m; } private static double areaIncrease(Rectangle r, HasGeometry g) { Rectangle gPlusR = g.geometry().mbr().add(r); return gPlusR.area() - g.geometry().mbr().area(); } /** * <p> * Returns a comparator that can be used to sort entries returned by search * methods. For example: * </p> * <p> * <code>search(100).toSortedList(ascendingDistance(r))</code> * </p> * * @param <T> * the value type * @param <S> * the entry type * @param r * rectangle to measure distance to * @return a comparator to sort by ascending distance from the rectangle */
// Path: src/main/java/com/github/davidmoten/rtree/Entry.java // public interface Entry<T, S extends Geometry> extends HasGeometry { // // T value(); // // @Override // S geometry(); // // } // // Path: src/main/java/com/github/davidmoten/rtree/Splitter.java // public interface Splitter { // // /** // * Splits a list of items into two lists of at least minSize. // * // * @param <T> // * geometry type // * @param items // * list of items to split // * @param minSize // * min size of each list // * @return two lists // */ // <T extends HasGeometry> ListPair<T> split(List<T> items, int minSize); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // } // Path: src/main/java/com/github/davidmoten/rtree/internal/Comparators.java import java.util.Comparator; import java.util.List; import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.Selector; import com.github.davidmoten.rtree.Splitter; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Rectangle; for (HasGeometry other : list) { if (other != g) { m += gPlusR.intersectionArea(other.geometry().mbr()); } } return m; } private static double areaIncrease(Rectangle r, HasGeometry g) { Rectangle gPlusR = g.geometry().mbr().add(r); return gPlusR.area() - g.geometry().mbr().area(); } /** * <p> * Returns a comparator that can be used to sort entries returned by search * methods. For example: * </p> * <p> * <code>search(100).toSortedList(ascendingDistance(r))</code> * </p> * * @param <T> * the value type * @param <S> * the entry type * @param r * rectangle to measure distance to * @return a comparator to sort by ascending distance from the rectangle */
public static <T, S extends Geometry> Comparator<Entry<T, S>> ascendingDistance(
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/Utilities.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.Rectangle;
package com.github.davidmoten.rtree; public class Utilities { static List<Entry<Object, Rectangle>> entries1000(Precision precision) { List<Entry<Object, Rectangle>> list = new ArrayList<Entry<Object, Rectangle>>(); BufferedReader br = new BufferedReader( new InputStreamReader(BenchmarksRTree.class.getResourceAsStream("/1000.txt"))); String line; try { while ((line = br.readLine()) != null) { String[] items = line.split(" "); double x = Double.parseDouble(items[0]); double y = Double.parseDouble(items[1]); Entry<Object, Rectangle> entry; if (precision == Precision.DOUBLE)
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometries.java // public final class Geometries { // // private Geometries() { // // prevent instantiation // } // // public static Point point(double x, double y) { // return PointDouble.create(x, y); // } // // public static Point point(float x, float y) { // return PointFloat.create(x, y); // } // // public static Point pointGeographic(double lon, double lat) { // return point(normalizeLongitudeDouble(lon), lat); // } // // public static Point pointGeographic(float lon, float lat) { // return point(normalizeLongitude(lon), lat); // } // // public static Rectangle rectangle(double x1, double y1, double x2, double y2) { // return rectangleDouble(x1, y1, x2, y2); // } // // public static Rectangle rectangle(float x1, float y1, float x2, float y2) { // return RectangleFloat.create(x1, y1, x2, y2); // } // // public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2, // double lat2) { // return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2); // } // // public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) { // float x1 = normalizeLongitude(lon1); // float x2 = normalizeLongitude(lon2); // if (x2 < x1) { // x2 += 360; // } // return rectangle(x1, lat1, x2, lat2); // } // // private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) { // return RectangleDouble.create(x1, y1, x2, y2); // } // // public static Circle circle(double x, double y, double radius) { // return CircleDouble.create(x, y, radius); // } // // public static Circle circle(float x, float y, float radius) { // return CircleFloat.create(x, y, radius); // } // // public static Line line(double x1, double y1, double x2, double y2) { // return LineDouble.create(x1, y1, x2, y2); // } // // public static Line line(float x1, float y1, float x2, float y2) { // return LineFloat.create(x1, y1, x2, y2); // } // // @VisibleForTesting // static double normalizeLongitude(double d) { // return normalizeLongitude((float) d); // } // // private static float normalizeLongitude(float d) { // if (d == -180.0f) // return -180.0f; // else { // float sign = Math.signum(d); // float x = Math.abs(d) / 360; // float x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // private static double normalizeLongitudeDouble(double d) { // if (d == -180.0f) // return -180.0d; // else { // double sign = Math.signum(d); // double x = Math.abs(d) / 360; // double x2 = (x - (float) Math.floor(x)) * 360; // if (x2 >= 180) // x2 -= 360; // return x2 * sign; // } // } // // } // // Path: src/main/java/com/github/davidmoten/rtree/geometry/Rectangle.java // public interface Rectangle extends Geometry, HasGeometry { // // double x1(); // // double y1(); // // double x2(); // // double y2(); // // double area(); // // double intersectionArea(Rectangle r); // // double perimeter(); // // Rectangle add(Rectangle r); // // boolean contains(double x, double y); // // boolean isDoublePrecision(); // // } // Path: src/test/java/com/github/davidmoten/rtree/Utilities.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import com.github.davidmoten.rtree.geometry.Geometries; import com.github.davidmoten.rtree.geometry.Rectangle; package com.github.davidmoten.rtree; public class Utilities { static List<Entry<Object, Rectangle>> entries1000(Precision precision) { List<Entry<Object, Rectangle>> list = new ArrayList<Entry<Object, Rectangle>>(); BufferedReader br = new BufferedReader( new InputStreamReader(BenchmarksRTree.class.getResourceAsStream("/1000.txt"))); String line; try { while ((line = br.readLine()) != null) { String[] items = line.split(" "); double x = Double.parseDouble(items[0]); double y = Double.parseDouble(items[1]); Entry<Object, Rectangle> entry; if (precision == Precision.DOUBLE)
entry = Entries.entry(new Object(), Geometries.rectangle(x, y, x + 1, y + 1));
davidmoten/rtree
src/test/java/com/github/davidmoten/rtree/GalleryMain.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Point.java // public interface Point extends Rectangle { // // double x(); // // double y(); // // }
import java.util.Arrays; import java.util.List; import com.github.davidmoten.rtree.geometry.Point; import rx.Observable;
package com.github.davidmoten.rtree; public class GalleryMain { public static void main(String[] args) {
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Point.java // public interface Point extends Rectangle { // // double x(); // // double y(); // // } // Path: src/test/java/com/github/davidmoten/rtree/GalleryMain.java import java.util.Arrays; import java.util.List; import com.github.davidmoten.rtree.geometry.Point; import rx.Observable; package com.github.davidmoten.rtree; public class GalleryMain { public static void main(String[] args) {
Observable<Entry<Object, Point>> entries = GreekEarthquakes.entries(Precision.DOUBLE)
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/SerializerHelper.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // }
import com.github.davidmoten.rtree.geometry.Geometry; import java.util.Optional;
package com.github.davidmoten.rtree; public final class SerializerHelper { private SerializerHelper() { // prevent instantiation }
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // Path: src/main/java/com/github/davidmoten/rtree/SerializerHelper.java import com.github.davidmoten.rtree.geometry.Geometry; import java.util.Optional; package com.github.davidmoten.rtree; public final class SerializerHelper { private SerializerHelper() { // prevent instantiation }
public static <T, S extends Geometry> RTree<T, S> create(Optional<Node<T, S>> root, int size,
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/Entries.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/EntryDefault.java // public final class EntryDefault<T, S extends Geometry> implements Entry<T, S> { // private final T value; // private final S geometry; // // /** // * Constructor. // * // * @param value // * the value of the entry // * @param geometry // * the geometry of the value // */ // public EntryDefault(T value, S geometry) { // Preconditions.checkNotNull(geometry); // this.value = value; // this.geometry = geometry; // } // // /** // * Factory method. // * // * @param <T> // * type of value // * @param <S> // * type of geometry // * @param value // * object being given a spatial context // * @param geometry // * geometry associated with the value // * @return entry wrapping value and associated geometry // */ // public static <T, S extends Geometry> Entry<T, S> entry(T value, S geometry) { // return new EntryDefault<T, S>(value, geometry); // } // // /** // * Returns the value wrapped by this {@link EntryDefault}. // * // * @return the entry value // */ // @Override // public T value() { // return value; // } // // @Override // public S geometry() { // return geometry; // } // // @Override // public String toString() { // String builder = "Entry [value=" + value + ", geometry=" + geometry + "]"; // return builder; // } // // @Override // public int hashCode() { // return Objects.hash(value, geometry); // } // // @Override // public boolean equals(Object obj) { // @SuppressWarnings("rawtypes") // Optional<EntryDefault> other = ObjectsHelper.asClass(obj, EntryDefault.class); // if (other.isPresent()) { // return Objects.equals(value, other.get().value) // && Objects.equals(geometry, other.get().geometry); // } else // return false; // } // // }
import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.internal.EntryDefault;
package com.github.davidmoten.rtree; public final class Entries { private Entries() { // prevent instantiation }
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/EntryDefault.java // public final class EntryDefault<T, S extends Geometry> implements Entry<T, S> { // private final T value; // private final S geometry; // // /** // * Constructor. // * // * @param value // * the value of the entry // * @param geometry // * the geometry of the value // */ // public EntryDefault(T value, S geometry) { // Preconditions.checkNotNull(geometry); // this.value = value; // this.geometry = geometry; // } // // /** // * Factory method. // * // * @param <T> // * type of value // * @param <S> // * type of geometry // * @param value // * object being given a spatial context // * @param geometry // * geometry associated with the value // * @return entry wrapping value and associated geometry // */ // public static <T, S extends Geometry> Entry<T, S> entry(T value, S geometry) { // return new EntryDefault<T, S>(value, geometry); // } // // /** // * Returns the value wrapped by this {@link EntryDefault}. // * // * @return the entry value // */ // @Override // public T value() { // return value; // } // // @Override // public S geometry() { // return geometry; // } // // @Override // public String toString() { // String builder = "Entry [value=" + value + ", geometry=" + geometry + "]"; // return builder; // } // // @Override // public int hashCode() { // return Objects.hash(value, geometry); // } // // @Override // public boolean equals(Object obj) { // @SuppressWarnings("rawtypes") // Optional<EntryDefault> other = ObjectsHelper.asClass(obj, EntryDefault.class); // if (other.isPresent()) { // return Objects.equals(value, other.get().value) // && Objects.equals(geometry, other.get().geometry); // } else // return false; // } // // } // Path: src/main/java/com/github/davidmoten/rtree/Entries.java import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.internal.EntryDefault; package com.github.davidmoten.rtree; public final class Entries { private Entries() { // prevent instantiation }
public static <T, S extends Geometry> Entry<T,S> entry(T object, S geometry) {
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/Entries.java
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/EntryDefault.java // public final class EntryDefault<T, S extends Geometry> implements Entry<T, S> { // private final T value; // private final S geometry; // // /** // * Constructor. // * // * @param value // * the value of the entry // * @param geometry // * the geometry of the value // */ // public EntryDefault(T value, S geometry) { // Preconditions.checkNotNull(geometry); // this.value = value; // this.geometry = geometry; // } // // /** // * Factory method. // * // * @param <T> // * type of value // * @param <S> // * type of geometry // * @param value // * object being given a spatial context // * @param geometry // * geometry associated with the value // * @return entry wrapping value and associated geometry // */ // public static <T, S extends Geometry> Entry<T, S> entry(T value, S geometry) { // return new EntryDefault<T, S>(value, geometry); // } // // /** // * Returns the value wrapped by this {@link EntryDefault}. // * // * @return the entry value // */ // @Override // public T value() { // return value; // } // // @Override // public S geometry() { // return geometry; // } // // @Override // public String toString() { // String builder = "Entry [value=" + value + ", geometry=" + geometry + "]"; // return builder; // } // // @Override // public int hashCode() { // return Objects.hash(value, geometry); // } // // @Override // public boolean equals(Object obj) { // @SuppressWarnings("rawtypes") // Optional<EntryDefault> other = ObjectsHelper.asClass(obj, EntryDefault.class); // if (other.isPresent()) { // return Objects.equals(value, other.get().value) // && Objects.equals(geometry, other.get().geometry); // } else // return false; // } // // }
import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.internal.EntryDefault;
package com.github.davidmoten.rtree; public final class Entries { private Entries() { // prevent instantiation } public static <T, S extends Geometry> Entry<T,S> entry(T object, S geometry) {
// Path: src/main/java/com/github/davidmoten/rtree/geometry/Geometry.java // public interface Geometry { // // /** // * <p> // * Returns the distance to the given {@link Rectangle}. For a {@link Rectangle} // * this might be Euclidean distance but for an EPSG4326 lat-long Rectangle might // * be great-circle distance. The distance function should satisfy the following // * properties: // * </p> // * // * <p> // * <code>distance(r) &gt;= 0</code> // * </p> // * // * <p> // * <code>if r1 contains r2 then distance(r1)&lt;=distance(r2)</code> // * </p> // * // * // * @param r // * rectangle to measure distance to // * @return distance to the rectangle r from the geometry // */ // double distance(Rectangle r); // // /** // * Returns the minimum bounding rectangle of this geometry. // * // * @return minimum bounding rectangle // */ // Rectangle mbr(); // // boolean intersects(Rectangle r); // // boolean isDoublePrecision(); // } // // Path: src/main/java/com/github/davidmoten/rtree/internal/EntryDefault.java // public final class EntryDefault<T, S extends Geometry> implements Entry<T, S> { // private final T value; // private final S geometry; // // /** // * Constructor. // * // * @param value // * the value of the entry // * @param geometry // * the geometry of the value // */ // public EntryDefault(T value, S geometry) { // Preconditions.checkNotNull(geometry); // this.value = value; // this.geometry = geometry; // } // // /** // * Factory method. // * // * @param <T> // * type of value // * @param <S> // * type of geometry // * @param value // * object being given a spatial context // * @param geometry // * geometry associated with the value // * @return entry wrapping value and associated geometry // */ // public static <T, S extends Geometry> Entry<T, S> entry(T value, S geometry) { // return new EntryDefault<T, S>(value, geometry); // } // // /** // * Returns the value wrapped by this {@link EntryDefault}. // * // * @return the entry value // */ // @Override // public T value() { // return value; // } // // @Override // public S geometry() { // return geometry; // } // // @Override // public String toString() { // String builder = "Entry [value=" + value + ", geometry=" + geometry + "]"; // return builder; // } // // @Override // public int hashCode() { // return Objects.hash(value, geometry); // } // // @Override // public boolean equals(Object obj) { // @SuppressWarnings("rawtypes") // Optional<EntryDefault> other = ObjectsHelper.asClass(obj, EntryDefault.class); // if (other.isPresent()) { // return Objects.equals(value, other.get().value) // && Objects.equals(geometry, other.get().geometry); // } else // return false; // } // // } // Path: src/main/java/com/github/davidmoten/rtree/Entries.java import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.internal.EntryDefault; package com.github.davidmoten.rtree; public final class Entries { private Entries() { // prevent instantiation } public static <T, S extends Geometry> Entry<T,S> entry(T object, S geometry) {
return EntryDefault.entry(object, geometry);