file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Spectrogram.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Spectrogram.java | /*
* Spectrogram.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import org.jtransforms.fft.FloatFFT_1D;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import static hcm.ssj.signal.FilterTools.WINDOW_TYPE;
import static hcm.ssj.signal.Matrix.MATRIX_DIMENSION;
/**
* Created by Johnny on 07.04.2017.
* Computes spectrogram of input stream
*
* Code adapted from SSI's Spectrogram.cpp
*/
public class Spectrogram extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<Integer> nfft = new Option<>("nbanks", 512, Integer.class, "#fft coefficients");
public final Option<Integer> nbanks = new Option<>("nbanks", 2, Integer.class, "#filter banks");
// public final Option<Double> minfreq = new Option<> ("minfreq", 0.0, Double.class, "mininmum frequency");
// public final Option<Double> maxfreq = new Option<> ("maxfreq", 0.0, Double.class, "maximum frequency (nyquist if 0)");
public final Option<FilterTools.WINDOW_TYPE> wintype = new Option<> ("wintype", FilterTools.WINDOW_TYPE.HAMMING, FilterTools.WINDOW_TYPE.class, "window type");
public final Option<Boolean> dolog = new Option<> ("dolog", true, Boolean.class, "apply logarithm");
public final Option<Boolean> dopower = new Option<>("dopower", false, Boolean.class, "compute the PSD for every bank");
public final Option<String> banks = new Option<>("banks", "0.040 0.150, 0.150 0.400", String.class, "string with filter banks that gets applied if no file was set (example: \"0.003 0.040\n0.040 0.150\n0.150 0.400\").");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private int _fft_size = 0;
private int _rfft;
private FilterTools.WINDOW_TYPE _win_type = FilterTools.WINDOW_TYPE.HAMMING;
private int _win_size = 0;
private Matrix<Float> _filterbank = null;
private FloatFFT_1D _fft = null;
private Matrix<Float> _fftmag = null;
private Matrix<Float> _window = null;
private boolean _apply_log = false;
Matrix<Float> _matrix_in;
Matrix<Float> _matrix_out;
float _data_in[];
float _data_out[];
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (_filterbank == null) {
if (options.banks.get() != null)
{
readFilterbank(options.banks.get(), stream_in[0].sr);
}
else
{
Log.e("frequency banks not set");
}
}
if (stream_in[0].num > options.nfft.get())
{
Log.w("nfft too small (" + options.nfft.get() + ") for input stream (num=" + stream_in[0].num + "), extra samples will get ignored");
}
_matrix_in = new Matrix<>(stream_in[0].num, 1);
_matrix_out = new Matrix<>(1, _filterbank.getCols());
_data_in = new float[_fft_size];
Arrays.fill(_data_in, 0);
_data_out = new float[_rfft];
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
for(int i = 0; i < stream_in[0].num; i++)
{
switch (stream_in[0].type)
{
case FLOAT:
_matrix_in.setData(i, stream_in[0].ptrF()[i]);
break;
case DOUBLE:
_matrix_in.setData(i, (float)stream_in[0].ptrD()[i]);
break;
}
}
//apply window
if (_win_size != _matrix_in.getRows()) {
_win_size = _matrix_in.getRows();
if (_win_type != WINDOW_TYPE.RECTANGLE) {
_window = FilterTools.getInstance().Window (_win_size, _win_type, MATRIX_DIMENSION.COL);
}
}
if (_win_type != WINDOW_TYPE.RECTANGLE)
{
MatrixOps.getInstance().mult(_matrix_in, _window);
}
//copy data from matrix for fft
//if nfft to large, fill with zeroes
for (int i = 0; i < _data_in.length && i < _matrix_in.getSize(); i++)
{
_data_in[i] = _matrix_in.getData(i);
}
for (int i = _matrix_in.getSize(); i < _data_in.length; i++)
{
_data_in[i] = 0;
}
// Calculate FFT
_fft.realForward(_data_in);
// Format values like in SSI
Util.joinFFT(_data_in, _data_out);
for (int i = 0; i < _data_out.length; ++i)
{
if (options.dopower.get())
{
_data_out[i] = (float) Math.pow(_data_out[i], 2) / _data_out.length;
}
_fftmag.setData(i, _data_out[i]);
}
MatrixOps.getInstance().multM (_fftmag, _filterbank, _matrix_out);
//compute log
if (_apply_log) {
MatrixOps.getInstance().log10 (_matrix_out);
}
float output[] = stream_out.ptrF();
for (int i = 0; i < _matrix_out.getSize(); i++)
{
output[i] = _matrix_out.getData(i);
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_win_size = 0;
}
private void readFilterbank (String string, double sr)
{
int n_banks = 0;
Matrix<Float> intervals;
String[] banks = string.split("\\s*,\\s*");
n_banks = banks.length;
if (options.nbanks.get() != n_banks) {
Log.e("#banks ("+n_banks+") in string '"+string+"' differs from #banks ("+options.nbanks+") in options");
}
intervals = new Matrix<>(n_banks, 2);
int current_bank = 0;
for (String bank : banks){
String[] freq = bank.split("\\s+");
intervals.setData(current_bank * 2, Float.valueOf(freq[0]));
intervals.setData(current_bank * 2 + 1, Float.valueOf(freq[1]));
current_bank++;
}
Matrix<Float> filterbank = FilterTools.getInstance().Filterbank(options.nfft.get(), sr, intervals, options.wintype.get());
setFilterbank(filterbank, options.wintype.get(), options.dolog.get());
}
private void setFilterbank (Matrix<Float> filterbank, FilterTools.WINDOW_TYPE win_type, boolean apply_log)
{
_fft = null;
_fftmag = null;
_filterbank = null;
_fft_size = (filterbank.getCols() - 1) << 1;
_rfft = (_fft_size >> 1) + 1;
_win_type = win_type;
_apply_log = apply_log;
_filterbank = filterbank;
_filterbank.transpose();
_fft = new FloatFFT_1D (_fft_size);
_fftmag = new Matrix<> (1, _rfft);
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
if(stream_in[0].dim > 1)
Log.e("dimension > 1 not supported");
if (_filterbank != null) {
return _filterbank.getCols();
} else {
return options.nbanks.get();
}
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT && stream_in[0].type != Cons.Type.DOUBLE)
Log.e("input stream type not supported");
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[]{"spectrogram"};
}
}
| 8,337 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IIR.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/IIR.java | /*
* IIR.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Provides second-order infinite impulse response (IIR) filtering.
*
* Created by Michael Dietz on 11.08.2015.
*/
public class IIR extends Transformer
{
int _sections;
Matrix<Float> _coefficients;
Matrix<Float> _history;
public IIR()
{
_name = "IIR";
}
public void setCoefficients(Matrix<Float> coefficients)
{
_coefficients = null;
_sections = coefficients.getRows();
// filt = [b_11, b_12, b_13, 1, a_12, a_13;
// b_21, b_22, b_23, 1, a_22, a_23;
// ...
// b_n1, b_n2, b_n3, 1, a_n2, a_n3];
//
// so all we need to store are b_x1, b_x2, b_x3 and a_x2, a_x3
// also, we store them in the order a_x2, a_x3, b_x1, b_x2, b_x3
// since this is the order in which we'll access them later
_coefficients = new Matrix<>(_sections, 5);
for (int i = 0; i < _sections; i++)
{
_coefficients.setData(i, 0, coefficients.getData(i, 4));
_coefficients.setData(i, 1, coefficients.getData(i, 5));
_coefficients.setData(i, 2, coefficients.getData(i, 0));
_coefficients.setData(i, 3, coefficients.getData(i, 1));
_coefficients.setData(i, 4, coefficients.getData(i, 2));
}
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int sampleDimension = stream_in[0].dim;
_history = new Matrix<>(_sections * sampleDimension, 2);
_history.fillValue(0.0f);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int sampleDimension = stream_in[0].dim;
int sampleNumber = stream_in[0].num;
float[] srcPtr = stream_in[0].ptrF();
float[] dstPtr = stream_out.ptrF();
float hist1;
float hist2;
float newHist;
int srcIndex = 0;
int dstIndex = 0;
int histPtrIndex = 0;
int coefsPtrIndex = 0;
int coefsTmpPtrIndex = 0;
int histPtrTmpIndex = 0;
int histPtrTmp1Index = 0;
int histPtrTmp2Index = 0;
for (int i = 0; i < sampleNumber; i++)
{
histPtrTmpIndex = histPtrIndex;
for (int j = 0; j < sampleDimension; j++)
{
dstPtr[dstIndex] = srcPtr[srcIndex];
coefsTmpPtrIndex = coefsPtrIndex;
histPtrTmp1Index = histPtrTmpIndex;
histPtrTmp2Index = histPtrTmp1Index + 1;
for (int k = 0; k < _sections; k++)
{
hist1 = _history.getData(histPtrTmp1Index);
hist2 = _history.getData(histPtrTmp2Index);
dstPtr[dstIndex] -= hist1 * _coefficients.getData(coefsTmpPtrIndex++); // a_x2
newHist = dstPtr[dstIndex] - hist2 * _coefficients.getData(coefsTmpPtrIndex++); // a_x3
dstPtr[dstIndex] = newHist * _coefficients.getData(coefsTmpPtrIndex++); // b_x1
dstPtr[dstIndex] += hist1 * _coefficients.getData(coefsTmpPtrIndex++); // b_x2
dstPtr[dstIndex] += hist2 * _coefficients.getData(coefsTmpPtrIndex++); // b_x3
_history.setData(histPtrTmp2Index++, hist1);
_history.setData(histPtrTmp1Index++, newHist);
histPtrTmp2Index++;
histPtrTmp1Index++;
}
srcIndex++;
dstIndex++;
histPtrTmpIndex += (_sections << 1);
}
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return stream_in[0].dim;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT); // Float
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 5,391 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MvgAvgVar.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MvgAvgVar.java | /*
* MvgAvgVar.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Provides moving/sliding average and/or variance.
*
* Moving average: https://en.wikipedia.org/wiki/Moving_average#Simple_moving_average
* Sliding average: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
*/
public class MvgAvgVar extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public enum Method
{
MOVING,
SLIDING
}
public enum Format
{
AVERAGE,
VARIANCE,
AVG_AND_VAR
}
public class Options extends OptionList
{
public final Option<Double> window = new Option<>("window", 10., Double.class, "size of moving/sliding window in seconds");
public final Option<Method> method = new Option<>("method", Method.MOVING, Method.class, "");
public final Option<Format> format = new Option<>("format", Format.AVERAGE, Format.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
Implementation _impl;
public MvgAvgVar()
{
_name = "MvgAvgVar";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (options.method.get() == Method.MOVING)
{
_impl = new Moving(options);
}
else
{
_impl = new Sliding(options);
}
_impl.enter(stream_in[0], stream_out);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_impl.transform(stream_in[0], stream_out);
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_impl.flush(stream_in[0], stream_out);
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
if (options.format.get() == Format.AVG_AND_VAR)
{
return stream_in[0].dim * 2;
}
return stream_in[0].dim;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return 4; //float
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
interface Implementation
{
void enter(Stream stream_in, Stream stream_out);
void transform(Stream stream_in, Stream stream_out);
void flush(Stream stream_in, Stream stream_out);
}
class Moving implements Implementation
{
Options options;
int _window_size_N;
boolean _first_call;
int _history_size;
int _counter;
float _history[];
int _hist_iter_0;
int _hist_iter_N;
float _cumsum[];
float _cumsum_2[];
public Moving(Options options)
{
this.options = options;
}
@Override
public void enter(Stream stream_in, Stream stream_out)
{
// calculate history size
_window_size_N = (int) (options.window.get() * stream_in.sr + 0.5);
_history_size = _window_size_N + 1;
// allocate history array
_history = new float[_history_size * stream_in.dim];
_counter = _history_size;
_hist_iter_0 = _history_size - 1;
_hist_iter_N = 0;
_cumsum = new float[stream_in.dim];
_cumsum_2 = new float[stream_in.dim];
// set first call to true
_first_call = true;
}
@Override
public void transform(Stream stream_in, Stream stream_out)
{
int sample_dimension = stream_in.dim;
int sample_number = stream_in.num;
float srcptr[] = stream_in.ptrF();
float dstptr[] = stream_out.ptrF();
int hist_iter, src_iter = 0, dst_iter = 0;
float x_0, x_N, sum, sum_2;
float var;
// initialize history array
if (_first_call)
{
hist_iter = 0;
for (int i = 0; i < _history_size; ++i)
{
for (int j = 0; j < sample_dimension; ++j)
{
_history[hist_iter++] = srcptr[j];
}
}
for (int j = 0; j < sample_dimension; ++j)
{
_cumsum[j] = _window_size_N * srcptr[j];
_cumsum_2[j] = _window_size_N * srcptr[j] * srcptr[j];
}
_first_call = false;
}
for (int i = 0; i < sample_number; ++i)
{
// increment history;
++_counter;
_hist_iter_N += sample_dimension;
_hist_iter_0 += sample_dimension;
if (_counter > _history_size)
{
_counter = 1;
_hist_iter_0 = 0;
}
if (_counter == _history_size)
{
_hist_iter_N = 0;
}
for (int j = 0; j < sample_dimension; ++j)
{
x_0 = srcptr[src_iter++];
x_N = _history[_hist_iter_N + j];
sum = _cumsum[j];
sum_2 = _cumsum_2[j];
// insert new sample
_history[_hist_iter_0 + j] = x_0;
// update sum
sum = sum - x_N + x_0;
sum_2 = sum_2 - x_N * x_N + x_0 * x_0;
// calculate avg and var
if (options.format.get() == Format.AVERAGE || options.format.get() == Format.AVG_AND_VAR)
{
dstptr[dst_iter++] = sum / _window_size_N;
}
if (options.format.get() == Format.VARIANCE || options.format.get() == Format.AVG_AND_VAR)
{
var = (_window_size_N * sum_2 - sum * sum) / (_window_size_N * (_window_size_N - 1));
dstptr[dst_iter++] = var > 0 ? var : Float.MIN_VALUE;
}
_cumsum[j] = sum;
_cumsum_2[j] = sum_2;
}
}
}
@Override
public void flush(Stream stream_in, Stream stream_out)
{
}
}
class Sliding implements Implementation
{
Options options;
float _alpha = 0;
float _1_alpha = 0;
float _avg_hist[];
float _var_hist[];
boolean _first_call = true;
public Sliding(Options options)
{
this.options = options;
}
@Override
public void enter(Stream stream_in, Stream stream_out)
{
int sample_dimension = stream_in.dim;
double sample_rate = stream_in.sr;
// allocate history arrays
_avg_hist = new float[sample_dimension];
_var_hist = new float[sample_dimension];
// allocate and initialize alpha array
_alpha = (float) (1.0 - (2.0 * Math.sqrt(3.0)) / (options.window.get() * sample_rate));
_1_alpha = 1 - _alpha;
// set first call to true
_first_call = true;
}
@Override
public void transform(Stream stream_in, Stream stream_out)
{
int sample_dimension = stream_in.dim;
int sample_number = stream_in.num;
float srcptr[] = stream_in.ptrF();
float dstptr[] = stream_out.ptrF();
int avg_iter, var_iter, src_iter = 0, dst_iter = 0;
float x, x_avg, avg, var;
// initialize history array
if (_first_call)
{
avg_iter = 0;
var_iter = 0;
for (int i = 0; i < sample_dimension; ++i)
{
_avg_hist[avg_iter++] = srcptr[i];
_var_hist[var_iter++] = 0;
}
_first_call = false;
}
// do transformation
switch (options.format.get())
{
case AVERAGE:
{
for (int i = 0; i < sample_number; ++i)
{
avg_iter = 0;
for (int j = 0; j < sample_dimension; ++j)
{
x = srcptr[src_iter++];
avg = _avg_hist[avg_iter];
avg = _alpha * avg + _1_alpha * x;
_avg_hist[avg_iter++] = avg;
dstptr[dst_iter++] = avg;
}
}
break;
}
case VARIANCE:
case AVG_AND_VAR:
{
boolean store_all = options.format.get() == Format.AVG_AND_VAR;
for (int i = 0; i < sample_number; ++i)
{
avg_iter = 0;
var_iter = 0;
for (int j = 0; j < sample_dimension; ++j)
{
x = srcptr[src_iter++];
avg = _avg_hist[avg_iter];
var = _var_hist[var_iter];
avg = _alpha * avg + _1_alpha * x;
x_avg = x - avg;
var = _alpha * var + _1_alpha * x_avg * x_avg;
var = var > 0 ? var : Float.MIN_VALUE;
_avg_hist[avg_iter++] = avg;
_var_hist[var_iter++] = var;
if (store_all)
{
dstptr[dst_iter++] = avg;
}
dstptr[dst_iter++] = var;
}
}
break;
}
}
}
@Override
public void flush(Stream stream_in, Stream stream_out)
{
}
}
}
| 9,611 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MinMax.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MinMax.java | /*
* MinMax.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* A general transformer to calculate min and/or max for every dimension in the provided streams.<br>
* The output is ordered for every dimension as min than max.
* Created by Frank Gaibler on 27.08.2015.
*/
public class MinMax extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<Boolean> min = new Option<>("min", true, Boolean.class, "Calculate minimum for each frame");
public final Option<Boolean> max = new Option<>("max", true, Boolean.class, "Calculate maximum for each frame");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//helper variables
private float[][] floats;
private int multiplier;
private int[] streamDimensions;
float[] minValues;
float[] maxValues;
/**
*
*/
public MinMax()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//no check for a specific type to allow for different providers
if (stream_in.length < 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
//every stream should have the same sample number
int num = stream_in[0].num;
for (int i = 1; i < stream_in.length; i++)
{
if (num != stream_in[i].num)
{
Log.e("invalid input stream num for stream " + i);
return;
}
}
floats = new float[stream_in.length][];
for (int i = 0; i < floats.length; i++)
{
floats[i] = new float[stream_in[i].num * stream_in[i].dim];
}
if (multiplier > 0)
{
minValues = new float[stream_out.dim / multiplier];
maxValues = new float[stream_out.dim / multiplier];
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
super.flush(stream_in, stream_out);
floats = null;
minValues = null;
maxValues = null;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (multiplier > 0)
{
float[] out = stream_out.ptrF();
if (options.min.get())
{
Arrays.fill(minValues, Float.MAX_VALUE);
}
if (options.max.get())
{
Arrays.fill(maxValues, -Float.MAX_VALUE); //Float.MIN_VALUE is the value closest to zero and not the lowest float value possible
}
//calculate values for each stream
for (int i = 0; i < stream_in[0].num; i++)
{
int t = 0;
for (int j = 0; j < stream_in.length; j++)
{
Util.castStreamPointerToFloat(stream_in[j], floats[j]);
for (int k = 0; k < stream_in[j].dim; k++, t++)
{
float value = floats[j][i * stream_in[j].dim + k];
if (options.min.get())
{
minValues[t] = minValues[t] < value ? minValues[t] : value;
}
if (options.max.get())
{
maxValues[t] = maxValues[t] > value ? maxValues[t] : value;
}
}
}
}
if (options.min.get() && !options.max.get())
{
System.arraycopy(minValues, 0, out, 0, minValues.length);
} else if (!options.min.get() && options.max.get())
{
System.arraycopy(maxValues, 0, out, 0, maxValues.length);
} else
{
for (int i = 0, j = 0; i < maxValues.length; i++)
{
out[j++] = minValues[i];
out[j++] = maxValues[i];
}
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
multiplier = 0;
multiplier = options.min.get() ? multiplier + 1 : multiplier;
multiplier = options.max.get() ? multiplier + 1 : multiplier;
if (multiplier <= 0)
{
Log.e("no option selected");
}
int overallDimension = 0;
streamDimensions = new int[stream_in.length];
for (int i = 0; i < streamDimensions.length; i++)
{
streamDimensions[i] = stream_in[i].dim * multiplier;
overallDimension += streamDimensions[i];
}
return overallDimension;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0, k = 0; i < streamDimensions.length; i++)
{
for (int j = 0, m = 0; j < streamDimensions[i]; j += multiplier, m++)
{
if (options.min.get())
{
stream_out.desc[k++] = "min" + i + "." + m;
}
if (options.max.get())
{
stream_out.desc[k++] = "max" + i + "." + m;
}
}
}
}
} | 8,810 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MatrixOps.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MatrixOps.java | /*
* MatrixOps.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 12.08.2015.
*/
public class MatrixOps
{
private static MatrixOps _instance = null;
/**
* Private constructor for singleton pattern.
*/
private MatrixOps()
{
}
/**
* Method for accessing the singleton instance.
*
* @return singleton instance
*/
public static MatrixOps getInstance()
{
if (_instance == null)
{
_instance = new MatrixOps();
}
return _instance;
}
public Matrix<Float> array (float start, float delta, float end, Matrix.MATRIX_DIMENSION dimension)
{
int steps = (int) (((end - start) / (double)(delta)) + 1.001);
Matrix<Float> matrix;
if (steps <= 0) {
matrix = new Matrix<> (0,0);
return matrix;
}
switch (dimension) {
case ROW:
matrix = new Matrix<> (1, steps);
break;
case COL:
default:
matrix = new Matrix<> (steps, 1);
break;
}
int dataptr = 0;
matrix.setData(dataptr, start);
for (int i = 0; i < steps-1; i++)
{
matrix.setData(dataptr+1, matrix.getData(dataptr) + delta);
dataptr++;
}
return matrix;
}
public Complex multiplyVector(Matrix<Complex> vec1, Matrix<Complex> vec2)
{
Complex result = new Complex(0, 0);
int len = vec1.getCols() * vec1.getRows();
for (int i = 0; i < len; i++)
{
Complex c = vec1.getData(i).times(vec2.getData(i));
result = result.plus(c);
}
return result;
}
public void plus (Matrix<Float> matrix, float scalar)
{
if (matrix.getData().isEmpty()) {
return;
}
for (int i = 0; i < matrix.getSize(); i++) {
matrix.setData(i, matrix.getData(i) + scalar);
}
}
public void mult (Matrix<Float> matrix, float scalar)
{
if (matrix.getData().isEmpty()) {
return;
}
for (int i = 0; i < matrix.getSize(); i++) {
matrix.setData(i, matrix.getData(i) * scalar);
}
}
public void mult(Matrix<Float> a, Matrix<Float> b)
{
if(a.getRows() != b.getRows() || a.getCols() != b.getCols())
{
Log.w("matrices not matching");
return;
}
if(a.getData().isEmpty())
return;
for(int i = 0; i < a.getSize(); i++)
{
a.setData(i, a.getData(i) * b.getData(i));
}
}
public void multM(Matrix<Float> a, Matrix<Float> b, Matrix<Float> dst)
{
if(a.getCols() != b.getRows() || dst.getRows() != a.getRows() || dst.getCols() != b.getCols())
{
Log.w("matrices not matching");
return;
}
dst.fillValue(0f);
int aptr = 0;
int bptr = 0;
int dstptr = 0;
int dstptr2 = 0;
for (int i = 0; i < a.getRows(); i++) {
bptr = 0;
for (int j = 0; j < b.getRows(); j++) {
dstptr2 = dstptr;
for (int k = 0; k < b.getCols(); k++) {
dst.setData(dstptr2, dst.getData(dstptr2) + b.getData(bptr) * a.getData(aptr));
bptr++;
dstptr2++;
}
aptr++;
}
dstptr = dstptr2;
}
}
public void div(Matrix<Float> a, Matrix<Float> b)
{
if(a.getRows() != b.getRows() || a.getCols() != b.getCols())
{
Log.w("matrices not matching");
return;
}
if(a.getData().isEmpty())
return;
int elements = a.getRows() * a.getCols();
for(int i = 0; i < elements; i++)
{
a.setData(i, a.getData(i) / b.getData(i));
}
}
public void div (Matrix<Float> matrix, float scalar)
{
if (matrix.getData().isEmpty()) {
return;
}
int elems = matrix.getRows() * matrix.getCols();
for (int i = 0; i < elems; i++) {
matrix.setData(i, matrix.getData(i) / scalar);
}
}
public float sum(Matrix<Float> matrix)
{
float sum = 0;
int elems = matrix.getRows() * matrix.getCols();
for (int i = 0; i < elems; i++) {
sum += matrix.getData(i);
}
return sum;
}
public void cos (Matrix<Float> matrix)
{
if (matrix.getData().isEmpty()) {
return;
}
for (int i = 0; i < matrix.getSize(); i++) {
matrix.setData(i, (float)Math.cos(matrix.getData(i)));
}
}
public void log10 (Matrix<Float> matrix)
{
if (matrix.getData().isEmpty()) {
return;
}
for (int i = 0; i < matrix.getSize(); i++) {
float val = matrix.getData(i);
matrix.setData(i, (val <= 0) ? 0 : (float)Math.log10(val));
}
}
}
| 5,421 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FilterTools.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/FilterTools.java | /*
* FilterTools.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Log;
import hcm.ssj.signal.Matrix.MATRIX_DIMENSION;
import static java.lang.Math.PI;
/**
* Created by Michael Dietz on 13.08.2015.
*/
public class FilterTools
{
private static FilterTools _instance = null;
public enum WINDOW_TYPE
{
//! rectangular window
RECTANGLE,
//! triangle window
TRIANGLE,
//! gauss window
GAUSS,
//! hamming window
HAMMING
}
;
/**
* Private constructor for singleton pattern.
*/
private FilterTools()
{
}
/**
* Method for accessing the singleton instance.
*
* @return singleton instance
*/
public static FilterTools getInstance()
{
if (_instance == null)
{
_instance = new FilterTools();
}
return _instance;
}
public Matrix<Float> getLPButter(int order, double cutoff)
{
int sections = (order + 1) / 2;
Matrix<Float> sos = new Matrix<>(sections, 6);
sos.fillValue(1.0f);
double freq = cutoff / 2.0;
Matrix<Complex> poles = getButterPoles(sections, freq);
for (int i = 0; i < sections; i++)
{
double poleReal = poles.getData(i).real();
double poleImag = poles.getData(i).imag();
double a1 = -2.0 * poleReal;
double a2 = poleReal * poleReal + poleImag * poleImag;
double gain = 4.0 / (1.0 + a1 + a2);
sos.setData(i, 0, (float) (1.0 / gain));
sos.setData(i, 1, (float) (2.0 / gain));
sos.setData(i, 2, (float) (1.0 / gain));
sos.setData(i, 3, (float) (1.0));
sos.setData(i, 4, (float) (a1));
sos.setData(i, 5, (float) (a2));
}
return sos;
}
public Matrix<Float> getHPButter(int order, double cutoff)
{
int sections = (order + 1) / 2;
Matrix<Float> sos = new Matrix<>(sections, 6);
sos.fillValue(1.0f);
double freq = cutoff / 2.0;
Matrix<Complex> poles = getButterPoles(sections, 0.5 - freq);
for (int i = 0; i < sections; i++)
{
double poleReal = -poles.getData(i).real();
double poleImag = poles.getData(i).imag();
double a1 = -2.0 * poleReal;
double a2 = poleReal * poleReal + poleImag * poleImag;
Matrix<Complex> tmp = new Matrix<>(3, 1);
tmp.setData(0, new Complex(1.0, 0.0));
tmp.setData(1, new Complex(Math.cos(0.5 * PI), Math.sin(0.5 * PI)));
tmp.setData(2, new Complex(Math.cos(PI), Math.sin(PI)));
Matrix<Complex> tmp2 = new Matrix<>(1, 3);
tmp2.setData(0, new Complex(1.0, 0.0));
tmp2.setData(1, new Complex(a1, 0.0));
tmp2.setData(2, new Complex(a2, 0.0));
double gain = new Complex(2.0, 0.0).div(MatrixOps.getInstance().multiplyVector(tmp2, tmp)).mod();
sos.setData(i, 0, (float) (1.0 / gain));
sos.setData(i, 1, (float) (-2.0 / gain));
sos.setData(i, 2, (float) (1.0 / gain));
sos.setData(i, 3, (float) (1.0));
sos.setData(i, 4, (float) (a1));
sos.setData(i, 5, (float) (a2));
}
return sos;
}
public Matrix<Float> getBPButter(int order, double lowCutoff, double highCutoff)
{
int sections = (order + 1) / 2;
Matrix<Float> sos = new Matrix<>(sections, 6);
sos.fillValue(1.0f);
double lFreq = lowCutoff / 2.0;
double hFreq = highCutoff / 2.0;
Matrix<Complex> polesTmp = getButterPoles(sections / 2, hFreq - lFreq);
double wLow = 2 * PI * lFreq;
double wHigh = 2 * PI * hFreq;
double ang = Math.cos((wHigh + wLow) / 2) / Math.cos((wHigh - wLow) / 2);
Matrix<Complex> poles = new Matrix<>(sections, 1);
poles.fillValue(new Complex(0, 0));
for (int i = 0; i < sections / 2; i++)
{
Complex p1 = new Complex(polesTmp.getData(i).real() + 1, polesTmp.getData(i).imag());
Complex tmp = p1.times(p1).times(ang * ang * 0.25).minus(polesTmp.getData(i)).sqrt();
poles.setData(2 * i, p1.times(ang * 0.5).plus(tmp));
poles.setData(2 * i + 1, p1.times(ang * 0.5).minus(tmp));
}
for (int i = 0; i < sections; i++)
{
double poleReal = poles.getData(i).real();
double poleImag = poles.getData(i).imag();
double a1 = -2.0 * poleReal;
double a2 = poleReal * poleReal + poleImag * poleImag;
Matrix<Complex> tmp = new Matrix<>(3, 1);
tmp.setData(0, new Complex(1.0, 0.0));
tmp.setData(1, new Complex(Math.cos((lFreq + hFreq) * PI), Math.sin((lFreq + hFreq) * PI)));
tmp.setData(2, new Complex(Math.cos(2 * (lFreq + hFreq) * PI), Math.sin(2 * (lFreq + hFreq) * PI)));
Matrix<Complex> tmp2 = new Matrix<>(1, 3);
tmp2.setData(0, new Complex(1.0, 0.0));
tmp2.setData(1, new Complex(a1, 0.0));
tmp2.setData(2, new Complex(a2, 0.0));
double gain = Math.abs(new Complex(0.1685, 0.5556).div(MatrixOps.getInstance().multiplyVector(tmp2, tmp)).mod());
sos.setData(i, 0, (float) (1.0 / gain));
sos.setData(i, 1, 0.0f);
sos.setData(i, 2, (float) (-1.0 / gain));
sos.setData(i, 3, (float) (1.0));
sos.setData(i, 4, (float) (a1));
sos.setData(i, 5, (float) (a2));
}
return sos;
}
public Matrix<Complex> getButterPoles(int sections, double frequency)
{
int columns = 1;
Matrix<Complex> poles = new Matrix<>(sections, columns);
// Fill with zeros
for (int row = 0; row < sections; row++)
{
for (int col = 0; col < columns; col++)
{
poles.setData(row, col, new Complex(0, 0));
}
}
double w = PI * frequency;
double tanW = Math.sin(w) / Math.cos(w);
int polesIndex = 0;
for (int m = sections; m <= 2 * sections - 1; m++)
{
double ang = (2.0 * m + 1) * PI / (4.0 * sections);
double d = 1.0 - 2.0 * tanW * Math.cos(ang) + tanW * tanW;
double real = (1.0 - tanW * tanW) / d;
double imag = 2.0 * tanW * Math.sin(ang) / d;
poles.setData(polesIndex++, new Complex(real, imag));
}
return poles;
}
Matrix<Float> Filterbank(int size, double sample_rate, Matrix<Float> intervals, WINDOW_TYPE type)
{
Matrix<Float> filterbank = new Matrix<>(intervals.getRows(), size);
filterbank.fillValue(0f);
sample_rate /= 2; // convert sampling to nyquist rate
int intervalsptr = 0;
for (int i = 0; i < filterbank.getRows(); i++)
{
int minind = (int) ((intervals.getData(intervalsptr) / sample_rate) * size + 0.5f);
intervalsptr++;
int maxind = (int) ((intervals.getData(intervalsptr) / sample_rate) * size + 0.5f);
intervalsptr++;
maxind = Math.min(maxind, size - 1);
Matrix<Float> winmat = Window(1 + (maxind - minind), type, MATRIX_DIMENSION.ROW);
MatrixOps.getInstance().div(winmat, MatrixOps.getInstance().sum(winmat));
filterbank.setSubMatrix(i, minind, winmat);
}
return filterbank;
}
public Matrix<Float> Window(int size, WINDOW_TYPE type, MATRIX_DIMENSION dimension)
{
Matrix<Float> window;
if (size < 1)
{
window = new Matrix<>(0, 0);
}
else if (size == 1)
{
window = new Matrix<>(1, 1);
window.setData(0, 1f);
}
else
{
switch (type)
{
default:
case RECTANGLE:
window = new Matrix<>(1, size);
window.fillValue(1f);
break;
case TRIANGLE:
Log.e("window "+type.name()+" not supported yet");
return null;
case GAUSS:
Log.e("window "+type.name()+" not supported yet");
return null;
case HAMMING:
{
window = MatrixOps.getInstance().array(0,1, size-1, MATRIX_DIMENSION.ROW);
float scalar = (float) ((2.0 * PI) / size);
MatrixOps.getInstance().mult (window, scalar);
MatrixOps.getInstance().cos (window);
MatrixOps.getInstance().mult (window, -0.46f);
MatrixOps.getInstance().plus (window, 0.54f);
}
break;
}
// swap dimension if column vector
if (dimension == MATRIX_DIMENSION.COL)
{
window.transpose();
}
}
return window;
}
}
| 8,807 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Serializer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Serializer.java | /*
* Serializer.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Merges input streams which the same sample rate and the same type to one stream.<br>
* Created by Frank Gaibler on 24.11.2015.
*/
public class Serializer extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<Cons.Type> outputType = new Option<>("outputType", Cons.Type.FLOAT, Cons.Type.class, "The output type for which the input streams have to match.");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
/**
*
*/
public Serializer()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//check for valid stream
if (stream_in.length < 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
//every stream should have the same sample number
int num = stream_in[0].num;
for (int i = 1; i < stream_in.length; i++)
{
if (num != stream_in[i].num)
{
Log.e("invalid sample number for stream_in " + i);
return;
}
}
//not all types are supported
if (options.outputType.get() == Cons.Type.EMPTY || options.outputType.get() == Cons.Type.UNDEF)
{
Log.e("output type is not supported");
}
//every stream should have the same type
for (int i = 0; i < stream_in.length; i++)
{
if (options.outputType.get() != stream_in[i].type)
{
Log.e("invalid type for stream_in " + i);
return;
}
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
switch (options.outputType.get())
{
case BOOL:
{
boolean[] out = stream_out.ptrBool();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrBool()[i * aStream_in.dim + k];
}
}
}
break;
}
case BYTE:
{
byte[] out = stream_out.ptrB();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrB()[i * aStream_in.dim + k];
}
}
}
break;
}
case CHAR:
{
char[] out = stream_out.ptrC();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrC()[i * aStream_in.dim + k];
}
}
}
break;
}
case DOUBLE:
{
double[] out = stream_out.ptrD();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrD()[i * aStream_in.dim + k];
}
}
}
break;
}
case FLOAT:
{
float[] out = stream_out.ptrF();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrF()[i * aStream_in.dim + k];
}
}
}
break;
}
case INT:
{
int[] out = stream_out.ptrI();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrI()[i * aStream_in.dim + k];
}
}
}
break;
}
case LONG:
{
long[] out = stream_out.ptrL();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrL()[i * aStream_in.dim + k];
}
}
}
break;
}
case SHORT:
{
short[] out = stream_out.ptrS();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, z++)
{
//write to output
out[z] = aStream_in.ptrS()[i * aStream_in.dim + k];
}
}
}
break;
}
default:
Log.e("output type is not supported");
break;
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
int overallDimension = 0;
for (Stream stream : stream_in)
{
overallDimension += stream.dim;
}
return overallDimension;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(options.outputType.get());
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return options.outputType.get();
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0, k = 0; i < stream_in.length; i++)
{
for (int j = 0; j < stream_in[i].dim; j++, k++)
{
stream_out.desc[k] = "srlz" + i + "." + j;
}
}
}
} | 10,562 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Functionals.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Functionals.java | /*
* Functionals.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* A variety of metrics. <br>
* Created by Frank Gaibler on 10.01.2017.
*/
public class Functionals extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<Boolean> mean = new Option<>("mean", true, Boolean.class, "Calculate mean of each frame");
public final Option<Boolean> energy = new Option<>("energy", true, Boolean.class, "Calculate energy of each frame");
public final Option<Boolean> std = new Option<>("std", true, Boolean.class, "Calculate standard deviation of each frame");
public final Option<Boolean> min = new Option<>("min", true, Boolean.class, "Calculate minimum of each frame");
public final Option<Boolean> max = new Option<>("max", true, Boolean.class, "Calculate maximum of each frame");
public final Option<Boolean> range = new Option<>("range", true, Boolean.class, "Calculate range of each frame");
public final Option<Boolean> minPos = new Option<>("minPos", true, Boolean.class, "Calculate sample position of the minimum of each frame");
public final Option<Boolean> maxPos = new Option<>("maxPos", true, Boolean.class, "Calculate sample position of the maximum of each frame");
public final Option<Boolean> zeros = new Option<>("zeros", true, Boolean.class, "Calculate zeros of each frame");
public final Option<Boolean> peaks = new Option<>("peaks", true, Boolean.class, "Calculate peaks of each frame");
public final Option<Boolean> len = new Option<>("len", true, Boolean.class, "Calculate sample number of each frame");
public final Option<Boolean> path = new Option<>("path", false, Boolean.class, "Calculate path length of each frame");
public final Option<Integer> delta = new Option<>("delta", 2, Integer.class, "zero/peaks search offset");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//helper variables
private int _delta;
private float[] _mean_val;
private float[] _energy_val;
private float[] _std_val;
private float[] _min_val;
private float[] _max_val;
private int[] _min_pos;
private int[] _max_pos;
private int[] _zeros;
private int[] _peaks;
private float[] _left_val;
private float[] _mid_val;
private float[] _path;
private float[] _old_val;
/**
*
*/
public Functionals()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (stream_in.length != 1 || stream_in[0].dim < 1 || stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("invalid input stream");
return;
}
_delta = options.delta.get();
int sample_dimension = stream_in[0].dim;
_mean_val = new float[sample_dimension];
_energy_val = new float[sample_dimension];
_std_val = new float[sample_dimension];
_min_val = new float[sample_dimension];
_max_val = new float[sample_dimension];
_min_pos = new int[sample_dimension];
_max_pos = new int[sample_dimension];
_zeros = new int[sample_dimension];
_peaks = new int[sample_dimension];
_left_val = new float[sample_dimension];
_mid_val = new float[sample_dimension];
_path = new float[sample_dimension];
_old_val = new float[sample_dimension];
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
super.flush(stream_in, stream_out);
_mean_val = null;
_energy_val = null;
_std_val = null;
_min_val = null;
_max_val = null;
_min_pos = null;
_max_pos = null;
_zeros = null;
_peaks = null;
_left_val = null;
_mid_val = null;
_path = null;
_old_val = null;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
boolean first_call = true;
int sample_number = stream_in[0].num, sample_dimension = stream_in[0].dim, c_in = 0, c_out = 0;
float[] ptr_in = stream_in[0].ptrF(), ptr_out = stream_out.ptrF();
float _val;
for (int i = 0; i < sample_dimension; i++)
{
_val = ptr_in[c_in++];
_mean_val[i] = _val;
_energy_val[i] = _val * _val;
_min_val[i] = _val;
_max_val[i] = _val;
_min_pos[i] = 0;
_max_pos[i] = 0;
_zeros[i] = 0;
_peaks[i] = 0;
_mid_val[i] = _val;
_path[i] = 0;
_old_val[i] = _val;
}
for (int i = 1; i < sample_number; i++)
{
for (int j = 0; j < sample_dimension; j++)
{
_val = ptr_in[c_in++];
_mean_val[j] += _val;
_energy_val[j] += _val * _val;
if (_val < _min_val[j])
{
_min_val[j] = _val;
_min_pos[j] = i;
} else if (_val > _max_val[j])
{
_max_val[j] = _val;
_max_pos[j] = i;
}
if ((i % _delta) == 0)
{
if (first_call)
{
first_call = false;
} else
{
if ((_left_val[j] > 0 && _mid_val[j] < 0) || (_left_val[j] < 0 && _mid_val[j] > 0))
{
_zeros[j]++;
}
if (_left_val[j] < _mid_val[j] && _mid_val[j] > _val)
{
_peaks[j]++;
}
}
_left_val[j] = _mid_val[j];
_mid_val[j] = _val;
}
_path[j] += Math.abs(_val - _old_val[j]);
_old_val[j] = _val;
}
}
for (int i = 0; i < sample_dimension; i++)
{
_mean_val[i] /= sample_number;
_energy_val[i] /= sample_number;
_std_val[i] = (float) Math.sqrt(Math.abs(_energy_val[i] - _mean_val[i] * _mean_val[i]));
}
if (options.mean.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _mean_val[i];
}
}
if (options.energy.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float)Math.sqrt(_energy_val[i]);
}
}
if (options.std.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _std_val[i];
}
}
if (options.min.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _min_val[i];
}
}
if (options.max.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _max_val[i];
}
}
if (options.range.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _max_val[i] - _min_val[i];
}
}
if (options.minPos.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float) (_min_pos[i]) / sample_number;
}
}
if (options.maxPos.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float) (_max_pos[i]) / sample_number;
}
}
if (options.zeros.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float) (_zeros[i]) / sample_number;
}
}
if (options.peaks.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float) (_peaks[i]) / sample_number;
}
}
if (options.len.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = (float) sample_number;
}
}
if (options.path.get())
{
for (int i = 0; i < sample_dimension; i++)
{
ptr_out[c_out++] = _path[i];
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = 0;
if (options.mean.get())
{
dim += stream_in[0].dim;
}
if (options.energy.get())
{
dim += stream_in[0].dim;
}
if (options.std.get())
{
dim += stream_in[0].dim;
}
if (options.min.get())
{
dim += stream_in[0].dim;
}
if (options.max.get())
{
dim += stream_in[0].dim;
}
if (options.range.get())
{
dim += stream_in[0].dim;
}
if (options.minPos.get())
{
dim += stream_in[0].dim;
}
if (options.maxPos.get())
{
dim += stream_in[0].dim;
}
if (options.zeros.get())
{
dim += stream_in[0].dim;
}
if (options.peaks.get())
{
dim += stream_in[0].dim;
}
if (options.len.get())
{
dim += stream_in[0].dim;
}
if (options.path.get())
{
dim += stream_in[0].dim;
}
return dim;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null && overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
} else
{
if (options.outputClass.get() != null && overallDimension != options.outputClass.get().length)
{
Log.w("invalid option outputClass length");
}
for (int i = 0; i < overallDimension; i++)
{
stream_out.desc[i] = "fnc" + i;
}
}
}
} | 13,631 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MathTools.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MathTools.java | /*
* MathTools.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.Arrays;
/**
* Created by Michael Dietz on 19.10.2016.
*/
public class MathTools
{
private static MathTools _instance = null;
/**
* Private constructor for singleton pattern.
*/
private MathTools()
{
}
/**
* Method for accessing the singleton instance.
*
* @return singleton instance
*/
public static MathTools getInstance()
{
if (_instance == null)
{
_instance = new MathTools();
}
return _instance;
}
/**
* Calculates the sum of all values
*
* @param values Input values
* @return Sum
*/
public float getSum(float[] values)
{
float sum = 0;
for (int i = 0; i < values.length; i++)
{
sum += values[i];
}
return sum;
}
/**
* Calculates the mean of all values
*
* @param values Input values
* @return Mean
*/
public float getMean(float[] values)
{
float mean = 0;
if (values.length > 0)
{
mean = getSum(values) / (float) values.length;
}
return mean;
}
/*
* Calculates the minimum of all values
*
* @param values Input values
* @return Min
*/
public float getMin(float[] values)
{
float min = Float.MAX_VALUE;
for (int i = 0; i < values.length; i++)
{
if (values[i] < min)
{
min = values[i];
}
}
if (min == Float.MAX_VALUE)
{
min = 0;
}
return min;
}
/*
* Calculates the maximum of all values
*
* @param values Input values
* @return Max
*/
public float getMax(float[] values)
{
float max = -Float.MAX_VALUE;
for (int i = 0; i < values.length; i++)
{
if (values[i] > max)
{
max = values[i];
}
}
if (max == -Float.MAX_VALUE)
{
max = 0;
}
return max;
}
/*
* Calculates the median of all values
*
* @param values Input values
* @return Median
*/
public float getMedian(float[] values)
{
float median = 0;
int n = values.length;
if (n > 0)
{
// Copy values for sorting
float[] valueCopies = new float[values.length];
System.arraycopy(values, 0, valueCopies, 0, values.length);
// Sort values ascending
Arrays.sort(valueCopies);
if (n % 2 == 0)
{
// Even
median = (valueCopies[n / 2 - 1] + valueCopies[n / 2]) / 2.0f;
}
else
{
// Odd
median = valueCopies[(n - 1) / 2];
}
}
return median;
}
/**
* Calculates the variance of all values
*
* @param values Input values
* @return Variance
*/
public float getVariance(float[] values)
{
float variance = 0;
if (values.length > 0)
{
float mean = getMean(values);
for (int i = 0; i < values.length; i++)
{
variance += Math.pow(values[i] - mean, 2);
}
variance = variance / (float) values.length;
}
return variance;
}
/**
* Calculates the standard deviation of all values
*
* @param values Input values
* @return Standard deviation
*/
public float getStdDeviation(float[] values)
{
float stdDeviation = 0;
if (values.length > 0)
{
stdDeviation = (float) Math.sqrt(getVariance(values));
}
return stdDeviation;
}
/*
* Calculates the skew of all values
*
* @param values Input values
* @return Skew
*/
public float getSkew(float[] values)
{
float skew = 0;
float mean = getMean(values);
float stdDeviation = getStdDeviation(values);
if (values.length > 0 && stdDeviation > 0)
{
for (int i = 0; i < values.length; i++)
{
skew += Math.pow((values[i] - mean) / stdDeviation, 3);
}
skew = skew / values.length;
}
return skew;
}
/*
* Calculates the kurtosis of all values
*
* @param values Input values
* @return Kurtosis
*/
public float getKurtosis(float[] values)
{
float kurtosis = 0;
float mean = getMean(values);
float stdDeviation = getStdDeviation(values);
if (values.length > 0 && stdDeviation > 0)
{
for (int i = 0; i < values.length; i++)
{
kurtosis += Math.pow((values[i] - mean) / stdDeviation, 4);
}
kurtosis = kurtosis / values.length;
}
return kurtosis;
}
/*
* Calculates the range of all values
*
* @param values Input values
* @return Range
*/
public float getRange(float[] values)
{
return getMax(values) - getMin(values);
}
/*
* Calculates the root mean square
*
* @param values Input values
* @return Root mean square
*/
public float getRMS(float[] values)
{
float rms = 0;
if (values.length > 0)
{
for (int i = 0; i < values.length; i++)
{
rms += Math.pow(values[i], 2);
}
rms = (float) Math.sqrt(rms / (float) values.length);
}
return rms;
}
/*
* Calculates the mean absolute deviation of all values
*
* @param values Input values
* @return Mean absolute deviation
*/
public float getMAD(float[] values)
{
float mad = 0;
float mean = getMean(values);
if (values.length > 0)
{
for (int i = 0; i < values.length; i++)
{
mad += Math.abs(values[i] - mean);
}
mad = (float) Math.sqrt(mad / (float) values.length);
}
return mad;
}
/*
* Calculates the interquartile range
*
* @param values Input values
* @return Interquartile range
*/
public float getIQR(float[] values)
{
float iqr = 0;
int n = values.length;
if (n > 0)
{
// Copy values for sorting
float[] valueCopies = new float[values.length];
System.arraycopy(values, 0, valueCopies, 0, values.length);
// Sort values ascending
Arrays.sort(valueCopies);
float[] lowerPercentile;
float[] upperPercentile;
if (n % 2 == 0)
{
lowerPercentile = new float[n / 2];
upperPercentile = new float[n / 2];
// Even
for (int i = 0; i < n; i++)
{
if (i < n / 2)
{
lowerPercentile[i] = valueCopies[i];
}
else
{
upperPercentile[i - n / 2] = valueCopies[i];
}
}
}
else
{
lowerPercentile = new float[(n - 1) / 2];
upperPercentile = new float[(n - 1) / 2];
// Odd
for (int i = 0; i < n; i++)
{
if (i < (n - 1) / 2)
{
lowerPercentile[i] = valueCopies[i];
}
// Exclude median
if (i > (n - 1) / 2)
{
upperPercentile[i - ((n - 1) / 2) - 1] = valueCopies[i];
}
}
}
iqr = getMedian(upperPercentile) - getMedian(lowerPercentile);
}
return iqr;
}
/*
* Calculates the crest factor
*
* @param values Input values
* @return Crest factor
*/
public float getCrest(float[] values)
{
float absValue = 0;
float crest = 0;
float peak = 0;
float rms = getRMS(values);
for (int i = 0; i < values.length; i++)
{
absValue = Math.abs(values[i]);
if (absValue > peak)
{
peak = absValue;
}
}
if (rms > 0)
{
crest = peak / rms;
}
return crest;
}
}
| 8,026 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Matrix.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Matrix.java | /*
* Matrix.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael Dietz on 11.08.2015.
*/
public class Matrix<T>
{
public enum MATRIX_DIMENSION {
//! rowwise
ROW,
//! columnwise
COL
};
private int rows;
private int cols;
ArrayList<T> data;
public Matrix(int rows, int cols)
{
reset(rows, cols);
}
public void reset(int rows, int cols)
{
if (rows * cols > 0)
{
this.rows = rows;
this.cols = cols;
data = new ArrayList<T>(rows * cols);
while(data.size() < rows * cols) data.add(null);
}
}
public Matrix<T> clone()
{
Matrix<T> ret = new Matrix<>(rows, cols);
for (int i = 0; i < getSize(); i++)
{
ret.setData(i, data.get(i));
}
return ret;
}
public List<T> getData()
{
return data;
}
public T getData(int index)
{
return data.get(index);
}
public T getData(int row, int col)
{
return data.get(row * cols + col);
}
public void setData(int index, T value)
{
data.set(index, value);
}
public void setData(int row, int col, T value)
{
data.set(row * cols + col, value);
}
public void fillValue(T value)
{
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
setData(row, col, value);
}
}
}
public int getRows()
{
return rows;
}
public int getCols()
{
return cols;
}
public int getSize()
{
return cols * rows;
}
public void transpose ()
{
if (data.isEmpty()) {
return;
}
if (rows > 1 && cols > 1) {
Matrix<T> tmp = this.clone();
int srcrows = tmp.getRows();
int srccols = tmp.getCols();
int srcptr = 0;
int dstptr = 0;
for (int i = 0; i < srccols; i++)
{
srcptr = i;
for (int j = 0; j < srcrows; j++)
{
data.set(dstptr, tmp.getData(srcptr));
srcptr += srccols;
dstptr++;
}
}
}
int tmp = cols;
cols = rows;
rows = tmp;
}
public void setSubMatrix(int row, int col, Matrix<T> submaxtrix)
{
setSubMatrix(row, col, 0, 0, submaxtrix.getRows(), submaxtrix.getCols(), submaxtrix);
}
public void setSubMatrix(int row_dst, int col_dst, int row_src, int col_src, int row_number, int col_number, Matrix<T> src)
{
if (row_dst + row_number > rows
|| col_dst + col_number > cols
|| row_src + row_number > src.getRows()
|| col_src + col_number > src.getCols())
return;
int srccols = src.getCols();
int srcptr = row_src * srccols + col_src;
int dstcols = cols;
int dstptr = row_dst * dstcols + col_dst;
for (int i = 0; i < row_number; i++) {
for(int j = 0; j < col_number; j++)
data.set(dstptr + j, src.getData(srcptr + j));
srcptr += srccols;
dstptr += dstcols;
}
}
}
| 4,023 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ConvertToDim.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/ConvertToDim.java | /*
* ConvertToDim.java
* Copyright (c) 2022
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 23.04.2022.
*/
public class ConvertToDim extends Transformer
{
public ConvertToDim()
{
_name = this.getClass().getSimpleName();
}
@Override
public OptionList getOptions()
{
return null;
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
for (int i = 0; i < stream_in[0].num; i++)
{
switch (stream_out.type)
{
case BOOL:
stream_out.ptrBool()[i] = stream_in[0].ptrBool()[i];
break;
case BYTE:
stream_out.ptrB()[i] = stream_in[0].ptrB()[i];
break;
case CHAR:
stream_out.ptrC()[i] = stream_in[0].ptrC()[i];
break;
case DOUBLE:
stream_out.ptrD()[i] = stream_in[0].ptrD()[i];
break;
case FLOAT:
stream_out.ptrF()[i] = stream_in[0].ptrF()[i];
break;
case INT:
stream_out.ptrI()[i] = stream_in[0].ptrI()[i];
break;
case LONG:
stream_out.ptrL()[i] = stream_in[0].ptrL()[i];
break;
case SHORT:
stream_out.ptrS()[i] = stream_in[0].ptrS()[i];
break;
}
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return stream_in[0].num;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return stream_in[0].type;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
for (int i = 0; i < stream_out.dim; i++)
{
stream_out.desc[i] = stream_in[0].desc[0] + "_dim" + i;
}
}
}
| 3,237 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Complex.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Complex.java | /*
* Complex.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
/**
* Created by Michael Dietz on 13.08.2015.
*/
public class Complex
{
private double real;
private double imag;
public Complex(double real, double imaginary)
{
this.real = real;
this.imag = imaginary;
}
public double real()
{
return this.real;
}
public double imag()
{
return this.imag;
}
public double mod()
{
return this.real == 0.0d && this.imag == 0.0d ? 0.0d : Math.sqrt(this.real * this.real + this.imag * this.imag);
}
public double arg()
{
return Math.atan2(this.imag, this.real);
}
public Complex conj()
{
return new Complex(this.real, -this.imag);
}
public Complex plus(Complex w)
{
return new Complex(this.real + w.real(), this.imag + w.imag());
}
public Complex minus(Complex w)
{
return new Complex(this.real - w.real(), this.imag - w.imag());
}
public Complex times(Complex w)
{
return new Complex(this.real * w.real() - this.imag * w.imag(), this.real * w.imag() + this.imag * w.real());
}
public Complex times(double factor)
{
return new Complex(this.real * factor, this.imag * factor);
}
public Complex div(Complex w)
{
double den = Math.pow(w.mod(), 2.0d);
return new Complex((this.real * w.real() + this.imag * w.imag()) / den, (this.imag * w.real() - this.real * w.imag()) / den);
}
public Complex exp()
{
return new Complex(Math.exp(this.real) * Math.cos(this.imag), Math.exp(this.real) * Math.sin(this.imag));
}
public Complex log()
{
return new Complex(Math.log(this.mod()), this.arg());
}
public Complex sqrt()
{
double r = Math.sqrt(this.mod());
double theta = this.arg() / 2.0d;
return new Complex(r * Math.cos(theta), r * Math.sin(theta));
}
private double cosh(double theta)
{
return (Math.exp(theta) + Math.exp(-theta)) / 2.0d;
}
private double sinh(double theta)
{
return (Math.exp(theta) - Math.exp(-theta)) / 2.0d;
}
public Complex sin()
{
return new Complex(this.cosh(this.imag) * Math.sin(this.real), this.sinh(this.imag) * Math.cos(this.real));
}
public Complex cos()
{
return new Complex(this.cosh(this.imag) * Math.cos(this.real), -this.sinh(this.imag) * Math.sin(this.real));
}
public Complex sinh()
{
return new Complex(this.sinh(this.real) * Math.cos(this.imag), this.cosh(this.real) * Math.sin(this.imag));
}
public Complex cosh()
{
return new Complex(this.cosh(this.real) * Math.cos(this.imag), this.sinh(this.real) * Math.sin(this.imag));
}
public Complex tan()
{
return this.sin().div(this.cos());
}
public Complex chs()
{
return new Complex(-this.real, -this.imag);
}
public String toString()
{
return this.real != 0.0d && this.imag > 0.0d ? this.real + " + " + this.imag + "i" : (this.real != 0.0d && this.imag < 0.0d ? this.real + " - " + -this.imag + "i" : (this.imag == 0.0d ? String.valueOf(this.real) : (this.real == 0.0d ? this.imag + "i" : this.real + " + i*" + this.imag)));
}
} | 4,254 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Merge.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Merge.java | /*
* Merge.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Merges multiple streams int one. Streams need to have same type, sr and num.<br>
* Created by Frank Gaibler on 24.11.2015.
*/
public class Merge extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
/**
*
*/
public Merge()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//check for valid stream
for (Stream s : stream_in)
{
if (stream_in[0].type != s.type || stream_in[0].sr != s.sr || stream_in[0].num != s.num)
{
Log.e("input streams are incompatible");
}
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int j = 0; j < stream_in.length; j++)
{
for (int k = 0; k < stream_in[j].dim; k++)
{
switch (stream_out.type)
{
case BOOL:
stream_out.ptrBool()[z++] = stream_in[j].ptrBool()[i * stream_in[j].dim + k];
break;
case BYTE:
stream_out.ptrB()[z++] = stream_in[j].ptrB()[i * stream_in[j].dim + k];
break;
case CHAR:
stream_out.ptrC()[z++] = stream_in[j].ptrC()[i * stream_in[j].dim + k];
break;
case DOUBLE:
stream_out.ptrD()[z++] = stream_in[j].ptrD()[i * stream_in[j].dim + k];
break;
case FLOAT:
stream_out.ptrF()[z++] = stream_in[j].ptrF()[i * stream_in[j].dim + k];
break;
case INT:
stream_out.ptrI()[z++] = stream_in[j].ptrI()[i * stream_in[j].dim + k];
break;
case LONG:
stream_out.ptrL()[z++] = stream_in[j].ptrL()[i * stream_in[j].dim + k];
break;
case SHORT:
stream_out.ptrS()[z++] = stream_in[j].ptrS()[i * stream_in[j].dim + k];
break;
}
}
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = 0;
for(Stream s : stream_in)
dim += s.dim;
return dim;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(stream_in[0].type);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return stream_in[0].type;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0; i < stream_out.desc.length; i++)
{
stream_out.desc[i] = "slctr" + i;
}
}
}
| 6,365 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Selector.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Selector.java | /*
* Selector.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Selects specific values from a stream.<br>
* Created by Frank Gaibler on 24.11.2015.
*/
public class Selector extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<int[]> values = new Option<>("values", new int[]{0}, int[].class, "The values to select. The selection interval is given by the selection size.");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
/**
*
*/
public Selector()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//check for valid stream
if (stream_in.length != 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
switch (stream_in[0].type)
{
case BOOL:
{
boolean[] out = stream_out.ptrBool();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrBool()[value + stream_in[0].dim * i];
}
}
break;
}
case BYTE:
{
byte[] out = stream_out.ptrB();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrB()[value + stream_in[0].dim * i];
}
}
break;
}
case CHAR:
{
char[] out = stream_out.ptrC();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrC()[value + stream_in[0].dim * i];
}
}
break;
}
case DOUBLE:
{
double[] out = stream_out.ptrD();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrD()[value + stream_in[0].dim * i];
}
}
break;
}
case FLOAT:
{
float[] out = stream_out.ptrF();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrF()[value + stream_in[0].dim * i];
}
}
break;
}
case INT:
{
int[] out = stream_out.ptrI();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrI()[value + stream_in[0].dim * i];
}
}
break;
}
case LONG:
{
long[] out = stream_out.ptrL();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrL()[value + stream_in[0].dim * i];
}
}
break;
}
case SHORT:
{
short[] out = stream_out.ptrS();
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
for (int value : options.values.get())
{
out[z++] = stream_in[0].ptrS()[value + stream_in[0].dim * i];
}
}
break;
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
return options.values.get().length;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(stream_in[0].type);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return stream_in[0].type;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0; i < stream_out.desc.length; i++)
{
stream_out.desc[i] = "slctr" + i;
}
}
}
| 8,071 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Envelope.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Envelope.java | /*
* Envelope.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Computes the envelope of the input signal
*
* An envelope detector is an electronic circuit that takes a high-frequency signal as input and provides
* an output which is the envelope of the original signal.
* The capacitor in the circuit stores up charge on the rising edge, and releases it slowly through the
* resistor when the signal falls. The diode in series rectifies the incoming signal, allowing current
* flow only when the positive input terminal is at a higher potential than the negative input terminal.
* (Wikipedia)
*
* Created by Johnny on 01.04.2015.
*/
public class Envelope extends Transformer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> attackSlope = new Option<>("attackSlope", 0.1f, Float.class, "increment by which the envelope should increase each sample");
public final Option<Float> releaseSlope = new Option<>("releaseSlope", 0.1f, Float.class, "increment by which the envelope should decrease each sample");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
float[] _lastValue;
public Envelope()
{
_name = "Envelope";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_lastValue = new float[stream_in[0].dim];
for (int i = 0; i < _lastValue.length; ++i)
{
_lastValue[i] = 0;
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] data = stream_in[0].ptrF();
float[] out = stream_out.ptrF();
int dim = stream_in[0].dim;
float valNew, valOld;
for(int j = 0; j < stream_in[0].dim; ++j)
{
for(int i = 0; i < stream_in[0].num; ++i)
{
valNew = data[i * dim + j];
valOld = (i > 1) ? out[(i-1) * dim + j] : _lastValue[j];
if (valNew > valOld)
{
out[i * dim + j] = (valOld + options.attackSlope.get() > valNew) ? valNew : valOld + options.attackSlope.get();
}
else if (valNew < valOld)
{
out[i * dim + j] = (valOld - options.releaseSlope.get() < valNew) ? valNew : valOld - options.releaseSlope.get();
}
else if (valNew == valOld)
{
out[i * dim + j] = valOld;
}
}
_lastValue[j] = out[(stream_in[0].num -1) * dim + j];
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
if(stream_in[0].dim != 1)
Log.e("can only handle 1-dimensional streams");
return 1;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(stream_in[0].bytes != 4) //float
Log.e("Unsupported input stream type");
return 4; //float
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT)
Log.e("Unsupported input stream type");
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
}
| 5,380 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MvgMinMax.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MvgMinMax.java | /*
* MvgMinMax.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.EnumSet;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.08.2015.
*
* Computes moving/sliding minim and/or maximum of the input stream for the chosen window.
*/
public class MvgMinMax extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public enum Method
{
MOVING,
SLIDING
}
public enum Format
{
MIN,
MAX,
ALL
}
public class Options extends OptionList
{
public final Option<Float> windowSize = new Option<>("windowSize", 10.f, Float.class, "");
public final Option<Method> method = new Option<>("method", Method.MOVING, Method.class, "");
public final Option<Format> format = new Option<>("format", Format.MIN, Format.class, "");
public final Option<Integer> numberOfBlocks = new Option<>("numberOfBlocks", 10, Integer.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
Implementation _impl;
public MvgMinMax()
{
_name = "MvgMinMax";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (options.method.get() == Method.MOVING)
{
_impl = new Moving(options);
}
else
{
_impl = new Sliding(options);
}
_impl.enter(stream_in[0], stream_out);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_impl.transform(stream_in[0], stream_out);
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_impl.flush(stream_in[0], stream_out);
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
int bits = 0;
if (EnumSet.of(Format.MIN, Format.ALL).contains(options.format.get()))
{
bits++;
}
if (EnumSet.of(Format.MAX, Format.ALL).contains(options.format.get()))
{
bits++;
}
return stream_in[0].dim * bits;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT); // Float
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
interface Implementation
{
void enter(Stream stream_in, Stream stream_out);
void transform(Stream stream_in, Stream stream_out);
void flush(Stream stream_in, Stream stream_out);
}
class Moving implements Implementation
{
Options options;
int _windowSizeInSamples;
int _blockLengthInSamples;
float[] _history;
float[] _minMax;
int _currentSampleIndex;
int _currentBlockIndex;
public Moving(Options options)
{
this.options = options;
}
@Override
public void enter(Stream stream_in, Stream stream_out)
{
int sampleDimension = stream_in.dim;
double sampleRate = stream_in.sr;
double exactWindowSizeInSamples = options.windowSize.get() * sampleRate;
double exactBlockLengthInSamples = exactWindowSizeInSamples / options.numberOfBlocks.get();
int newBlockLengthInSamples = (int) (exactBlockLengthInSamples + 0.5); // Round
int newWindowSizeInSamples = newBlockLengthInSamples * options.numberOfBlocks.get();
_windowSizeInSamples = newWindowSizeInSamples;
_blockLengthInSamples = newBlockLengthInSamples;
_history = new float[(options.numberOfBlocks.get() << 1) * sampleDimension];
_minMax = new float[sampleDimension << 1];
int historyIterator = 0;
for (int i = 0; i < options.numberOfBlocks.get(); i++)
{
for (int j = 0; j < sampleDimension; j++)
{
_history[historyIterator++] = Float.MAX_VALUE;
_history[historyIterator++] = -Float.MAX_VALUE;
}
}
int minMaxIterator = 0;
for (int i = 0; i < sampleDimension; i++)
{
_minMax[minMaxIterator++] = Float.MAX_VALUE;
_minMax[minMaxIterator++] = -Float.MAX_VALUE;
}
_currentSampleIndex = _blockLengthInSamples - 1;
_currentBlockIndex = options.numberOfBlocks.get() - 1;
}
@Override
public void transform(Stream stream_in, Stream stream_out)
{
int sampleDimension = stream_in.dim;
int sampleNumber = stream_in.num;
float[] srcPtr = stream_in.ptrF();
float[] dstPtr = stream_out.ptrF();
int historyIndex = 0;
int minMaxIndex = 0;
int dstIndex = 0;
for (int curRelSample = 0; curRelSample < sampleNumber; curRelSample++)
{
// Check if we have to move to next block
if (++_currentSampleIndex >= _blockLengthInSamples)
{
_currentSampleIndex = 0;
if (++_currentBlockIndex >= options.numberOfBlocks.get())
{
_currentBlockIndex = 0;
}
historyIndex = sampleDimension * (_currentBlockIndex << 1);
for (int forEachDimension = 0; forEachDimension < sampleDimension; forEachDimension++)
{
_history[historyIndex++] = srcPtr[forEachDimension];
_history[historyIndex++] = srcPtr[forEachDimension];
}
}
// Update min/max in current block
historyIndex = sampleDimension * (_currentBlockIndex << 1);
for (int forEachDimension = 0; forEachDimension < sampleDimension; forEachDimension++)
{
if (_history[historyIndex] > srcPtr[forEachDimension])
{
_history[historyIndex] = srcPtr[forEachDimension];
}
historyIndex++;
if (_history[historyIndex] < srcPtr[forEachDimension])
{
_history[historyIndex] = srcPtr[forEachDimension];
}
historyIndex++;
}
// Update min/max in all blocks
minMaxIndex = 0;
for (int i = 0; i < sampleDimension; i++)
{
_minMax[minMaxIndex++] = Float.MAX_VALUE;
_minMax[minMaxIndex++] = -Float.MAX_VALUE;
}
historyIndex = 0;
for (int forEachBlock = 0; forEachBlock < options.numberOfBlocks.get(); forEachBlock++)
{
minMaxIndex = 0;
for (int forEachDimension = 0; forEachDimension < sampleDimension; forEachDimension++)
{
if (_minMax[minMaxIndex] > _history[historyIndex])
{
_minMax[minMaxIndex] = _history[historyIndex];
}
minMaxIndex++;
historyIndex++;
if (_minMax[minMaxIndex] < _history[historyIndex])
{
_minMax[minMaxIndex] = _history[historyIndex];
}
minMaxIndex++;
historyIndex++;
}
}
// Write back min/max
minMaxIndex = 0;
dstIndex = 0;
for (int forEachDimension = 0; forEachDimension < sampleDimension; forEachDimension++)
{
if (EnumSet.of(Format.MIN, Format.ALL).contains(options.format.get()))
{
dstPtr[dstIndex++] = _minMax[minMaxIndex];
}
minMaxIndex++;
if (EnumSet.of(Format.MAX, Format.ALL).contains(options.format.get()))
{
dstPtr[dstIndex++] = _minMax[minMaxIndex];
}
minMaxIndex++;
}
}
}
@Override
public void flush(Stream stream_in, Stream stream_out)
{
_history = null;
_minMax = null;
}
}
class Sliding implements Implementation
{
Options options;
float[] _minHistory;
float[] _maxHistory;
float _alpha;
float _1_alpha;
boolean _firstCall;
public Sliding(Options options)
{
this.options = options;
}
@Override
public void enter(Stream stream_in, Stream stream_out)
{
int sampleDimension = stream_in.dim;
double sampleRate = stream_in.sr;
// Allocate history arrays
_minHistory = new float[sampleDimension];
_maxHistory = new float[sampleDimension];
// Allocate and initialize alpha array
_alpha = (float) (1.0 - (2.0 * Math.sqrt(3.0)) / (options.windowSize.get() * sampleRate));
_1_alpha = 1 - _alpha;
// Set first call to true
_firstCall = true;
}
@Override
public void transform(Stream stream_in, Stream stream_out)
{
int sampleDimension = stream_in.dim;
int sampleNumber = stream_in.num;
float[] srcPtr = stream_in.ptrF();
float[] dstPtr = stream_out.ptrF();
float x;
float minVal;
float maxVal;
int srcIndex = 0;
int dstIndex = 0;
// Initialize history array
if (_firstCall)
{
for (int i = 0; i < sampleDimension; i++)
{
_minHistory[i] = srcPtr[i];
_maxHistory[i] = srcPtr[i];
}
_firstCall = false;
}
for (int i = 0; i < sampleNumber; i++)
{
for (int j = 0; j < sampleDimension; j++)
{
x = srcPtr[srcIndex++];
if (EnumSet.of(Format.MIN, Format.ALL).contains(options.format.get()))
{
minVal = _minHistory[j];
minVal = Math.min(x, _alpha * minVal + _1_alpha * x);
_minHistory[j] = minVal;
dstPtr[dstIndex] = minVal;
}
if (EnumSet.of(Format.MAX, Format.ALL).contains(options.format.get()))
{
maxVal = _maxHistory[j];
maxVal = Math.max(x, _alpha * maxVal + _1_alpha * x);
_maxHistory[j] = maxVal;
dstPtr[dstIndex] = maxVal;
}
}
}
}
@Override
public void flush(Stream stream_in, Stream stream_out)
{
_minHistory = null;
_maxHistory = null;
}
}
}
| 10,779 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MvgNorm.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/MvgNorm.java | /*
* MvgNorm.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 10.08.2015.
*
* Normalizes input stream using moving/sliding minim and/or maximum for the chosen window.
*/
public class MvgNorm extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public enum Norm
{
AVG_VAR,
MIN_MAX,
SUB_AVG,
SUB_MIN
}
public enum Method
{
MOVING,
SLIDING
}
public class Options extends OptionList
{
public final Option<Norm> norm = new Option<>("norm", Norm.AVG_VAR, Norm.class, "");
public final Option<Float> rangeA = new Option<>("rangeA", 0.f, Float.class, "");
public final Option<Float> rangeB = new Option<>("rangeB", 1.f, Float.class, "");
public final Option<Float> windowSize = new Option<>("windowSize", 10.f, Float.class, "");
public final Option<Method> method = new Option<>("method", Method.MOVING, Method.class, "");
public final Option<Integer> numberOfBlocks = new Option<>("numberOfBlocks", 10, Integer.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
float _rangeA;
float _rangeD;
Norm _norm;
Transformer _mvg;
Stream _dataTmp;
public MvgNorm()
{
_name = "MvgNorm";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
_rangeA = options.rangeA.get();
_rangeD = options.rangeB.get() - options.rangeA.get();
_norm = options.norm.get();
switch (_norm)
{
case AVG_VAR:
{
MvgAvgVar mvgAvgVar = new MvgAvgVar();
mvgAvgVar.options.format.set(MvgAvgVar.Format.AVG_AND_VAR);
mvgAvgVar.options.method.set(options.method.get() == Method.MOVING ? MvgAvgVar.Method.MOVING : MvgAvgVar.Method.SLIDING);
mvgAvgVar.options.window.set((double) options.windowSize.get());
_mvg = mvgAvgVar;
break;
}
case MIN_MAX:
{
MvgMinMax mvgMinMax = new MvgMinMax();
mvgMinMax.options.format.set(MvgMinMax.Format.ALL);
mvgMinMax.options.method.set(options.method.get() == Method.MOVING ? MvgMinMax.Method.MOVING : MvgMinMax.Method.SLIDING);
mvgMinMax.options.windowSize.set(options.windowSize.get());
_mvg = mvgMinMax;
break;
}
case SUB_AVG:
{
MvgAvgVar mvgAvgVar = new MvgAvgVar();
mvgAvgVar.options.format.set(MvgAvgVar.Format.AVERAGE);
mvgAvgVar.options.method.set(options.method.get() == Method.MOVING ? MvgAvgVar.Method.MOVING : MvgAvgVar.Method.SLIDING);
mvgAvgVar.options.window.set((double) options.windowSize.get());
_mvg = mvgAvgVar;
break;
}
case SUB_MIN:
{
MvgMinMax mvgMinMax = new MvgMinMax();
mvgMinMax.options.format.set(MvgMinMax.Format.MIN);
mvgMinMax.options.method.set(options.method.get() == Method.MOVING ? MvgMinMax.Method.MOVING : MvgMinMax.Method.SLIDING);
mvgMinMax.options.windowSize.set(options.windowSize.get());
mvgMinMax.options.numberOfBlocks.set(options.numberOfBlocks.get());
_mvg = mvgMinMax;
break;
}
}
_dataTmp = Stream.create(stream_in[0].num, _mvg.getSampleDimension(stream_in), Util.calcSampleRate(_mvg, stream_in[0]), _mvg.getSampleType(stream_in));
_mvg.enter(stream_in, _dataTmp);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int sampleDimension = stream_in[0].dim;
int sampleNumber = stream_in[0].num;
_mvg.transform(stream_in, _dataTmp);
float[] srcPtr = stream_in[0].ptrF();
float[] dstPtr = stream_out.ptrF();
float[] tmpPtr = _dataTmp.ptrF();
int srcPtrIndex = 0;
int dstPtrIndex = 0;
int tmpPtrIndex = 0;
switch (_norm)
{
case AVG_VAR:
{
float x, y, avgVal, varVal;
for (int i = 0; i < sampleNumber; i++)
{
for (int j = 0; j < sampleDimension; j++)
{
x = srcPtr[srcPtrIndex++];
avgVal = tmpPtr[tmpPtrIndex++];
varVal = tmpPtr[tmpPtrIndex++];
y = (float) ((x - avgVal) / Math.sqrt(varVal));
dstPtr[dstPtrIndex++] = y;
}
}
break;
}
case MIN_MAX:
{
float x, y, minVal, maxVal, difVal;
for (int i = 0; i < sampleNumber; i++)
{
for (int j = 0; j < sampleDimension; j++)
{
x = srcPtr[srcPtrIndex++];
minVal = tmpPtr[tmpPtrIndex++];
maxVal = tmpPtr[tmpPtrIndex++];
difVal = maxVal - minVal;
if (difVal != 0)
{
y = (x - minVal) / difVal;
}
else
{
y = 0;
}
y = _rangeA + y * _rangeD;
dstPtr[dstPtrIndex++] = y;
}
}
break;
}
case SUB_AVG:
{
float x, y, avgVal;
for (int i = 0; i < sampleNumber; i++)
{
for (int j = 0; j < sampleDimension; j++)
{
x = srcPtr[srcPtrIndex++];
avgVal = tmpPtr[tmpPtrIndex++];
y = x - avgVal;
dstPtr[dstPtrIndex++] = y;
}
}
break;
}
case SUB_MIN:
{
float x, y, minVal;
for (int i = 0; i < sampleNumber; i++)
{
for (int j = 0; j < sampleDimension; j++)
{
x = srcPtr[srcPtrIndex++];
minVal = tmpPtr[tmpPtrIndex++];
y = x - minVal;
dstPtr[dstPtrIndex++] = y;
}
}
break;
}
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return stream_in[0].dim;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT); // Float
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
}
| 7,458 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Median.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Median.java | /*
* Median.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* A general transformer to calculate the median for every dimension in the provided streams.<br>
* Created by Frank Gaibler on 09.09.2015.
*/
public class Median extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//helper variables
private float[][] floats;
private float[][] dimensions;
/**
*
*/
public Median()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//no check for a specific type to allow for different providers
if (stream_in.length < 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
floats = new float[stream_in.length][];
for (int i = 0; i < floats.length; i++)
{
floats[i] = new float[stream_in[i].num * stream_in[i].dim];
}
dimensions = new float[stream_in.length][];
for (int i = 0; i < dimensions.length; i++)
{
dimensions[i] = new float[stream_in[i].num];
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
super.flush(stream_in, stream_out);
floats = null;
dimensions = null;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
for (int i = 0, t = 0; i < stream_in.length; i++)
{
Util.castStreamPointerToFloat(stream_in[i], floats[i]);
if (stream_in[i].dim > 1)
{
int size = stream_in[i].num * stream_in[i].dim;
for (int j = 0; j < stream_in[i].dim; j++)
{
for (int k = j, l = 0; k < size; k += stream_in[i].dim, l++)
{
dimensions[i][l] = floats[i][k];
}
out[t++] = getMedian(dimensions[i]);
}
} else
{
out[t++] = getMedian(floats[i]);
}
}
}
/**
* @param in float[]
* @return float
*/
private float getMedian(float[] in)
{
Arrays.sort(in);
int n = in.length;
if (n % 2 == 0)
{
return (in[n / 2] + in[(n / 2) - 1]) / 2;
} else
{
return in[(n - 1) / 2];
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
int overallDimension = 0;
for (Stream stream : stream_in)
{
overallDimension += stream.dim;
}
return overallDimension;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0, k = 0; i < stream_in.length; i++)
{
for (int j = 0; j < stream_in[i].dim; j++, k++)
{
stream_out.desc[k] = "median" + i + "." + j;
}
}
}
} | 6,648 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Progress.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/Progress.java | /*
* Progress.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Transformer to calculate progress in android sensor data.<br>
* Created by Frank Gaibler on 31.08.2015.
*/
public class Progress extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//helper variables
private boolean initState = true;
private float[] oldValues;
/**
*
*/
public Progress()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//no check for a specific type to allow for different providers
if (stream_in.length < 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
//every stream should have the same sample number.
//Otherwise the sample number of the transformer will not be correct
int num = stream_in[0].num;
for (int i = 1; i < stream_in.length; i++)
{
if (num != stream_in[i].num)
{
Log.e("invalid input stream num for stream " + i);
}
}
initState = true;
oldValues = new float[stream_out.dim];
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
if (initState)
{
initState = false;
int t = 0;
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, t++)
{
oldValues[t] = aStream_in.ptrF()[k];
}
}
}
for (int i = 0, z = 0; i < stream_in[0].num; i++)
{
int t = 0;
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, t++, z++)
{
float value = aStream_in.ptrF()[i * aStream_in.dim + k];
//write to output
out[z] = value - oldValues[t];
//save old variables
oldValues[t] = value;
}
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
int overallDimension = 0;
for (Stream stream : stream_in)
{
overallDimension += stream.dim;
}
return overallDimension;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0, k = 0; i < stream_in.length; i++)
{
for (int j = 0; j < stream_in[i].dim; j++, k++)
{
stream_out.desc[k] = "prgrss" + i + "." + j;
}
}
}
} | 6,247 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AvgVar.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/signal/AvgVar.java | /*
* AvgVar.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.signal;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* A general transformer to calculate average and/or variance for every dimension in the provided streams.<br>
* The output is ordered for every dimension average than variance.<br>
* Created by Frank Gaibler on 02.09.2015.
*/
public class AvgVar extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends OptionList
{
public final Option<String[]> outputClass = new Option<>("outputClass", null, String[].class, "Describes the output names for every dimension in e.g. a graph");
public final Option<Boolean> avg = new Option<>("avg", true, Boolean.class, "Calculate average for each frame");
public final Option<Boolean> var = new Option<>("var", true, Boolean.class, "Calculate variance for each frame");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//helper variables
private float[][] floats;
private int multiplier;
private int[] streamDimensions;
private float[] avgValues;
private float[] varValues;
/**
*
*/
public AvgVar()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
//no check for a specific type to allow for different providers
if (stream_in.length < 1 || stream_in[0].dim < 1)
{
Log.e("invalid input stream");
return;
}
//every stream should have the same sample number
int num = stream_in[0].num;
for (int i = 1; i < stream_in.length; i++)
{
if (num != stream_in[i].num)
{
Log.e("invalid input stream num for stream " + i);
return;
}
}
floats = new float[stream_in.length][];
for (int i = 0; i < floats.length; i++)
{
floats[i] = new float[stream_in[i].num * stream_in[i].dim];
}
if (multiplier > 0)
{
avgValues = new float[stream_out.dim / multiplier];
varValues = new float[stream_out.dim / multiplier];
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
super.flush(stream_in, stream_out);
floats = null;
avgValues = null;
varValues = null;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (multiplier > 0)
{
float[] out = stream_out.ptrF();
Arrays.fill(avgValues, 0);
//add up average values
for (int i = 0; i < stream_in[0].num; i++)
{
int t = 0;
for (int j = 0; j < stream_in.length; j++)
{
Util.castStreamPointerToFloat(stream_in[j], floats[j]);
for (int k = 0; k < stream_in[j].dim; k++, t++)
{
float value = floats[j][i * stream_in[j].dim + k];
avgValues[t] += value;
}
}
}
//calculate average
for (int i = 0; i < avgValues.length; i++)
{
avgValues[i] = avgValues[i] / stream_in[0].num;
}
if (options.var.get())
{
Arrays.fill(varValues, 0);
//add up variance values
for (int i = 0; i < stream_in[0].num; i++)
{
int t = 0;
for (Stream aStream_in : stream_in)
{
for (int k = 0; k < aStream_in.dim; k++, t++)
{
float value = aStream_in.ptrF()[i * aStream_in.dim + k];
varValues[t] += (value - avgValues[t]) * (value - avgValues[t]);
}
}
}
//calculate variance
for (int i = 0; i < varValues.length; i++)
{
varValues[i] = varValues[i] / stream_in[0].num;
}
if (!options.avg.get())
{
System.arraycopy(varValues, 0, out, 0, varValues.length);
} else
{
for (int i = 0, j = 0; i < varValues.length; i++)
{
out[j++] = avgValues[i];
out[j++] = varValues[i];
}
}
return;
}
System.arraycopy(avgValues, 0, out, 0, avgValues.length);
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
multiplier = 0;
multiplier = options.avg.get() ? multiplier + 1 : multiplier;
multiplier = options.var.get() ? multiplier + 1 : multiplier;
if (multiplier <= 0)
{
Log.e("no option selected");
}
int overallDimension = 0;
streamDimensions = new int[stream_in.length];
for (int i = 0; i < streamDimensions.length; i++)
{
streamDimensions[i] = stream_in[i].dim * multiplier;
overallDimension += streamDimensions[i];
}
return overallDimension;
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
/**
* @param stream_in Stream[]
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
/**
* @param sampleNumber_in int
* @return int
*/
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
int overallDimension = getSampleDimension(stream_in);
stream_out.desc = new String[overallDimension];
if (options.outputClass.get() != null)
{
if (overallDimension == options.outputClass.get().length)
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
return;
} else
{
Log.w("invalid option outputClass length");
}
}
for (int i = 0, k = 0; i < streamDimensions.length; i++)
{
for (int j = 0, m = 0; j < streamDimensions[i]; j += multiplier, m++)
{
if (options.avg.get())
{
stream_out.desc[k++] = "avg" + i + "." + m;
}
if (options.var.get())
{
stream_out.desc[k++] = "var" + i + "." + m;
}
}
}
}
} | 9,236 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CPULoadChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/test/CPULoadChannel.java | /*
* CPULoadChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Audio Sensor - get data from audio interface and forwards it
* Created by Johnny on 05.03.2015.
*/
public class CPULoadChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
public final Option<String> packagename = new Option<>("packagename", SSJApplication.getAppContext().getPackageName(), String.class, "name of the package to monitor");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private String cmd;
public CPULoadChannel()
{
_name = "Profiler_CPU";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
//set delay to be < frame window since top is blocking
cmd = "top -n 1 -m 10 -d " + (1.0 / options.sampleRate.get()) * 0.9;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
stream_out.ptrF()[0] = getCPULoad(cmd, options.packagename.get());
return true;
}
private float getCPULoad(String cmd, String packagename)
{
try {
Process proc = Runtime.getRuntime().exec(cmd);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
int cpuid = 0;
String line;
while ((line = read.readLine()) != null) {
if (line.length() == 0 || line.startsWith("User"))
continue;
line = line.trim();
if(line.startsWith("PID"))
{
//compute index of CPU load
String elems[] = line.split("\\s+");
for(int i = 0; i< elems.length; i++)
{
if(elems[i].contains("CPU")) {
cpuid = i;
break;
}
}
}
else if (line.contains(packagename)) {
String elems[] = line.split("\\s+");
return Float.parseFloat(elems[cpuid].replace("%", ""));
}
}
}
catch(IOException e)
{
Log.w("error executing top cmd", e);
}
return 0;
}
@Override
public void flush(Stream stream_out) throws SSJFatalException
{
}
@Override
public int getSampleDimension()
{
return 1;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream stream_out)
{
stream_out.desc = new String[1];
stream_out.desc[0] = "CPU";
}
}
| 4,810 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Profiler.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/test/Profiler.java | /*
* Profiler.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.test;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.OptionList;
/**
* Device profiler
*/
public class Profiler extends Sensor {
public Profiler()
{
_name = "Profiler";
}
@Override
public boolean connect() throws SSJFatalException
{
return true;
}
@Override
public void disconnect() throws SSJFatalException
{
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 1,849 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EventLogger.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/test/EventLogger.java | /*
* EventLogger.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.test;
import java.util.Arrays;
import java.util.Map;
import hcm.ssj.core.EventChannel;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.OptionList;
/**
* Outputs all incoming events using logcat
*/
public class EventLogger extends EventHandler
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
/**
*
*/
private Options() {addOptions();}
}
public final Options options = new Options();
public EventLogger()
{
_name = "EventLogger";
_doWakeLock = true;
Log.d("Instantiated EventLogger "+this.hashCode());
}
int _lastBehavEventID;
@Override
public void enter() throws SSJFatalException
{
_lastBehavEventID = -1;
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new RuntimeException("no input channels");
}
}
@Override
protected void process() throws SSJFatalException
{
for(EventChannel ch : _evchannel_in)
{
Event ev = ch.getEvent(_lastBehavEventID + 1, true);
if (ev == null)
{
return;
}
_lastBehavEventID = ev.id;
String msg = "";
switch(ev.type)
{
case BYTE:
msg = Arrays.toString(ev.ptrB());
break;
case CHAR:
msg = ev.ptrStr();
break;
case STRING:
msg = ev.ptrStr();
break;
case SHORT:
msg = Arrays.toString(ev.ptrShort());
break;
case INT:
msg = Arrays.toString(ev.ptrI());
break;
case LONG:
msg = Arrays.toString(ev.ptrL());
break;
case FLOAT:
msg = Arrays.toString(ev.ptrF());
break;
case DOUBLE:
msg = Arrays.toString(ev.ptrD());
break;
case BOOL:
msg = Arrays.toString(ev.ptrBool());
break;
case MAP:
Map<String, String> map = ev.ptrMap();
for (String key: map.keySet())
{
msg += key + "=" + map.get(key) + " ";
}
break;
}
Log.i(ev.sender + "_" + ev.name + "_" + ev.id + " (" + ev.state.toString() + ", " + ev.time + ", " + ev.dur + ") : " + msg);
}
}
@Override
public void flush() throws SSJFatalException
{}
}
| 4,237 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Logger.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/test/Logger.java | /*
* Logger.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.test;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 05.03.2015.
*/
public class Logger extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Boolean> reduceNum = new Option<>("reduceNum", true, Boolean.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
public Logger() {
_name = "Logger";
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
}
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
String msg;
for (int k = 0; k < stream_in.length; ++k)
{
int num = (options.reduceNum.get()) ? 1 : stream_in[k].num;
for (int i = 0; i < num; ++i)
{
msg = "";
for (int j = 0; j < stream_in[k].dim; ++j)
{
switch (stream_in[k].type)
{
case BYTE:
msg += stream_in[k].ptrB()[i * stream_in[k].dim + j] + " ";
break;
case CHAR:
msg += stream_in[k].ptrC()[i * stream_in[k].dim + j] + " ";
break;
case SHORT:
msg += stream_in[k].ptrS()[i * stream_in[k].dim + j] + " ";
break;
case INT:
msg += stream_in[k].ptrI()[i * stream_in[k].dim + j] + " ";
break;
case LONG:
msg += stream_in[k].ptrL()[i * stream_in[k].dim + j] + " ";
break;
case FLOAT:
msg += stream_in[k].ptrF()[i * stream_in[k].dim + j] + " ";
break;
case DOUBLE:
msg += stream_in[k].ptrD()[i * stream_in[k].dim + j] + " ";
break;
case BOOL:
msg += stream_in[k].ptrBool()[i * stream_in[k].dim + j] + " ";
break;
}
}
Log.i(msg);
}
}
}
public void flush(Stream[] stream_in) throws SSJFatalException
{
}
}
| 4,127 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BLESensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BLESensor.java | /*
* BLESensor.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
public class BLESensor extends Sensor {
protected boolean angelInitialized;
protected BLESensorListener listener;
private BleDevicesScanner mBleScanner;
private BluetoothAdapter bluetoothAdapter;
BluetoothDevice bluetoothDevice;
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList {
public final Option<String> sensorName = new Option<>("sensorName", "HCM", String.class, "Sensor Name to connect to");
//public final Option<String> service = new Option<>("service", "0000180d-0000-1000-8000-00805f9b34fb", String.class, "UUID of service" );//hr
//public final Option<String> service = new Option<>("service", "481d178c-10dd-11e4-b514-b2227cce2b54", String.class, "UUID of service" ); //angel
public final Option<String> service = new Option<>("service", "00002220-0000-1000-8000-00805f9b34fb", String.class, "UUID of service");// andys
//public final Option<String> characteristic = new Option<>("characteristic", "00002a37-0000-1000-8000-00805f9b34fb", String.class, "UUID of characteristic"); //hr
//public final Option<String> characteristic = new Option<>("characteristic", "334c0be8-76f9-458b-bb2e-7df2b486b4d7", String.class, "UUID of characteristic");//angel
public final Option<String> characteristic = new Option<>("characteristic", "00002221-0000-1000-8000-00805f9b34fb", String.class, "UUID of characteristic"); // andys
/**
*
*/
private Options() {
addOptions();
}
}
public final BLESensor.Options options = new BLESensor.Options();
public LeScanCallback mScanCallback = new LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device.getName() != null) {
Log.i("Bluetooth LE device found: " + device.getName());
//mBleScanner.stopScan();
if (device.getName() != null && device.getName().startsWith(options.sensorName.get())) {
bluetoothDevice = device;
//mBleScanner.stop();
mBleScanner.stop();
listener.initialize();
listener.connect(device.getAddress());
Log.i("connected to device " + device.getName());
}
}
}
};
public BLESensor() {
_name = "BLESensor";
angelInitialized = false;
}
@Override
public boolean connect() throws SSJFatalException
{
listener = new BLESensorListener(options.service.get(), options.characteristic.get());
try {
if (mBleScanner == null) {
bluetoothAdapter = BleUtils.getBluetoothAdapter(SSJApplication.getAppContext());
mBleScanner = new BleDevicesScanner(bluetoothAdapter, mScanCallback);
}
} catch (Exception e) {
Log.e("Exception:", e);
}
mBleScanner.start();
return true;
}
@Override
public void disconnect() throws SSJFatalException
{
}
public void didDiscoverDevice(BluetoothDevice bluetoothDevice, int rssi, boolean allowed) {
}
}
| 4,990 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BVPBLEChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BVPBLEChannel.java | /*
* BVPBLEChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class BVPBLEChannel extends SensorChannel {
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 100f, Float.class, "sensor sample rate in Hz");
private Options()
{
addOptions();
}
}
public Options options = new Options();
protected BLESensorListener _listener;
public BVPBLEChannel() {
_name = "BLE_BVP";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((BLESensor) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
_listener.readCh();
int[] out = stream_out.ptrI();
out[0] = _listener.getBvp();
return true;
}
@Override
public double getSampleRate() {
return options.sampleRate.get();
}
@Override
public int getSampleDimension() {
return 1;
}
@Override
public Cons.Type getSampleType() {
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out) {
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "BVP";
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 2,982 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BleUtils.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BleUtils.java | /*
* BleUtils.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
/*
* adapted version of:
* https://github.com/StevenRudenko/BleSensorTag/blob/master/src/sample/ble/sensortag/ble/BleUtils.java
*
*/
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
public class BleUtils {
public static final int STATUS_BLE_ENABLED = 0;
public static final int STATUS_BLUETOOTH_NOT_AVAILABLE = 1;
public static final int STATUS_BLE_NOT_AVAILABLE = 2;
public static final int STATUS_BLUETOOTH_DISABLED = 3;
public static BluetoothAdapter getBluetoothAdapter(Context context) {
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
return null;
}
return bluetoothManager.getAdapter();
}
public static int getBleStatus(Context context) {
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return STATUS_BLE_NOT_AVAILABLE;
}
final BluetoothAdapter adapter = getBluetoothAdapter(context);
// Checks if Bluetooth is supported on the device.
if (adapter == null) {
return STATUS_BLUETOOTH_NOT_AVAILABLE;
}
if (!adapter.isEnabled()) {
return STATUS_BLUETOOTH_DISABLED;
}
return STATUS_BLE_ENABLED;
}
/*public static BleGattExecutor createExecutor(final BleExecutorListener listener) {
return new BleGattExecutor() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
listener.onConnectionStateChange(gatt, status, newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
listener.onServicesDiscovered(gatt, status);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
super.onCharacteristicRead(gatt, characteristic, status);
listener.onCharacteristicRead(gatt, characteristic, status);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
listener.onCharacteristicChanged(gatt, characteristic);
}
};
}*/
}
| 4,534 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BLESensorListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BLESensorListener.java | /*
* BLESensorListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.os.Handler;
import android.util.Log;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import hcm.ssj.core.SSJApplication;
/*
import com.angel.sdk.BleCharacteristic;
import com.angel.sdk.BleDevice;
import com.angel.sdk.ChAccelerationWaveform;
import com.angel.sdk.ChOpticalWaveform;
import com.angel.sdk.SrvActivityMonitoring;
import com.angel.sdk.SrvBattery;
import com.angel.sdk.SrvHealthThermometer;
import com.angel.sdk.SrvHeartRate;
import com.angel.sdk.SrvWaveformSignal;
*/
/**
* Created by simon on 17.06.16.
*/
public class BLESensorListener {
//private BleDevice mBleDevice;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static UUID UUID_HEART_RATE_MEASUREMENT =
UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
private final static String TAG = "BLETAG";
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
//private Vector<Tupel<float, float, float>> acceleration;
private Handler mHandler;
//angel sensor
private Vector<Integer> opticalGreenLED;
private Vector<Integer> opticalBlueLED;
//andys wearable
private int accelerometer = 0;
private int temperature = 0;
private int RMSSD = 0; //bvp raw values
private int bpm = 0;
private int gsr = 0;
private String service;
private String characterisitc;
//private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private BluetoothGattService bleService;
private BluetoothGattCharacteristic bleCharacteristic;
private int mConnectionState = STATE_DISCONNECTED;
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (gatt.getService(UUID.fromString(service)) != null) {
bleService = gatt.getService(UUID.fromString(service));
bleCharacteristic = bleService.getCharacteristic(UUID.fromString(characterisitc));
//readCharacteristic(bleCharacteristic);
setCharacteristicNotification(bleCharacteristic, true);
Log.i(TAG, "connect to GATT service" + service);
}
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
Log.i(TAG, "bt ch read");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "bt ch changed");
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
public BLESensorListener(String service, String characteristic) {
this.service = service;
bleCharacteristic = null;
this.characterisitc = characteristic;
reset();
}
private static int unsignedByte(byte x) {
return x & 0xFF;
}
public void reset() {
if (opticalGreenLED == null) {
opticalGreenLED = new Vector<Integer>();
} else {
opticalGreenLED.removeAllElements();
}
if (opticalBlueLED == null) {
opticalBlueLED = new Vector<Integer>();
} else {
opticalBlueLED.removeAllElements();
}
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
//final Intent intent = new Intent(action);
Log.i(TAG, "bt callback");
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
opticalGreenLED.add(heartRate);
} else if (UUID.fromString("334c0be8-76f9-458b-bb2e-7df2b486b4d7").equals(characteristic.getUuid())) {
byte[] buffer = characteristic.getValue();
Log.i(TAG, "Optical Waveform.");
final int TWO_SAMPLES_SIZE = 6;
for (int i = TWO_SAMPLES_SIZE - 1; i < buffer.length; i += TWO_SAMPLES_SIZE) {
int green = unsignedByte(buffer[i - 5]) +
unsignedByte(buffer[i - 4]) * 256 +
unsignedByte(buffer[i - 3]) * 256 * 256;
int blue = unsignedByte(buffer[i - 2]) +
unsignedByte(buffer[i - 1]) * 256 +
unsignedByte(buffer[i]) * 256 * 256;
opticalGreenLED.add(green);
opticalBlueLED.add(blue);
}
} else if (UUID.fromString("00002221-0000-1000-8000-00805f9b34fb").equals(characteristic.getUuid())) {
//HCM Andis wearable:
byte[] buffer = characteristic.getValue();
Log.i(TAG, "Optical Waveform.");
final int TWO_SAMPLES_SIZE = 6;
if (buffer.length > 6) {
Log.i(TAG, "more than 6 byte data, discarding");
}
if (buffer[1] != -128) {
accelerometer = buffer[1] + 128;
}
if (buffer[2] != -128) {
temperature = buffer[2] + 128;
}
if (buffer[3] != -128) {
bpm = buffer[3] + 128;
}
if (buffer[5] != -128) {
RMSSD = buffer[5] + 128;
}
if (buffer[4] != -128) {
gsr = buffer[4] + 128;
}
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data) {
stringBuilder.append(String.format("%02X ", byteChar));
}
//intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
Log.i(TAG, "ElseData." + stringBuilder.toString());
}
}
}
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
//mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(SSJApplication.getAppContext(), false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
public void readCh() {
if (bleCharacteristic != null) {
readCharacteristic(bleCharacteristic);
}
}
/**
* Enables or disables notification on a give characteristic.
*
* @param characteristic Characteristic to act on.
* @param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
if (UUID.fromString("00002221-0000-1000-8000-00805f9b34fb").equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
byte[] NOTIFY_AND_INDICATE = new byte[]{(byte) 3, (byte) 0};
descriptor.setValue(NOTIFY_AND_INDICATE);
mBluetoothGatt.writeDescriptor(descriptor);
}
if (UUID.fromString("334c0be8-76f9-458b-bb2e-7df2b486b4d7").equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
byte[] NOTIFY_AND_INDICATE = new byte[]{(byte) 3, (byte) 0};
descriptor.setValue(NOTIFY_AND_INDICATE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) {
return null;
}
return mBluetoothGatt.getServices();
}
public int getBvp() {
if (opticalGreenLED.size() > 0) {
int tmp = opticalGreenLED.lastElement();
if (opticalGreenLED.size() > 1) {
opticalGreenLED.removeElementAt(opticalGreenLED.size() - 1);
}
return tmp;
} else {
return 0;
}
}
public int getBpm() {return bpm;}
public int getRMSSD() { return RMSSD;}
public int getAcc() {return accelerometer;}
public int getGsr() { return gsr;}
public int getTemperature() { return temperature;}
};
| 17,779 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SampleGattAttributes.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/SampleGattAttributes.java | /*
* SampleGattAttributes.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
import java.util.HashMap;
/**
* This class includes a small subset of standard GATT attributes for demonstration purposes.
*/
public class SampleGattAttributes {
private static HashMap<String, String> attributes = new HashMap();
public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
static {
// Sample Services.
attributes.put("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
attributes.put("0000180a-0000-1000-8000-00805f9b34fb", "Device Information Service");
// Sample Characteristics.
attributes.put(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
}
public static String lookup(String uuid, String defaultName) {
String name = attributes.get(uuid);
return name == null ? defaultName : name;
}
}
| 2,407 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BleDevicesScanner.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BleDevicesScanner.java | /*
* BleDevicesScanner.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
/*
*
* https://github.com/StevenRudenko/BleSensorTag/blob/master/src/sample/ble/sensortag/ble/BleDevicesScanner.java
*
*/
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.os.Looper;
public class BleDevicesScanner implements Runnable, BluetoothAdapter.LeScanCallback {
private static final String TAG = BleDevicesScanner.class.getSimpleName();
private static final long DEFAULT_SCAN_PERIOD = 500L;
public static final long PERIOD_SCAN_ONCE = -1;
private final BluetoothAdapter bluetoothAdapter;
private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
private final LeScansPoster leScansPoster;
private long scanPeriod = DEFAULT_SCAN_PERIOD;
private Thread scanThread;
private volatile boolean isScanning = false;
public BleDevicesScanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) {
bluetoothAdapter = adapter;
leScansPoster = new LeScansPoster(callback);
}
public synchronized void setScanPeriod(long scanPeriod) {
this.scanPeriod = scanPeriod < 0 ? PERIOD_SCAN_ONCE : scanPeriod;
}
public boolean isScanning() {
return scanThread != null && scanThread.isAlive();
}
public synchronized void start() {
if (isScanning()) {
return;
}
if (scanThread != null) {
scanThread.interrupt();
}
scanThread = new Thread(this);
scanThread.setName(TAG);
scanThread.start();
}
public synchronized void stop() {
isScanning = false;
if (scanThread != null) {
scanThread.interrupt();
scanThread = null;
}
bluetoothAdapter.stopLeScan(this);
}
@Override
public void run() {
try {
isScanning = true;
do {
synchronized (this) {
bluetoothAdapter.startLeScan(this);
}
if (scanPeriod > 0) {
Thread.sleep(scanPeriod);
}
synchronized (this) {
bluetoothAdapter.stopLeScan(this);
}
} while (isScanning && scanPeriod > 0);
} catch (InterruptedException ignore) {
} finally {
synchronized (this) {
bluetoothAdapter.stopLeScan(this);
}
}
}
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
synchronized (leScansPoster) {
leScansPoster.set(device, rssi, scanRecord);
mainThreadHandler.post(leScansPoster);
}
}
private static class LeScansPoster implements Runnable {
private final BluetoothAdapter.LeScanCallback leScanCallback;
private BluetoothDevice device;
private int rssi;
private byte[] scanRecord;
private LeScansPoster(BluetoothAdapter.LeScanCallback leScanCallback) {
this.leScanCallback = leScanCallback;
}
public void set(BluetoothDevice device, int rssi, byte[] scanRecord) {
this.device = device;
this.rssi = rssi;
this.scanRecord = scanRecord;
}
@Override
public void run() {
leScanCallback.onLeScan(device, rssi, scanRecord);
}
}
}
| 4,814 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BVPAndisChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bleSensor/BVPAndisChannel.java | /*
* BVPAndisChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bleSensor;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 15.04.2015.
*/
public class BVPAndisChannel extends SensorChannel {
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 100f, Float.class, "sensor sample rate in Hz");
public final Option<Integer> dimensions = new Option<>("dimensions", 5, Integer.class, "number of dimensions");
private Options()
{
addOptions();
}
}
public Options options = new Options();
protected BLESensorListener _listener;
public BVPAndisChannel() {
_name = "BLE_BVP";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((BLESensor) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
int dimension = getSampleDimension();
int[] out = stream_out.ptrI();
out[0] = _listener.getAcc();
out[1] = _listener.getTemperature();
out[2] = _listener.getBpm();
out[3] = _listener.getRMSSD();
out[4] = _listener.getGsr();
return true;
}
@Override
public double getSampleRate() {
return options.sampleRate.get();
}
@Override
public int getSampleDimension() {
return options.dimensions.get();
}
@Override
public Cons.Type getSampleType() {
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out) {
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Acc";
stream_out.desc[1] = "Tmp";
stream_out.desc[2] = "Bvp";
stream_out.desc[3] = "Rmssd"; //bvp raw values
stream_out.desc[4] = "gsr";
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 3,473 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
OpenSmileFeatures.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/opensmile/OpenSmileFeatures.java | /*
* OpenSmile.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.opensmile;
import android.content.Context;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.FilePath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.FileUtils;
/**
* Created by Michael Dietz on 05.05.2021.
*/
public class OpenSmileFeatures extends Transformer
{
public static final String DEFAULT_CONFIG_NAME = "opensmile_egemaps_23.conf";
public static final String DEFAULT_CONFIG_FOLDER = "opensmile";
public static final String DEFAULT_CONFIG_PATH = FileCons.CONFIGS_DIR + File.separator + DEFAULT_CONFIG_FOLDER;
public class Options extends OptionList
{
public final Option<FilePath> configFile = new Option<>("path", new FilePath(DEFAULT_CONFIG_PATH + File.separator + DEFAULT_CONFIG_NAME), FilePath.class, "location of openSMILE config file");
public final Option<Cons.AudioFormat> audioFormat = new Option<>("audioFormat", Cons.AudioFormat.ENCODING_DEFAULT, Cons.AudioFormat.class, "input audio format");
public final Option<Integer> featureCount = new Option<>("featureCount", 23, Integer.class, "number of openSMILE features");
public final Option<String> featureNames = new Option<>("featureNames", "loudness,alphaRatio,hammarbergIndex,slope0-500,slope500-1500,spectralFlux,mfcc1,mfcc2,mfcc3,mfcc4,F0semitoneFrom27.5Hz,jitterLocal,shimmerLocaldB,HNRdBACF,logRelF0-H1-H2,logRelF0-H1-A3,F1frequency,F1bandwidth,F1amplitudeLogRelF0,F2frequency,F2amplitudeLogRelF0,F3frequency,F3amplitudeLogRelF0", String.class, "names of features separated by comma");
public final Option<Boolean> showLog = new Option<>("showLog", false, Boolean.class, "show openSMILE log output");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
Cons.AudioDataFormat dataFormat;
OpenSmileWrapper osWrapper;
OpenSmileDataCallback callback;
String[] featureNames;
byte[] byteBuffer;
public OpenSmileFeatures()
{
_name = this.getClass().getSimpleName();
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void init(double frame, double delta) throws SSJException
{
super.init(frame, delta);
Context context = SSJApplication.getAppContext();
List<String> assetList = new ArrayList<>();
FileUtils.listAssetFiles(context, DEFAULT_CONFIG_FOLDER, assetList);
for (String file : assetList)
{
String targetPath = FileCons.CONFIGS_DIR + File.separator + file;
// Copy default openSMILE config if it does not exist
if (!new File(targetPath).exists())
{
Log.i("Providing openSMILE config: " + file);
FileUtils.copyAsset(context, file, targetPath);
}
}
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (stream_in.length != 1)
{
throw new SSJFatalException("Stream count not supported");
}
switch (stream_in[0].type)
{
case BYTE:
{
dataFormat = Cons.AudioDataFormat.BYTE;
break;
}
case SHORT:
{
dataFormat = Cons.AudioDataFormat.SHORT;
break;
}
case FLOAT:
{
if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_DEFAULT || options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_16BIT)
{
dataFormat = Cons.AudioDataFormat.FLOAT_16;
}
else if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_8BIT)
{
dataFormat = Cons.AudioDataFormat.FLOAT_8;
}
else
{
Log.e("Audio format not supported");
}
break;
}
default:
{
Log.e("Stream type not supported");
return;
}
}
Log.d("Audio format: " + dataFormat.toString());
byteBuffer = new byte[stream_in[0].num * stream_in[0].dim * dataFormat.byteCount];
callback = new OpenSmileDataCallback();
osWrapper = new OpenSmileWrapper(options.configFile.get().toString(), options.showLog.get());
osWrapper.start(callback);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Fill byte buffer (inverse operations from audio channel)
switch (dataFormat)
{
case BYTE:
{
byte[] audioIn = stream_in[0].ptrB();
System.arraycopy(audioIn, 0, byteBuffer, 0, byteBuffer.length);
break;
}
case SHORT:
{
short[] audioIn = stream_in[0].ptrS();
ByteBuffer.wrap(byteBuffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(audioIn, 0, byteBuffer.length / 2);
break;
}
case FLOAT_8:
{
float[] audioIn = stream_in[0].ptrF();
for (int i = 0; i < audioIn.length; i++)
{
byteBuffer[i] = (byte) (audioIn[i] * 128);
}
break;
}
case FLOAT_16:
{
float[] audioIn = stream_in[0].ptrF();
for (int i = 0, j = 0; i < audioIn.length; i++)
{
short value = (short) (audioIn[i] * 32768);
byteBuffer[j++] = (byte) (value & 0xff);
byteBuffer[j++] = (byte) ((value >> 8) & 0xff);
}
break;
}
}
osWrapper.writeData(byteBuffer);
if (callback.openSmileData != null)
{
float[] out = stream_out.ptrF();
System.arraycopy(callback.getData(), 0, out, 0, out.length);
}
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (osWrapper != null)
{
osWrapper.stop();
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return options.featureCount.get();
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(getSampleType(stream_in));
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
if (options.featureNames.get() != null && !options.featureNames.get().equalsIgnoreCase(""))
{
featureNames = options.featureNames.get().split(",");
}
for (int i = 0; i < stream_out.dim; i++)
{
if (featureNames != null && i < featureNames.length)
{
stream_out.desc[i] = featureNames[i];
}
else
{
stream_out.desc[i] = "OS feat " + (i + 1);
}
}
}
}
| 7,876 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
OpenSmileWrapper.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/opensmile/OpenSmileWrapper.java | /*
* OpenSmileWrapper.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.opensmile;
import com.audeering.opensmile.OpenSmileAdapter;
import com.audeering.opensmile.smileres_t;
import java.util.HashMap;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
/**
* Created by Michael Dietz on 05.05.2021.
*/
public class OpenSmileWrapper implements Runnable
{
public static final int OS_LOG_LEVEL = 3;
public static final int OS_DEBUG = 1;
public final int OS_CONSOLE_OUTPUT;
HashMap<String, String> params = new HashMap<>();
boolean running = false;
smileres_t state;
Thread osThread;
String configPath;
OpenSmileAdapter osa;
public OpenSmileWrapper(String configPath, boolean showLog)
{
this.configPath = configPath;
if (showLog)
{
OS_CONSOLE_OUTPUT = 1;
}
else
{
OS_CONSOLE_OUTPUT = 0;
}
}
public synchronized void start(OpenSmileDataCallback callback) throws SSJFatalException
{
if (!running)
{
running = true;
osa = new OpenSmileAdapter();
state = osa.smile_initialize(configPath, params, OS_LOG_LEVEL, OS_DEBUG, OS_CONSOLE_OUTPUT);
checkState("smile_initialize");
state = osa.smile_extsink_set_data_callback("externalSink", callback);
checkState("smile_extsink_set_data_callback");
osThread = new Thread(this);
osThread.start();
}
}
@Override
public void run()
{
state = osa.smile_run();
Log.i("openSMILE thread finished running!");
}
public synchronized void stop()
{
if (running)
{
if (osa != null)
{
osa.smile_extaudiosource_set_external_eoi("externalAudioSource");
osa.smile_abort();
try
{
osThread.join(1000);
}
catch (InterruptedException e)
{
Log.e("Failed to wait for openSMILE thread to finish.");
}
osa.smile_free();
}
running = false;
}
}
public void writeData(byte[] data)
{
osa.smile_extaudiosource_write_data("externalAudioSource", data);
}
private void checkState(String step) throws SSJFatalException
{
if (state != smileres_t.SMILE_SUCCESS)
{
running = false;
throw new SSJFatalException("openSMILE step '" + step + "' failed!");
}
}
}
| 3,447 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
OpenSmileDataCallback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/opensmile/OpenSmileDataCallback.java | /*
* OpenSmileDataCallback.java
* Copyright (c) 2021
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.opensmile;
import com.audeering.opensmile.CallbackExternalSink;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 05.05.2021.
*/
public class OpenSmileDataCallback extends CallbackExternalSink
{
float[] openSmileData;
@Override
public boolean onCalledExternalSinkCallback(float[] data)
{
synchronized (this)
{
// Log.i("Length: " + data.length);
openSmileData = data;
}
return true;
}
public float[] getData()
{
synchronized (this)
{
return openSmileData;
}
}
}
| 1,885 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
OverallActivation.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/body/OverallActivation.java | /*
* OverallActivation.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.body;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Computes the expressivity feature Overall Activation as defined by Hartmann et al. 2005 and Baur et al. 2015
* Created by Johnny on 05.03.2015.
*/
public class OverallActivation extends Transformer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public OverallActivation()
{
_name = "OverallActivation";
}
float _displacement[];
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream acc = null;
for(Stream s : stream_in) {
if (s.findDataClass("AccX") >= 0)
{
acc = s;
}
}
if(acc == null || acc.dim != 3) {
Log.w("non-standard input stream");
}
_displacement = new float[stream_in[0].dim];
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = computeOA(stream_in[0]);
}
public float computeOA(Stream stream)
{
float ptr[] = stream.ptrF();
Arrays.fill(_displacement, 0);
/*
* compute displacement for each dimension
*/
float a;
for (int i = 0; i < stream.dim; ++i)
{
float velOld = 0;
float velNew = 0;
for (int j = 0; j < stream.num; ++j)
{
a = (Math.abs(ptr[j * stream.dim + i]) < 0.1) ? 0 : ptr[j * stream.dim + i];
// v1 = a * t + v0
velNew = (float) (a * stream.step) + velOld;
if(velNew < 0) velNew = 0; //ignore negative velocities -> this can happen at the start of a frame
// d = v0 * t + 0.5 * a * t² or d = v0 * t + 0.5 * (v1 - v0) * t
_displacement[i] += velOld * stream.step + 0.5 * (velNew - velOld) * stream.step;
// Update v0
velOld = velNew;
}
}
/*
* compute displacement by summing up the displacement of all dimensions
*/
float displacement = 0;
for (int i = 0; i < stream.dim; ++i)
{
displacement += _displacement[i];
}
return displacement;
}
@Override
public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 1;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(stream_in[0].bytes != 4)
Log.e("Unsupported input stream type");
return 4;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT)
Log.e("Unsupported input stream type");
return Cons.Type.FLOAT;
}
@Override
public void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Activation";
}
}
| 4,916 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AccelerationFeatures.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/body/AccelerationFeatures.java | /*
* AccelerationFeatures.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.body;
import org.jtransforms.fft.FloatFFT_1D;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.signal.MathTools;
/**
* Created by Michael Dietz on 18.10.2016.
*/
public class AccelerationFeatures extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Boolean> meanX = new Option<>("meanX", true, Boolean.class, "Mean acceleration for x-axis");
public final Option<Boolean> meanY = new Option<>("meanY", true, Boolean.class, "Mean acceleration for y-axis");
public final Option<Boolean> meanZ = new Option<>("meanZ", true, Boolean.class, "Mean acceleration for z-axis");
public final Option<Boolean> stdDeviationX = new Option<>("stdDeviationX", true, Boolean.class, "Standard deviation for x-axis");
public final Option<Boolean> stdDeviationY = new Option<>("stdDeviationY", true, Boolean.class, "Standard deviation for y-axis");
public final Option<Boolean> stdDeviationZ = new Option<>("stdDeviationZ", true, Boolean.class, "Standard deviation for z-axis");
public final Option<Boolean> energyX = new Option<>("energyX", true, Boolean.class, "Energy for x-axis");
public final Option<Boolean> energyY = new Option<>("energyY", true, Boolean.class, "Energy for y-axis");
public final Option<Boolean> energyZ = new Option<>("energyZ", true, Boolean.class, "Energy for z-axis");
public final Option<Boolean> correlationXY = new Option<>("correlationXY", true, Boolean.class, "Correlation between x and y-axis");
public final Option<Boolean> correlationXZ = new Option<>("correlationXZ", true, Boolean.class, "Correlation between x and z-axis");
public final Option<Boolean> correlationYZ = new Option<>("correlationYZ", true, Boolean.class, "Correlation between y and z-axis");
public final Option<Boolean> displacementX = new Option<>("displacementX", false, Boolean.class, "Displacement for x-axis");
public final Option<Boolean> displacementY = new Option<>("displacementY", false, Boolean.class, "Displacement for y-axis");
public final Option<Boolean> displacementZ = new Option<>("displacementZ", false, Boolean.class, "Displacement for z-axis");
public final Option<Boolean> entropyX = new Option<>("entropyX", true, Boolean.class, "Frequency domain entropy for x-axis");
public final Option<Boolean> entropyY = new Option<>("entropyY", true, Boolean.class, "Frequency domain entropy for y-axis");
public final Option<Boolean> entropyZ = new Option<>("entropyZ", true, Boolean.class, "Frequency domain entropy for z-axis");
public final Option<Boolean> skewX = new Option<>("skewX", true, Boolean.class, "Skew for x-axis");
public final Option<Boolean> skewY = new Option<>("skewY", true, Boolean.class, "Skew for y-axis");
public final Option<Boolean> skewZ = new Option<>("skewZ", true, Boolean.class, "Skew for z-axis");
public final Option<Boolean> kurtosisX = new Option<>("kurtosisX", true, Boolean.class, "Kurtosis for x-axis");
public final Option<Boolean> kurtosisY = new Option<>("kurtosisY", true, Boolean.class, "Kurtosis for y-axis");
public final Option<Boolean> kurtosisZ = new Option<>("kurtosisZ", true, Boolean.class, "Kurtosis for z-axis");
public final Option<Boolean> iqrX = new Option<>("iqrX", true, Boolean.class, "Interquartile range for x-axis");
public final Option<Boolean> iqrY = new Option<>("iqrY", true, Boolean.class, "Interquartile range for y-axis");
public final Option<Boolean> iqrZ = new Option<>("iqrZ", true, Boolean.class, "Interquartile range for z-axis");
public final Option<Boolean> madX = new Option<>("madX", true, Boolean.class, "Mean absolute deviation for x-axis");
public final Option<Boolean> madY = new Option<>("madY", true, Boolean.class, "Mean absolute deviation for y-axis");
public final Option<Boolean> madZ = new Option<>("madZ", true, Boolean.class, "Mean absolute deviation for z-axis");
public final Option<Boolean> rmsX = new Option<>("rmsX", true, Boolean.class, "Root mean square for x-axis");
public final Option<Boolean> rmsY = new Option<>("rmsY", true, Boolean.class, "Root mean square for y-axis");
public final Option<Boolean> rmsZ = new Option<>("rmsZ", true, Boolean.class, "Root mean square for z-axis");
public final Option<Boolean> varianceX = new Option<>("varianceX", true, Boolean.class, "Variance for x-axis");
public final Option<Boolean> varianceY = new Option<>("varianceY", true, Boolean.class, "Variance for y-axis");
public final Option<Boolean> varianceZ = new Option<>("varianceZ", true, Boolean.class, "Variance for z-axis");
public final Option<Boolean> signalMagnitudeArea = new Option<>("signalMagnitudeArea", true, Boolean.class, "Signal magnitude area for all axes");
public final Option<Boolean> haarFilterX = new Option<>("haarFilterX", true, Boolean.class, "Haar-like filter for x-axis");
public final Option<Boolean> haarFilterY = new Option<>("haarFilterY", true, Boolean.class, "Haar-like filter for y-axis");
public final Option<Boolean> haarFilterZ = new Option<>("haarFilterZ", true, Boolean.class, "Haar-like filter for z-axis");
public final Option<Boolean> haarFilterBiaxialXY = new Option<>("haarFilterBiaxialXY", true, Boolean.class, "Biaxial Haar-like filter between x and y-axis");
public final Option<Boolean> haarFilterBiaxialYZ = new Option<>("haarFilterBiaxialYZ", true, Boolean.class, "Biaxial Haar-like filter between y and z-axis");
public final Option<Boolean> haarFilterBiaxialZX = new Option<>("haarFilterBiaxialZX", true, Boolean.class, "Biaxial Haar-like filter between z and x-axis");
public final Option<Boolean> crestX = new Option<>("crestX", true, Boolean.class, "Crest factor for x-axis");
public final Option<Boolean> crestY = new Option<>("crestY", true, Boolean.class, "Crest factor for y-axis");
public final Option<Boolean> crestZ = new Option<>("crestZ", true, Boolean.class, "Crest factor for z-axis");
public final Option<Boolean> spectralFluxX = new Option<>("spectralFluxX", true, Boolean.class, "Spectral flux for x-axis");
public final Option<Boolean> spectralFluxY = new Option<>("spectralFluxY", true, Boolean.class, "Spectral flux for y-axis");
public final Option<Boolean> spectralFluxZ = new Option<>("spectralFluxZ", true, Boolean.class, "Spectral flux for z-axis");
public final Option<Boolean> spectralCentroidX = new Option<>("spectralCentroidX", true, Boolean.class, "Spectral centroid for x-axis");
public final Option<Boolean> spectralCentroidY = new Option<>("spectralCentroidY", true, Boolean.class, "Spectral centroid for y-axis");
public final Option<Boolean> spectralCentroidZ = new Option<>("spectralCentroidZ", true, Boolean.class, "Spectral centroid for z-axis");
public final Option<Boolean> spectralRolloffX = new Option<>("spectralRolloffX", true, Boolean.class, "Spectral rolloff for x-axis");
public final Option<Boolean> spectralRolloffY = new Option<>("spectralRolloffY", true, Boolean.class, "Spectral rolloff for y-axis");
public final Option<Boolean> spectralRolloffZ = new Option<>("spectralRolloffZ", true, Boolean.class, "Spectral rolloff for z-axis");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
FloatFFT_1D fft;
float[] inputCopy;
float[] xValues;
float[] yValues;
float[] zValues;
float[] joined;
float[] psd;
float[] xValuesFFT;
float[] yValuesFFT;
float[] zValuesFFT;
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int values = stream_in[0].num;
fft = new FloatFFT_1D(values);
inputCopy = new float[values];
xValues = new float[values];
yValues = new float[values];
zValues = new float[values];
joined = new float[(values >> 1) + 1];
psd = new float[(values >> 1) + 1];
xValuesFFT = new float[(values >> 1) + 1];
yValuesFFT = new float[(values >> 1) + 1];
zValuesFFT = new float[(values >> 1) + 1];
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
MathTools math = MathTools.getInstance();
getValues(stream_in[0], 0, xValues);
getValues(stream_in[0], 1, yValues);
getValues(stream_in[0], 2, zValues);
calculateFFT(xValues, xValuesFFT);
calculateFFT(yValues, yValuesFFT);
calculateFFT(zValues, zValuesFFT);
float[] out = stream_out.ptrF();
int featureCount = 0;
if (options.meanX.get())
{
out[featureCount++] = math.getMean(xValues);
}
if (options.meanY.get())
{
out[featureCount++] = math.getMean(yValues);
}
if (options.meanZ.get())
{
out[featureCount++] = math.getMean(zValues);
}
if (options.stdDeviationX.get())
{
out[featureCount++] = math.getStdDeviation(xValues);
}
if (options.stdDeviationY.get())
{
out[featureCount++] = math.getStdDeviation(yValues);
}
if (options.stdDeviationZ.get())
{
out[featureCount++] = math.getStdDeviation(zValues);
}
if (options.energyX.get())
{
out[featureCount++] = getEnergy(xValuesFFT);
}
if (options.energyY.get())
{
out[featureCount++] = getEnergy(yValuesFFT);
}
if (options.energyZ.get())
{
out[featureCount++] = getEnergy(zValuesFFT);
}
if (options.correlationXY.get())
{
out[featureCount++] = getCorrelation(xValues, yValues);
}
if (options.correlationXZ.get())
{
out[featureCount++] = getCorrelation(xValues, zValues);
}
if (options.correlationYZ.get())
{
out[featureCount++] = getCorrelation(yValues, zValues);
}
if (options.displacementX.get())
{
out[featureCount++] = getDisplacement(xValues, stream_in[0].sr);
}
if (options.displacementY.get())
{
out[featureCount++] = getDisplacement(yValues, stream_in[0].sr);
}
if (options.displacementZ.get())
{
out[featureCount++] = getDisplacement(zValues, stream_in[0].sr);
}
if (options.entropyX.get())
{
out[featureCount++] = getEntropy(xValuesFFT);
}
if (options.entropyY.get())
{
out[featureCount++] = getEntropy(yValuesFFT);
}
if (options.entropyZ.get())
{
out[featureCount++] = getEntropy(zValuesFFT);
}
if (options.skewX.get())
{
out[featureCount++] = math.getSkew(xValues);
}
if (options.skewY.get())
{
out[featureCount++] = math.getSkew(yValues);
}
if (options.skewZ.get())
{
out[featureCount++] = math.getSkew(zValues);
}
if (options.kurtosisX.get())
{
out[featureCount++] = math.getKurtosis(xValues);
}
if (options.kurtosisY.get())
{
out[featureCount++] = math.getKurtosis(yValues);
}
if (options.kurtosisZ.get())
{
out[featureCount++] = math.getKurtosis(zValues);
}
if (options.iqrX.get())
{
out[featureCount++] = math.getIQR(xValues);
}
if (options.iqrY.get())
{
out[featureCount++] = math.getIQR(yValues);
}
if (options.iqrZ.get())
{
out[featureCount++] = math.getIQR(zValues);
}
if (options.madX.get())
{
out[featureCount++] = math.getMAD(xValues);
}
if (options.madY.get())
{
out[featureCount++] = math.getMAD(yValues);
}
if (options.madZ.get())
{
out[featureCount++] = math.getMAD(zValues);
}
if (options.rmsX.get())
{
out[featureCount++] = math.getRMS(xValues);
}
if (options.rmsY.get())
{
out[featureCount++] = math.getRMS(yValues);
}
if (options.rmsZ.get())
{
out[featureCount++] = math.getRMS(zValues);
}
if (options.varianceX.get())
{
out[featureCount++] = math.getVariance(xValues);
}
if (options.varianceY.get())
{
out[featureCount++] = math.getVariance(yValues);
}
if (options.varianceZ.get())
{
out[featureCount++] = math.getVariance(zValues);
}
if (options.signalMagnitudeArea.get())
{
out[featureCount++] = getSignalMagnitudeArea(xValues, yValues, zValues);
}
if (options.haarFilterX.get())
{
out[featureCount++] = getHaarFilter(xValues);
}
if (options.haarFilterY.get())
{
out[featureCount++] = getHaarFilter(yValues);
}
if (options.haarFilterZ.get())
{
out[featureCount++] = getHaarFilter(zValues);
}
if (options.haarFilterBiaxialXY.get())
{
out[featureCount++] = getHaarFilterBiaxial(xValues, yValues);
}
if (options.haarFilterBiaxialYZ.get())
{
out[featureCount++] = getHaarFilterBiaxial(yValues, zValues);
}
if (options.haarFilterBiaxialZX.get())
{
out[featureCount++] = getHaarFilterBiaxial(zValues, xValues);
}
if (options.crestX.get())
{
out[featureCount++] = math.getCrest(xValues);
}
if (options.crestY.get())
{
out[featureCount++] = math.getCrest(yValues);
}
if (options.crestZ.get())
{
out[featureCount++] = math.getCrest(zValues);
}
if (options.spectralFluxX.get())
{
out[featureCount++] = getSpectralFlux(xValuesFFT);
}
if (options.spectralFluxY.get())
{
out[featureCount++] = getSpectralFlux(yValuesFFT);
}
if (options.spectralFluxZ.get())
{
out[featureCount++] = getSpectralFlux(zValuesFFT);
}
if (options.spectralCentroidX.get())
{
out[featureCount++] = getSpectralCentroid(xValuesFFT);
}
if (options.spectralCentroidY.get())
{
out[featureCount++] = getSpectralCentroid(yValuesFFT);
}
if (options.spectralCentroidZ.get())
{
out[featureCount++] = getSpectralCentroid(zValuesFFT);
}
if (options.spectralRolloffX.get())
{
out[featureCount++] = getSpectralRolloff(xValuesFFT);
}
if (options.spectralRolloffY.get())
{
out[featureCount++] = getSpectralRolloff(yValuesFFT);
}
if (options.spectralRolloffZ.get())
{
out[featureCount++] = getSpectralRolloff(zValuesFFT);
}
}
/*
* Energy for acceleration value
*
* based on
* Bao, Ling et al. - Activity Recognition from User-Annotated Acceleration Data
* Ravi, N. et al. - Activity recognition from accelerometer data
*/
private float getEnergy(float[] fftValues)
{
float energy = 0;
// Calculate energy
for (int i = 0; i < fftValues.length; i++)
{
energy += Math.pow(fftValues[i], 2);
}
if (fftValues.length > 0)
{
energy = energy / (float) fftValues.length;
}
return energy;
}
/*
* Correlation for acceleration value
*
* based on
* Bao, Ling et al. - Activity Recognition from User-Annotated Acceleration Data
* Ravi, N. et al. - Activity recognition from accelerometer data
*/
private float getCorrelation(float[] aValues, float[] bValues)
{
MathTools math = MathTools.getInstance();
float correlation = 0;
float covariance = 0;
if (aValues.length > 0 && bValues.length > 0)
{
float meanA = math.getMean(aValues);
float meanB = math.getMean(bValues);
float stdDeviationA = math.getStdDeviation(aValues);
float stdDeviationB = math.getStdDeviation(bValues);
for (int i = 0; i < aValues.length; i++)
{
covariance += (aValues[i] - meanA) * (bValues[i] - meanB);
}
covariance = covariance / (float) aValues.length;
if (stdDeviationA * stdDeviationB != 0)
{
correlation = covariance / (stdDeviationA * stdDeviationB);
}
}
return correlation;
}
/*
* Displacement for acceleration value in meter
*/
private float getDisplacement(float[] values, double sampleRate)
{
float displacement = 0;
float a = 0;
float velNew = 0;
float velOld = 0;
// Time for which the object moves with that acceleration
float t = 1.0f / (float) sampleRate;
// Sum up displacement steps
for (int i = 0; i < values.length; i++)
{
a = (Math.abs(values[i]) < 0.1) ? 0 : values[i];
// v1 = a * t + v0
velNew = a * t + velOld;
// d = v0 * t + 0.5 * a * t² or d = v0 * t + 0.5 * (v1 - v0) * t
displacement += velOld * t + 0.5f * (velNew - velOld) * t;
// Update v0
velOld = velNew;
}
return displacement;
}
/*
* Frequency domain entropy for acceleration value
*
* based on
* Bao, Ling et al. - Activity Recognition from User-Annotated Acceleration Data
* Huynh, T. et al. - Analyzing features for activity recognition
* Lara, Oscar D. et al. - A Survey on Human Activity Recognition using Wearable Sensors
* Khan, A. et al. - Accelerometer's position free human activity recognition using a hierarchical recognition model
*
* http://stackoverflow.com/questions/30418391/what-is-frequency-domain-entropy-in-fft-result-and-how-to-calculate-it
* http://dsp.stackexchange.com/questions/23689/what-is-spectral-entropy
*/
private float getEntropy(float[] fftValues)
{
float entropy = 0;
if (fftValues.length > 0)
{
// Calculate Power Spectral Density
for (int i = 0; i < fftValues.length; i++)
{
psd[i] = (float) (Math.pow(fftValues[i], 2) / fftValues.length);
}
float psdSum = MathTools.getInstance().getSum(psd);
if (psdSum > 0)
{
// Normalize calculated PSD so that it can be viewed as a Probability Density Function
for (int i = 0; i < fftValues.length; i++)
{
psd[i] = psd[i] / psdSum;
}
// Calculate the Frequency Domain Entropy
for (int i = 0; i < fftValues.length; i++)
{
if (psd[i] != 0)
{
entropy += psd[i] * Math.log(psd[i]);
}
}
entropy *= -1;
}
}
return entropy;
}
/*
* Signal magnitude area for acceleration
*
* based on
* Khan, A. et al. - Accelerometer's position free human activity recognition using a hierarchical recognition model
*/
private float getSignalMagnitudeArea(float[] xValues, float[] yValues, float[] zValues)
{
float sma = 0;
if (xValues.length == yValues.length && yValues.length == zValues.length)
{
for (int i = 0; i < xValues.length; i++)
{
sma += Math.abs(xValues[i]) + Math.abs(yValues[i]) + Math.abs(zValues[i]);
}
}
return sma;
}
/*
* Haar-like filter for acceleration
*
* based on
* Hanai, Yuya et al. - Haar-Like Filtering for Human Activity Recognition Using 3D Accelerometer
*/
private float getHaarFilter(float[] values)
{
float haar = 0;
// Sizes in number of samples
int wFrame = values.length;
int wFilter = (int) (0.2 * wFrame);
int wShift = (int) (0.5 * wFilter);
int N = (wFrame - wFilter) / wShift + 1;
float filterValue;
for (int n = 0; n < N; n++)
{
filterValue = 0;
for (int k = 0; k < wFilter; k++)
{
if (n * wShift + k < wFrame)
{
if (k < wFilter / 2)
{
// Left side of haar filter
filterValue -= values[n * wShift + k];
}
else
{
// Right side of haar filter
filterValue += values[n * wShift + k];
}
}
}
haar += Math.abs(filterValue);
}
return haar;
}
/*
* Biaxial Haar-like filter for acceleration
*
* based on
* Hanai, Yuya et al. - Haar-Like Filtering for Human Activity Recognition Using 3D Accelerometer
*/
private float getHaarFilterBiaxial(float[] aValues, float[] bValues)
{
float haarBiaxial = 0;
// Sizes in number of samples
int wFrame = aValues.length;
int wFilter = (int)(0.2 * wFrame);
int wShift = (int)(0.5 * wFilter);
int N = (wFrame - wFilter) / wShift + 1;
float aFilterValue;
float bFilterValue;
for (int n = 0; n < N; n++)
{
aFilterValue = 0;
bFilterValue = 0;
for (int k = 0; k < wFilter; k++)
{
if (n * wShift + k < wFrame)
{
if (k < wFilter / 2)
{
// Left side of haar filter
aFilterValue -= aValues[n * wShift + k];
bFilterValue -= bValues[n * wShift + k];
}
else
{
// Right side of haar filter
aFilterValue += aValues[n * wShift + k];
bFilterValue += bValues[n * wShift + k];
}
}
}
haarBiaxial += Math.abs(aFilterValue - bFilterValue);
}
return haarBiaxial;
}
/*
* Spectral flux for acceleration
*
* based on
* Rahman, Shah et al. - Unintrusive eating recognition using Google glass
* Lu, Hong et al. - SoundSense: Scalable Sound Sensing for People-Centric Applications on Mobile Phones
*/
private float getSpectralFlux(float[] fftValues)
{
float spectralFlux = 0;
if (fftValues.length > 0)
{
float previousValue = 0;
float currentValue = 0;
for (int i = 0; i < fftValues.length; i++)
{
currentValue = fftValues[i];
spectralFlux += Math.pow(currentValue - previousValue, 2);
previousValue = fftValues[i];
}
}
return spectralFlux;
}
/*
* Spectral centroid for acceleration
*
* based on
* Rahman, Shah et al. - Unintrusive eating recognition using Google glass
* Lu, Hong et al. - SoundSense: Scalable Sound Sensing for People-Centric Applications on Mobile Phones
*/
private float getSpectralCentroid(float[] fftValues)
{
float spectralCentroid = 0;
if (fftValues.length > 0)
{
float sumTop = 0;
float sumBottom = 0;
for (int i = 0; i < fftValues.length; i++)
{
sumTop += i * Math.pow(fftValues[i], 2);
sumBottom += Math.pow(fftValues[i], 2);
}
if (sumBottom > 0)
{
spectralCentroid = sumTop / sumBottom;
}
}
return spectralCentroid;
}
/*
* Spectral rolloff for acceleration
*
* based on
* Rahman, Shah et al. - Unintrusive eating recognition using Google glass
* Lu, Hong et al. - SoundSense: Scalable Sound Sensing for People-Centric Applications on Mobile Phones
*/
private float getSpectralRolloff(float[] fftValues)
{
float spectralRolloff = 0;
float threshold = 0.93f;
if (fftValues.length > 0)
{
float fftSumTotal = 0;
float fftSum = 0;
for (int i = 0; i < fftValues.length; i++)
{
fftSumTotal += fftValues[i];
}
for (int i = 0; i < fftValues.length; i++)
{
fftSum += fftValues[i];
if (fftSum / fftSumTotal >= threshold)
{
spectralRolloff = i;
break;
}
}
}
return spectralRolloff;
}
/**
* Helper function to get all values from a specific dimension
*/
private void getValues(Stream stream, int dimension, float[] out)
{
float[] in = stream.ptrF();
for (int i = 0; i < stream.num; i++)
{
out[i] = in[i * stream.dim + dimension];
}
}
private void calculateFFT(float[] values, float[] out)
{
System.arraycopy(values, 0, inputCopy, 0, values.length);
// Calculate FFT
fft.realForward(inputCopy);
// Format values like in SSI
Util.joinFFT(inputCopy, out);
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
int dim = 0;
if (stream_in[0].dim != 3)
{
Log.e("Unsupported input stream dimension");
}
if (options.meanX.get()) dim++;
if (options.meanY.get()) dim++;
if (options.meanZ.get()) dim++;
if (options.stdDeviationX.get()) dim++;
if (options.stdDeviationY.get()) dim++;
if (options.stdDeviationZ.get()) dim++;
if (options.energyX.get()) dim++;
if (options.energyY.get()) dim++;
if (options.energyZ.get()) dim++;
if (options.correlationXY.get()) dim++;
if (options.correlationXZ.get()) dim++;
if (options.correlationYZ.get()) dim++;
if (options.displacementX.get()) dim++;
if (options.displacementY.get()) dim++;
if (options.displacementZ.get()) dim++;
if (options.entropyX.get()) dim++;
if (options.entropyY.get()) dim++;
if (options.entropyZ.get()) dim++;
if (options.skewX.get()) dim++;
if (options.skewY.get()) dim++;
if (options.skewZ.get()) dim++;
if (options.kurtosisX.get()) dim++;
if (options.kurtosisY.get()) dim++;
if (options.kurtosisZ.get()) dim++;
if (options.iqrX.get()) dim++;
if (options.iqrY.get()) dim++;
if (options.iqrZ.get()) dim++;
if (options.madX.get()) dim++;
if (options.madY.get()) dim++;
if (options.madZ.get()) dim++;
if (options.rmsX.get()) dim++;
if (options.rmsY.get()) dim++;
if (options.rmsZ.get()) dim++;
if (options.varianceX.get()) dim++;
if (options.varianceY.get()) dim++;
if (options.varianceZ.get()) dim++;
if (options.signalMagnitudeArea.get()) dim++;
if (options.haarFilterX.get()) dim++;
if (options.haarFilterY.get()) dim++;
if (options.haarFilterZ.get()) dim++;
if (options.haarFilterBiaxialXY.get()) dim++;
if (options.haarFilterBiaxialYZ.get()) dim++;
if (options.haarFilterBiaxialZX.get()) dim++;
if (options.crestX.get()) dim++;
if (options.crestY.get()) dim++;
if (options.crestZ.get()) dim++;
if (options.spectralFluxX.get()) dim++;
if (options.spectralFluxY.get()) dim++;
if (options.spectralFluxZ.get()) dim++;
if (options.spectralCentroidX.get()) dim++;
if (options.spectralCentroidY.get()) dim++;
if (options.spectralCentroidZ.get()) dim++;
if (options.spectralRolloffX.get()) dim++;
if (options.spectralRolloffY.get()) dim++;
if (options.spectralRolloffZ.get()) dim++;
return dim;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(getSampleType(stream_in));
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("Unsupported input stream type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
int featureCount = 0;
if (options.meanX.get())
{
stream_out.desc[featureCount++] = "meanX";
}
if (options.meanY.get())
{
stream_out.desc[featureCount++] = "meanY";
}
if (options.meanZ.get())
{
stream_out.desc[featureCount++] = "meanZ";
}
if (options.stdDeviationX.get())
{
stream_out.desc[featureCount++] = "stdDeviationX";
}
if (options.stdDeviationY.get())
{
stream_out.desc[featureCount++] = "stdDeviationY";
}
if (options.stdDeviationZ.get())
{
stream_out.desc[featureCount++] = "stdDeviationZ";
}
if (options.energyX.get())
{
stream_out.desc[featureCount++] = "energyX";
}
if (options.energyY.get())
{
stream_out.desc[featureCount++] = "energyY";
}
if (options.energyZ.get())
{
stream_out.desc[featureCount++] = "energyZ";
}
if (options.correlationXY.get())
{
stream_out.desc[featureCount++] = "correlationXY";
}
if (options.correlationXZ.get())
{
stream_out.desc[featureCount++] = "correlationXZ";
}
if (options.correlationYZ.get())
{
stream_out.desc[featureCount++] = "correlationYZ";
}
if (options.displacementX.get())
{
stream_out.desc[featureCount++] = "displacementX";
}
if (options.displacementY.get())
{
stream_out.desc[featureCount++] = "displacementY";
}
if (options.displacementZ.get())
{
stream_out.desc[featureCount++] = "displacementZ";
}
if (options.entropyX.get())
{
stream_out.desc[featureCount++] = "entropyX";
}
if (options.entropyY.get())
{
stream_out.desc[featureCount++] = "entropyY";
}
if (options.entropyZ.get())
{
stream_out.desc[featureCount++] = "entropyZ";
}
if (options.skewX.get())
{
stream_out.desc[featureCount++] = "skewX";
}
if (options.skewY.get())
{
stream_out.desc[featureCount++] = "skewY";
}
if (options.skewZ.get())
{
stream_out.desc[featureCount++] = "skewZ";
}
if (options.kurtosisX.get())
{
stream_out.desc[featureCount++] = "kurtosisX";
}
if (options.kurtosisY.get())
{
stream_out.desc[featureCount++] = "kurtosisY";
}
if (options.kurtosisZ.get())
{
stream_out.desc[featureCount++] = "kurtosisZ";
}
if (options.iqrX.get())
{
stream_out.desc[featureCount++] = "iqrX";
}
if (options.iqrY.get())
{
stream_out.desc[featureCount++] = "iqrY";
}
if (options.iqrZ.get())
{
stream_out.desc[featureCount++] = "iqrZ";
}
if (options.madX.get())
{
stream_out.desc[featureCount++] = "madX";
}
if (options.madY.get())
{
stream_out.desc[featureCount++] = "madY";
}
if (options.madZ.get())
{
stream_out.desc[featureCount++] = "madZ";
}
if (options.rmsX.get())
{
stream_out.desc[featureCount++] = "rmsX";
}
if (options.rmsY.get())
{
stream_out.desc[featureCount++] = "rmsY";
}
if (options.rmsZ.get())
{
stream_out.desc[featureCount++] = "rmsZ";
}
if (options.varianceX.get())
{
stream_out.desc[featureCount++] = "varianceX";
}
if (options.varianceY.get())
{
stream_out.desc[featureCount++] = "varianceY";
}
if (options.varianceZ.get())
{
stream_out.desc[featureCount++] = "varianceZ";
}
if (options.signalMagnitudeArea.get())
{
stream_out.desc[featureCount++] = "signalMagnitudeArea";
}
if (options.haarFilterX.get())
{
stream_out.desc[featureCount++] = "haarFilterX";
}
if (options.haarFilterY.get())
{
stream_out.desc[featureCount++] = "haarFilterY";
}
if (options.haarFilterZ.get())
{
stream_out.desc[featureCount++] = "haarFilterZ";
}
if (options.haarFilterBiaxialXY.get())
{
stream_out.desc[featureCount++] = "haarFilterBiaxialXY";
}
if (options.haarFilterBiaxialYZ.get())
{
stream_out.desc[featureCount++] = "haarFilterBiaxialYZ";
}
if (options.haarFilterBiaxialZX.get())
{
stream_out.desc[featureCount++] = "haarFilterBiaxialZX";
}
if (options.crestX.get())
{
stream_out.desc[featureCount++] = "crestX";
}
if (options.crestY.get())
{
stream_out.desc[featureCount++] = "crestY";
}
if (options.crestZ.get())
{
stream_out.desc[featureCount++] = "crestZ";
}
if (options.spectralFluxX.get())
{
stream_out.desc[featureCount++] = "spectralFluxX";
}
if (options.spectralFluxY.get())
{
stream_out.desc[featureCount++] = "spectralFluxY";
}
if (options.spectralFluxZ.get())
{
stream_out.desc[featureCount++] = "spectralFluxZ";
}
if (options.spectralCentroidX.get())
{
stream_out.desc[featureCount++] = "spectralCentroidX";
}
if (options.spectralCentroidY.get())
{
stream_out.desc[featureCount++] = "spectralCentroidY";
}
if (options.spectralCentroidZ.get())
{
stream_out.desc[featureCount++] = "spectralCentroidZ";
}
if (options.spectralRolloffX.get())
{
stream_out.desc[featureCount++] = "spectralRolloffX";
}
if (options.spectralRolloffY.get())
{
stream_out.desc[featureCount++] = "spectralRolloffY";
}
if (options.spectralRolloffZ.get())
{
stream_out.desc[featureCount++] = "spectralRolloffZ";
}
}
}
| 31,482 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CaloriesChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/CaloriesChannel.java | /*
* CaloriesChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class CaloriesChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public CaloriesChannel()
{
_name = "MSBand_Calories";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.Calories, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
long[] out = stream_out.ptrL();
out[0] = _listener.getCalories();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.LONG;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Calories";
}
}
| 3,000 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GSRChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/GSRChannel.java | /*
* GSRChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import com.microsoft.band.sensors.GsrSampleRate;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Provides skin resistance in kOhms
*
* Created by Michael Dietz on 06.07.2016.
*/
public class GSRChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 5.0f, Float.class, "supported sample rates: 0.2, 5.0 Hz");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public GSRChannel()
{
_name = "MSBand_GSR";
}
@Override
public void init() throws SSJException
{
GsrSampleRate sr;
if (options.sampleRate.get() <= 0.2)
{
sr = GsrSampleRate.MS5000;
}
else
{
sr = GsrSampleRate.MS200;
}
((MSBand)_sensor).configureChannel(MSBand.Channel.GSR, true, sr.ordinal());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = (float)_listener.getGsr();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "GSR";
}
}
| 3,251 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GyroscopeChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/GyroscopeChannel.java | /*
* GyroscopeChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import com.microsoft.band.sensors.SampleRate;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class GyroscopeChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 62.5f, Float.class, "supported sample rates: 7.8125, 31.25, 62.5 Hz");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public GyroscopeChannel()
{
_name = "MSBand_Gyroscope";
}
@Override
public void init() throws SSJException
{
SampleRate sr;
if (options.sampleRate.get() <= 7.8125)
{
sr = SampleRate.MS128;
}
else if (options.sampleRate.get() <= 31.25)
{
sr = SampleRate.MS32;
}
else
{
sr = SampleRate.MS16;
}
((MSBand)_sensor).configureChannel(MSBand.Channel.Gyroscope, true, sr.ordinal());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = _listener.getAngularVelocityX();
out[1] = _listener.getAngularVelocityY();
out[2] = _listener.getAngularVelocityZ();
out[3] = _listener.getAngularAccelerationX();
out[4] = _listener.getAngularAccelerationY();
out[5] = _listener.getAngularAccelerationZ();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 6;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AngularVelX";
stream_out.desc[1] = "AngularVelY";
stream_out.desc[2] = "AngularVelZ";
stream_out.desc[3] = "AngularAccX";
stream_out.desc[4] = "AngularAccY";
stream_out.desc[5] = "AngularAccZ";
}
}
| 3,757 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PedometerChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/PedometerChannel.java | /*
* PedometerChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class PedometerChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public PedometerChannel()
{
_name = "MSBand_Pedometer";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.Pedometer, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
long[] out = stream_out.ptrL();
out[0] = _listener.getSteps();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.LONG;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Steps";
}
}
| 2,999 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BrightnessChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/BrightnessChannel.java | /*
* BrightnessChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class BrightnessChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 2, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public BrightnessChannel()
{
_name = "MSBand_Brightness";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.AmbientLight, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
int[] out = stream_out.ptrI();
out[0] = _listener.getBrightness();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Brightness";
}
}
| 3,014 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AccelerationChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/AccelerationChannel.java | /*
* AccelerationChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import com.microsoft.band.sensors.SampleRate;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class AccelerationChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 62.5f, Float.class, "supported sample rates: 7.8125, 31.25, 62.5 Hz");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public AccelerationChannel()
{
_name = "MSBand_Acceleration";
}
@Override
public void init() throws SSJException
{
SampleRate sr;
if (options.sampleRate.get() <= 7.8125)
{
sr = SampleRate.MS128;
}
else if (options.sampleRate.get() <= 31.25)
{
sr = SampleRate.MS32;
}
else
{
sr = SampleRate.MS16;
}
((MSBand)_sensor).configureChannel(MSBand.Channel.Acceleration, true, sr.ordinal());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = _listener.getAccelerationX();
out[1] = _listener.getAccelerationY();
out[2] = _listener.getAccelerationZ();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 3;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AccX";
stream_out.desc[1] = "AccY";
stream_out.desc[2] = "AccZ";
}
}
| 3,484 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
DistanceChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/DistanceChannel.java | /*
* DistanceChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class DistanceChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public DistanceChannel()
{
_name = "MSBand_Distance";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.Distance, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
int[] out = stream_out.ptrI();
out[0] = (int)_listener.getDistance();
out[1] = (int)_listener.getSpeed();
out[2] = (int)_listener.getPace();
out[3] = _listener.getMotionType();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 4;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Distance";
stream_out.desc[1] = "Speed";
stream_out.desc[2] = "Pace";
stream_out.desc[3] = "MotionType";
}
}
| 3,216 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IBIChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/IBIChannel.java | /*
* IBIChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class IBIChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 30, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public IBIChannel()
{
_name = "MSBand_IBI";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.RRInterval, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = (float)_listener.getInterBeatInterval();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "IBI";
}
}
| 2,996 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AltimeterChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/AltimeterChannel.java | /*
* AltimeterChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class AltimeterChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public AltimeterChannel()
{
_name = "MSBand_Altimeter";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.Altimeter, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
long[] out = stream_out.ptrL();
out[0] = _listener.getFlightsAscended();
out[1] = _listener.getFlightsDescended();
out[2] = _listener.getSteppingGain();
out[3] = _listener.getSteppingLoss();
out[4] = _listener.getStepsAscended();
out[5] = _listener.getStepsDescended();
out[6] = _listener.getAltimeterGain();
out[7] = _listener.getAltimeterLoss();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 8;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.LONG;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "FlightsAscended";
stream_out.desc[1] = "FlightsDescended";
stream_out.desc[2] = "SteppingGain";
stream_out.desc[3] = "SteppingLoss";
stream_out.desc[4] = "StepsAscended";
stream_out.desc[5] = "StepsDescended";
stream_out.desc[6] = "AltimeterGain";
stream_out.desc[7] = "AltimeterLoss";
}
}
| 3,590 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
HeartRateChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/HeartRateChannel.java | /*
* HeartRateChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class HeartRateChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public HeartRateChannel()
{
_name = "MSBand_HeartRate";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.HeartRate, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = (float)_listener.getHeartRate();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "HeartRate";
}
}
| 3,016 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BandListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/BandListener.java | /*
* BandListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import com.microsoft.band.BandConnectionCallback;
import com.microsoft.band.ConnectionState;
import com.microsoft.band.sensors.BandAccelerometerEvent;
import com.microsoft.band.sensors.BandAccelerometerEventListener;
import com.microsoft.band.sensors.BandAltimeterEvent;
import com.microsoft.band.sensors.BandAltimeterEventListener;
import com.microsoft.band.sensors.BandAmbientLightEvent;
import com.microsoft.band.sensors.BandAmbientLightEventListener;
import com.microsoft.band.sensors.BandBarometerEvent;
import com.microsoft.band.sensors.BandBarometerEventListener;
import com.microsoft.band.sensors.BandCaloriesEvent;
import com.microsoft.band.sensors.BandCaloriesEventListener;
import com.microsoft.band.sensors.BandDistanceEvent;
import com.microsoft.band.sensors.BandDistanceEventListener;
import com.microsoft.band.sensors.BandGsrEvent;
import com.microsoft.band.sensors.BandGsrEventListener;
import com.microsoft.band.sensors.BandGyroscopeEvent;
import com.microsoft.band.sensors.BandGyroscopeEventListener;
import com.microsoft.band.sensors.BandHeartRateEvent;
import com.microsoft.band.sensors.BandHeartRateEventListener;
import com.microsoft.band.sensors.BandPedometerEvent;
import com.microsoft.band.sensors.BandPedometerEventListener;
import com.microsoft.band.sensors.BandRRIntervalEvent;
import com.microsoft.band.sensors.BandRRIntervalEventListener;
import com.microsoft.band.sensors.BandSkinTemperatureEvent;
import com.microsoft.band.sensors.BandSkinTemperatureEventListener;
import com.microsoft.band.sensors.MotionType;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class BandListener implements BandGsrEventListener, BandSkinTemperatureEventListener, BandHeartRateEventListener, BandAccelerometerEventListener, BandGyroscopeEventListener, BandAmbientLightEventListener, BandBarometerEventListener, BandCaloriesEventListener, BandDistanceEventListener, BandPedometerEventListener, BandRRIntervalEventListener, BandAltimeterEventListener, BandConnectionCallback
{
private final int TIMEOUT = 10000; //in ms
private int gsr; // Resistance in ohm
private float skinTemperature;
private int heartRate;
private float accelerationX;
private float accelerationY;
private float accelerationZ;
private float gyrVelocityX;
private float gyrVelocityY;
private float gyrVelocityZ;
private float gyrAccelerationX;
private float gyrAccelerationY;
private float gyrAccelerationZ;
private int brightness;
private double airPressure;
private double temperature;
private long calories;
private long distance;
private float speed;
private float pace;
private long steps;
private int motionType;
private double interBeatInterval; // time between two heart beats
private long flightsAscended;
private long flightsDescended;
private long steppingGain;
private long steppingLoss;
private long stepsAscended;
private long stepsDescended;
private long altimeterGain;
private long altimeterLoss;
private long lastDataTimestamp = 0;
private boolean connected;
public BandListener()
{
reset();
}
public void reset()
{
gsr = 0;
skinTemperature = 0;
heartRate = 0;
accelerationX = 0;
accelerationY = 0;
accelerationZ = 0;
gyrVelocityX = 0;
gyrVelocityY = 0;
gyrVelocityZ = 0;
gyrAccelerationX = 0;
gyrAccelerationY = 0;
gyrAccelerationZ = 0;
brightness = 0;
airPressure = 0;
temperature = 0;
calories = 0;
distance = 0;
speed = 0;
pace = 0;
steps = 0;
interBeatInterval = 0;
flightsAscended = 0;
flightsDescended = 0;
motionType = MotionType.UNKNOWN.ordinal();
lastDataTimestamp = 0;
connected = false;
}
@Override
public void onStateChanged(ConnectionState connectionState)
{
connected = (connectionState == ConnectionState.CONNECTED);
Log.i("MSBand connection status: " + connectionState.toString());
}
@Override
public void onBandGsrChanged(BandGsrEvent bandGsrEvent)
{
dataReceived();
gsr = bandGsrEvent.getResistance();
}
@Override
public void onBandSkinTemperatureChanged(BandSkinTemperatureEvent bandSkinTemperatureEvent)
{
dataReceived();
skinTemperature = bandSkinTemperatureEvent.getTemperature();
}
@Override
public void onBandHeartRateChanged(BandHeartRateEvent bandHeartRateEvent)
{
dataReceived();
heartRate = bandHeartRateEvent.getHeartRate();
}
@Override
public void onBandAccelerometerChanged(BandAccelerometerEvent bandAccelerometerEvent)
{
dataReceived();
accelerationX = bandAccelerometerEvent.getAccelerationX();
accelerationY = bandAccelerometerEvent.getAccelerationY();
accelerationZ = bandAccelerometerEvent.getAccelerationZ();
}
@Override
public void onBandGyroscopeChanged(BandGyroscopeEvent bandGyroscopeEvent)
{
dataReceived();
gyrVelocityX = bandGyroscopeEvent.getAngularVelocityX();
gyrVelocityY = bandGyroscopeEvent.getAngularVelocityY();
gyrVelocityZ = bandGyroscopeEvent.getAngularVelocityZ();
gyrAccelerationX = bandGyroscopeEvent.getAccelerationX();
gyrAccelerationY = bandGyroscopeEvent.getAccelerationY();
gyrAccelerationZ = bandGyroscopeEvent.getAccelerationZ();
}
@Override
public void onBandAmbientLightChanged(BandAmbientLightEvent bandAmbientLightEvent)
{
dataReceived();
brightness = bandAmbientLightEvent.getBrightness();
}
@Override
public void onBandBarometerChanged(BandBarometerEvent bandBarometerEvent)
{
dataReceived();
airPressure = bandBarometerEvent.getAirPressure();
temperature = bandBarometerEvent.getTemperature();
}
@Override
public void onBandCaloriesChanged(BandCaloriesEvent bandCaloriesEvent)
{
dataReceived();
calories = bandCaloriesEvent.getCalories();
}
@Override
public void onBandDistanceChanged(BandDistanceEvent bandDistanceEvent)
{
dataReceived();
distance = bandDistanceEvent.getTotalDistance();
speed = bandDistanceEvent.getSpeed();
pace = bandDistanceEvent.getPace();
motionType = bandDistanceEvent.getMotionType().ordinal();
}
@Override
public void onBandPedometerChanged(BandPedometerEvent bandPedometerEvent)
{
dataReceived();
steps = bandPedometerEvent.getTotalSteps();
}
@Override
public void onBandRRIntervalChanged(BandRRIntervalEvent bandRRIntervalEvent)
{
dataReceived();
interBeatInterval = bandRRIntervalEvent.getInterval();
}
@Override
public void onBandAltimeterChanged(BandAltimeterEvent bandAltimeterEvent)
{
dataReceived();
flightsAscended = bandAltimeterEvent.getFlightsAscended();
flightsDescended = bandAltimeterEvent.getFlightsDescended();
steppingGain = bandAltimeterEvent.getSteppingGain();
steppingLoss = bandAltimeterEvent.getSteppingLoss();
stepsAscended = bandAltimeterEvent.getStepsAscended();
stepsDescended = bandAltimeterEvent.getStepsDescended();
altimeterGain = bandAltimeterEvent.getTotalGain();
altimeterLoss = bandAltimeterEvent.getTotalLoss();
}
public int getGsr()
{
return gsr;
}
public float getSkinTemperature()
{
return skinTemperature;
}
public int getHeartRate()
{
return heartRate;
}
public float getAccelerationX()
{
return accelerationX;
}
public float getAccelerationY()
{
return accelerationY;
}
public float getAccelerationZ()
{
return accelerationZ;
}
public float getAngularVelocityX()
{
return gyrVelocityX;
}
public float getAngularVelocityY()
{
return gyrVelocityY;
}
public float getAngularVelocityZ()
{
return gyrVelocityZ;
}
public float getAngularAccelerationX()
{
return gyrAccelerationX;
}
public float getAngularAccelerationY()
{
return gyrAccelerationY;
}
public float getAngularAccelerationZ()
{
return gyrAccelerationZ;
}
public int getBrightness()
{
return brightness;
}
public double getAirPressure()
{
return airPressure;
}
public double getTemperature()
{
return temperature;
}
public long getCalories()
{
return calories;
}
public long getDistance()
{
return distance;
}
public float getSpeed()
{
return speed;
}
public float getPace()
{
return pace;
}
public int getMotionType()
{
return motionType;
}
public long getSteps()
{
return steps;
}
public double getInterBeatInterval()
{
return interBeatInterval;
}
public long getFlightsAscended()
{
return flightsAscended;
}
public long getFlightsDescended()
{
return flightsDescended;
}
public long getSteppingGain()
{
return steppingGain;
}
public long getSteppingLoss()
{
return steppingLoss;
}
public long getStepsAscended()
{
return stepsAscended;
}
public long getStepsDescended()
{
return stepsDescended;
}
public long getAltimeterGain()
{
return altimeterGain;
}
public long getAltimeterLoss()
{
return altimeterLoss;
}
private synchronized void dataReceived()
{
lastDataTimestamp = System.currentTimeMillis();
}
public boolean isConnected()
{
return (connected && System.currentTimeMillis() - lastDataTimestamp < TIMEOUT);
}
public boolean hasReceivedData()
{
return lastDataTimestamp != 0;
}
}
| 10,353 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MSBand.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/MSBand.java | /*
* MSBand.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import android.content.SharedPreferences;
import android.os.SystemClock;
import com.microsoft.band.BandClient;
import com.microsoft.band.BandClientManager;
import com.microsoft.band.BandException;
import com.microsoft.band.BandInfo;
import com.microsoft.band.ConnectionState;
import com.microsoft.band.InvalidBandVersionException;
import com.microsoft.band.sensors.GsrSampleRate;
import com.microsoft.band.sensors.SampleRate;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class MSBand extends Sensor
{
protected BandClient client;
protected BandListener listener;
protected enum Channel
{
HeartRate,
RRInterval,
GSR,
SkinTemperature,
Acceleration,
Gyroscope,
AmbientLight,
Barometer,
Calories,
Distance,
Pedometer,
Altimeter
}
private class ChannelInfo {
public boolean active = false;
public int srMode = SampleRate.MS16.ordinal();
}
protected ChannelInfo channels[] = new ChannelInfo[Channel.values().length];
public void configureChannel(Channel ch, boolean active, int srMode)
{
channels[ch.ordinal()].active = active;
channels[ch.ordinal()].srMode = srMode;
}
public MSBand()
{
_name = "MSBand";
for (int i = 0; i < channels.length; i++) {
channels[i] = new ChannelInfo();
}
listener = new BandListener();
}
@Override
protected boolean connect() throws SSJFatalException
{
boolean connected = false;
disconnect(); //clean up old connection
listener.reset();
Log.i("connecting to ms band ...");
BandInfo[] devices = BandClientManager.getInstance().getPairedBands();
if (devices.length > 0)
{
client = BandClientManager.getInstance().create(SSJApplication.getAppContext(), devices[0]);
client.registerConnectionCallback(listener);
try
{
if (ConnectionState.CONNECTED == client.connect().await())
{
SharedPreferences pref = SSJApplication.getAppContext().getSharedPreferences("p7", 0);
pref.edit().putInt("c3", 1).commit();
// Register listeners
if(channels[Channel.HeartRate.ordinal()].active) client.getSensorManager().registerHeartRateEventListener(listener);
if(channels[Channel.RRInterval.ordinal()].active) client.getSensorManager().registerRRIntervalEventListener(listener);
if(channels[Channel.GSR.ordinal()].active) client.getSensorManager().registerGsrEventListener(listener, GsrSampleRate.values()[channels[Channel.GSR.ordinal()].srMode]);
if(channels[Channel.SkinTemperature.ordinal()].active) client.getSensorManager().registerSkinTemperatureEventListener(listener);
if(channels[Channel.Acceleration.ordinal()].active) client.getSensorManager().registerAccelerometerEventListener(listener, SampleRate.values()[channels[Channel.Acceleration.ordinal()].srMode]);
if(channels[Channel.Gyroscope.ordinal()].active) client.getSensorManager().registerGyroscopeEventListener(listener, SampleRate.values()[channels[Channel.Gyroscope.ordinal()].srMode]);
if(channels[Channel.AmbientLight.ordinal()].active) client.getSensorManager().registerAmbientLightEventListener(listener);
if(channels[Channel.Barometer.ordinal()].active) client.getSensorManager().registerBarometerEventListener(listener);
if(channels[Channel.Calories.ordinal()].active) client.getSensorManager().registerCaloriesEventListener(listener);
if(channels[Channel.Distance.ordinal()].active) client.getSensorManager().registerDistanceEventListener(listener);
if(channels[Channel.Pedometer.ordinal()].active) client.getSensorManager().registerPedometerEventListener(listener);
if(channels[Channel.Altimeter.ordinal()].active) client.getSensorManager().registerAltimeterEventListener(listener);
// Wait for values
long time = SystemClock.elapsedRealtime();
while (!_terminate && !listener.hasReceivedData() && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException e)
{
}
}
if (listener.hasReceivedData())
{
connected = true;
}
else
{
Log.e("Unable to connect to ms band");
}
}
}
catch (InterruptedException | BandException e)
{
throw new SSJFatalException("Error while connecting to ms band", e);
}
catch (InvalidBandVersionException e)
{
throw new SSJFatalException("Old ms band version not supported", e);
}
}
return connected;
}
protected boolean checkConnection()
{
return listener.isConnected();
}
@Override
protected void disconnect() throws SSJFatalException
{
Log.d("Disconnecting from MS Band");
if (client != null)
{
try
{
client.getSensorManager().unregisterAllListeners();
client.disconnect().await(1000, TimeUnit.MILLISECONDS);
}
catch (InterruptedException | TimeoutException | BandException e)
{
Log.e("Error while disconnecting from ms band", e);
}
}
client = null;
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 6,673 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BarometerChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/BarometerChannel.java | /*
* BarometerChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class BarometerChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public BarometerChannel()
{
_name = "MSBand_Barometer";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.Barometer, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
double[] out = stream_out.ptrD();
out[0] = _listener.getAirPressure();
out[1] = _listener.getTemperature();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 2;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.DOUBLE;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AirPressure";
stream_out.desc[1] = "Temperature";
}
}
| 3,092 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SkinTempChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/msband/SkinTempChannel.java | /*
* SkinTempChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.msband;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class SkinTempChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 1, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BandListener _listener;
public SkinTempChannel()
{
_name = "MSBand_SkinTemp";
}
@Override
public void init() throws SSJException
{
((MSBand)_sensor).configureChannel(MSBand.Channel.SkinTemperature, true, 0);
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((MSBand) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
out[0] = _listener.getSkinTemperature();
return true;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "SkinTemperature";
}
}
| 3,023 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PulseChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/PulseChannel.java | /*
* PulseChannel.java
* Copyright (c) 2020
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.LimitedSizeQueue;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import info.plux.pluxapi.bitalino.BITalinoFrame;
/**
* Created by Michael Dietz on 07.01.2020.
*/
public class PulseChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("Channel", 0, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> beatThreshold = new Option<>("Beat threshold", 550, Integer.class, "Signal threshold for heart beat");
public final Option<Boolean> outputRaw = new Option<>("Output Raw", true, Boolean.class, "Output raw signal value");
public final Option<Boolean> outputBpm = new Option<>("Output BPM", false, Boolean.class, "Output calculated bpm value");
public final Option<Boolean> outputIbi = new Option<>("Output IBI", false, Boolean.class, "Output calculated ibi value");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
PulseListener listener;
public PulseChannel()
{
_name = "Bitalino_PulseChannel";
this.listener = new PulseListener();
}
@Override
protected void init() throws SSJException
{
Bitalino sensor = ((Bitalino)_sensor);
sensor.addChannel(options.channel.get());
sensor.listener = this.listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
int dim = 0;
if (options.outputRaw.get())
{
out[dim++] = listener.rawSignal;
}
if (options.outputBpm.get())
{
out[dim++] = listener.bpm;
}
if (options.outputIbi.get())
{
out[dim] = listener.ibi;
}
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
int dim = 0;
if (options.outputRaw.get())
{
dim += 1;
}
if (options.outputBpm.get())
{
dim += 1;
}
if (options.outputIbi.get())
{
dim += 1;
}
return dim;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
int dim = 0;
if (options.outputRaw.get())
{
stream_out.desc[dim++] = "raw pulse signal";
}
if (options.outputBpm.get())
{
stream_out.desc[dim++] = "bpm";
}
if (options.outputIbi.get())
{
stream_out.desc[dim] = "ibi";
}
}
class PulseListener extends BitalinoListener
{
private static final int QUEUE_SIZE = 10;
private long lastDataTime;
private long lastBeatTime;
private int max;
private int min;
private int amplitude;
private int threshold;
private boolean isPulse;
private boolean firstBeat;
private boolean secondBeat;
private LimitedSizeQueue<Long> lastIbis;
int rawSignal;
long ibi;
float avgIbi;
float bpm;
public PulseListener()
{
lastIbis = new LimitedSizeQueue<>(QUEUE_SIZE);
reset();
}
public void reset()
{
super.reset();
lastDataTime = 0;
lastBeatTime = 0;
// 750ms per beat = 80 Beats Per Minute (BPM)
ibi = 750;
avgIbi = 0;
rawSignal = 0;
// Max at 1/2 the input range of 0..1023
max = 512;
// Min at 1/2 the input range
min = 512;
threshold = options.beatThreshold.get();
// Beat amplitude 1/10 of input range.
amplitude = 100;
bpm = 0;
isPulse = false;
firstBeat = true;
secondBeat = false;
if (lastIbis != null)
{
lastIbis.clear();
}
}
@Override
public void onBITalinoDataAvailable(BITalinoFrame biTalinoFrame)
{
dataReceived();
lastDataTime = System.currentTimeMillis();
rawSignal = biTalinoFrame.getAnalog(options.channel.get());
// Monitor the time since the last beat to avoid noise
long timeSinceLastBeat = lastDataTime - lastBeatTime;
// Find min of the pulse wave and avoid noise by waiting 3/5 of last IBI
if (rawSignal < threshold && timeSinceLastBeat > ibi / 5.0 * 3.0)
{
if (rawSignal < min)
{
min = rawSignal;
}
}
// Find highest point in pulse wave (threshold condition helps avoid noise)
if (rawSignal > threshold && rawSignal > max)
{
max = rawSignal;
}
// Avoid high frequency noise
if (timeSinceLastBeat > 250)
{
// Pulse detected
if (rawSignal > threshold && !isPulse && timeSinceLastBeat > ibi / 5.0 * 3.0)
{
// Set the Pulse flag when we think there is a pulse
isPulse = true;
// Measure time between beats in ms
ibi = lastDataTime - lastBeatTime;
// Keep track of time for next pulse
lastBeatTime = lastDataTime;
// Fill the queue to get a realistic BPM at startup
if (secondBeat)
{
secondBeat = false;
for (int i = 0; i < QUEUE_SIZE; i++)
{
lastIbis.add(ibi);
}
}
// IBI value is unreliable so discard it
if (firstBeat)
{
firstBeat = false;
secondBeat = true;
return;
}
// Add the latest IBI to the rate array
lastIbis.add(ibi);
// Average the last 10 IBI values
avgIbi = 0;
for (int i = 0; i < QUEUE_SIZE; i++)
{
avgIbi += lastIbis.get(i);
}
avgIbi = avgIbi / (float) QUEUE_SIZE;
// Calculate beats per minute
bpm = 60000 / avgIbi;
}
}
// When the values are going down, the beat is over
if (rawSignal < threshold && isPulse)
{
// Reset the Pulse flag
isPulse = false;
// Get amplitude of the pulse wave
amplitude = max - min;
// Set threshold at 50% of amplitude
threshold = (int) (amplitude / 2.0f + min);
// Reset min and max
min = threshold;
max = threshold;
}
// If 2.5 seconds go by without a beat
if (timeSinceLastBeat > 2500)
{
reset();
lastDataTime = System.currentTimeMillis();
lastBeatTime = lastDataTime;
}
}
}
}
| 7,606 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BitalinoListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/BitalinoListener.java | /*
* BitalinoListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import info.plux.pluxapi.bitalino.BITalinoFrame;
import info.plux.pluxapi.bitalino.bth.OnBITalinoDataAvailable;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class BitalinoListener implements OnBITalinoDataAvailable
{
private final int TIMEOUT = 10000; //in ms
BITalinoFrame lastDataFrame = null;
private long lastDataTimestamp = 0;
private int[] analog = new int[6];
private int[] digital = new int[4];
public BitalinoListener()
{
reset();
}
public void reset()
{
lastDataFrame = null;
lastDataTimestamp = 0;
}
public int getAnalogData(int pos)
{
return analog[pos];
}
public int getDigitalData(int pos)
{
return digital[pos];
}
synchronized void dataReceived()
{
lastDataTimestamp = System.currentTimeMillis();
}
public boolean isConnected()
{
return System.currentTimeMillis() - lastDataTimestamp < TIMEOUT;
}
public boolean hasReceivedData()
{
return lastDataTimestamp != 0;
}
@Override
public void onBITalinoDataAvailable(BITalinoFrame biTalinoFrame)
{
synchronized (this)
{
dataReceived();
for (int i = 0; i < analog.length; i++)
analog[i] = biTalinoFrame.getAnalog(i);
for (int i = 0; i < digital.length; i++)
digital[i] = biTalinoFrame.getDigital(i);
}
}
}
| 2,640 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LUXChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/LUXChannel.java | /*
* LUXChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 06.07.2016.
* outputs luminosity in percent
*/
public class LUXChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("channel", 5, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> numBits = new Option<>("numBits", 10, Integer.class, "the first 4 channels are sampled using 10-bit resolution, the last two may be sampled using 6-bit");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BitalinoListener _listener;
public LUXChannel()
{
_name = "Bitalino_LUXChannel";
}
@Override
public void init() throws SSJException
{
((Bitalino)_sensor).addChannel(options.channel.get());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Bitalino) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
float adc = _listener.getAnalogData(options.channel.get());
out[0] = adc / (2 << options.numBits.get() -1);
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "LUX";
}
}
| 3,307 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EDAChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/EDAChannel.java | /*
* EDAChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 06.07.2016.
* outputs EDA value in micro Siemens
*/
public class EDAChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("channel", 2, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> numBits = new Option<>("numBits", 10, Integer.class, "the first 4 channels are sampled using 10-bit resolution, the last two may be sampled using 6-bit");
public final Option<Float> vcc = new Option<>("vcc", 3.3f, Float.class, "voltage at the common collector (default 3.3)");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BitalinoListener _listener;
public EDAChannel()
{
_name = "Bitalino_EDAChannel";
}
@Override
public void init() throws SSJException
{
((Bitalino)_sensor).addChannel(options.channel.get());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Bitalino) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
float adc = _listener.getAnalogData(options.channel.get());
out[0] = (float)(((adc / (2 << options.numBits.get() - 1)) * options.vcc.get() - 0.574) / 0.132);
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "EDA";
}
}
| 3,486 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ECGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/ECGChannel.java | /*
* ECGChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 06.07.2016.
* outputs ECG value in mV
*/
public class ECGChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("channel", 1, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> numBits = new Option<>("numBits", 10, Integer.class, "the first 4 channels are sampled using 10-bit resolution, the last two may be sampled using 6-bit");
public final Option<Float> vcc = new Option<>("vcc", 3.3f, Float.class, "voltage at the common collector (default 3.3)");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BitalinoListener _listener;
public ECGChannel()
{
_name = "Bitalino_ECGChannel";
}
@Override
public void init() throws SSJException
{
((Bitalino)_sensor).addChannel(options.channel.get());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Bitalino) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
float adc = _listener.getAnalogData(options.channel.get());
out[0] = (float)(((adc / (2 << options.numBits.get() -1) - 0.5) * options.vcc.get()) / 1.1);
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "ECG";
}
}
| 3,471 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GenericChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/GenericChannel.java | /*
* GenericChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 06.07.2016.
* Outputs data from any channel of the BITalino board.
* No data processing is performed.
*/
public class GenericChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("channel", 5, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> channelType = new Option<>("channelType", 0, Integer.class, "analogue (0) or digital (1)");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BitalinoListener _listener;
public GenericChannel()
{
_name = "Bitalino_Channel";
}
@Override
public void init() throws SSJException
{
((Bitalino)_sensor).addChannel(options.channel.get());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Bitalino) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
int[] out = stream_out.ptrI();
if (options.channelType.get() == 0)
{
out[0] = _listener.getAnalogData(options.channel.get());
}
else
{
out[0] = _listener.getDigitalData(options.channel.get());
}
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "Ch" + options.channel.get();
}
}
| 3,401 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EMGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/EMGChannel.java | /*
* EMGChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 06.07.2016.
* outputs EMG value in mV
*/
public class EMGChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel = new Option<>("channel", 0, Integer.class, "channel id (between 0 and 5)");
public final Option<Integer> numBits = new Option<>("numBits", 10, Integer.class, "the first 4 channels are sampled using 10-bit resolution, the last two may be sampled using 6-bit");
public final Option<Float> vcc = new Option<>("vcc", 3.3f, Float.class, "voltage at the common collector (default 3.3)");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected BitalinoListener _listener;
public EMGChannel()
{
_name = "Bitalino_EMGChannel";
}
@Override
public void init() throws SSJException
{
((Bitalino)_sensor).addChannel(options.channel.get());
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Bitalino) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!_listener.isConnected())
{
return false;
}
float[] out = stream_out.ptrF();
float adc = _listener.getAnalogData(options.channel.get());
out[0] = (float)((((adc / (2 << options.numBits.get() -1)) - 0.5) * options.vcc.get()) / 1.009);
return true;
}
@Override
protected double getSampleRate()
{
return ((Bitalino)_sensor).options.sr.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "EMG";
}
}
| 3,475 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Bitalino.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/bitalino/Bitalino.java | /*
* Bitalino.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.bitalino;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.SystemClock;
import java.util.LinkedList;
import java.util.Set;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import info.plux.pluxapi.Communication;
import info.plux.pluxapi.bitalino.BITalinoCommunication;
import info.plux.pluxapi.bitalino.BITalinoCommunicationFactory;
import info.plux.pluxapi.bitalino.BITalinoException;
/**
* Created by Michael Dietz on 06.07.2016.
*/
public class Bitalino extends Sensor
{
public class Options extends OptionList
{
public final Option<String> name = new Option<>("name", null, String.class, "device name, e.g. BITalino-47-08");
public final Option<String> address = new Option<>("address", null, String.class, "mac address of device, only used if name is left empty");
public final Option<Communication> connectionType = new Option<>("connectionType", Communication.BTH, Communication.class, "type of connection");
public final Option<Integer> sr = new Option<>("sr", 10, Integer.class, "sample rate, supported values: 1, 10, 100, 1000");
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected BITalinoCommunication client;
protected BitalinoListener listener;
protected LinkedList<Integer> channels;
void addChannel(Integer ch)
{
channels.add(ch);
}
void removeChannel(Integer ch)
{
channels.remove(ch);
}
public Bitalino()
{
_name = "Bitalino";
channels = new LinkedList<>();
listener = new BitalinoListener();
}
@Override
protected boolean connect() throws SSJFatalException
{
boolean connected = false;
disconnect(); //clean up old connection
listener.reset();
Log.i("connecting to bitalino ...");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
String address = null;
if(options.address.get() != null && !options.address.get().equals(""))
{
if (!BluetoothAdapter.checkBluetoothAddress(options.address.get())) {
throw new SSJFatalException("invalid MAC address: " + options.address.get());
}
address = options.address.get();
}
else if(options.name.get() != null && !options.name.get().equals(""))
{
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0)
{
// Loop through paired devices
for (BluetoothDevice d : pairedDevices)
{
if (d.getName().equalsIgnoreCase(options.name.get()))
{
address = d.getAddress();
}
}
}
}
if (address != null)
{
try
{
client = new BITalinoCommunicationFactory().getCommunication(options.connectionType.get(), SSJApplication.getAppContext(), listener);
connected = client.connect(address);
Log.i("waiting for connection ...");
//wait for connection
long time = SystemClock.elapsedRealtime();
while (!_terminate && !listener.hasReceivedData() && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {}
}
int[] analogue_channels = new int[channels.size()];
int i = 0;
for (Integer ch : channels)
{
analogue_channels[i++] = ch;
}
int sr = options.sr.get();
if (sr > 100)
{
sr = 1000;
}
else if (sr > 10)
{
sr = 100;
}
else if (sr > 1)
{
sr = 10;
}
connected = client.start(analogue_channels, sr);
Log.i("connected to bitalino " + address);
}
catch (BITalinoException e)
{
Log.e("Error connecting to device", e);
}
}
return connected;
}
protected boolean checkConnection()
{
return listener.isConnected();
}
@Override
protected void disconnect() throws SSJFatalException
{
Log.d("Disconnecting from Bitalino");
if (client != null)
{
try
{
client.stop();
try { Thread.sleep(100); }
catch (InterruptedException e) {}
client.disconnect();
}
catch (BITalinoException e)
{
Log.e("Error while disconnecting from device", e);
}
}
client = null;
}
@Override
public void clear()
{
channels.clear();
super.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 5,835 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
RRTimeFeatures.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/biosig/RRTimeFeatures.java | /*
* RRTimeFeatures.java
* Copyright (c) 2023
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.biosig;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Cons;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 14.02.2023.
* Calculates QRS HRV time domain features
*
* Code adapted from SSI's QRSHRVtime.cpp
*/
public class RRTimeFeatures extends Transformer
{
public class Options extends OptionList
{
public final Option<Boolean> calculateRR = new Option<>("calculateRR", false, Boolean.class, "Whether RR intervals need to be calculated first");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
boolean firstRR;
int samplesSinceLastRR;
double timePerSample;
boolean calibrated;
List<Float> rrIntervals;
public RRTimeFeatures()
{
_name = "RRTimeFeatures";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
timePerSample = 1000.0 / stream_in[0].sr;
firstRR = true;
samplesSinceLastRR = 0;
calibrated = false;
rrIntervals = new ArrayList<>();
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int sampleNumber = stream_in[0].num;
float[] ptrIn = stream_in[0].ptrF();
float[] ptrOut = stream_out.ptrF();
int nRRs = 0;
float rrDiff = 0.0f;
float rr = 0.0f;
float sumRR = 0.0f;
// Mean RR interval in ms
float mRR = 0.0f;
// Mean heart rate in bpm
float mHR = 0.0f;
// Standard deviation of RR-Intervals in ms
float SDRR = 0.0f;
// Standard deviation of heart rate in bpm
float SDHR = 0.0f;
// Coefficient of variance of RR's
float CVRR = 0.0f;
// Root mean square successive difference in ms
float RMSSD = 0.0f;
// Number of pairs of RR's differing by >20ms in percent
float pRR20 = 0.0f;
// Number of pairs of RR's differing by >50ms in percent
float pRR50 = 0.0f;
if (options.calculateRR.get())
{
for (int i = 0; i < sampleNumber; i++)
{
if (ptrIn[i] == 1)
{
if (firstRR)
{
firstRR = false;
}
else
{
rr = (float) (samplesSinceLastRR * timePerSample);
rrIntervals.add(rr);
}
samplesSinceLastRR = 0;
}
else
{
samplesSinceLastRR++;
}
}
}
else
{
for (int i = 0; i < sampleNumber; i++)
{
if (ptrIn[i] > 0.0)
{
rrIntervals.add(ptrIn[i]);
}
}
}
nRRs = rrIntervals.size();
// Check if there are rr intervals
if (nRRs > 1)
{
// Calculate features
for (int i = 0; i < nRRs; i++)
{
sumRR += rrIntervals.get(i);
mHR += (60000.0f / rrIntervals.get(i));
}
mRR = sumRR / nRRs;
mHR = mHR / nRRs;
for (int i = 0; i < nRRs; i++)
{
SDRR += Math.pow(rrIntervals.get(i) - mRR, 2);
SDHR += Math.pow((60000.0f / rrIntervals.get(i)) - mHR, 2);
}
SDRR = (float) Math.sqrt(SDRR / (nRRs - 1));
SDHR = (float) Math.sqrt(SDHR / (nRRs - 1));
CVRR = (SDRR * 100.0f) / mRR;
for (int i = 0; i < nRRs - 1; i++)
{
rrDiff = rrIntervals.get(i + 1) - rrIntervals.get(i);
RMSSD += Math.pow(rrDiff, 2);
if (Math.abs(rrDiff) > 20.0f)
{
pRR20++;
if (Math.abs(rrDiff) > 50.0f)
{
pRR50++;
}
}
}
RMSSD = (float) Math.sqrt(RMSSD / (nRRs - 1));
pRR20 = (pRR20 * 100.0f) / (nRRs - 1);
pRR50 = (pRR50 * 100.0f) / (nRRs - 1);
rrIntervals.clear();
}
int ptrIndex = 0;
ptrOut[ptrIndex++] = mRR;
ptrOut[ptrIndex++] = mHR;
ptrOut[ptrIndex++] = SDRR;
ptrOut[ptrIndex++] = SDHR;
ptrOut[ptrIndex++] = CVRR;
ptrOut[ptrIndex++] = RMSSD;
ptrOut[ptrIndex++] = pRR20;
ptrOut[ptrIndex] = pRR50;
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 8;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[]{"mRR", "mHR", "SDRR", "SDHR", "CVRR", "RMSSD", "pRR20", "pRR50"};
}
}
| 5,635 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
HRVSpectral.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/biosig/HRVSpectral.java | /*
* HRVSpectral.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.biosig;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 07.04.2017.
* computes common spectral features for heart rate
*
* code adapted from SSI's QRSHRVspectral.cpp
*/
public class HRVSpectral extends Transformer
{
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (stream_in[0].num != 1)
{
Log.e("ambiguous call: more than one sample gathered from spectogram");
}
float ptr_in[] = stream_in[0].ptrF();
float ptr_out[] = stream_out.ptrF();
float VLF = 0.0f;
float LF = 0.0f;
float HF = 0.0f;
float nVLF = 0.0f;
float nLF = 0.0f;
float nHF = 0.0f;
float dLFHF = 0.0f;
float SMI = 0.0f;
float VMI = 0.0f;
float SVI = 0.0f;
VLF = ptr_in[0];
LF = ptr_in[1];
HF = ptr_in[2];
nVLF = (VLF * 100.0f) / (VLF + LF + HF);
nLF = (LF * 100.0f) / (VLF + LF + HF);
nHF = (HF * 100.0f) / (VLF + LF + HF);
dLFHF = Math.abs(nLF - nHF);
SMI = LF / (LF + HF);
VMI = HF / (LF + HF);
SVI = ( Math.abs(HF) < 0.0001) ? 0 : LF / HF;
int iter = 0;
ptr_out[iter++] = VLF;
ptr_out[iter++] = LF;
ptr_out[iter++] = HF;
ptr_out[iter++] = nVLF;
ptr_out[iter++] = nLF;
ptr_out[iter++] = nHF;
ptr_out[iter++] = dLFHF;
ptr_out[iter++] = SMI;
ptr_out[iter++] = VMI;
ptr_out[iter] = SVI;
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
if(stream_in[0].dim != 3)
Log.e("dimension > 1 not supported");
return 10;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return Util.sizeOf(Cons.Type.FLOAT);
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(stream_in[0].type != Cons.Type.FLOAT)
Log.e("input stream type not supported");
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return 1;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[]{"VLF", "LF", "HF", "nVLF", "nLF", "nHF", "dLFHF", "SMI", "VMI", "SVI"};
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 3,646 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GSRArousalEstimation.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/biosig/GSRArousalEstimation.java | /*
* GSRArousalEstimation.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.biosig;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.signal.Butfilt;
import hcm.ssj.signal.MvgAvgVar;
import hcm.ssj.signal.MvgNorm;
/**
* Created by Michael Dietz on 06.08.2015.
*/
public class GSRArousalEstimation extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Double> windowSizeShortTerm = new Option<>("windowSizeShortTerm", 5., Double.class, "Size of short time window in seconds");
public final Option<Double> windowSizeLongTerm = new Option<>("windowSizeLongTerm", 60., Double.class, "Size of long time window in seconds");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
MvgNorm _detrend;
MvgNorm _detrendNormMinMax;
MvgAvgVar _mvgAvgLongTerm;
MvgAvgVar _mvgAvgShortTerm;
MvgAvgVar _mvgAvgCombination;
Butfilt _butfiltLongTerm;
GSRArousalCombination _combination;
Stream _detrendStream;
Stream _detrendNormMinMaxStream;
Stream _mvgAvgLongTermStream;
Stream _butfiltLongTermStream;
Stream _mvgAvgShortTermStream;
Stream _combinationStream;
Stream _mvgAvgCombinationStream;
Stream[] _detrendStreamArray;
Stream[] _detrendNormMinMaxStreamArray;
Stream[] _mvgAvgLongTermStreamArray;
Stream[] _mvgAvgShortTermStreamArray;
Stream[] _combinationStreamArray;
Stream[] _combinationInput;
public GSRArousalEstimation()
{
_name = "GSRArousalEstimation";
}
@Override
public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
// Detrend: remove y offset
_detrend = new MvgNorm();
_detrend.options.norm.set(MvgNorm.Norm.SUB_MIN);
_detrend.options.method.set(MvgNorm.Method.SLIDING);
_detrend.options.windowSize.set(60.f);
_detrendStream = Stream.create(_detrend.getSampleNumber(stream_in[0].num), _detrend.getSampleDimension(stream_in), Util.calcSampleRate(_detrend, stream_in[0]), _detrend.getSampleType(stream_in));
_detrendStreamArray = new Stream[]{_detrendStream};
_detrend.enter(stream_in, _detrendStream);
// Detrend min max: convert to 0..1 range
_detrendNormMinMax = new MvgNorm();
_detrendNormMinMax.options.norm.set(MvgNorm.Norm.MIN_MAX);
_detrendNormMinMax.options.rangeA.set(0.f);
_detrendNormMinMax.options.rangeB.set(1.f);
_detrendNormMinMax.options.method.set(MvgNorm.Method.SLIDING);
_detrendNormMinMax.options.windowSize.set(60.f);
_detrendNormMinMaxStream = Stream.create(_detrendNormMinMax.getSampleNumber(_detrendStream.num), _detrendNormMinMax.getSampleDimension(_detrendStreamArray), Util.calcSampleRate(_detrendNormMinMax, _detrendStream), _detrendNormMinMax.getSampleType(_detrendStreamArray));
_detrendNormMinMaxStreamArray = new Stream[]{_detrendNormMinMaxStream};
_detrendNormMinMax.enter(_detrendStreamArray, _detrendNormMinMaxStream);
// Moving average long term
_mvgAvgLongTerm = new MvgAvgVar();
_mvgAvgLongTerm.options.format.set(MvgAvgVar.Format.AVERAGE);
_mvgAvgLongTerm.options.method.set(MvgAvgVar.Method.SLIDING);
_mvgAvgLongTerm.options.window.set(90.);
_mvgAvgLongTermStream = Stream.create(_mvgAvgLongTerm.getSampleNumber(_detrendNormMinMaxStream.num), _mvgAvgLongTerm.getSampleDimension(_detrendNormMinMaxStreamArray), Util.calcSampleRate(_mvgAvgLongTerm, _detrendNormMinMaxStream), _mvgAvgLongTerm.getSampleType(_detrendNormMinMaxStreamArray));
_mvgAvgLongTermStreamArray = new Stream[]{_mvgAvgLongTermStream};
_mvgAvgLongTerm.enter(_detrendNormMinMaxStreamArray, _mvgAvgLongTermStream);
_butfiltLongTerm = new Butfilt();
_butfiltLongTerm.options.zero.set(true);
_butfiltLongTerm.options.norm.set(false);
_butfiltLongTerm.options.low.set(0.1);
_butfiltLongTerm.options.order.set(3);
_butfiltLongTerm.options.type.set(Butfilt.Type.LOW);
_butfiltLongTermStream = Stream.create(_butfiltLongTerm.getSampleNumber(_mvgAvgLongTermStream.num), _butfiltLongTerm.getSampleDimension(_mvgAvgLongTermStreamArray), Util.calcSampleRate(_butfiltLongTerm, _mvgAvgLongTermStream), _butfiltLongTerm.getSampleType(_mvgAvgLongTermStreamArray));
_butfiltLongTerm.enter(_mvgAvgLongTermStreamArray, _butfiltLongTermStream);
// Moving average short term
_mvgAvgShortTerm = new MvgAvgVar();
_mvgAvgShortTerm.options.format.set(MvgAvgVar.Format.AVERAGE);
_mvgAvgShortTerm.options.method.set(MvgAvgVar.Method.SLIDING);
_mvgAvgShortTerm.options.window.set(5.);
_mvgAvgShortTermStream = Stream.create(_mvgAvgShortTerm.getSampleNumber(_detrendNormMinMaxStream.num), _mvgAvgShortTerm.getSampleDimension(_detrendNormMinMaxStreamArray), Util.calcSampleRate(_mvgAvgShortTerm, _detrendNormMinMaxStream), _mvgAvgShortTerm.getSampleType(_detrendNormMinMaxStreamArray));
_mvgAvgShortTermStreamArray = new Stream[]{_mvgAvgShortTermStream};
_mvgAvgShortTerm.enter(_detrendNormMinMaxStreamArray, _mvgAvgShortTermStream);
// GSR Arousal Combination
_combination = new GSRArousalCombination();
_combinationStream = Stream.create(_combination.getSampleNumber(_mvgAvgShortTermStream.num), _combination.getSampleDimension(_mvgAvgShortTermStreamArray), Util.calcSampleRate(_combination, _mvgAvgShortTermStream), _combination.getSampleType(_mvgAvgShortTermStreamArray));
_combinationStreamArray = new Stream[]{_combinationStream};
_combinationInput = new Stream[]{_butfiltLongTermStream, _mvgAvgShortTermStream};
_combination.enter(_combinationInput, _combinationStream);
// Moving average combination
_mvgAvgCombination = new MvgAvgVar();
_mvgAvgCombination.options.format.set(MvgAvgVar.Format.AVERAGE);
_mvgAvgCombination.options.method.set(MvgAvgVar.Method.SLIDING);
_mvgAvgCombination.options.window.set(30.);
_mvgAvgCombinationStream = Stream.create(_mvgAvgCombination.getSampleNumber(_combinationStream.num), _mvgAvgCombination.getSampleDimension(_combinationStreamArray), Util.calcSampleRate(_mvgAvgCombination, _combinationStream), _mvgAvgCombination.getSampleType(_combinationStreamArray));
_mvgAvgCombination.enter(_combinationStreamArray, _mvgAvgCombinationStream);
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int n = stream_in[0].num;
double sr = stream_in[0].sr;
// Adjust stream size
_detrendStream.adjust(n);
_detrendNormMinMaxStream.adjust(n);
_mvgAvgLongTermStream.adjust(n);
_butfiltLongTermStream.adjust(n);
_mvgAvgShortTermStream.adjust(n);
_combinationStream.adjust(n);
_mvgAvgCombinationStream.adjust(n);
_detrend.transform(stream_in, _detrendStream);
_detrendNormMinMax.transform(_detrendStreamArray, _detrendNormMinMaxStream);
// Copy stream
Stream detrendNormMinMaxStreamCopy = _detrendNormMinMaxStream.clone();
Stream[] detrendNormMinMaxStreamCopyArray = new Stream[]{detrendNormMinMaxStreamCopy};
_mvgAvgLongTerm.transform(_detrendNormMinMaxStreamArray, _mvgAvgLongTermStream);
_butfiltLongTerm.transform(_mvgAvgLongTermStreamArray, _butfiltLongTermStream);
_mvgAvgShortTerm.transform(detrendNormMinMaxStreamCopyArray, _mvgAvgShortTermStream);
_combination.transform(_combinationInput, _combinationStream);
_mvgAvgCombination.transform(_combinationStreamArray , _mvgAvgCombinationStream);
float[] ptrResult = _mvgAvgCombinationStream.ptrF();
float[] ptrOut = stream_out.ptrF();
for (int nSamp = 0; nSamp < stream_in[0].num; nSamp++)
{
ptrOut[nSamp] = ptrResult[nSamp];
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
}
| 9,672 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GSRArousalCombination.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/biosig/GSRArousalCombination.java | /*
* GSRArousalCombination.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.biosig;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Transformer;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 13.08.2015.
*/
public class GSRArousalCombination extends Transformer
{
public GSRArousalCombination()
{
_name = "GSRArousalCombination";
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
int n = stream_in[0].num;
double sr = stream_in[0].sr;
float[] ptrLongTerm = stream_in[0].ptrF();
float[] ptrShortTerm = stream_in[1].ptrF();
float[] ptrOut = stream_out.ptrF();
for (int nSamp = 0; nSamp < stream_in[0].num; nSamp++)
{
if (ptrLongTerm[nSamp] >= 0.0f && ptrShortTerm[nSamp] > 0.0f)
{
ptrOut[nSamp] = (float) (Math.sqrt(ptrShortTerm[nSamp]) * Math.sqrt(ptrLongTerm[nSamp])) * 1.5f;
if (ptrOut[nSamp] >= 1.0f)
{
ptrOut[nSamp] = 1.0f;
}
if (ptrOut[nSamp] <= 0.0f)
{
ptrOut[nSamp] = 0.0f;
}
}
else
{
ptrOut[nSamp] = 0.0f;
}
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
return 1;
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
return stream_in[0].bytes;
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if (stream_in[0].type != Cons.Type.FLOAT)
{
Log.e("unsupported input type");
}
return Cons.Type.FLOAT;
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return sampleNumber_in;
}
@Override
protected void describeOutput(Stream[] stream_in, Stream stream_out)
{
stream_out.desc = new String[stream_in[0].dim];
System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length);
}
@Override
public OptionList getOptions()
{
return null;
}
}
| 3,230 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Vibrate2Command.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/Vibrate2Command.java | /*
* Vibrate2Command.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import java.util.Arrays;
/**
* Approach to use vibrate2 without having to modify the existing library
* (by using reflection and only call methods necessary)
*/
public class Vibrate2Command extends Command {
private static final byte COMMAND_VIBRATION2 = 0x07; //NEW
private static enum Vibration2 {
COMMAND_TYPE,
PAYLOAD_SIZE,
DURATION,
STRENGTH;
private Vibration2() {
}
}
public Vibrate2Command(Hub hub) {
super(hub);
}
public void vibrate(Myo myo, int duration, byte strength) {
byte[] vibrate2Command = createForVibrate2(duration, strength);
this.writeControlCommand(myo.getMacAddress(), vibrate2Command);
}
/**
* Vibrate pattern, up to 6 times duration/strength
*
* @param myo myo
* @param duration duration
* @param strength strength
*/
public void vibrate(Myo myo, int[] duration, byte[] strength) {
byte[] vibrate2Command = createForVibrate2(duration, strength);
this.writeControlCommand(myo.getMacAddress(), vibrate2Command);
}
public void vibrate(Myo myo,
int duration1, byte strength1,
int duration2, byte strength2,
int duration3, byte strength3,
int duration4, byte strength4,
int duration5, byte strength5,
int duration6, byte strength6) {
byte[] vibrate2Command = createForVibrate2(duration1, strength1, duration2, strength2, duration3, strength3, duration4, strength4, duration5, strength5, duration6, strength6);
this.writeControlCommand(myo.getMacAddress(), vibrate2Command);
}
// #see https://github.com/thalmiclabs/myo-bluetooth/blob/master/myohw.h
public static byte[] createForVibrate2(int duration, byte strength) {
byte[] command = new byte[20]; //COMMAND, PAYLOAD, 6*(Duration (uint16), Strength (uint8))
Arrays.fill(command, (byte) 0);
command[Vibration2.COMMAND_TYPE.ordinal() /* 0 */] = COMMAND_VIBRATION2;
command[Vibration2.PAYLOAD_SIZE.ordinal() /* 1 */] = 18; /* MYOHW_PAYLOAD = 18 */
command[2 /* duration 1/2 */] = (byte) (duration & 0xFF);
command[3 /* duration 2/2 */] = (byte) ((duration >> 8) & 0xFF);
command[4 /* strength */] = strength;
/* rest of the byte-array should be 0 */
return command;
}
// #see https://github.com/thalmiclabs/myo-bluetooth/blob/master/myohw.h
public static byte[] createForVibrate2(int[] duration, byte[] strength) {
byte[] command = new byte[20]; //COMMAND, PAYLOAD, 6*(Duration (uint16), Strength (uint8))
Arrays.fill(command, (byte) 0);
command[Vibration2.COMMAND_TYPE.ordinal() /* 0 */] = COMMAND_VIBRATION2;
command[Vibration2.PAYLOAD_SIZE.ordinal() /* 1 */] = 18; /* MYOHW_PAYLOAD = 18 */
/* maximum of 6 times, but not more often than duration or strength array*/
int iterations = Math.min(6, Math.min(duration.length, strength.length));
for (int i = 0; i < iterations; i++) {
command[3 * i + 2 /* duration 1/2 */] = (byte) (duration[i] & 0xFF);
command[3 * i + 3 /* duration 2/2 */] = (byte) ((duration[i] >> 8) & 0xFF);
command[3 * i + 4 /* strength */] = strength[i];
}
return command;
}
// #see https://github.com/thalmiclabs/myo-bluetooth/blob/master/myohw.h
public static byte[] createForVibrate2(int duration1, byte strength1,
int duration2, byte strength2,
int duration3, byte strength3,
int duration4, byte strength4,
int duration5, byte strength5,
int duration6, byte strength6) {
return createForVibrate2(new int[]{duration1, duration2, duration3, duration4, duration5, duration6}, new byte[]{strength1, strength2, strength3, strength4, strength5, strength6});
}
}
| 5,563 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Myo.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/Myo.java | /*
* Myo.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import com.thalmic.myo.Hub;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 01.04.2015.
*/
public class Myo extends Sensor
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> macAddress = new Option<>("macAddress", "F3:41:FA:27:EB:08", String.class, "");
//when locking is enabled, myo is locked by default
//and gesture events are not triggered while in this state.
//A special gesture is required to "unlock" the device
public final Option<Boolean> locking = new Option<>("locking", false, Boolean.class, "A special gesture is required to \"unlock\" the device");
public final Option<Boolean> imu = new Option<>("imu", true, Boolean.class, "");
public final Option<Configuration.EmgMode> emg = new Option<>("emg", Configuration.EmgMode.FILTERED, Configuration.EmgMode.class, "");
public final Option<Boolean> gestures = new Option<>("gestures", false, Boolean.class, "disabling the gesture classifier will also disable the \"sync\" mechanism");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected Hub hub;
protected com.thalmic.myo.Myo myo;
protected MyoListener listener;
protected boolean myoInitialized;
Configuration config;
public Myo()
{
_name = "Myo";
}
class MyoConnThread implements Runnable
{
public boolean finished = false;
public String errorMsg = "";
public void run()
{
finished = false;
// Check if hub can be initialized
if (!hub.init(SSJApplication.getAppContext()))
{
errorMsg = "Could not initialize the Hub.";
finished = true;
return;
}
else
{
myoInitialized = true;
}
hub.setLockingPolicy(options.locking.get() ? Hub.LockingPolicy.STANDARD : Hub.LockingPolicy.NONE);
// Disable usage data sending
hub.setSendUsageData(false);
// Add listener for callbacks
hub.addListener(listener);
// Connect to myo
if (hub.getConnectedDevices().isEmpty())
{
// If there is a mac address connect to it, otherwise look for myo nearby
if (options.macAddress.get() != null && !options.macAddress.get().isEmpty())
{
Log.i("Connecting to MAC: " + options.macAddress.get());
hub.attachByMacAddress(options.macAddress.get());
}
else
{
//Log.i("Connecting to nearest myo");
//hub.attachToAdjacentMyo(); //buggy, not usable
errorMsg = "Cannot connect, please specify MAC address of Myo.";
}
}
finished = true;
}
}
@Override
public boolean connect() throws SSJFatalException
{
myoInitialized = false;
hub = Hub.getInstance();
listener = new MyoListener();
// Myo hub must be initialized in the main ui thread
Handler handler = new Handler(Looper.getMainLooper());
MyoConnThread connThread = new MyoConnThread();
handler.postDelayed(connThread, 1);
// Wait until myo is connected
long time = SystemClock.elapsedRealtime();
while (hub.getConnectedDevices().isEmpty() && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000 && !_terminate)
{
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {}
}
if(connThread.errorMsg != null && !connThread.errorMsg.isEmpty())
{
throw new SSJFatalException(connThread.errorMsg);
}
if(hub.getConnectedDevices().isEmpty())
{
hub.shutdown();
Log.e("device not found");
return false;
}
myo = hub.getConnectedDevices().get(0);
//configure myo
config = new Configuration(hub, listener, options.emg.get(), options.imu.get(), options.gestures.get());
config.apply(myo.getMacAddress());
myo.unlock(com.thalmic.myo.Myo.UnlockType.HOLD);
Log.i("Myo successfully connected: " + myo.getMacAddress());
return true;
}
@Override
public void disconnect() throws SSJFatalException
{
if(myo != null)
{
myo.lock();
config.undo(myo.getMacAddress());
}
hub.shutdown();
}
}
| 5,711 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AccelerationChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/AccelerationChannel.java | /*
* AccelerationChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 01.04.2015.
*/
public class AccelerationChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected MyoListener _listener;
public AccelerationChannel()
{
_name = "Myo_Acceleration";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Myo)_sensor).listener;
if (stream_out.num != 1)
{
Log.w("unsupported stream format. sample number = " + stream_out.num);
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
out[0] = _listener.accelerationX;
out[1] = _listener.accelerationY;
out[2] = _listener.accelerationZ;
return true;
}
@Override
public void flush(Stream stream_out) throws SSJFatalException
{
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 3;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AccX";
stream_out.desc[1] = "AccY";
stream_out.desc[2] = "AccZ";
}
}
| 3,298 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Command.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/Command.java | /*
* Command.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import com.thalmic.myo.Hub;
import com.thalmic.myo.internal.ble.BleManager;
import java.lang.reflect.Field;
import java.util.UUID;
import hcm.ssj.core.Log;
/**
* ParentClass for executing commands
*/
public class Command {
String _name = "Myo_Cmd";
BleManager mBleManager;
public Command(Hub hub) {
/* try to access mBleManager field which is private by using reflection */
/* this field is required as this is the communication-module */
Field field;
try {
field = Hub.class.getDeclaredField("mBleManager");
field.setAccessible(true);
mBleManager = (BleManager) field.get(hub);
}
catch (NoSuchFieldException e) {Log.w("unable to access BleManager", e);}
catch (IllegalAccessException e) {Log.w("unable to access BleManager", e);}
}
static final UUID CONTROL_SERVICE_UUID = UUID.fromString("d5060001-a904-deb9-4748-2c7f4a124842");
static final UUID COMMAND_CHAR_UUID = UUID.fromString("d5060401-a904-deb9-4748-2c7f4a124842");
void writeControlCommand(String address, byte[] controlCommand) {
UUID serviceUuid = CONTROL_SERVICE_UUID;
UUID charUuid = COMMAND_CHAR_UUID;
this.mBleManager.getBleGatt().writeCharacteristic(address, serviceUuid, charUuid, controlCommand);
}
}
| 2,695 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Configuration.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/Configuration.java | /*
* Configuration.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import hcm.ssj.core.Log;
/**
* Approach to add a ValueListener to the hub-interface
*
* Authors: Daniel Langerenken, Ionut Damian, Michael Dietz
*/
public class Configuration extends Command {
private static final byte EMG_MODE_DISABLED = 0x00; //New
private static final byte EMG_MODE_FILTERED = 0x02;
private static final byte EMG_MODE_RAW = 0x03;
private static final byte IMU_MODE_DISABLED = 0;
private static final byte IMU_MODE_ENABLED = 1;
private static final byte COMMAND_SET_MODE = 0x01;
private static final byte COMMAND_SLEEP_MODE = 0x09;
static final UUID EMG0_DATA_CHAR_UUID = UUID.fromString("d5060105-a904-deb9-4748-2c7f4a124842");
static final UUID EMG1_DATA_CHAR_UUID = UUID.fromString("d5060205-a904-deb9-4748-2c7f4a124842");
static final UUID EMG2_DATA_CHAR_UUID = UUID.fromString("d5060305-a904-deb9-4748-2c7f4a124842");
static final UUID EMG3_DATA_CHAR_UUID = UUID.fromString("d5060405-a904-deb9-4748-2c7f4a124842");
private static final byte CLASSIFIER_MODE_DISABLED = 0;
private static final byte CLASSIFIER_MODE_ENABLED = 1;
private Hub hub;
private MyoListener mListener;
private EmgMode emgMode;
private boolean imuMode;
private boolean gesturesMode;
private SleepMode sleepMode = SleepMode.NEVER_SLEEP;
Object myValueListener;
public Configuration(Hub hub, final MyoListener listener, EmgMode emg, boolean imu, boolean gestures)
{
super(hub);
_name = "Myo_Config";
this.hub = hub;
mListener = listener;
this.emgMode = emg;
this.imuMode = imu;
this.gesturesMode = gestures;
}
public void apply(String macAddress)
{
configureDataAcquisition(macAddress, emgMode, imuMode, gesturesMode);
configureSleepMode(macAddress, sleepMode);
try
{
Method method = null;
for (Method mt : hub.getClass().getDeclaredMethods()) {
if (mt.getName().contains("addGattValueListener")) {
method = mt;
break;
}
}
if (method == null) {
Log.e("Method not found!!");
return;
}
method.setAccessible(true);
Class<?> valueListener = method.getParameterTypes()[0];
myValueListener = Proxy.newProxyInstance(valueListener.getClassLoader(), new Class<?>[]{valueListener}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("onCharacteristicChanged")) {
Myo myo = (Myo) args[0];
UUID uuid = (UUID) args[1];
byte[] data = (byte[]) args[2];
if (EMG0_DATA_CHAR_UUID.equals(uuid) || EMG1_DATA_CHAR_UUID.equals(uuid) || EMG2_DATA_CHAR_UUID.equals(uuid) || EMG3_DATA_CHAR_UUID.equals(uuid)) {
onEMGData(myo, uuid, data);
return 1;
}
}
//because invoke replaces ALL method call ups to this instance, we need to catch ALL possible call ups
//because the listeners are stored in a hashmap, the hashmap calls equals when a new listener is added
else if (method.getName().equals("equals"))
{
return args[0].equals(this);
}
return -1;
}
});
Object o = method.invoke(hub, myValueListener);
} catch (Exception e) {
Log.w("unable to set EMG listener", e);
}
}
public void undo(String macAddress)
{
configureSleepMode(macAddress, SleepMode.NORMAL);
// Get field
Field field = null;
try
{
field = hub.getClass().getDeclaredField("mGattCallback");
// Make it accessible
field.setAccessible(true);
// Obtain the field value from the object instance
Object fieldValue = field.get(hub);
// Get remove method
Method myMethod = null;
for (Method mt : fieldValue.getClass().getDeclaredMethods()) {
if (mt.getName().contains("removeValueListener")) {
myMethod = mt;
break;
}
}
if(myMethod == null)
throw new NoSuchMethodException();
myMethod.setAccessible(true);
// Invoke removeValueListener on instance field mGattCallback
myMethod.invoke(fieldValue, myValueListener);
}
catch (NoSuchFieldException e) { Log.w("unable to undo config", e); }
catch (InvocationTargetException e) { Log.w("unable to undo config", e); }
catch (NoSuchMethodException e) { Log.w("unable to undo config", e); }
catch (IllegalAccessException e) { Log.w("unable to undo config", e); }
}
public void onEMGData(Myo myo, UUID uuid, byte[] data)
{
mListener.onEMGData(myo, uuid, data);
}
public void configureDataAcquisition(String address, EmgMode mode, boolean streamImu, boolean enableClassifier) {
byte[] enableCommand = createForSetMode(mode, streamImu, enableClassifier);
writeControlCommand(address, enableCommand);
}
static byte[] createForSetMode(EmgMode streamEmg, boolean streamImu, boolean enableClassifier) {
byte emgMode = EMG_MODE_DISABLED;
switch (streamEmg) {
case FILTERED: {
emgMode = EMG_MODE_FILTERED;
break;
}
case RAW: {
emgMode = EMG_MODE_RAW;
}
}
byte imuMode = streamImu ? IMU_MODE_ENABLED : IMU_MODE_DISABLED;
byte classifierMode = enableClassifier ? CLASSIFIER_MODE_ENABLED : CLASSIFIER_MODE_DISABLED;
return createForSetMode(emgMode, imuMode, classifierMode);
}
private static byte[] createForSetMode(byte emgMode, byte imuMode, byte classifierMode) {
byte[] controlCommand = new byte[SetModeCmd.values().length];
controlCommand[SetModeCmd.COMMAND_TYPE.ordinal()] = COMMAND_SET_MODE;
controlCommand[SetModeCmd.PAYLOAD_SIZE.ordinal()] = (byte) (controlCommand.length - 2);
controlCommand[SetModeCmd.EMG_MODE.ordinal()] = emgMode;
controlCommand[SetModeCmd.IMU_MODE.ordinal()] = imuMode;
controlCommand[SetModeCmd.CLASSIFIER_MODE.ordinal()] = classifierMode;
return controlCommand;
}
public void configureSleepMode(String address, SleepMode mode) {
byte[] cmd = createSleepMode(mode.id);
writeControlCommand(address, cmd);
}
private static byte[] createSleepMode(byte sleepMode) {
byte[] controlCommand = new byte[SleepModeCmd.values().length];
controlCommand[SleepModeCmd.COMMAND_TYPE.ordinal()] = COMMAND_SLEEP_MODE;
controlCommand[SleepModeCmd.PAYLOAD_SIZE.ordinal()] = (byte) (controlCommand.length - 2);
controlCommand[SleepModeCmd.SLEEP_MODE.ordinal()] = sleepMode;
return controlCommand;
}
private enum SetModeCmd {
COMMAND_TYPE,
PAYLOAD_SIZE,
EMG_MODE,
IMU_MODE,
CLASSIFIER_MODE;
}
public enum EmgMode {
DISABLED,
FILTERED,
RAW;
}
public enum SleepMode {
NORMAL((byte)0), ///< Normal sleep mode; Myo will sleep after a period of inactivity.
NEVER_SLEEP ((byte)1); ///< Never go to sleep.
public final byte id;
SleepMode(byte id) { this.id = id; }
}
public enum SleepModeCmd {
COMMAND_TYPE,
PAYLOAD_SIZE,
SLEEP_MODE;
}
}
| 9,546 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MyoListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/MyoListener.java | /*
* MyoListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import com.thalmic.myo.Arm;
import com.thalmic.myo.DeviceListener;
import com.thalmic.myo.Myo;
import com.thalmic.myo.Pose;
import com.thalmic.myo.Quaternion;
import com.thalmic.myo.Vector3;
import com.thalmic.myo.XDirection;
import java.util.Arrays;
import java.util.UUID;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 01.04.2015.
*/
public class MyoListener implements DeviceListener
{
boolean onArm;
boolean isUnlocked;
float accelerationX;
float accelerationY;
float accelerationZ;
double orientationX;
double orientationY;
double orientationZ;
double orientationW;
int rollW;
int yawW;
int pitchW;
Pose currentPose;
Arm whichArm;
int emg[] = new int[16];
private static final String TAG = "MyoListener";
public MyoListener()
{
reset();
}
public void reset()
{
onArm = false;
whichArm = Arm.UNKNOWN;
currentPose = Pose.UNKNOWN;
accelerationX = 0;
accelerationY = 0;
accelerationZ = 0;
orientationX = 0;
orientationY = 0;
orientationZ = 0;
orientationW = 0;
rollW = 0;
yawW = 0;
pitchW = 0;
Arrays.fill(emg, 0);
}
@Override
public void onAttach(Myo myo, long l)
{
}
@Override
public void onDetach(Myo myo, long l)
{
reset();
}
@Override
public void onConnect(Myo myo, long l)
{
Log.i("Successfully connected to Myo with MAC: " + myo.getMacAddress());
}
@Override
public void onDisconnect(Myo myo, long l)
{
Log.i("Disconnected from Myo");
reset();
}
@Override
public void onArmSync(Myo myo, long l, Arm arm, XDirection xDirection)
{
onArm = true;
whichArm = arm;
}
@Override
public void onArmUnsync(Myo myo, long l)
{
onArm = false;
}
@Override
public void onUnlock(Myo myo, long l)
{
isUnlocked = true;
}
@Override
public void onLock(Myo myo, long l)
{
isUnlocked = false;
}
@Override
public void onPose(Myo myo, long l, Pose pose)
{
currentPose = pose;
}
@Override
public void onOrientationData(Myo myo, long l, Quaternion quaternion)
{
orientationW = quaternion.w();
orientationX = quaternion.x();
orientationY = quaternion.y();
orientationZ = quaternion.z();
float roll = (float) Math.atan2(2.0 * (quaternion.w() * quaternion.x() + quaternion.y() * quaternion.z()), 1.0 - 2.0 * (quaternion.x() * quaternion.x() + quaternion.y() * quaternion.y()));
float pitch = (float) Math.asin(Math.max(-1.0, Math.min(1.0, 2.0 * (quaternion.w() * quaternion.y() - quaternion.z() * quaternion.x()))));
float yaw = (float) Math.atan2(2.0 * (quaternion.w() * quaternion.z() + quaternion.x() * quaternion.y()), 1.0 - 2.0 * (quaternion.y() * quaternion.y() + quaternion.z() * quaternion.z()));
// Convert the floating point angles in radians to a scale from 0 to 18.
rollW = (int) ((roll + (float) Math.PI) / (Math.PI * 2.0) * 18);
pitchW = (int) ((pitch + (float) Math.PI / 2.0) / Math.PI * 18);
yawW = (int) ((yaw + (float) Math.PI) / (Math.PI * 2.0) * 18);
}
@Override
public void onAccelerometerData(Myo myo, long l, Vector3 vector3)
{
accelerationX = (float) vector3.x();
accelerationY = (float) vector3.y();
accelerationZ = (float) vector3.z();
}
@Override
public void onGyroscopeData(Myo myo, long l, Vector3 vector3)
{
}
@Override
public void onRssi(Myo myo, long l, int i)
{
}
public void onEMGData(Myo myo, UUID uuid, byte[] data)
{
for (int i = 0; i < 16; i++) {
emg[i] = data[i];
}
}
}
| 4,877 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EMGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/EMGChannel.java | /*
* EMGChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 01.04.2015.
*/
public class EMGChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected MyoListener _listener;
public EMGChannel()
{
_name = "Myo_EMG";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Myo)_sensor).listener;
if (stream_out.num != 1)
{
Log.w("unsupported stream format. sample number = " + stream_out.num);
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
int[] out = stream_out.ptrI();
for (int j = 0; j < stream_out.dim; j++)
{
out[j] = _listener.emg[j];
}
return true;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 8;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.INT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
for (int j = 0; j < stream_out.dim; j++)
stream_out.desc[j] = "EMG";
}
}
| 3,119 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
DynAccelerationChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/myo/DynAccelerationChannel.java | /*
* DynAccelerationChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.myo;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Dynamic Acceleration which has the gravity component removed
*
* Created by Johnny on 01.04.2015.
*/
public class DynAccelerationChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Float> gravity = new Option<>("gravity", 9.814f, Float.class, "Frankfurt");
public final Option<Boolean> meterPerSecond = new Option<>("meterPerSecond", false, Boolean.class, "");
public final Option<Boolean> absolute = new Option<>("absolute", false, Boolean.class, "do measurements relative to the global coordinate system");
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected MyoListener _listener;
float[] _acc = new float[3];
float[] _ori = new float[4];
float[] _gravity = new float[3];
public DynAccelerationChannel()
{
_name = "Myo_DynAcceleration";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((Myo)_sensor).listener;
if (stream_out.num != 1)
{
Log.w("unsupported stream format. sample number = " + stream_out.num);
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
_acc[0] = _listener.accelerationX;
_acc[1] = _listener.accelerationY;
_acc[2] = _listener.accelerationZ;
_ori[0] = (float)_listener.orientationW;
_ori[1] = (float)_listener.orientationX;
_ori[2] = (float)_listener.orientationY;
_ori[3] = (float)_listener.orientationZ;
/**
* Determine gravity direction
* Code taken from http://www.varesano.net/blog/fabio/simple-gravity-compensation-9-dom-imus
* Author: Fabio Varesano
*/
_gravity[0] = 2 * (_ori[1] * _ori[3] - _ori[0] * _ori[2]);
_gravity[1] = 2 * (_ori[0] * _ori[1] + _ori[2] * _ori[3]);
_gravity[2] = _ori[0] * _ori[0] - _ori[1] * _ori[1] - _ori[2] * _ori[2] + _ori[3] * _ori[3];
for (int k = 0; k < 3; k++)
{
out[k] = _acc[k] - _gravity[k];
}
if (options.absolute.get())
{
//TODO, need to find proper mat/vec/quat library in java
Log.w("not supported yet");
//convert to global coordinate system
// Quaternion q(xq.x(), xq.y(), xq.z(), xq.w());
// Matrix mat(q);
// dynacc = mat * dynacc;
}
if (options.meterPerSecond.get())
{
for (int k = 0; k < 3; k++)
{
out[k] *= options.gravity.get();
}
}
return true;
}
@Override
public void flush(Stream stream_out) throws SSJFatalException
{
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleDimension()
{
return 3;
}
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "AccX";
stream_out.desc[1] = "AccY";
stream_out.desc[2] = "AccZ";
}
}
| 4,748 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FeedbackManager.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/FeedbackManager.java | /*
* FeedbackManager.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.content.Context;
import android.os.Environment;
import android.util.Xml;
import android.widget.TableLayout;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackClass;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackListener;
/**
* Enables the loading and execution of feedback as configured in a strategy file
* Note: strategy files are deprecated, use feedback collections instead
*/
@Deprecated
public class FeedbackManager extends EventHandler
{
private static int MANAGER_UPDATE_TIMEOUT = 100; //ms
private final String STARTEGY_FOLDER = Environment.getExternalStorageDirectory() + File.separator + "logue";
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> strategy = new Option<>("strategy", null, String.class, "strategy file");
public final Option<Boolean> fromAssets = new Option<>("fromAssets", false, Boolean.class, "load feedback strategy file from assets");
public final Option<Float> progression = new Option<>("progression", 12f, Float.class, "timeout for progressing to the next feedback level");
public final Option<Float> regression = new Option<>("regression", 60f, Float.class, "timeout for going back to the previous feedback level");
public final Option<TableLayout> layout = new Option<>("layout", null, TableLayout.class, "TableLayout in which to render visual feedback");
private Options()
{
addOptions();
}
}
public Options options = new Options();
protected Context context;
protected List<FeedbackClass> classes = new ArrayList<>();
protected int level = 0;
private int max_level = 3;
private long lastDesireableState;
private long lastUndesireableState;
private long progressionTimeout;
private long regressionTimeout;
public FeedbackManager()
{
context = SSJApplication.getAppContext();
_name = "FeedbackManager";
}
public List<FeedbackClass> getClasses()
{
return classes;
}
@Override
public void enter() throws SSJFatalException
{
lastDesireableState = lastUndesireableState = System.currentTimeMillis();
progressionTimeout = (int)(options.progression.get() * 1000);
regressionTimeout = (int)(options.regression.get() * 1000);
try
{
load(options.strategy.get(), options.fromAssets.get());
}
catch (IOException | XmlPullParserException e)
{
Log.e("error reading strategy file");
}
}
@Override
public void process() throws SSJFatalException
{
for(FeedbackClass i : classes)
{
i.update();
}
try {
Thread.sleep(MANAGER_UPDATE_TIMEOUT);
} catch (InterruptedException e) {
Log.w("thread interrupted");
}
}
public void flush() throws SSJFatalException
{
for(FeedbackClass f : classes)
{
f.release();
}
classes.clear();
}
@Override
public void notify(hcm.ssj.core.event.Event behavEvent) {
if(classes.size() == 0)
return;
//validate feedback
for(FeedbackClass i : classes)
{
if(i.getLevel() == level)
{
if(i.getValence() == FeedbackClass.Valence.Desirable && i.getLastExecutionTime() > lastDesireableState)
{
lastDesireableState = i.getLastExecutionTime();
}
else if(i.getValence() == FeedbackClass.Valence.Undesirable && i.getLastExecutionTime() > lastUndesireableState)
{
lastUndesireableState = i.getLastExecutionTime();
}
}
}
//if all current feedback classes are in a non desirable state, check if we should progress to next level
if (System.currentTimeMillis() - progressionTimeout > lastDesireableState && level < max_level) {
level++;
lastDesireableState = System.currentTimeMillis();
Log.d("activating level " + level);
}
//if all current feedback classes are in a desirable state, check if we can go back to the previous level
else if (System.currentTimeMillis() - regressionTimeout > lastUndesireableState && level > 0) {
level--;
lastUndesireableState = System.currentTimeMillis();
Log.d("activating level " + level);
}
//execute feedback
for(FeedbackClass i : classes)
{
if(i.getLevel() == level)
{
try
{
i.process(behavEvent);
}
catch (Exception e)
{
Log.e("error processing event", e);
}
}
}
}
private void load(String path, boolean fromAsset) throws IOException, XmlPullParserException
{
InputStream in;
if(fromAsset)
in = SSJApplication.getAppContext().getAssets().open(path);
else
in = new FileInputStream(new File(STARTEGY_FOLDER, path));
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
while(parser.next() != XmlPullParser.END_DOCUMENT)
{
switch(parser.getEventType())
{
case XmlPullParser.START_TAG:
if(parser.getName().equalsIgnoreCase("strategy"))
{
load(parser);
}
break;
}
}
//find max progression level
max_level = 0;
for(FeedbackClass i : classes) {
if(i.getLevel() > max_level)
max_level = i.getLevel();
}
in.close();
}
private void load(XmlPullParser parser) throws IOException, XmlPullParserException
{
parser.require(XmlPullParser.START_TAG, null, "strategy");
//iterate through classes
while (parser.next() != XmlPullParser.END_DOCUMENT)
{
if(parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("feedback"))
{
//parse feedback classes
FeedbackClass c = FeedbackClass.create(parser, context, options);
classes.add(c);
}
else if(parser.getEventType() == XmlPullParser.END_TAG && parser.getName().equalsIgnoreCase("strategy"))
break; //jump out once we reach end tag for classes
}
parser.require(XmlPullParser.END_TAG, null, "strategy");
Log.i("loaded " + classes.size() + " feedback classes");
}
public void addFeedbackListener(FeedbackListener listener)
{
for(FeedbackClass i : classes)
{
i.addFeedbackListener(listener);
}
}
}
| 8,955 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BandComm.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/BandComm.java | /*
* BandComm.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.content.Context;
import android.os.AsyncTask;
import com.microsoft.band.BandClient;
import com.microsoft.band.BandClientManager;
import com.microsoft.band.BandException;
import com.microsoft.band.BandInfo;
import com.microsoft.band.ConnectionState;
import com.microsoft.band.notifications.VibrationType;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
/**
* Created by Johnny on 01.02.2017.
*/
public class BandComm {
private BandClient client;
private int id;
public BandComm()
{
this.id = 0;
}
public BandComm(int id)
{
this.id = id;
}
public void vibrate(VibrationType type)
{
new VibrateTask(type).execute();
}
private class VibrateTask extends AsyncTask<Void, Void, Boolean> {
VibrationType type;
public VibrateTask(VibrationType type)
{
this.type = type;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
if (getConnectedBandClient()) {
client.getNotificationManager().vibrate(type);
} else {
Log.e("Band isn't connected. Please make sure bluetooth is on and the band is in range.\n");
return false;
}
} catch (BandException e) {
handleBandException(e);
return false;
} catch (Exception e) {
Log.e(e.getMessage());
return false;
}
return true;
}
}
private boolean getConnectedBandClient() throws InterruptedException, BandException {
if (client == null) {
BandInfo[] devices = BandClientManager.getInstance().getPairedBands();
if (devices.length == 0 || id >= devices.length) {
Log.e("Requested Band isn't paired with your phone.");
return false;
}
Context c = SSJApplication.getAppContext();
client = BandClientManager.getInstance().create(c, devices[id]);
} else if (ConnectionState.CONNECTED == client.getConnectionState()) {
return true;
}
Log.i("Band is connecting...\n");
return ConnectionState.CONNECTED == client.connect().await();
}
private void handleBandException(BandException e) {
String exceptionMessage = "";
switch (e.getErrorType()) {
case DEVICE_ERROR:
exceptionMessage = "Please make sure bluetooth is on and the band is in range.\n";
break;
case UNSUPPORTED_SDK_VERSION_ERROR:
exceptionMessage = "Microsoft Health BandService doesn't support your SDK Version. Please update to latest SDK.\n";
break;
case SERVICE_ERROR:
exceptionMessage = "Microsoft Health BandService is not available. Please make sure Microsoft Health is installed and that you have the correct permissions.\n";
break;
case BAND_FULL_ERROR:
exceptionMessage = "Band is full. Please use Microsoft Health to remove a tile.\n";
break;
default:
exceptionMessage = "Unknown error occured: " + e.getMessage() + "\n";
break;
}
Log.e(exceptionMessage);
}
}
| 4,770 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AuditoryFeedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/AuditoryFeedback.java | /*
* AuditoryFeedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.media.AudioManager;
import android.media.SoundPool;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.FilePath;
import hcm.ssj.core.option.Option;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public class AuditoryFeedback extends Feedback
{
public final Options options = new Options();
private SoundPool player;
private int soundId;
public AuditoryFeedback()
{
_name = "AuditoryFeedback";
Log.d("Instantiated AuditoryFeedback " + this.hashCode());
}
@Override
public Feedback.Options getOptions()
{
return options;
}
@Override
public void enterFeedback() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no input channels");
}
player = new SoundPool(4, AudioManager.STREAM_NOTIFICATION, 0);
soundId = player.load(options.audioFile.get().value, 1);
}
@Override
public void notifyFeedback(Event event)
{
player.play(soundId, options.intensity.get(), options.intensity.get(), 1, 0, 1);
}
@Override
public void flush() throws SSJFatalException
{
player.release();
}
public class Options extends Feedback.Options
{
public final Option<Float> intensity = new Option<>("intensity", 1.0f, Float.class, "intensity of auditory feedback");
public final Option<FilePath> audioFile = new Option<>("audioFile", null, FilePath.class, "audiofile to play");
private Options()
{
super();
addOptions();
}
}
}
| 2,908 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MyoTactileFeedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/MyoTactileFeedback.java | /*
* MyoTactileFeedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.os.SystemClock;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.myo.Vibrate2Command;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public class MyoTactileFeedback extends Feedback
{
public class Options extends Feedback.Options
{
public final Option<int[]> duration = new Option<>("duration", new int[]{500}, int[].class, "duration of tactile feedback");
public final Option<byte[]> intensity = new Option<>("intensity", new byte[]{(byte) 150}, byte[].class, "intensity of tactile feedback");
public final Option<String> deviceId = new Option<>("deviceId", null, String.class, "device Id");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Myo myo = null;
private hcm.ssj.myo.Myo myoConnector = null;
private Vibrate2Command cmd = null;
public MyoTactileFeedback()
{
_name = "MyoTactileFeedback";
Log.d("Instantiated MyoTactileFeedback " + this.hashCode());
}
@Override
public Feedback.Options getOptions()
{
return options;
}
@Override
public void enterFeedback() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no input channels");
}
Hub hub = Hub.getInstance();
if (hub.getConnectedDevices().isEmpty())
{
myoConnector = new hcm.ssj.myo.Myo();
myoConnector.options.macAddress.set(options.deviceId.get());
try
{
myoConnector.connect();
}
catch (hcm.ssj.core.SSJFatalException e)
{
e.printStackTrace();
}
}
long time = SystemClock.elapsedRealtime();
while (hub.getConnectedDevices().isEmpty() && SystemClock.elapsedRealtime() - time < Pipeline.getInstance().options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException e)
{
Log.d("connection interrupted", e);
}
}
if (hub.getConnectedDevices().isEmpty())
{
throw new SSJFatalException("device not found");
}
Log.i("connected to Myo");
myo = hub.getConnectedDevices().get(0);
cmd = new Vibrate2Command(hub);
}
@Override
public void notifyFeedback(Event event)
{
Log.i("vibration " + options.duration.get()[0] + "/" + (int) options.intensity.get()[0]);
cmd.vibrate(myo, options.duration.get(), options.intensity.get());
}
@Override
public void flush() throws SSJFatalException
{
if (myoConnector != null)
{
myoConnector.disconnect();
}
}
}
| 4,051 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FeedbackCollection.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/FeedbackCollection.java | /*
* FeedbackCollection.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.widget.TableLayout;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Antonio Grieco on 18.09.2017.
*/
public class FeedbackCollection extends EventHandler
{
public FeedbackCollection.Options options = new FeedbackCollection.Options();
private int currentLevel;
private List<Map<Feedback, LevelBehaviour>> feedbackList;
private long lastLevelActivationTime;
public FeedbackCollection()
{
_name = "FeedbackCollection";
feedbackList = new ArrayList<>();
}
@Override
public void enter() throws SSJFatalException
{
currentLevel = 0;
setLevelActive(currentLevel);
}
@Override
public void notify(Event event)
{
if (feedbackList.isEmpty() || feedbackList.get(currentLevel).isEmpty())
{
return;
}
List<Long> lastProgressExecutionTimes = new ArrayList<>();
List<Long> lastNeutralExecutionTimes = new ArrayList<>();
List<Long> lastRegressExecutionTimes = new ArrayList<>();
for (Map.Entry<Feedback, LevelBehaviour> feedbackEntry : feedbackList.get(currentLevel).entrySet())
{
long feedbackEntryLastExecutionTime = feedbackEntry.getKey().getLastExecutionTime();
switch (feedbackEntry.getValue())
{
case Regress:
lastRegressExecutionTimes.add(feedbackEntryLastExecutionTime);
break;
case Neutral:
lastNeutralExecutionTimes.add(feedbackEntryLastExecutionTime);
break;
case Progress:
lastProgressExecutionTimes.add(feedbackEntryLastExecutionTime);
break;
}
}
//if all progress feedback classes are active and no other class is active, check if we should progress to next level
if ((currentLevel + 1) < feedbackList.size() &&
lastLevelActivationExceedsTime(options.progression.get()*1000) &&
allTimeStampsInIntervalFromNow(lastProgressExecutionTimes, (long) (options.progression.get() * 1000)) &&
noTimeStampInIntervalFromNow(lastNeutralExecutionTimes, (long) (options.progression.get() * 1000)) &&
noTimeStampInIntervalFromNow(lastRegressExecutionTimes, (long) (options.progression.get() * 1000)))
{
Log.d("progressing");
setLevelActive(currentLevel + 1);
}
//if all regress feedback classes are active and no other class is active, check if we can go back to the previous level
else if (currentLevel > 0 &&
lastLevelActivationExceedsTime(options.regression.get()*1000) &&
noTimeStampInIntervalFromNow(lastProgressExecutionTimes, (long) (options.regression.get() * 1000)) &&
noTimeStampInIntervalFromNow(lastNeutralExecutionTimes, (long) (options.regression.get() * 1000)) &&
allTimeStampsInIntervalFromNow(lastRegressExecutionTimes, (long) (options.regression.get() * 1000)))
{
Log.d("regressing");
setLevelActive(currentLevel - 1);
}
}
private boolean lastLevelActivationExceedsTime(float time)
{
return (System.currentTimeMillis() - lastLevelActivationTime) >= time;
}
private boolean allTimeStampsInIntervalFromNow(List<Long> timeStamps, long interval)
{
if (timeStamps.isEmpty())
{
return false;
}
long currentTime = System.currentTimeMillis();
for (Long timeStamp : timeStamps)
{
if (currentTime - interval > timeStamp)
{
return false;
}
}
return true;
}
private boolean noTimeStampInIntervalFromNow(List<Long> timeStamps, long interval)
{
if (timeStamps.isEmpty())
{
return true;
}
long currentTime = System.currentTimeMillis();
for (Long timeStamp : timeStamps)
{
if (currentTime - interval < timeStamp)
{
return false;
}
}
return true;
}
private void setLevelActive(int level)
{
if (level >= feedbackList.size())
{
throw new RuntimeException("Setting level " + level + " active exceeds available levels.");
}
Log.d("activating level " + level);
currentLevel = level;
for (int i = 0; i < feedbackList.size(); i++)
{
for (Feedback feedback : feedbackList.get(i).keySet())
{
feedback.setActive(currentLevel == i);
}
}
this.lastLevelActivationTime = System.currentTimeMillis();
}
public List<Map<Feedback, LevelBehaviour>> getFeedbackList()
{
return feedbackList;
}
public void addFeedback(Feedback feedback, int level, LevelBehaviour levelBehaviour)
{
removeFeedback(feedback);
while (feedbackList.size() <= level)
{
feedbackList.add(new LinkedHashMap<Feedback, LevelBehaviour>());
}
feedbackList.get(level).put(feedback, levelBehaviour);
if (feedback instanceof VisualFeedback)
{
((VisualFeedback) feedback).options.layout.set(options.layout.get());
}
}
public void removeFeedback(Feedback feedback)
{
for (Map<Feedback, LevelBehaviour> feedbackLevelBehaviourMap : feedbackList)
{
feedbackLevelBehaviourMap.remove(feedback);
}
}
public void removeAllFeedbacks()
{
feedbackList = new ArrayList<>();
}
@Override
public OptionList getOptions()
{
return options;
}
public enum LevelBehaviour
{
Regress,
Neutral,
Progress;
}
public class Options extends OptionList
{
public final Option<Float> progression = new Option<>("progression", 12f, Float.class, "timeout for progressing to the next feedback level");
public final Option<Float> regression = new Option<>("regression", 60f, Float.class, "timeout for going back to the previous feedback level");
public final Option<TableLayout> layout = new Option<>("layout", null, TableLayout.class, "TableLayout in which to render every visual feedback");
private Options()
{
addOptions();
}
}
}
| 7,084 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Feedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/Feedback.java | /*
* Feedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public abstract class Feedback extends EventHandler
{
private long lastExecutionTime = 0;
private boolean active = true;
private boolean checkLock()
{
if (System.currentTimeMillis() - lastExecutionTime < getOptions().lock.get())
{
Log.i("ignoring event, lock active for another " +
(getOptions().lock.get() - (System.currentTimeMillis() - lastExecutionTime)) +
"ms");
return false;
}
else
{
lastExecutionTime = System.currentTimeMillis();
return true;
}
}
@Override
protected final void enter() throws SSJFatalException
{
lastExecutionTime = 0;
enterFeedback();
}
protected abstract void enterFeedback() throws SSJFatalException;
public boolean isActive()
{
return active;
}
protected void setActive(boolean active)
{
this.active = active;
}
long getLastExecutionTime()
{
return lastExecutionTime;
}
private boolean activatedByEventName(String eventName)
{
// Allways activate if no eventnames are specified
if (getOptions().eventNames.get() == null || getOptions().eventNames.get().length == 0)
{
return true;
}
for (String eventNameToActivate : getOptions().eventNames.get())
{
if (eventNameToActivate.equals(eventName))
{
return true;
}
}
return false;
}
@Override
public final void notify(Event event)
{
if (active && activatedByEventName(event.name) && checkLock())
{
notifyFeedback(event);
}
}
public abstract Options getOptions();
public abstract void notifyFeedback(Event event);
public class Options extends OptionList
{
public final Option<Integer> lock = new Option<>("lock", 0, Integer.class, "lock time in ms");
public final Option<String[]> eventNames = new Option<>("eventNames", null, String[].class, "event names to listen on");
protected Options()
{
addOptions();
}
}
}
| 3,470 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MSBandTactileFeedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/MSBandTactileFeedback.java | /*
* MSBandTactileFeedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import com.microsoft.band.notifications.VibrationType;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public class MSBandTactileFeedback extends Feedback
{
public class Options extends Feedback.Options
{
public final Option<int[]> duration = new Option<>("duration", new int[]{500}, int[].class, "duration of tactile feedback");
public final Option<VibrationType> vibrationType = new Option<>("vibrationType", VibrationType.NOTIFICATION_ONE_TONE, VibrationType.class, "vibration type");
public final Option<Integer> deviceId = new Option<>("deviceId", 0, Integer.class, "device Id");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private BandComm msband = null;
public MSBandTactileFeedback()
{
_name = "MSBandTactileFeedback";
Log.d("Instantiated MSBandTactileFeedback " + this.hashCode());
}
@Override
public Feedback.Options getOptions()
{
return options;
}
@Override
public void enterFeedback() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no input channels");
}
msband = new BandComm(options.deviceId.get());
}
@Override
public void notifyFeedback(Event event)
{
Log.i("vibration " + options.vibrationType.get());
msband.vibrate(options.vibrationType.get());
}
}
| 2,876 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
VisualFeedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/VisualFeedback.java | /*
* VisualFeedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.FilePath;
import hcm.ssj.core.option.Option;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public class VisualFeedback extends Feedback
{
public final Options options = new Options();
private final int TIMEOUT_CHECK_DELAY = 100;
private List<Drawable> iconList;
private List<ImageSwitcher> imageSwitcherList;
private Activity activity = null;
private long timeout = 0;
private float defaultBrightness;
public VisualFeedback()
{
_name = "VisualFeedback";
Log.d("Instantiated VisualFeedback " + this.hashCode());
}
@Override
public Feedback.Options getOptions()
{
return options;
}
@Override
public void enterFeedback() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no input channels");
}
if (options.layout.get() == null)
{
throw new SSJFatalException("layout not set, cannot render visual feedback");
}
activity = getActivity(options.layout.get());
if (activity == null)
{
throw new SSJFatalException("unable to get activity from layout");
}
imageSwitcherList = new ArrayList<>();
getDefaultBrightness();
loadIcons();
buildLayout();
clearIcons();
}
private void loadIcons()
{
iconList = new ArrayList<>();
Drawable feedbackDrawable = Drawable.createFromPath(options.feedbackIcon.get().value);
if (feedbackDrawable != null)
{
iconList.add(feedbackDrawable);
}
if(options.qualityIcon.get() != null)
{
Drawable qualityDrawable = Drawable.createFromPath(options.qualityIcon.get().value);
if (qualityDrawable != null)
{
iconList.add(qualityDrawable);
}
}
}
@Override
public void notifyFeedback(Event event)
{
if (options.duration.get() > 0)
{
timeout = System.currentTimeMillis() + options.duration.get();
}
updateIcons();
if(options.brightness.get() > 0)
updateBrightness(options.brightness.get());
}
@Override
public void process() throws SSJFatalException
{
try
{
Thread.sleep(TIMEOUT_CHECK_DELAY);
}
catch (InterruptedException e)
{
throw new SSJFatalException("timeout interrupted", e);
}
if (timeout == 0 || System.currentTimeMillis() < timeout)
{
return;
}
if (isActive())
{
Log.i("clearing icons");
clearIcons();
if(options.brightness.get() > 0)
updateBrightness(defaultBrightness);
timeout = 0;
}
}
@Override
public void flush() throws SSJFatalException
{
clearIcons();
}
private void clearIcons()
{
for (ImageSwitcher imageSwitcher : imageSwitcherList)
{
updateImageSwitcher(imageSwitcher, null);
}
}
private void updateIcons()
{
int minimal = Math.min(imageSwitcherList.size(), iconList.size());
for (int i = 0; i < minimal; i++)
{
updateImageSwitcher(imageSwitcherList.get(i), iconList.get(i));
}
}
private void updateImageSwitcher(final ImageSwitcher imageSwitcher, final Drawable drawable)
{
imageSwitcher.post(new Runnable()
{
public void run()
{
imageSwitcher.setImageDrawable(drawable);
}
});
}
private void getDefaultBrightness()
{
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
defaultBrightness = lp.screenBrightness;
}
private void updateBrightness(final float brightness)
{
activity.runOnUiThread(new Runnable()
{
public void run()
{
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
lp.screenBrightness = brightness;
activity.getWindow().setAttributes(lp);
}
});
}
private Activity getActivity(View view)
{
Context context = view.getContext();
while (context instanceof ContextWrapper)
{
if (context instanceof Activity)
{
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
//alternative method
View content = view.findViewById(android.R.id.content);
if (content != null)
{
return (Activity) content.getContext();
}
else
{
return null;
}
}
private void buildLayout()
{
if (options.layout.get() == null)
{
Log.e("layout not set, cannot render visual feedback");
return;
}
Handler handler = new Handler(activity.getMainLooper());
handler.post(new Runnable()
{
@Override
public void run()
{
TableLayout table = options.layout.get();
table.setStretchAllColumns(true);
if (table.getChildCount() < iconList.size())
{
for (int i = table.getChildCount(); i < iconList.size(); ++i)
{
table.addView(new TableRow(activity), i);
}
}
for (int i = 0; i < iconList.size(); ++i)
{
TableRow tr = (TableRow) table.getChildAt(i);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1f));
//if the image switcher has already been initialized by a class on previous level
if (tr.getChildAt(options.position.get()) instanceof ImageSwitcher)
{
imageSwitcherList.add((ImageSwitcher) tr.getChildAt(options.position.get()));
}
else
{
ImageSwitcher imageSwitcher = new ImageSwitcher(activity);
imageSwitcher.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1f));
Animation in = AnimationUtils.loadAnimation(activity, android.R.anim.fade_in);
in.setDuration(options.fade.get());
Animation out = AnimationUtils.loadAnimation(activity, android.R.anim.fade_out);
out.setDuration(options.fade.get());
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory()
{
@Override
public View makeView()
{
ImageView imageView = new ImageView(activity);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(ImageSwitcher.LayoutParams.MATCH_PARENT, ImageSwitcher.LayoutParams.MATCH_PARENT));
return imageView;
}
});
// Fill with empty views to match position
for (int columnCount = 0; columnCount <= options.position.get(); columnCount++)
{
if (tr.getChildAt(columnCount) == null)
{
tr.addView(new View(activity), columnCount);
}
}
tr.removeViewAt(options.position.get());
tr.addView(imageSwitcher, options.position.get());
imageSwitcherList.add(imageSwitcher);
}
}
}
});
}
public class Options extends Feedback.Options
{
public final Option<FilePath> feedbackIcon = new Option<>("feedbackIcon", null, FilePath.class, "feedback icon file");
public final Option<FilePath> qualityIcon = new Option<>("qualityIcon", null, FilePath.class, "quality icon file");
public final Option<Float> brightness = new Option<>("brightness", -1f, Float.class, "screen brightness (-1 = no change)");
public final Option<Integer> duration = new Option<>("duration", 0, Integer.class, "duration until icons disappear (ms)");
public final Option<Integer> fade = new Option<>("fade", 0, Integer.class, "fade duration (ms)");
public final Option<Integer> position = new Option<>("position", 0, Integer.class, "position of the icons");
public final Option<TableLayout> layout = new Option<>("layout", null, TableLayout.class, "TableLayout in which to render visual feedback");
private Options()
{
super();
addOptions();
}
}
}
| 9,386 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AndroidTactileFeedback.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/AndroidTactileFeedback.java | /*
* AndroidTactileFeedback.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback;
import android.content.Context;
import android.os.Vibrator;
import java.util.Arrays;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
/**
* Created by Antonio Grieco on 06.09.2017.
*/
public class AndroidTactileFeedback extends Feedback
{
public class Options extends Feedback.Options
{
public final Option<long[]> vibrationPattern = new Option<>("vibrationPattern", new long[]{0, 500}, long[].class, "vibration pattern (starts with delay)");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Vibrator vibrator = null;
public AndroidTactileFeedback()
{
_name = "AndroidTactileFeedback";
Log.d("Instantiated AndroidTactileFeedback " + this.hashCode());
}
@Override
public Feedback.Options getOptions()
{
return options;
}
@Override
public void enterFeedback() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no input channels");
}
vibrator = (Vibrator) SSJApplication.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);
if (!vibrator.hasVibrator())
{
throw new SSJFatalException("device can't vibrate");
}
}
@Override
public void notifyFeedback(Event event)
{
Log.i("vibration on android: " + Arrays.toString(options.vibrationPattern.get()));
vibrator.vibrate(options.vibrationPattern.get(), -1);
}
@Override
public void flush() throws SSJFatalException
{
vibrator.cancel();
}
}
| 2,994 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SpeechDuration.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/conditions/SpeechDuration.java | /*
* SpeechDuration.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.conditions;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 01.12.2014.
*/
public class SpeechDuration extends Condition
{
float _dur = 0;
boolean _shouldSum= false;
@Override
public float parseEvent(Event event)
{
if(_shouldSum)
_dur += event.dur / 1000.0f;
else
_dur = event.dur / 1000.0f;
return _dur;
}
public boolean checkEvent(Event event)
{
if (event.name.equalsIgnoreCase(_event)
&& event.sender.equalsIgnoreCase(_sender)
&& event.state == Event.State.COMPLETED)
{
float value = parseEvent(event);
if((value == thres_lower) || (value >= thres_lower && value < thres_upper))
return true;
}
return false;
}
@Override
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "condition");
}
catch (XmlPullParserException | IOException e)
{
Log.e("error parsing config file", e);
}
_shouldSum = Boolean.getBoolean(xml.getAttributeValue(null, "sum"));
super.load(xml, context);
}
}
| 2,806 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Loudness.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/conditions/Loudness.java | /*
* Loudness.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.conditions;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.LinkedList;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 01.12.2014.
*/
public class Loudness extends Condition
{
LinkedList<Float> _loudness = new LinkedList<Float>();
int _history_size;
@Override
public float parseEvent(Event event)
{
float loudness = Float.parseFloat(event.ptrStr());
_loudness.add(loudness);
if (_loudness.size() > _history_size)
_loudness.removeFirst();
float value = getAvg(_loudness);
Log.d("Loudness = " + value);
return value;
}
private float getAvg(LinkedList<Float> vec)
{
if(vec.size() == 0)
return 0;
float sum = 0;
for(float i : vec)
{
sum += i;
}
return sum / vec.size();
}
@Override
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "condition");
}
catch (XmlPullParserException | IOException e)
{
Log.e("error parsing config file", e);
}
_history_size = Integer.getInteger(xml.getAttributeValue(null, "history"), 5);
super.load(xml, context);
}
}
| 2,824 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
KeyPress.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/conditions/KeyPress.java | /*
* KeyPress.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.conditions;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 01.12.2014.
*/
public class KeyPress extends Condition
{
protected String _text;
protected boolean _isToggle;
protected float _lastValue = 0;
public boolean checkEvent(Event event)
{
if (event.name.equalsIgnoreCase(_event)
&& event.sender.equalsIgnoreCase(_sender)
&& (_text == null || event.ptrStr().equalsIgnoreCase(_text))
&& (!_isToggle || event.state == Event.State.COMPLETED))
{
float value = parseEvent(event);
if((value == thres_lower) || (value >= thres_lower && value < thres_upper))
return true;
}
return false;
}
public float parseEvent(Event event)
{
float value;
if(_isToggle)
{
value = 1 - _lastValue;
_lastValue = value;
}
else
{
value = (event.state == Event.State.COMPLETED) ? 0 : 1;
}
return value;
}
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "condition");
_text = xml.getAttributeValue(null, "text");
String toggle = xml.getAttributeValue(null, "toggle");
if(toggle == null || toggle.compareToIgnoreCase("false") == 0)
_isToggle = false;
else
_isToggle = true;
}
catch(IOException | XmlPullParserException e)
{
Log.e("error parsing config file", e);
}
super.load(xml, context);
}
public float getLastValue()
{
return _lastValue;
}
}
| 3,285 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SpeechRate.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/conditions/SpeechRate.java | /*
* SpeechRate.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.conditions;
import android.content.Context;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 01.12.2014.
*/
public class SpeechRate extends Condition
{
LinkedList<Float> _sr = new LinkedList<Float>();
int _history_size;
XmlPullParser _parser;
public SpeechRate()
{
try
{
_parser = Xml.newPullParser();
_parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
}
catch (XmlPullParserException e)
{
throw new RuntimeException(e);
}
}
@Override
public float parseEvent(Event event)
{
try
{
float srate = 0;
_parser.setInput(new StringReader(event.ptrStr()));
while (_parser.next() != XmlPullParser.END_DOCUMENT)
{
if (_parser.getEventType() == XmlPullParser.START_TAG && _parser.getName().equalsIgnoreCase("tuple"))
{
if (_parser.getAttributeValue(null, "string").equalsIgnoreCase("Speechrate (syllables/sec)")) {
srate = Float.parseFloat(_parser.getAttributeValue(null, "value"));
_sr.add(srate);
if (_sr.size() > _history_size)
_sr.removeFirst();
break;
}
}
else if(_parser.getEventType() == XmlPullParser.END_TAG && _parser.getName().equalsIgnoreCase("event"))
break; //jump out once we reach end tag
}
}
catch (XmlPullParserException | IOException e)
{
throw new RuntimeException("failed parsing event", e);
}
float value = getAvg(_sr);
Log.d("SpeechRate_avg = " + value);
return value;
}
private float getAvg(LinkedList<Float> vec)
{
if(vec.size() == 0)
return 0;
float sum = 0;
for(float i : vec)
{
sum += i;
}
return sum / vec.size();
}
@Override
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "condition");
}
catch (XmlPullParserException | IOException e)
{
Log.e("error parsing config file", e);
}
_history_size = Integer.getInteger(xml.getAttributeValue(null, "history"), 5);
super.load(xml, context);
}
}
| 4,130 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Condition.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/conditions/Condition.java | /*
* Condition.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.conditions;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
/**
* Created by Johnny on 01.12.2014.
*/
public class Condition
{
protected String _event;
protected String _sender;
public float thres_lower = 0;
public float thres_upper = 0;
public static Condition create(XmlPullParser xml, Context context)
{
Condition b = null;
String type = xml.getAttributeValue(null, "type");
if (type != null && type.equalsIgnoreCase("SpeechRate"))
b = new SpeechRate();
else if (type != null && type.equalsIgnoreCase("Loudness"))
b = new Loudness();
else if (type != null && type.equalsIgnoreCase("KeyPress"))
b = new KeyPress();
else
b = new Condition();
b.load(xml, context);
return b;
}
public boolean checkEvent(Event event)
{
if (event.name.equalsIgnoreCase(_event)
&& event.sender.equalsIgnoreCase(_sender))
{
float value = parseEvent(event);
if((value == thres_lower) || (value >= thres_lower && value < thres_upper))
return true;
}
return false;
}
public float parseEvent(Event event)
{
switch(event.type)
{
case BYTE:
return (float) event.ptrB()[0];
case CHAR:
case STRING:
return Float.parseFloat(event.ptrStr());
case SHORT:
return (float) event.ptrShort()[0];
case INT:
return (float) event.ptrI()[0];
case LONG:
return (float) event.ptrL()[0];
case FLOAT:
return event.ptrF()[0];
case DOUBLE:
return (float) event.ptrD()[0];
case BOOL:
return (event.ptrBool()[0]) ? 1 : 0;
case EMPTY:
return 1;
default:
throw new UnsupportedOperationException("unknown event");
}
}
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "condition");
_event = xml.getAttributeValue(null, "event");
_sender = xml.getAttributeValue(null, "sender");
String from = xml.getAttributeValue(null, "from");
String equals = xml.getAttributeValue(null, "equals");
String to = xml.getAttributeValue(null, "to");
if(equals != null)
{
thres_lower = Float.parseFloat(equals);
}
else if(from != null && to != null)
{
thres_lower = Float.parseFloat(from);
thres_upper = Float.parseFloat(to);
}
else
{
throw new IOException("threshold value(s) not set");
}
}
catch(IOException | XmlPullParserException e)
{
Log.e("error parsing config file", e);
}
}
}
| 4,605 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Auditory.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/classes/Auditory.java | /*
* Auditory.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.classes;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import org.xmlpull.v1.XmlPullParser;
import hcm.ssj.core.Log;
import hcm.ssj.feedback.FeedbackManager;
import hcm.ssj.feedback.feedbackmanager.actions.Action;
import hcm.ssj.feedback.feedbackmanager.actions.AudioAction;
/**
* Created by Johnny on 01.12.2014.
*/
public class Auditory extends FeedbackClass
{
long lock = 0;
SoundPool player;
public Auditory(Context context, FeedbackManager.Options options)
{
this.context = context;
this.options = options;
type = Type.Audio;
}
public void release()
{
player.release();
super.release();
}
@Override
public boolean execute(Action action)
{
AudioAction ev = (AudioAction) action;
//check locks
//global
if(System.currentTimeMillis() < lock)
{
Log.i("ignoring event, global lock active for another " + (lock - System.currentTimeMillis()) + "ms");
return false;
}
//local
if (System.currentTimeMillis() - ev.lastExecutionTime < ev.lockSelf)
{
Log.i("ignoring event, self lock active for another " + (ev.lockSelf - (System.currentTimeMillis() - ev.lastExecutionTime)) + "ms");
return false;
}
player.play(ev.soundId, ev.intensity, ev.intensity, 1, 0, 1);
//set lock
if(ev.lock > 0)
lock = System.currentTimeMillis() + (long) ev.lock;
else
lock = 0;
return true;
}
protected void load(XmlPullParser xml, final Context context)
{
super.load(xml, context);
player = new SoundPool(4, AudioManager.STREAM_NOTIFICATION, 0);
((AudioAction) action).registerWithPlayer(player);
}
}
| 3,150 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Visual.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/classes/Visual.java | /*
* Visual.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.classes;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.ViewSwitcher;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.security.InvalidParameterException;
import hcm.ssj.core.Log;
import hcm.ssj.feedback.FeedbackManager;
import hcm.ssj.feedback.feedbackmanager.actions.Action;
import hcm.ssj.feedback.feedbackmanager.actions.VisualAction;
/**
* Created by Johnny on 01.12.2014.
*/
public class Visual extends FeedbackClass
{
protected ImageSwitcher img[];
protected float defBrightness = 0.5f;
protected static long s_lock = 0;
protected long timeout = 0;
private boolean isSetup;
private int position = 0;
private Activity activity;
public Visual(Context context, FeedbackManager.Options options)
{
this.context = context;
this.options = options;
type = Type.Visual;
isSetup = false;
}
@Override
public boolean execute(Action action)
{
if(!isSetup)
return false;
VisualAction ev = (VisualAction) action;
//check locks
//global
if(System.currentTimeMillis() < s_lock)
{
Log.i("ignoring event, global lock active for another " + (s_lock - System.currentTimeMillis()) + "ms");
return false;
}
//local
if (System.currentTimeMillis() - ev.lastExecutionTime < ev.lockSelf + ev.dur)
{
Log.i("ignoring event, self lock active for another " + (ev.lockSelf + ev.dur - (System.currentTimeMillis() - ev.lastExecutionTime)) + "ms");
return false;
}
updateIcons(ev.icons);
updateBrightness(ev.brightness);
//set dur
if(ev.dur > 0)
//return to default (first) event after dur milliseconds has passed
timeout = System.currentTimeMillis() + (long) ev.dur;
else
timeout = 0;
//set global lock
if(ev.lock > 0)
s_lock = System.currentTimeMillis() + (long) ev.dur + (long) ev.lock;
else
s_lock = 0;
return true;
}
public void update()
{
if(timeout == 0 || System.currentTimeMillis() < timeout)
return;
//if a lock is set, return icons to default configuration
Log.i("restoring default icons");
updateIcons(new Drawable[]{null, null});
updateBrightness(defBrightness);
timeout = 0;
}
protected void updateIcons(Drawable icons[])
{
//set feedback icon
updateImageSwitcher(img[0], icons[0]);
//set quality icon
if(icons.length == 2 && img.length == 2 && img[1] != null)
{
updateImageSwitcher(img[1], icons[1]);
}
}
protected void updateBrightness(final float brightness)
{
activity.runOnUiThread(new Runnable()
{
public void run()
{
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
lp.screenBrightness = brightness;
activity.getWindow().setAttributes(lp);
}
});
}
protected void updateImageSwitcher(final ImageSwitcher view, final Drawable img)
{
view.post(new Runnable()
{
public void run()
{
view.setImageDrawable(img);
}
});
}
protected void load(XmlPullParser xml, final Context context)
{
int fade = 0;
try
{
xml.require(XmlPullParser.START_TAG, null, "feedback");
String fade_str = xml.getAttributeValue(null, "fade");
if (fade_str != null)
fade = Integer.valueOf(fade_str);
String pos_str = xml.getAttributeValue(null, "position");
if (pos_str != null)
position = Integer.valueOf(pos_str);
String bright_str = xml.getAttributeValue(null, "def_brightness");
if (bright_str != null)
defBrightness = Float.valueOf(bright_str);
}
catch(IOException | XmlPullParserException | InvalidParameterException e)
{
Log.e("error parsing config file", e);
}
super.load(xml, context);
buildLayout(context, fade);
}
private void buildLayout(final Context context, final int fade)
{
if(options.layout.get() == null)
{
Log.e("layout not set, cannot render visual feedback");
return;
}
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable()
{
@Override
public void run()
{
TableLayout table = options.layout.get();
table.setStretchAllColumns(true);
activity = getActivity(table);
if(activity == null)
Log.w("unable to get activity from layout");
int rows = ((VisualAction) action).icons.length;
img = new ImageSwitcher[rows];
//if this is the first visual class, init rows
if (table.getChildCount() == 0)
for(int i = 0; i < rows; ++i)
table.addView(new TableRow(context), i);
for(int i = 0; i < rows; ++i)
{
TableRow tr = (TableRow) table.getChildAt(i);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1f));
//if the image switcher has already been initialized by a class on previous level
if(tr.getChildAt(position) != null)
{
img[i] = (ImageSwitcher)tr.getChildAt(position);
}
else
{
img[i] = new ImageSwitcher(context);
img[i].setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1f));
Animation in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
in.setDuration(fade);
Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
out.setDuration(fade);
img[i].setInAnimation(in);
img[i].setOutAnimation(out);
img[i].setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(context);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(ImageSwitcher.LayoutParams.MATCH_PARENT, ImageSwitcher.LayoutParams.MATCH_PARENT));
return imageView;
}
});
tr.addView(img[i], position);
}
}
isSetup = true;
//init view
updateIcons(new Drawable[]{null, null});
updateBrightness(defBrightness);
}
});
}
private Activity getActivity(View view)
{
Context context = view.getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
//alternative method
View content = view.findViewById(android.R.id.content);
if(content != null)
return (Activity) content.getContext();
else
return null;
}
}
| 9,702 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FeedbackClass.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/classes/FeedbackClass.java | /*
* FeedbackClass.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.classes;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import hcm.ssj.core.Log;
import hcm.ssj.core.event.Event;
import hcm.ssj.feedback.FeedbackManager;
import hcm.ssj.feedback.feedbackmanager.actions.Action;
import hcm.ssj.feedback.feedbackmanager.conditions.Condition;
/**
* Created by Johnny on 01.12.2014.
*/
public abstract class FeedbackClass
{
protected Type type;
protected Context context;
protected Condition condition = null;
protected Action action = null;
protected int level = 0;
protected FeedbackClass.Valence valence;
private ArrayList<FeedbackListener> listeners = new ArrayList<>();
protected FeedbackManager.Options options;
public static FeedbackClass create(XmlPullParser xml, Context context, FeedbackManager.Options options)
{
FeedbackClass f = null;
if(xml.getAttributeValue(null, "type").equalsIgnoreCase("visual"))
f = new Visual(context, options);
else if(xml.getAttributeValue(null, "type").equalsIgnoreCase("tactile"))
f = new Tactile(context, options);
else if(xml.getAttributeValue(null, "type").equalsIgnoreCase("audio"))
f = new Auditory(context, options);
else
throw new UnsupportedOperationException("feedback type "+ xml.getAttributeValue(null, "type") +" not yet implemented");
f.load(xml, context);
return f;
}
public int getLevel() {
return level;
}
public Valence getValence() {
return valence;
}
public void release()
{
action.release();
}
public Condition getCondition()
{
return condition;
}
public Action getAction()
{
return action;
}
/*
* called every frame by the manager
*/
public void update() {}
public void process(Event event)
{
if(!condition.checkEvent(event))
return;
if(action != null && execute(action)) {
action.lastExecutionTime = System.currentTimeMillis();
}
// Notify event listeners
callPostFeedback(event, action, condition.parseEvent(event));
}
private void callPostFeedback(final hcm.ssj.core.event.Event ssjEvent, final Action ev, final float value)
{
for (final FeedbackListener listener : listeners)
{
new Thread(new Runnable()
{
public void run()
{
listener.onPostFeedback(ssjEvent, ev, value);
}
}).start();
}
}
public abstract boolean execute(Action action);
protected void load(XmlPullParser xml, Context context)
{
try
{
xml.require(XmlPullParser.START_TAG, null, "feedback");
String level_str = xml.getAttributeValue(null, "level");
if(level_str != null)
level = Integer.parseInt(level_str);
String valence_str = xml.getAttributeValue(null, "valence");
if(valence_str != null)
valence = FeedbackClass.Valence.valueOf(valence_str);
while (xml.next() != XmlPullParser.END_DOCUMENT)
{
if (xml.getEventType() == XmlPullParser.START_TAG && xml.getName().equalsIgnoreCase("condition"))
{
condition = Condition.create(xml, context);
}
else if (xml.getEventType() == XmlPullParser.START_TAG && xml.getName().equalsIgnoreCase("action"))
{
action = Action.create(type, xml, context);
}
else if (xml.getEventType() == XmlPullParser.END_TAG && xml.getName().equalsIgnoreCase("feedback"))
break; //jump out once we reach end tag
}
}
catch(IOException | XmlPullParserException e)
{
Log.e("error parsing config file", e);
}
}
public void addFeedbackListener(FeedbackListener listener)
{
listeners.add(listener);
}
public long getLastExecutionTime()
{
return action.lastExecutionTime;
}
public enum Type
{
Visual,
Tactile,
Audio
}
public enum Valence
{
Unknown,
Desirable,
Undesirable
}
}
| 5,858 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FeedbackListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/classes/FeedbackListener.java | /*
* FeedbackListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.classes;
import hcm.ssj.feedback.feedbackmanager.actions.Action;
/**
* Created by Johnny on 03.06.2016.
*/
public interface FeedbackListener
{
void onPostFeedback(hcm.ssj.core.event.Event ssjEvent, Action action, float value);
}
| 1,632 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Tactile.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/classes/Tactile.java | /*
* Tactile.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.classes;
import android.content.Context;
import android.os.SystemClock;
import android.os.Vibrator;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.security.InvalidParameterException;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.feedback.BandComm;
import hcm.ssj.feedback.FeedbackManager;
import hcm.ssj.feedback.feedbackmanager.actions.Action;
import hcm.ssj.feedback.feedbackmanager.actions.TactileAction;
import hcm.ssj.myo.Vibrate2Command;
/**
* Created by Johnny on 01.12.2014.
*/
public class Tactile extends FeedbackClass
{
enum Device
{
Myo,
MsBand,
Android
}
boolean firstCall = true;
boolean connected = false;
private Myo myo = null;
private hcm.ssj.myo.Myo myoConnector = null;
private String deviceId;
private BandComm msband = null;
private Vibrate2Command cmd = null;
private Vibrator vibrator = null;
private long lock = 0;
private Device deviceType = Device.Myo;
public Tactile(Context context, FeedbackManager.Options options)
{
this.context = context;
this.options = options;
type = Type.Tactile;
}
public void firstCall()
{
firstCall = false;
connected = false;
if(deviceType == Device.Myo) {
Hub hub = Hub.getInstance();
if (hub.getConnectedDevices().isEmpty())
{
myoConnector = new hcm.ssj.myo.Myo();
myoConnector.options.macAddress.set(deviceId);
try
{
myoConnector.connect();
}
catch (hcm.ssj.core.SSJFatalException e)
{
e.printStackTrace();
}
}
long time = SystemClock.elapsedRealtime();
while (hub.getConnectedDevices().isEmpty() && SystemClock.elapsedRealtime() - time < Pipeline.getInstance().options.waitSensorConnect.get() * 1000) {
try {
Thread.sleep(Cons.SLEEP_IN_LOOP);
} catch (InterruptedException e) {
}
}
if (hub.getConnectedDevices().isEmpty())
throw new RuntimeException("device not found");
Log.i("connected to Myo");
connected = true;
myo = hub.getConnectedDevices().get(0);
cmd = new Vibrate2Command(hub);
}
else if(deviceType == Device.MsBand)
{
int id = deviceId == null ? 0 : Integer.valueOf(deviceId);
msband = new BandComm(id);
connected = true;
}
else if(deviceType == Device.Android)
{
vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (!vibrator.hasVibrator())
{
throw new RuntimeException("device can't vibrate");
}
connected = true;
}
}
@Override
public boolean execute(Action action)
{
if(firstCall)
firstCall();
if(!connected)
return false;
Log.i("execute");
TactileAction ev = (TactileAction) action;
//check locks
//global
if(System.currentTimeMillis() < lock)
{
Log.i("ignoring event, lock active for another " + (lock - System.currentTimeMillis()) + "ms");
return false;
}
//local
if (System.currentTimeMillis() - ev.lastExecutionTime < ev.lockSelf)
{
Log.i("ignoring event, self lock active for another " + (ev.lockSelf - (System.currentTimeMillis() - ev.lastExecutionTime)) + "ms");
return false;
}
if(deviceType == Device.Myo) {
Log.i("vibration " + ev.duration[0] + "/" + (int) ev.intensity[0]);
cmd.vibrate(myo, ev.duration, ev.intensity);
}
else if(deviceType == Device.MsBand) {
Log.i("vibration " + ev.vibrationType);
msband.vibrate(ev.vibrationType);
} else if(deviceType == Device.Android) {
Log.i("vibration on android");
long[] longDuration = new long[ev.duration.length];
for(int i=0; i < longDuration.length; ++i)
{
longDuration[i] = ev.duration[i];
}
vibrator.vibrate(longDuration, -1);
}
//set lock
if(ev.lock > 0)
lock = System.currentTimeMillis() + (long) ev.lock;
else
lock = 0;
return true;
}
public byte[] multiply(byte[] src, float mult)
{
byte dst[] = new byte[src.length];
int val_int;
for(int i = 0; i < src.length; ++i)
{
val_int = (int)((int)src[i] * mult);
if(val_int > 255)
val_int = 255;
dst[i] = (byte)val_int;
}
return dst;
}
protected void load(XmlPullParser xml, final Context context)
{
try {
xml.require(XmlPullParser.START_TAG, null, "feedback");
String device_name = xml.getAttributeValue(null, "device");
if (device_name != null) {
deviceType = Device.valueOf(device_name);
}
deviceId = xml.getAttributeValue(null, "deviceId");
}
catch(IOException | XmlPullParserException | InvalidParameterException e)
{
Log.e("error parsing config file", e);
}
super.load(xml, context);
}
@Override
public void release()
{
connected = false;
firstCall = true;
if(myoConnector != null)
try
{
myoConnector.disconnect();
}
catch (hcm.ssj.core.SSJFatalException e)
{
e.printStackTrace();
}
super.release();
}
}
| 7,277 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
VisualAction.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/actions/VisualAction.java | /*
* VisualAction.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.actions;
import android.content.Context;
import android.graphics.drawable.Drawable;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackClass;
import hcm.ssj.file.FileCons;
/**
* Created by Johnny on 01.12.2014.
*/
public class VisualAction extends Action
{
public Drawable icons[];
public int dur = 0;
public float brightness = 1;
public VisualAction()
{
type = FeedbackClass.Type.Visual;
}
protected void load(XmlPullParser xml, Context context)
{
super.load(xml, context);
try
{
xml.require(XmlPullParser.START_TAG, null, "action");
String res_str = xml.getAttributeValue(null, "res");
if(res_str == null)
throw new IOException("event resource not defined");
String[] icon_names = res_str.split("\\s*,\\s*");
if(icon_names.length > 2)
throw new IOException("unsupported amount of resources");
int num = icon_names.length;
icons = new Drawable[num];
for(int i = 0; i< icon_names.length; i++)
{
String assetsString = "assets:";
if(icon_names[i].startsWith(assetsString))
{
icons[i] = Drawable.createFromStream(context.getAssets().open(icon_names[i].substring(assetsString.length())), null);
}
else {
String path = FileCons.SSJ_EXTERNAL_STORAGE + File.separator + icon_names[i];
icons[i] = Drawable.createFromStream(new FileInputStream(path), null);
}
}
String bright_str = xml.getAttributeValue(null, "brightness");
if (bright_str != null)
brightness = Float.valueOf(bright_str);
String dur_str = xml.getAttributeValue(null, "duration");
if (dur_str != null)
dur = Integer.valueOf(dur_str);
}
catch(IOException | XmlPullParserException e)
{
Log.e("error parsing config file", e);
}
}
}
| 3,689 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TactileAction.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/actions/TactileAction.java | /*
* TactileAction.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.actions;
import android.content.Context;
import com.microsoft.band.notifications.VibrationType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackClass;
/**
* Created by Johnny on 01.12.2014.
*/
public class TactileAction extends Action
{
public int[] duration = {500};
public byte[] intensity = {(byte)150};
public VibrationType vibrationType = VibrationType.NOTIFICATION_ONE_TONE;
public TactileAction()
{
type = FeedbackClass.Type.Tactile;
}
protected void load(XmlPullParser xml, Context context)
{
super.load(xml, context);
try
{
xml.require(XmlPullParser.START_TAG, null, "action");
String str = xml.getAttributeValue(null, "intensity");
if(str != null) intensity = parseByteArray(str, ",");
str = xml.getAttributeValue(null, "duration");
if(str != null) duration = parseIntArray(str, ",");
str = xml.getAttributeValue(null, "type");
if(str != null) vibrationType = VibrationType.valueOf(str);
}
catch(IOException | XmlPullParserException e)
{
Log.e("error parsing config file", e);
}
}
}
| 2,739 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioAction.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/actions/AudioAction.java | /*
* AudioAction.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.actions;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.SoundPool;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.IOException;
import hcm.ssj.core.Log;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackClass;
import hcm.ssj.file.FileCons;
/**
* Created by Johnny on 01.12.2014.
*/
public class AudioAction extends Action
{
Context _context = null;
public AssetFileDescriptor fd = null;
public float intensity = 1;
public int soundId;
private String res;
public AudioAction()
{
type = FeedbackClass.Type.Audio;
}
protected void load(XmlPullParser xml, Context context)
{
super.load(xml, context);
_context = context;
try
{
res = xml.getAttributeValue(null, "res");
if(res == null)
throw new IOException("no sound defined");
if(res.startsWith("assets:"))
{
fd = context.getAssets().openFd(res.substring(7));
}
else
{
res = FileCons.SSJ_EXTERNAL_STORAGE + File.separator + res;
}
String intensity_str = xml.getAttributeValue(null, "intensity");
if(intensity_str != null)
intensity = Float.valueOf(intensity_str);
}
catch(IOException e)
{
Log.e("error parsing config file", e);
}
}
public void registerWithPlayer(SoundPool player)
{
try
{
if(fd != null)
{
soundId = player.load(fd, 1);
fd.close();
}
else
{
soundId = player.load(res, 1);
}
}
catch (IOException e)
{
Log.e("error loading audio files", e);
}
}
}
| 3,303 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Action.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/feedback/feedbackmanager/actions/Action.java | /*
* Action.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.feedback.feedbackmanager.actions;
import android.content.Context;
import org.xmlpull.v1.XmlPullParser;
import hcm.ssj.feedback.feedbackmanager.classes.FeedbackClass;
/**
* Created by Johnny on 01.12.2014.
*/
public class Action
{
protected static int s_id = 0;
public long lastExecutionTime = 0;
protected int id;
protected FeedbackClass.Type type;
public int lock = 0;
public int lockSelf = 0;
protected Action()
{
id = s_id++;
}
public static Action create(FeedbackClass.Type feedback_type, XmlPullParser xml, Context context)
{
Action i = null;
if (feedback_type == FeedbackClass.Type.Visual)
i = new VisualAction();
else if (feedback_type == FeedbackClass.Type.Tactile)
i = new TactileAction();
else if (feedback_type == FeedbackClass.Type.Audio)
i = new AudioAction();
else
i = new Action();
i.load(xml, context);
return i;
}
public void release()
{}
protected void load(XmlPullParser xml, Context context)
{
String lock_str = xml.getAttributeValue(null, "lock");
if(lock_str != null)
lock = Integer.valueOf(lock_str);
lock_str = xml.getAttributeValue(null, "lockSelf");
if(lock_str != null)
lockSelf = Integer.valueOf(lock_str);
}
public int[] parseIntArray(String str, String delim)
{
String arr[] = str.split(delim);
int out[] = new int[arr.length];
for(int i = 0; i < arr.length; ++i)
out[i] = Integer.valueOf(arr[i]);
return out;
}
public byte[] parseByteArray(String str, String delim)
{
String arr[] = str.split(delim);
byte out[] = new byte[arr.length];
for(int i = 0; i < arr.length; ++i)
out[i] = (byte)Integer.valueOf(arr[i]).intValue();
return out;
}
@Override
public String toString()
{
return type.toString() + "_" + id;
}
}
| 3,342 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
PlaybackListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/PlaybackListener.java | /*
* PlaybackListener.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
/**
* Created by hiwi on 04.12.2017.
*/
public interface PlaybackListener
{
void onProgress(int progress);
void onCompletion();
}
| 1,513 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioDecoder.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioDecoder.java | /*
* AudioDecoder.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import hcm.ssj.core.Log;
import hcm.ssj.file.FileCons;
/**
* Class that is responsible for decoding of audio files into a sequence of raw bytes.
* Bytes are represented in little-endian ordering.
* Supports and was tested with mp3, mp4, and wav files.
*/
public final class AudioDecoder
{
private static final int EOF = -1;
private int sampleRate;
private int channelCount;
private int audioLength;
private short[] samples;
public AudioDecoder(String filepath)
{
try
{
File rawAudio = decode(filepath);
samples = getAudioSample(rawAudio);
int sampleCount = samples.length;
audioLength = calculateAudioLength(sampleCount, sampleRate, channelCount);
}
catch (IOException e)
{
Log.e("Audio file with the given path couldn't be decoded: " + e.getMessage());
}
}
/**
* Calculates the length of the audio file in milliseconds.
* @param sampleCount Number of samples.
* @param sampleRate Sample rate (i.e. 16000, 44100, ..)
* @param channelCount Number of audio channels.
* @return length of audio file in seconds.
*/
private int calculateAudioLength(int sampleCount, int sampleRate, int channelCount)
{
return ((sampleCount / channelCount) * 1000) / sampleRate;
}
/**
* Converts given raw audio file to a byte array.
* @return Byte array in little-endian byte order.
* @throws IOException If given file couldn't be read.
*/
private short[] getAudioSample(File file) throws IOException
{
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int bytesRead = fileInputStream.read(data);
short[] samples = null;
if (bytesRead != EOF)
{
ShortBuffer sb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
samples = new short[sb.limit()];
sb.get(samples);
}
return samples;
}
public int getSampleRate()
{
return sampleRate;
}
public short[] getSamples()
{
return samples;
}
public int getAudioLength()
{
return audioLength;
}
/**
* Decodes audio file into a raw file. This method accepts audio file formats with valid
* headers (like .mp3, .mp4, and .wav).
* @param filepath Path of the file to decode.
* @return Decoded raw audio file.
* @throws IOException when file cannot be read.
*/
private File decode(String filepath) throws IOException
{
// Set selected audio file as a source.
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(filepath);
// Get audio format.
MediaFormat format = extractor.getTrackFormat(0);
String mime = format.getString(MediaFormat.KEY_MIME);
// Cache necessary audio attributes.
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
// Create and configure decoder based on audio format.
MediaCodec decoder = MediaCodec.createDecoderByType(mime);
decoder.configure(format, null, null, 0);
decoder.start();
// Create input/output buffers.
ByteBuffer[] inputBuffers = decoder.getInputBuffers();
ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
extractor.selectTrack(0);
File dst = new File(FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "output.raw");
FileOutputStream f = new FileOutputStream(dst);
boolean endOfStreamReached = false;
while (true)
{
if (!endOfStreamReached)
{
int inputBufferIndex = decoder.dequeueInputBuffer(10 * 1000);
if (inputBufferIndex >= 0)
{
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
int sampleSize = extractor.readSampleData(inputBuffer, 0);
if (sampleSize < 0)
{
// Pass empty buffer and the end of stream flag to the codec.
decoder.queueInputBuffer(inputBufferIndex, 0, 0,
0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
endOfStreamReached = true;
}
else
{
// Pass data-filled buffer to the decoder.
decoder.queueInputBuffer(inputBufferIndex, 0, sampleSize,
extractor.getSampleTime(), 0);
extractor.advance();
}
}
}
int outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 10 * 1000);
if (outputBufferIndex >= 0)
{
ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
byte[] data = new byte[bufferInfo.size];
outputBuffer.get(data);
outputBuffer.clear();
if (data.length > 0)
{
f.write(data, 0, data.length);
}
decoder.releaseOutputBuffer(outputBufferIndex, false);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
{
endOfStreamReached = true;
}
}
else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED)
{
outputBuffers = decoder.getOutputBuffers();
}
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
{
return dst;
}
}
}
}
| 6,575 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioChannel.java | /*
* AudioChannel.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.SensorChannel;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Audio Sensor - get data from audio interface and forwards it
* Created by Johnny on 05.03.2015.
*/
public class AudioChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 8000, Integer.class, "");
public final Option<Cons.ChannelFormat> channelConfig = new Option<>("channelConfig", Cons.ChannelFormat.CHANNEL_IN_MONO, Cons.ChannelFormat.class, "");
public final Option<Cons.AudioFormat> audioFormat = new Option<>("audioFormat", Cons.AudioFormat.ENCODING_PCM_16BIT, Cons.AudioFormat.class, "");
public final Option<Boolean> scale = new Option<>("scale", true, Boolean.class, "");
public final Option<Double> chunk = new Option<>("chunk", 0.1, Double.class, "how many samples to read at once (in seconds)");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected AudioRecord _recorder;
byte[] _data = null;
public AudioChannel()
{
_name = "Microphone_Audio";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
//setup android audio middleware
_recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, options.sampleRate.get(), options.channelConfig.get().val, options.audioFormat.get().val, stream_out.tot*10);
int state = _recorder.getState();
if (state != 1)
{
Log.w("unexpected AudioRecord state = " + state);
}
if(options.scale.get())
{
if (options.audioFormat.get() != Cons.AudioFormat.ENCODING_PCM_8BIT && options.audioFormat.get() != Cons.AudioFormat.ENCODING_PCM_16BIT)
{
Log.e("unsupported audio format for normalization");
}
int numBytes = Microphone.audioFormatSampleBytes(options.audioFormat.get().val);
_data = new byte[stream_out.num * stream_out.dim * numBytes];
}
//startRecording has to be called as close to the first read as possible.
_recorder.startRecording();
Log.i("Audio capturing started");
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if(!options.scale.get())
{
//read data
// this is blocking and thus defines the update rate
switch (options.audioFormat.get())
{
case ENCODING_PCM_8BIT:
_recorder.read(stream_out.ptrB(), 0, stream_out.num * stream_out.dim);
break;
case ENCODING_PCM_16BIT:
case ENCODING_DEFAULT:
_recorder.read(stream_out.ptrS(), 0, stream_out.num * stream_out.dim);
break;
default:
Log.w("unsupported audio format");
return false;
}
}
else
{
//read data
// this is blocking and thus defines the update rate
_recorder.read(_data, 0, _data.length);
//normalize it and convert it to floats
float[] outf = stream_out.ptrF();
int i = 0, j = 0;
while (i < _data.length)
{
switch (options.audioFormat.get())
{
case ENCODING_PCM_8BIT:
outf[j++] = _data[i++] / 128.0f;
break;
case ENCODING_PCM_16BIT:
case ENCODING_DEFAULT:
outf[j++] = ((short) ((_data[i + 1] & 0xFF) << 8 | (_data[i] & 0xFF))) / 32768.0f;
i += 2;
break;
default:
Log.w("unsupported audio format");
return false;
}
}
}
return true;
}
@Override
public void flush(Stream stream_out) throws SSJFatalException
{
_recorder.stop();
_recorder.release();
}
@Override
public int getSampleDimension()
{
switch(options.channelConfig.get())
{
case CHANNEL_IN_MONO:
return 1;
case CHANNEL_IN_STEREO:
return 2;
}
return 0;
}
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
@Override
public int getSampleNumber()
{
int minBufSize = AudioRecord.getMinBufferSize(options.sampleRate.get(), options.channelConfig.get().val, options.audioFormat.get().val);
int bytesPerSample = Microphone.audioFormatSampleBytes(options.audioFormat.get().val);
int dim = getSampleDimension();
double sr = getSampleRate();
int minSampleNum = (minBufSize / (bytesPerSample * dim));
double minFrameSize = minSampleNum / sr;
if(options.chunk.get() < minFrameSize) {
Log.w("requested chunk size too small, setting it to " + minFrameSize + "s");
options.chunk.set(minFrameSize);
}
return (int)(options.chunk.get() * sr + 0.5);
}
@Override
public int getSampleBytes()
{
if(options.scale.get())
return 4;
else
return Microphone.audioFormatSampleBytes(options.audioFormat.get().val);
}
@Override
public Cons.Type getSampleType()
{
if(options.scale.get())
return Cons.Type.FLOAT;
else
return Microphone.audioFormatSampleType(options.audioFormat.get().val);
}
@Override
public void describeOutput(Stream stream_out)
{
stream_out.desc = new String[1];
stream_out.desc[0] = "Audio";
}
}
| 7,561 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SpeechRate.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/SpeechRate.java | /*
* SpeechRate.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import java.util.Iterator;
import java.util.LinkedList;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Util;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
/**
* Computes the SpeechRate of the input signal
* Algorithm by Nivja H. De Jong
* - uses audio processing tools from TarsosDSP
* Created by Johnny on 05.03.2015.
*/
public class SpeechRate extends Consumer
{
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", "SpeechRate", String.class, "event sender name, written in every event");
public final Option<String> event = new Option<>("event", "SpeechRate", String.class, "event name");
public final Option<Float> thresholdVoicedProb = new Option<>("thresholdVoicedProb", 0.5f, Float.class, "in Hz");
public final Option<Float> intensityIgnoranceLevel = new Option<>("intensityIgnoranceLevel", 1.0f, Float.class, "in dB");
public final Option<Float> minDipBetweenPeaks = new Option<>("minDipBetweenPeaks", 3.0f, Float.class, "in dB");
public final Option<Integer> width = new Option<>("width", 3, Integer.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private Stream _intensity = null;
private Stream _voiced = null;
private int _intensity_ind = -1;
private int _voiced_ind = -1;
private float[] _tmp = new float[512];
public SpeechRate()
{
_name = "SpeechRate";
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
for(Stream s : stream_in)
{
if (_intensity_ind < 0)
{
_intensity_ind = s.findDataClass("Intensity");
if (_intensity_ind >= 0)
{
_intensity = s;
}
}
if (_voiced_ind < 0)
{
_voiced_ind = s.findDataClass("VoicedProb");
if (_voiced_ind >= 0)
{
_voiced = s;
}
}
}
if((_intensity == null || _intensity.type != Cons.Type.FLOAT)
|| (_voiced == null || _voiced.type != Cons.Type.FLOAT))
{
throw new SSJFatalException("invalid input configuration. SPL Energy (double) and VoicedProb (float) is required.");
}
if (_evchannel_out == null)
{
Log.e("no outgoing event channel has been registered");
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
float[] intensity = _intensity.select(_intensity_ind).ptrF();
float[] voiced = _voiced.ptrF();
Log.ds("computing sr for " + _intensity.num + " samples");
//compute peaks
LinkedList<Integer> peaks = findPeaks(intensity, _intensity.num, options.intensityIgnoranceLevel.get(), options.minDipBetweenPeaks.get());
Log.ds("peaks (pre-cull) = " + peaks.size());
//remove non-voiced peaks
Iterator<Integer> peak = peaks.iterator();
int i,j;
double t;
while (peak.hasNext())
{
i = peak.next();
t = _intensity.time + i * _intensity.step;
j = (int)((t - _voiced.time) / _voiced.step);
if (j >= _voiced.num)
{
j = _voiced.num - 1;
}
if (voiced[j * _voiced.dim + _voiced_ind] < options.thresholdVoicedProb.get())
{
peak.remove();
}
}
double duration = stream_in[0].num / stream_in[0].sr;
Log.ds("peaks = " + peaks.size() + ", sr = " + peaks.size() / duration);
Event ev = Event.create(Cons.Type.STRING);
ev.sender = options.sender.get();
ev.name = options.event.get();
ev.time = (int)(1000 * stream_in[0].time + 0.5);
ev.dur = (int)(1000 * duration + 0.5);
ev.state = Event.State.COMPLETED;
ev.setData("<tuple string=\"Speechrate (syllables/sec)\" value=\""+ (peaks.size() / duration) +"\" />");
_evchannel_out.pushEvent(ev);
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{}
/**
* Reimplementaiton of Jong and Wempe's PRAAT peak detector for speech rate analysis as described in
* N.H. De Jong and T. Wempe, Praat script to detect syllable nuclei and measure speech rate automatically, 2009, doi:10.3758/BRM.41.2.385
* @param data audio intensity
* @param threshold threshold to be applied above median
*/
private LinkedList<Integer> findPeaks(float[] data, int length, double threshold, double minDip)
{
float min = Util.min(data, 0, length);
if(_tmp.length < length)
_tmp = new float[length];
System.arraycopy(data, 0, _tmp, 0, length);
double med = Util.median(_tmp, 0, length);
threshold += med;
if(threshold < min)
threshold = min;
int width = options.width.get();
if(width == 0) width = 1;
LinkedList<Integer> peaks = findPeaks_(data, length, width, threshold);
if(peaks.size() == 0)
return peaks;
Log.ds("peaks (pre-mindip-cull) = " + peaks.size());
Iterator<Integer> i = peaks.iterator();
int prev = i.next();
int current;
double minLocal;
while(i.hasNext())
{
current = i.next();
//find min between the two peaks
minLocal = Util.min(data, prev, current - prev);
if(Math.abs(data[current] - minLocal) <= minDip)
i.remove();
else
prev = current;
}
return peaks;
}
private LinkedList<Integer> findPeaks_(float[] data, int length, int width, double threshold) {
return findPeaks_(data, length, width, threshold, 0.0D, false);
}
private LinkedList<Integer> findPeaks_(float[] data, int length, int width, double threshold, double decayRate, boolean isRelative) {
LinkedList<Integer> peaks = new LinkedList<>();
int mid = 0;
int end = length;
for(double av = data[0]; mid < end; ++mid) {
av = decayRate * av + (1.0D - decayRate) * data[mid];
if(av < data[mid]) {
av = data[mid];
}
int i = mid - width;
if(i < 0) {
i = 0;
}
int stop = mid + width + 1;
if(stop > length) {
stop = length;
}
int var15;
for(var15 = i++; i < stop; ++i) {
if(data[i] > data[var15]) {
var15 = i;
}
}
if(var15 == mid) {
if(overThreshold(data, length, var15, width, threshold, isRelative, av)) {
peaks.add(var15);
}
}
}
return peaks;
}
boolean overThreshold(float[] data, int length, int index, int width, double threshold, boolean isRelative, double av)
{
if(data[index] < av) {
return false;
} else if(!isRelative) {
return data[index] > threshold;
} else {
int iStart = index - 3 * width;
if(iStart < 0) {
iStart = 0;
}
int iStop = index + 1 * width;
if(iStop > length) {
iStop = length;
}
double sum = 0.0D;
int count;
for(count = iStop - iStart; iStart < iStop; iStart++) {
sum += data[iStart];
}
return data[index] > sum / (double)count + threshold;
}
}
@Override
public void clear()
{
super.clear();
_intensity = null;
_voiced = null;
_intensity_ind = -1;
_voiced_ind = -1;
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 9,578 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
WavWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/WavWriter.java | /*
* WavWriter.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import android.media.AudioFormat;
import android.text.TextUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Util;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.FolderPath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.IFileWriter;
/**
* Writes wav files.<br>
* Created by Frank Gaibler and Ionut Damian on 12.12.2016.
*/
public class WavWriter extends Consumer implements IFileWriter
{
@Override
public OptionList getOptions()
{
return options;
}
private enum DataFormat
{
BYTE(Microphone.audioFormatSampleBytes(AudioFormat.ENCODING_PCM_8BIT)),
SHORT(Microphone.audioFormatSampleBytes(AudioFormat.ENCODING_PCM_16BIT)),
FLOAT_8(BYTE.size),
FLOAT_16(SHORT.size);
private int size;
/**
* @param i int
*/
DataFormat(int i)
{
size = i;
}
}
//encoder
protected double dFrameRate;
//
protected byte[] aByShuffle;
protected long lFrameIndex;
//
protected File file = null;
private BufferedOutputStream outputStream;
public final WavWriter.Options options = new WavWriter.Options();
//
private int iSampleRate;
private int iSampleNumber;
private int iSampleDimension;
//
private WavWriter.DataFormat dataFormat = null;
/**
* All options for the audio writer
*/
public class Options extends IFileWriter.Options
{
public final Option<Cons.AudioFormat> audioFormat = new Option<>("audioFormat", Cons.AudioFormat.ENCODING_DEFAULT, Cons.AudioFormat.class, "");
/**
*
*/
private Options()
{
super();
addOptions();
}
}
/**
*
*/
public WavWriter()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 1)
{
throw new SSJFatalException("Stream count not supported");
}
switch (stream_in[0].type)
{
case BYTE:
{
dataFormat = WavWriter.DataFormat.BYTE;
break;
}
case SHORT:
{
dataFormat = WavWriter.DataFormat.SHORT;
break;
}
case FLOAT:
{
if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_DEFAULT || options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_16BIT)
{
dataFormat = WavWriter.DataFormat.FLOAT_16;
} else if (options.audioFormat.get() == Cons.AudioFormat.ENCODING_PCM_8BIT)
{
dataFormat = WavWriter.DataFormat.FLOAT_8;
} else
{
throw new SSJFatalException("Audio format not supported");
}
break;
}
default:
{
throw new SSJFatalException("Stream type not supported");
}
}
try
{
initFiles(stream_in[0], options);
}
catch (IOException e)
{
throw new SSJFatalException("error initializing files", e);
}
Log.d("Format: " + dataFormat.toString());
iSampleRate = (int) stream_in[0].sr;
iSampleDimension = stream_in[0].dim;
iSampleNumber = iSampleRate * dataFormat.size * iSampleDimension;
//recalculate frame rate
dFrameRate = stream_in[0].sr / stream_in[0].num;
aByShuffle = new byte[(int) (iSampleNumber / dFrameRate + 0.5)];
lFrameIndex = 0;
try
{
outputStream = new BufferedOutputStream(new FileOutputStream(file));
} catch (IOException ex)
{
throw new SSJFatalException("RawEncoder creation failed: " + ex.getMessage());
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
switch (dataFormat)
{
case BYTE:
{
byte[] in = stream_in[0].ptrB();
for (int i = 0; i < in.length; i += aByShuffle.length)
{
System.arraycopy(in, i, aByShuffle, 0, aByShuffle.length);
write(aByShuffle);
}
break;
}
case SHORT:
{
short[] in = stream_in[0].ptrS();
for (int i = 0; i < in.length; i += aByShuffle.length)
{
ByteBuffer.wrap(aByShuffle).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(in, i / 2, aByShuffle.length / 2);
write(aByShuffle);
}
break;
}
case FLOAT_8:
float[] in = stream_in[0].ptrF();
for (int i = 0; i < in.length; )
{
for (int j = 0; j < aByShuffle.length; j++, i += aByShuffle.length)
{
aByShuffle[j] = (byte) (in[i] * 128);
}
write(aByShuffle);
}
break;
case FLOAT_16:
{
float[] in16 = stream_in[0].ptrF();
for (int i = 0; i < in16.length; )
{
for (int j = 0; j < aByShuffle.length; i++, j += 2)
{
short value = (short) (in16[i] * 32768);
aByShuffle[j] = (byte) (value & 0xff);
aByShuffle[j + 1] = (byte) ((value >> 8) & 0xff);
}
write(aByShuffle);
}
break;
}
default:
{
Log.e("Data format not supported");
break;
}
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
if (outputStream != null)
{
try
{
outputStream.flush();
outputStream.close();
} catch (IOException ex)
{
Log.e("RawEncoder closing: " + ex.getMessage());
}
}
try
{
writeWavHeader(file);
}
catch (IOException e)
{
throw new SSJFatalException("error writing header", e);
}
dataFormat = null;
}
/**
* Checks for file consistency
*
* @param in Input stream
* @param options Options
* @throws IOException IO Exception
*/
protected final void initFiles(Stream in, Options options) throws IOException
{
if (options.filePath.get() == null)
{
Log.w("file path not set, setting to default " + FileCons.SSJ_EXTERNAL_STORAGE);
options.filePath.set(new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE));
}
File fileDirectory = Util.createDirectory(options.filePath.parseWildcards());
if (options.fileName.get() == null)
{
String defaultName = TextUtils.join("_", in.desc) + ".wav";
Log.w("file name not set, setting to " + defaultName);
options.fileName.set(defaultName);
}
file = new File(fileDirectory, options.fileName.get());
}
/**
* @param frameData byte[]
*/
protected final void write(byte[] frameData)
{
try
{
outputStream.write(frameData, 0, frameData.length);
} catch (IOException ex)
{
Log.e("RawEncoder: " + ex.getMessage());
}
}
/**
* Writes a PCM Wav header at the start of the provided file
* code taken from : http://stackoverflow.com/questions/9179536/writing-pcm-recorded-data-into-a-wav-file-java-android
* by: Oliver Mahoney, Oak Bytes
* @param fileToConvert File
*/
private void writeWavHeader(File fileToConvert) throws IOException
{
long mySubChunk1Size = 16;
int myBitsPerSample = 16;
int myFormat = 1;
long myChannels = iSampleDimension;
long mySampleRate = iSampleRate;
long myByteRate = mySampleRate * myChannels * myBitsPerSample / 8;
int myBlockAlign = (int) (myChannels * myBitsPerSample / 8);
int size = (int) fileToConvert.length();
byte[] bytes = new byte[size];
try
{
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(fileToConvert));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
long myDataSize = bytes.length;
long myChunk2Size = myDataSize * myChannels * myBitsPerSample / 8;
long myChunkSize = 36 + myChunk2Size;
OutputStream os;
os = new FileOutputStream(new File(fileToConvert.getPath()));
BufferedOutputStream bos = new BufferedOutputStream(os);
DataOutputStream outFile = new DataOutputStream(bos);
outFile.writeBytes("RIFF"); // 00 - RIFF
outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file?
outFile.writeBytes("WAVE"); // 08 - WAVE
outFile.writeBytes("fmt "); // 12 - fmt
outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk
outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation
outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???)
outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second)
outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second
outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels
outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24
outFile.writeBytes("data"); // 36 - data
outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk
outFile.write(bytes); // 44 - the actual data itself - just a long string of numbers
outFile.flush();
outFile.close();
/*
if (!fileToConvert.delete())
{
throw new IOException("error deleting temp file");
}
*/
}
/**
* Code taken from : http://stackoverflow.com/questions/9179536/writing-pcm-recorded-data-into-a-wav-file-java-android
* by: Oliver Mahoney, Oak Bytes
*/
private static byte[] intToByteArray(int i)
{
byte[] b = new byte[4];
b[0] = (byte) (i & 0x00FF);
b[1] = (byte) ((i >> 8) & 0x000000FF);
b[2] = (byte) ((i >> 16) & 0x000000FF);
b[3] = (byte) ((i >> 24) & 0x000000FF);
return b;
}
/**
* Convert a short to a byte array
* code taken from : http://stackoverflow.com/questions/9179536/writing-pcm-recorded-data-into-a-wav-file-java-android
* by: Oliver Mahoney, Oak Bytes
*/
private static byte[] shortToByteArray(short data)
{
return new byte[]{(byte) (data & 0xff), (byte) ((data >>> 8) & 0xff)};
}
}
| 13,859 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioUtils.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioUtils.java | /*
* AudioUtils.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
import java.util.Arrays;
/**
* Collection of helper methods for audio.
*/
public final class AudioUtils
{
/**
* Prevent class from being instantiated.
*/
private AudioUtils() {}
/**
* Calculate highest and lowest points in given byte array.
* @param data Audio sample.
* @param sampleSize Size of the given audio sample.
* @return Two dimensional byte array of minimums and maximums.
*/
public static short[][] getExtremes(short[] data, int sampleSize)
{
short[][] newData = new short[sampleSize][];
int groupSize = data.length / sampleSize;
for (int i = 0; i < sampleSize; i++)
{
short[] group = Arrays.copyOfRange(data, i * groupSize,
Math.min((i + 1) * groupSize, data.length));
short min = Short.MAX_VALUE;
short max = Short.MIN_VALUE;
for (short a : group)
{
min = (short) Math.min(min, a);
max = (short) Math.max(max, a);
}
newData[i] = new short[] { max, min };
}
return newData;
}
}
| 2,344 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioUtil.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/audio/AudioUtil.java | /*
* AudioUtil.java
* Copyright (c) 2018
* Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura,
* Vitalijs Krumins, Antonio Grieco
* *****************************************************
* This file is part of the Social Signal Interpretation for Java (SSJ) framework
* developed at the Lab for Human Centered Multimedia of the University of Augsburg.
*
* SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a
* one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend
* to offer SSI's comprehensive functionality and performance (this is java after all).
* Nevertheless, SSJ borrows a lot of programming patterns from SSI.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package hcm.ssj.audio;
/**
* Created by Ionut Damian on 21.12.2017.
*/
public class AudioUtil
{
/**
* Modified Bessel function I0. Abramowicz and Stegun, p. 378.
*
* Based on code from the PRAAT Toolbox by Paul Boersma and David Weenink.
* http://www.fon.hum.uva.nl/praat/
*
* @param x Input
* @return Output
*/
public static double bessel_i0_f(double x)
{
if (x < 0.0) return bessel_i0_f(-x);
if (x < 3.75)
{
/* Formula 9.8.1. Accuracy 1.6e-7. */
double t = x / 3.75;
t *= t;
return 1.0 + t * (3.5156229 + t * (3.0899424 + t * (1.2067492
+ t * (0.2659732 + t * (0.0360768 + t * 0.0045813)))));
}
/*
otherwise: x >= 3.75
*/
/* Formula 9.8.2. Accuracy of the polynomial factor 1.9e-7. */
double t = 3.75 / x; /* <= 1.0 */
return Math.exp(x) / Math.sqrt(x) * (0.39894228 + t * (0.01328592
+ t * (0.00225319 + t * (-0.00157565 + t * (0.00916281
+ t * (-0.02057706 + t * (0.02635537 + t * (-0.01647633
+ t * 0.00392377))))))));
}
}
| 2,386 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.