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 |
---|---|---|---|---|---|---|---|---|---|---|---|
BoolStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/BoolStream.java | /*
* BoolStream.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.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class BoolStream extends Stream
{
private boolean[] _ptr;
public BoolStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 1;
this.type = Cons.Type.BOOL;
tot = num * dim * bytes;
_ptr = new boolean[num * dim];
}
@Override
public boolean[] ptr()
{
return _ptr;
}
public boolean[] ptrBool()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new boolean[num * dim];
}
}
public BoolStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
BoolStream slice = new BoolStream(num, new_dims.length, sr);
slice.source = source;
boolean[] src = this.ptr();
boolean[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public BoolStream select(int new_dim)
{
if(dim == 1)
return this;
BoolStream slice = new BoolStream(num, 1, sr);
slice.source = source;
boolean[] src = this.ptr();
boolean[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
BoolStream copy = new BoolStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,374 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CharStream.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/stream/CharStream.java | /*
* CharStream.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.core.stream;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 11.06.2015.
*/
public class CharStream extends Stream
{
private char[] _ptr;
public CharStream(int num, int dim, double sr)
{
super(num, dim, sr);
this.bytes = 2;
this.type = Cons.Type.CHAR;
tot = num * dim * bytes;
_ptr = new char[num * dim];
}
@Override
public char[] ptr()
{
return _ptr;
}
public char[] ptrC()
{
return _ptr;
}
public void adjust(int num)
{
if(num < this.num)
{
this.num = num;
this.tot = num * dim * bytes;
}
else
{
this.num = num;
this.tot = num * dim * bytes;
_ptr = new char[num * dim];
}
}
public CharStream select(int[] new_dims)
{
if(dim == new_dims.length)
return this;
CharStream slice = new CharStream(num, new_dims.length, sr);
slice.source = source;
char[] src = this.ptr();
char[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
for(int i = 0; i < new_dims.length; i++)
dst[dstPos++] = src[srcPos + new_dims[i]];
srcPos += dim;
}
return slice;
}
public CharStream select(int new_dim)
{
if(dim == 1)
return this;
CharStream slice = new CharStream(num, 1, sr);
slice.source = source;
char[] src = this.ptr();
char[] dst = slice.ptr();
int srcPos = 0, dstPos = 0;
while(srcPos < num * dim)
{
dst[dstPos++] = src[srcPos + new_dim];
srcPos += dim;
}
return slice;
}
@Override
public Stream clone()
{
CharStream copy = new CharStream(num, dim, sr);
System.arraycopy(_ptr, 0, copy._ptr, 0, _ptr.length);
return copy;
}
}
| 3,344 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Event.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/Event.java | /*
* Event.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.core.event;
import java.io.Serializable;
import java.util.Map;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public abstract class Event implements Serializable
{
public enum State
{
COMPLETED,
CONTINUED
}
public String name;
public String sender;
public long time;
public int dur;
public State state;
public Cons.Type type;
public int id;
public static Event create(Cons.Type type)
{
switch(type)
{
case BYTE:
return new ByteEvent();
case CHAR:
case STRING:
return new StringEvent();
case SHORT:
return new ShortEvent();
case INT:
return new IntEvent();
case LONG:
return new LongEvent();
case FLOAT:
return new FloatEvent();
case DOUBLE:
return new DoubleEvent();
case BOOL:
return new BoolEvent();
case EMPTY:
return new EmptyEvent();
case MAP:
return new MapEvent();
default:
throw new UnsupportedOperationException("Event type not supported");
}
}
public Event()
{
this.name = "";
this.sender = "";
this.time = 0;
this.dur = 0;
this.state = State.COMPLETED;
}
public abstract void setData(Object data);
public void setData(byte[] data) { throw new UnsupportedOperationException(); }
public void setData(char[] data) { throw new UnsupportedOperationException(); }
public void setData(int[] data) { throw new UnsupportedOperationException(); }
public void setData(long[] data) { throw new UnsupportedOperationException(); }
public void setData(float[] data) { throw new UnsupportedOperationException(); }
public void setData(double[] data) { throw new UnsupportedOperationException(); }
public void setData(boolean[] data) { throw new UnsupportedOperationException(); }
public void setData(String data) { throw new UnsupportedOperationException(); }
public void setData(Map<String, String> data) { throw new UnsupportedOperationException(); }
public abstract Object ptr();
public byte[] ptrB() { throw new UnsupportedOperationException(); }
public char[] ptrC() { throw new UnsupportedOperationException(); }
public short[] ptrShort() { throw new UnsupportedOperationException(); }
public int[] ptrI() { throw new UnsupportedOperationException(); }
public long[] ptrL() { throw new UnsupportedOperationException(); }
public float[] ptrF() { throw new UnsupportedOperationException(); }
public double[] ptrD() { throw new UnsupportedOperationException(); }
public boolean[] ptrBool() { throw new UnsupportedOperationException(); }
public String ptrStr() { throw new UnsupportedOperationException(); }
public Map<String, String> ptrMap() { throw new UnsupportedOperationException(); }
}
| 4,432 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ShortEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/ShortEvent.java | /*
* ShortEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class ShortEvent extends Event {
public short[] data;
public ShortEvent() {
type = Cons.Type.SHORT;
data = null;
}
public ShortEvent(short[] data) {
type = Cons.Type.SHORT;
this.data = data;
}
public short[] ptr() {
return data;
}
public short[] ptrShort() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (short[])data;
}
public void setData(short[] data) {
this.data = data;
}
}
| 2,073 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
DoubleEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/DoubleEvent.java | /*
* DoubleEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class DoubleEvent extends Event {
public double[] data;
public DoubleEvent() {
type = Cons.Type.DOUBLE;
data = null;
}
public DoubleEvent(double[] data) {
type = Cons.Type.DOUBLE;
this.data = data;
}
public double[] ptr() {
return data;
}
public double[] ptrD() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (double[])data;
}
public void setData(double[] data) {
this.data = data;
}
}
| 2,081 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BoolEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/BoolEvent.java | /*
* BoolEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class BoolEvent extends Event {
public boolean[] data;
public BoolEvent() {
type = Cons.Type.BOOL;
data = null;
}
public BoolEvent(boolean[] data) {
type = Cons.Type.BOOL;
this.data = data;
}
public boolean[] ptr() {
return data;
}
public boolean[] ptrBool() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (boolean[])data;
}
public void setData(boolean[] data) {
this.data = data;
}
}
| 2,078 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
StringEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/StringEvent.java | /*
* StringEvent.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.core.event;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class StringEvent extends Event {
public String data;
public StringEvent() {
type = Cons.Type.STRING;
data = null;
}
public StringEvent(String data) {
type = Cons.Type.STRING;
this.data = data;
}
public String ptr() {
return data;
}
public String ptrStr() {
return data;
}
public char[] ptrC() {
return data.toCharArray();
}
public void setData(Object data) {
this.data = (String)data;
}
public void setData(String data) {
this.data = data;
}
public void setData(char[] data) {
this.data = new String(data);
}
}
| 2,125 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EmptyEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/EmptyEvent.java | /*
* EmptyEvent.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.core.event;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class EmptyEvent extends Event {
public EmptyEvent() {
type = Cons.Type.EMPTY;
}
public void setData(Object data) { throw new UnsupportedOperationException(); }
public boolean[] ptr() {
return null;
}
}
| 1,696 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
LongEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/LongEvent.java | /*
* LongEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class LongEvent extends Event {
public long[] data;
public LongEvent() {
type = Cons.Type.LONG;
data = null;
}
public LongEvent(long[] data) {
type = Cons.Type.LONG;
this.data = data;
}
public long[] ptr() {
return data;
}
public long[] ptrL() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (long[])data;
}
public void setData(long[] data) {
this.data = data;
}
}
| 2,057 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FloatEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/FloatEvent.java | /*
* FloatEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class FloatEvent extends Event {
public float[] data;
public FloatEvent() {
type = Cons.Type.FLOAT;
data = null;
}
public FloatEvent(float[] data) {
type = Cons.Type.FLOAT;
this.data = data;
}
public float[] ptr() {
return data;
}
public float[] ptrF() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (float[])data;
}
public void setData(float[] data) {
this.data = data;
}
}
| 2,069 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IntEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/IntEvent.java | /*
* IntEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class IntEvent extends Event {
public int[] data;
public IntEvent() {
type = Cons.Type.INT;
data = null;
}
public IntEvent(int[] data) {
type = Cons.Type.INT;
this.data = data;
}
public int[] ptr() {
return data;
}
public int[] ptrI() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (int[])data;
}
public void setData(int[] data) {
this.data = data;
}
}
| 2,045 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ByteEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/ByteEvent.java | /*
* ByteEvent.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.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
/**
* Created by Johnny on 19.03.2015.
*/
public class ByteEvent extends Event {
public byte[] data;
public ByteEvent() {
type = Cons.Type.BYTE;
data = null;
}
public ByteEvent(byte[] data) {
type = Cons.Type.BYTE;
this.data = data;
}
public byte[] ptr() {
return data;
}
public byte[] ptrB() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (byte[])data;
}
public void setData(byte[] data) {
this.data = data;
}
}
| 2,057 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MapEvent.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/core/event/MapEvent.java | /*
* MapEvent.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.core.event;
import java.util.HashMap;
import java.util.Map;
import hcm.ssj.core.Cons;
/**
* Created by Michael Dietz on 06.10.2020.
*/
public class MapEvent extends Event
{
public Map<String, String> data;
public MapEvent()
{
this(null);
}
public MapEvent(Map<String, String> data)
{
type = Cons.Type.MAP;
this.data = data;
}
@Override
public Map<String, String> ptr()
{
return data;
}
@Override
public Map<String, String> ptrMap()
{
return data;
}
@Override
public void setData(Object data)
{
setData((Map<String, String>) data);
}
public void setData(Map<String, String> data)
{
this.data = data;
}
}
| 2,012 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FFMPEGWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ffmpeg/FFMPEGWriter.java | /*
* FFMPEGWriter.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.ffmpeg;
import android.graphics.ImageFormat;
import android.text.TextUtils;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameRecorder;
import java.io.File;
import java.nio.ByteBuffer;
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.ImageStream;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.IFileWriter;
/**
* Created by Michael Dietz on 04.09.2017.
*/
public class FFMPEGWriter extends Consumer implements IFileWriter
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* FFMPEG writer options
*/
public class Options extends IFileWriter.Options
{
public final Option<String> url = new Option<>("url", null, String.class, "streaming address, e.g. udp://<ip:port>. If set, path is ignored.");
public final Option<Boolean> stream = new Option<>("stream", false, Boolean.class, "Set this flag for very fast decoding in streaming applications (forces h264 codec)");
public final Option<String> format = new Option<>("format", "mp4", String.class, "Default output format (e.g. mp4, h264, ...), set to 'mpegts' in streaming applications");
public final Option<Integer> bitRate = new Option<>("bitRate", 500, Integer.class, "Bitrate in kB/s");
/**
*
*/
protected Options()
{
addOptions();
}
}
public final Options options = new Options();
private FFmpegFrameRecorder writer;
private Frame imageFrame;
private int pixelFormat;
private int width;
private int height;
private int bufferSize;
private byte[] frameBuffer;
private int frameInterval;
private long frameTime;
private long startTime;
public FFMPEGWriter()
{
_name = this.getClass().getSimpleName();
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length != 1)
{
throw new SSJFatalException("Stream count not supported");
}
if (stream_in[0].type != Cons.Type.IMAGE)
{
throw new SSJFatalException("Stream type not supported");
}
frameInterval = (int) (1.0 / stream_in[0].sr * 1000 + 0.5);
width = ((ImageStream) stream_in[0]).width;
height = ((ImageStream) stream_in[0]).height;
// Set output address (path/url)
String address = options.url.get();
if (address == null)
{
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));
}
if (options.fileName.get() == null)
{
String defaultName = TextUtils.join("_", stream_in[0].desc) + ".mp4";
Log.w("file name not set, setting to " + defaultName);
options.fileName.set(defaultName);
}
// Parse wildcards
final String parsedPath = options.filePath.parseWildcards();
// Create dir
Util.createDirectory(parsedPath);
address = parsedPath + File.separator + options.fileName.get();
}
writer = new FFmpegFrameRecorder(address, width, height, 0);
writer.setFormat(options.format.get());
writer.setFrameRate(stream_in[0].sr);
writer.setVideoBitrate(options.bitRate.get() * 1000);
// Streaming options
if (options.stream.get())
{
writer.setVideoCodec(avcodec.AV_CODEC_ID_H264);
writer.setVideoOption("tune", "zerolatency");
writer.setVideoOption("preset", "ultrafast");
writer.setVideoOption("crf", "23");
writer.setVideoOption("x264opts", "bframes=0:force-cfr:no-mbtree:sliced-threads:sync-lookahead=0:rc-lookahead=0:intra-refresh=1:keyint=1");
writer.setInterleaved(true);
// Keyframe interval
writer.setGopSize((int) stream_in[0].sr);
}
bufferSize = width * height;
// Initialize frame
switch (((ImageStream) stream_in[0]).format)
{
case ImageFormat.NV21:
imageFrame = new Frame(width, height, Frame.DEPTH_UBYTE, 2);
pixelFormat = avutil.AV_PIX_FMT_NV21 ; // was AV_PIX_FMT_NONE for javacv 1.3.3
bufferSize *= 1.5;
break;
case ImageFormat.FLEX_RGB_888:
imageFrame = new Frame(width, height, Frame.DEPTH_UBYTE, 3);
pixelFormat = avutil.AV_PIX_FMT_RGB24;
bufferSize *= 3;
break;
case ImageFormat.FLEX_RGBA_8888:
imageFrame = new Frame(width, height, Frame.DEPTH_UBYTE, 4);
pixelFormat = avutil.AV_PIX_FMT_RGBA;
bufferSize *= 4;
break;
}
frameBuffer = new byte[bufferSize];
frameTime = 0;
startTime = 0;
try
{
writer.start();
}
catch (FrameRecorder.Exception e)
{
Log.e("Error while starting writer", e);
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
// Get bytes
byte[] in = stream_in[0].ptrB();
if (startTime == 0)
{
startTime = System.currentTimeMillis() - (stream_in[0].num - 1) * frameInterval;
}
frameTime = System.currentTimeMillis() - (stream_in[0].num - 1) * frameInterval;
// Loop through frames
for (int i = 0; i < stream_in[0].num; i++)
{
if (in.length > bufferSize)
{
System.arraycopy(in, i * bufferSize, frameBuffer, 0, bufferSize);
}
else
{
frameBuffer = in;
}
writeFrame(frameBuffer, frameTime + i * frameInterval);
}
}
private void writeFrame(byte[] frameData, long time)
{
try
{
// Update frame
((ByteBuffer) imageFrame.image[0].position(0)).put(frameData);
// Update timestamp
long t = 1000 * (time - startTime);
if (t > writer.getTimestamp())
{
writer.setTimestamp(t);
}
// Write frame
writer.record(imageFrame, pixelFormat);
}
catch (FrameRecorder.Exception e)
{
Log.e("Error while writing frame", e);
}
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{
try
{
writer.stop();
writer.release();
}
catch (FrameRecorder.Exception e)
{
Log.e("Error while stopping writer", e);
}
}
}
| 7,527 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FFMPEGReaderChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ffmpeg/FFMPEGReaderChannel.java | /*
* FFMPEGReaderChannel.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.ffmpeg;
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.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 04.09.2017.
*/
public class FFMPEGReaderChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the provider
*/
public class Options extends OptionList
{
public final Option<Double> sampleRate = new Option<>("sampleRate", 15., Double.class, "sample rate");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private int sampleDimension = 0;
private FFMPEGReader ffmpegReader = null;
public FFMPEGReaderChannel()
{
super();
_name = this.getClass().getSimpleName();
}
@Override
protected void init() throws SSJException
{
ffmpegReader = (FFMPEGReader) _sensor;
sampleDimension = ffmpegReader.getBufferSize();
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
byte[] out = stream_out.ptrB();
ffmpegReader.swapBuffer(out);
return true;
}
/**
* @return double
*/
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
/**
* @return int
*/
@Override
final public int getSampleDimension()
{
return sampleDimension;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.IMAGE;
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[]{"video"};
((ImageStream)_stream_out).width = ffmpegReader.options.width.get();
((ImageStream)_stream_out).height = ffmpegReader.options.height.get();
((ImageStream)_stream_out).format = Cons.ImageFormat.FLEX_RGB_888.val;
}
}
| 3,277 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FFMPEGReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ffmpeg/FFMPEGReader.java | /*
* FFMPEGReader.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.ffmpeg;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import java.nio.ByteBuffer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.option.FilePath;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 04.09.2017.
*/
public class FFMPEGReader extends Sensor
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the FFMPEGReader
*/
public class Options extends OptionList
{
public final Option<FilePath> file = new Option<>("file", null, FilePath.class, "file path");
public final Option<String> url = new Option<>("url", "", String.class, "streaming address, e.g. udp://127.0.0.1:5000. If set, file option is ignored");
public final Option<Integer> width = new Option<>("width", 640, Integer.class, "width in pixel");
public final Option<Integer> height = new Option<>("height", 480, Integer.class, "height in pixel");
public final Option<Double> fps = new Option<>("fps", 15., Double.class, "fps");
/**
*
*/
private Options()
{
addOptions();
}
}
// Options
public final Options options = new Options();
private FFmpegFrameGrabber reader;
private Frame imageFrame;
private volatile boolean reading;
private Thread readingThread;
private byte[] frameBuffer;
public FFMPEGReader()
{
_name = this.getClass().getSimpleName();
}
@Override
protected boolean connect() throws SSJFatalException
{
reading = true;
frameBuffer = new byte[getBufferSize()];
readingThread = new Thread(new ReaderThread());
readingThread.start();
return true;
}
@Override
protected void disconnect() throws SSJFatalException
{
reading = false;
try
{
readingThread.join();
}
catch (InterruptedException e)
{
Log.e("Error while waiting for reading thread", e);
}
}
public int getBufferSize()
{
int bufferSize = options.width.get() * options.height.get();
// 3 bytes per pixel
bufferSize *= 3;
return bufferSize;
}
public void swapBuffer(byte[] bytes)
{
synchronized (frameBuffer)
{
// Get data from buffer
if (bytes.length < frameBuffer.length)
{
Log.e("Buffer read changed from " + bytes.length + " to " + frameBuffer.length);
bytes = new byte[frameBuffer.length];
}
System.arraycopy(frameBuffer, 0, bytes, 0, frameBuffer.length);
}
}
private class ReaderThread implements Runnable
{
@Override
public void run()
{
ByteBuffer buffer;
try
{
String address;
long frameTime;
if (options.url.get() != null && !options.url.get().isEmpty())
{
address = options.url.get();
frameTime = 0;
}
else
{
address = options.file.get().value;
frameTime = (long) (1000 / options.fps.get());
}
reader = new FFmpegFrameGrabber(address);
reader.setImageWidth(options.width.get());
reader.setImageHeight(options.height.get());
reader.setFrameRate(options.fps.get());
reader.setPixelFormat(avutil.AV_PIX_FMT_RGB24);
reader.start();
while ((imageFrame = reader.grab()) != null && reading)
{
buffer = ((ByteBuffer) imageFrame.image[0].position(0));
if (buffer.remaining() == getBufferSize())
{
synchronized (frameBuffer)
{
buffer.get(frameBuffer);
}
if (frameTime > 0)
{
Thread.sleep(frameTime);
}
}
}
}
catch (FrameGrabber.Exception | InterruptedException e)
{
Log.e("Error while grabbing frames", e);
}
finally
{
try
{
if (reader != null)
{
reader.stop();
reader.release();
}
}
catch (FrameGrabber.Exception e)
{
Log.e("Error while closing reader", e);
}
}
}
}
}
| 5,263 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SensorType.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/androidSensor/SensorType.java | /*
* SensorType.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.androidSensor;
import android.hardware.Sensor;
/**
* Android sensor configurations.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
public enum SensorType
{
ACCELEROMETER("Accelerometer", Sensor.TYPE_ACCELEROMETER, new String[]{"AccX", "AccY", "AccZ"}),
AMBIENT_TEMPERATURE("AmbientTemperature", Sensor.TYPE_AMBIENT_TEMPERATURE, new String[]{"ATemp °C"}),
GAME_ROTATION_VECTOR("GameRotationVector", Sensor.TYPE_GAME_ROTATION_VECTOR, new String[]{"GameRotVX", "GameRotVY", "GameRotVZ"}),
GEOMAGNETIC_ROTATION_VECTOR("GeomagneticRotationVector", Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR, new String[]{"GeoRotVX", "GeoRotVY", "GeoRotVZ"}),
GRAVITY("Gravity", Sensor.TYPE_GRAVITY, new String[]{"GrvX", "GrvY", "GrvZ"}),
GYROSCOPE("Gyroscope", Sensor.TYPE_GYROSCOPE, new String[]{"GyrX", "GyrY", "GyrZ"}),
GYROSCOPE_UNCALIBRATED("GyroscopeUncalibrated", Sensor.TYPE_GYROSCOPE_UNCALIBRATED, new String[]{"UGyrX", "UGyrY", "UGyrZ", "UGyrDriftX", "UGyrDriftY", "UGyrDriftZ"}),
LIGHT("Light", Sensor.TYPE_LIGHT, new String[]{"lx"}),
LINEAR_ACCELERATION("LinearAcceleration", Sensor.TYPE_LINEAR_ACCELERATION, new String[]{"LAccX", "LAccY", "LAccZ"}),
MAGNETIC_FIELD("MagneticField", Sensor.TYPE_MAGNETIC_FIELD, new String[]{"MgnFiX", "MgnFiY", "MgnFiZ"}),
MAGNETIC_FIELD_UNCALIBRATED("MagneticFieldUncalibrated", Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED, new String[]{"UMgnFiX", "UMgnFiY", "UMgnFiZ", "UMgnFiBiasX", "UMgnFiBiasY", "UMgnFiBiasZ"}),
ORIENTATION("Orientation", Sensor.TYPE_ORIENTATION, new String[]{"OriAzi", "OriPitch", "OriRoll"}),
PRESSURE("Pressure", Sensor.TYPE_PRESSURE, new String[]{"Pressure"}),
PROXIMITY("Proximity", Sensor.TYPE_PROXIMITY, new String[]{"Proximity"}),
RELATIVE_HUMIDITY("RelativeHumidity", Sensor.TYPE_RELATIVE_HUMIDITY, new String[]{"Humidity"}),
ROTATION_VECTOR("RotationVector", Sensor.TYPE_ROTATION_VECTOR, new String[]{"RotVX", "RotVY", "RotVZ", "RotVSc"}),
STEP_COUNTER("StepCounter", Sensor.TYPE_STEP_COUNTER, new String[]{"Steps"}),
TEMPERATURE("Temperature", Sensor.TYPE_TEMPERATURE, new String[]{"Temp °C"}),
HEART_RATE("HeartRate", Sensor.TYPE_HEART_RATE, new String[]{"BPM"});
final private String name;
final private int type;
final private int dataSize;
final private String[] output;
/**
* @param name String
* @param type int
* @param output String[]
*/
SensorType(String name, int type, String[] output)
{
this.name = name;
this.type = type;
this.dataSize = output.length;
this.output = output;
}
/**
* @return String
*/
public String getName()
{
return name;
}
/**
* @return int
*/
public int getType()
{
return type;
}
/**
* @return int
*/
public int getDataSize()
{
return dataSize;
}
/**
* @return String[]
*/
public String[] getOutput()
{
return output;
}
/**
* @param name String
* @return SensorType
*/
protected static SensorType getSensorType(String name)
{
try
{
return SensorType.valueOf(name);
} catch (IllegalArgumentException ex)
{
for (SensorType sensorType : SensorType.values())
{
if (sensorType.getName().equalsIgnoreCase(name))
{
return sensorType;
}
}
}
return null;
}
}
| 4,910 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SensorListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/androidSensor/SensorListener.java | /*
* SensorListener.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.androidSensor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import java.util.Arrays;
/**
* Standard listener for android sensors.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
class SensorListener implements SensorEventListener
{
private SensorType sensorType;
private SensorData data;
/**
* @param sensorType SensorType
*/
public SensorListener(SensorType sensorType)
{
this.sensorType = sensorType;
float[] val = new float[this.sensorType.getDataSize()];
Arrays.fill(val, 0);
data = new SensorData(val);
}
/**
* @param event SensorEvent
*/
@Override
public void onSensorChanged(SensorEvent event)
{
// test for proper event
if (event.sensor.getType() == sensorType.getType())
{
synchronized (this) {
// set values
if (event.values != null)
data = new SensorData(event.values);
}
}
}
/**
* @param sensor Sensor
* @param accuracy int
*/
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
/**
* @return SensorData
*/
public SensorData getData()
{
SensorData d;
synchronized (this) {
d = data;
}
return d;
}
public SensorType getType()
{
return sensorType;
}
}
| 2,864 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AndroidSensorChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/androidSensor/AndroidSensorChannel.java | /*
* AndroidSensorChannel.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.androidSensor;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
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;
/**
* Standard provider for android sensors.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
public class AndroidSensorChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the sensor provider
*/
public class Options extends OptionList
{
public final Option<SensorType> sensorType = new Option<>("sensorType", SensorType.ACCELEROMETER, SensorType.class, "android sensor type");
/**
* The rate in which the provider samples data from the sensor.<br>
* <b>Attention!</b> The sensor will provide new data according to its sensor delay.
*/
public final Option<Integer> sampleRate = new Option<>("sampleRate", 50, Integer.class, "sample rate of sensor to provider");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected SensorListener listener;
private SensorType sensorType;
/**
*
*/
public AndroidSensorChannel()
{
super();
_name = "AndroidSensorChannel";
}
/**
*
*/
@Override
public void init() throws SSJException
{
if (options.sensorType.get() == null)
{
Log.e("sensor type not set");
return;
}
sensorType = options.sensorType.get();
_name = this.sensorType.getName();
listener = new SensorListener(sensorType);
((AndroidSensor) _sensor).register(listener);
}
/**
* @param stream_out Stream
*/
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (stream_out.num != 1)
{
Log.w("[" + sensorType.getName() + "] unsupported stream format. sample number = " + stream_out.num);
}
}
/**
* @param stream_out Stream
*/
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
int dimension = getSampleDimension();
float[] out = stream_out.ptrF();
for (int k = 0; k < dimension; k++)
{
out[k] = listener.getData().getData(k);
}
return true;
}
/**
* @return double
*/
@Override
public double getSampleRate()
{
return options.sampleRate.get();
}
/**
* @return int
*/
@Override
final public int getSampleDimension()
{
return sensorType.getDataSize();
}
/*
* @return Cons.Type
*/
@Override
public Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
/**
* @param stream_out Stream
*/
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = sensorType.getOutput();
}
}
| 4,548 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AndroidSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/androidSensor/AndroidSensor.java | /*
* AndroidSensor.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.androidSensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import java.util.ArrayList;
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;
/**
* Standard connection for android sensors.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
public class AndroidSensor extends hcm.ssj.core.Sensor
{
/**
* All options for the sensor
*/
public class Options extends OptionList
{
/**
* According to documentation, the sensor will usually sample values
* at a higher rate than the one specified.
* The delay is declared in microseconds or as a constant value.
* Every value above 3 will be processed as microseconds.
* SENSOR_DELAY_FASTEST = 0 = 0µs
* SENSOR_DELAY_GAME = 1 = 20000µs
* SENSOR_DELAY_UI = 2 = 66667µs
* SENSOR_DELAY_NORMAL = 3 = 200000µs
*/
public final Option<Integer> sensorDelay = new Option<>("sensorDelay", SensorManager.SENSOR_DELAY_FASTEST, Integer.class, "see android documentation");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected SensorManager manager;
protected ArrayList<SensorListener> listeners;
/**
*
*/
public AndroidSensor()
{
super();
_name = "AndroidSensor";
listeners = new ArrayList<>();
}
/**
* register a channel to this sensor
*/
void register(SensorListener listener)
{
listeners.add(listener);
}
/**
*
*/
@Override
protected boolean connect() throws SSJFatalException
{
manager = (SensorManager) SSJApplication.getAppContext().getSystemService(Context.SENSOR_SERVICE);
boolean ok = true;
for(SensorListener l : listeners)
{
Sensor s = manager.getDefaultSensor(l.getType().getType());
if (s == null)
{
Log.e(l.getType().getName() + " not found on device");
ok = false;
}
else
{
ok &= manager.registerListener(l, s, options.sensorDelay.get());
}
}
return ok;
}
/**
*
*/
@Override
protected void disconnect() throws SSJFatalException
{
for (int i = 0; i < listeners.size(); i++)
{
manager.unregisterListener(listeners.get(i));
}
}
@Override
public void clear()
{
listeners.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 4,159 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SensorData.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/androidSensor/SensorData.java | /*
* SensorData.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.androidSensor;
import hcm.ssj.core.Log;
/**
* Standard wrapper for android sensor data.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
class SensorData
{
private int size;
private float[] data;
/**
* @param values float[]
*/
public SensorData(float[] values)
{
this.size = values.length;
data = values;
}
/**
* @return int
*/
public int getSize()
{
return size;
}
/**
* @param index int
* @param data float
*/
public void setData(int index, float data)
{
this.data[index] = data;
}
/**
* @param index int
* @return float
*/
public float getData(int index)
{
if(data == null) {
Log.e("data == null, size = " + size);
return 0;
}
return data[index];
}
}
| 2,230 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GPSChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/gps/GPSChannel.java | /*
* GPSChannel.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.gps;
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 05.07.2016.
*/
public class GPSChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> sampleRate = new Option<>("sampleRate", 5, Integer.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected GPSListener _listener;
public GPSChannel()
{
_name = "GPS_Provider";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((GPSSensor) _sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
double[] out = stream_out.ptrD();
out[0] = _listener.getLatitude();
out[1] = _listener.getLongitude();
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] = "Latitude";
stream_out.desc[1] = "Longitude";
}
}
| 2,836 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GPSListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/gps/GPSListener.java | /*
* GPSListener.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.gps;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
/**
* Created by Michael Dietz on 05.07.2016.
*/
public class GPSListener implements LocationListener
{
private double latitude;
private double longitude;
private long time;
private long updateTime;
public boolean receivedData;
public GPSListener(long updateTime)
{
reset();
this.updateTime = updateTime;
}
public void reset()
{
latitude = 0;
longitude = 0;
time = 0;
receivedData = false;
}
@Override
public void onLocationChanged(Location location)
{
if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER) && location.getTime() - time > updateTime * 2)
{
receivedData = true;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
if (location.getProvider().equals(LocationManager.GPS_PROVIDER))
{
receivedData = true;
latitude = location.getLatitude();
longitude = location.getLongitude();
time = location.getTime();
}
}
public double getLatitude()
{
return latitude;
}
public double getLongitude()
{
return longitude;
}
public long getTime()
{
return time;
}
// Unused listener methods
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onProviderDisabled(String provider)
{
receivedData = false;
}
}
| 2,884 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GPSSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/gps/GPSSensor.java | /*
* GPSSensor.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.gps;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
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 05.07.2016.
*/
public class GPSSensor extends Sensor
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Long> minTime = new Option<>("minTime", 200L, Long.class, "Minimum time interval between location updates, in milliseconds");
public final Option<Float> minDistance = new Option<>("minDistance", 1f, Float.class, "Minimum distance between location updates, in meters");
public final Option<Boolean> ignoreData = new Option<>("ignoreData", false, Boolean.class, "Set to 'true' if no error should occur when no data is received from gps");
public final Option<Boolean> useNetwork = new Option<>("useNetwork", true, Boolean.class, "Set to 'false' if NETWORK_PROVIDER should not be used as fallback");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
GPSListener listener;
LocationManager locationManager;
public GPSSensor()
{
_name = "GPS";
}
@SuppressLint("MissingPermission")
@Override
protected boolean connect() throws SSJFatalException
{
boolean connected = false;
listener = new GPSListener(options.minTime.get());
locationManager = (LocationManager) SSJApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> {
// Register listener
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, options.minTime.get(), options.minDistance.get(), listener);
if (options.useNetwork.get())
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, options.minTime.get(), options.minDistance.get(), listener);
}
}, 1);
// Wait for values
long time = SystemClock.elapsedRealtime();
while (!_terminate && !listener.receivedData && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException ignored)
{
}
}
if (listener.receivedData)
{
connected = true;
}
else
{
Log.e("unable to connect to gps");
}
}
if (options.ignoreData.get() && !connected)
{
connected = true;
}
return connected;
}
@Override
protected void disconnect() throws SSJFatalException
{
if (locationManager != null && listener != null)
{
// Remove listener
locationManager.removeUpdates(listener);
}
}
@Override
protected boolean checkConnection()
{
boolean connected = false;
if (listener != null)
{
connected = listener.receivedData;
}
if (options.ignoreData.get())
{
connected = true;
}
return connected;
}
}
| 4,649 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothPressureMatChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/pressureMat/BluetoothPressureMatChannel.java | /*
* BluetoothPressureMatChannel.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.pressureMat;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
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;
/**
* Created by Johnny on 05.03.2015.
*/
public class BluetoothPressureMatChannel extends SensorChannel {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList {
public final Option<Integer> channel_id = new Option<>("channel_id", 0, Integer.class, "the channel index as defined by the order in which the streams were sent");
public final Option<Integer> bytes = new Option<>("bytes", 0, Integer.class, "");
public final Option<Integer> dim = new Option<>("dim", 0, Integer.class, "");
public final Option<Double> sr = new Option<>("sr", 0., Double.class, "");
public final Option<Integer> num = new Option<>("num", 1, Integer.class, "values >1 make buffer error handling less efficient");
public final Option<Cons.Type> type = new Option<>("type", Cons.Type.UNDEF, Cons.Type.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
public BluetoothPressureMatChannel() {
_name = "BluetoothReader_Data";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (options.sr.get() == 0 || options.bytes.get() == 0 || options.dim.get() == 0 || options.type.get() == Cons.Type.UNDEF) {
Log.e("input channel not configured");
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
short[] data = ((BluetoothPressureSensor) _sensor).getDataInt(options.channel_id.get());
if (data.length != stream_out.tot) {
Log.w("data mismatch");
return false;
}
Util.arraycopy(data, 0, stream_out.ptr(), 0, stream_out.tot);
return true;
}
@Override
public int getSampleDimension() {
return options.dim.get();
}
@Override
public double getSampleRate() {
return options.sr.get();
}
@Override
public int getSampleBytes() {
return options.bytes.get();
}
@Override
public int getSampleNumber() {
return options.num.get();
}
@Override
public Cons.Type getSampleType() {
return options.type.get();
}
protected void describeOutput(Stream stream_out) {
stream_out.desc = new String[stream_out.dim];
for (int i = 0; i < stream_out.desc.length; i++) {
stream_out.desc[i] = "Press" + i;
}
}
}
| 4,147 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothPressureSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/pressureMat/BluetoothPressureSensor.java | /*
* BluetoothPressureSensor.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.pressureMat;
import java.io.IOException;
import java.util.UUID;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.ioput.BluetoothClient;
import hcm.ssj.ioput.BluetoothReader;
import static hcm.ssj.core.Cons.DEFAULT_BL_SERIAL_UUID;
/**
* Created by Johnny on 05.03.2015.
*/
public class BluetoothPressureSensor extends BluetoothReader {
protected short[][] _irecvData;
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList {
public final Option<String> connectionName = new Option<>("connectionName", "SSJ", String.class, "must match that of the peer");
public final Option<String> serverName = new Option<>("serverName", "SSJ_BLServer", String.class, "");
public final Option<String> serverAddr = new Option<>("serverAddr", null, String.class, "if this is a client");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected boolean _isreallyConnected = false;
public BluetoothPressureSensor() {
_name = "BLPressure";
}
@Override
public void init() throws SSJException
{
try {
_conn = new BluetoothClient(UUID.fromString(DEFAULT_BL_SERIAL_UUID), options.serverName.get(), options.serverAddr.get());
} catch (IOException e) {
Log.e("error in setting up connection " + options.connectionName, e);
}
}
@Override
public boolean connect() throws SSJFatalException
{
_irecvData = new short[_provider.size()][];
for (int i = 0; i < _provider.size(); ++i) {
_irecvData[i] = new short[_provider.get(i).getOutputStream().tot];
}
if (!super.connect()) {
return false;
}
try {
byte[] data = {10, 0};
_conn.output().write(data);
} catch (IOException e) {
Log.w("unable to write init sequence to bt socket", e);
}
_isreallyConnected = true;
return true;
}
public void update() throws SSJFatalException
{
if (!_conn.isConnected() && _isreallyConnected) {
return;
}
try {
byte[] header = new byte[4];
byte[] data = new byte[1];
short[] pair = new short[2];
int stateVariable = -1;
for (; _conn.input().read(data) != -1; ) {
//shift header further
header[3] = header[2];
header[2] = header[1];
header[1] = header[0];
header[0] = data[0];
// new header found
if (header[0] == -128 && header[1] == 0 && header[3] == 0 && header[3] == 0) {
stateVariable = 0;
} else // process data
if (stateVariable >= 0) {
if (stateVariable % 3 == 0) {
//first 8 bit of 12 bit int
pair[1] = (short) ((short) (((short) data[0]) + 128) << 4);
} else if (stateVariable % 3 == 1) {
// second 4 bit of 12 bit int
pair[1] = (short) (pair[1] | (((((short) data[0]) + 128) & 0xf0) >> 4));
//first 4 bit of 12 bit int
pair[0] = (short) (((short) (((short) data[0]) + 128) & 0x0f) << 8);
} else if (stateVariable % 3 == 2) {
//second 8 bit of 12 bit int
pair[0] = (short) ((((short) data[0]) + 128) | pair[0]);
//copy package of two pixels tp output
_irecvData[0][(stateVariable / 3) * 2] = pair[0];
_irecvData[0][((stateVariable / 3) * 2) + 1] = pair[1];
}
if (stateVariable == 1535) { //search new header
stateVariable = -1;
}
stateVariable++;
}
}
} catch (IOException e) {
Log.w("unable to read from data stream", e);
}
}
public short[] getDataInt(int channel_id) {
return _irecvData[channel_id];
}
}
| 5,878 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SamsungHRChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/samsung/SamsungHRChannel.java | /*
* HRChannel.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.samsung;
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 11.06.2021.
*/
public class SamsungHRChannel extends SensorChannel
{
public static final float WATCH_SR = 10;
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 10f, Float.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
SamsungAccessoryConsumer accessoryConsumer;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
Float currentHR;
Float currentRR;
public SamsungHRChannel()
{
_name = "Samsung_HR";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
accessoryConsumer = ((SamsungWearable) _sensor).accessoryConsumer;
accessoryConsumer.sendCommand(SamsungAccessoryConsumer.AccessoryCommand.SENSOR_HR);
accessoryConsumer.hrQueue.clear();
lastIndex = 0;
currentIndex = 0;
if (options.sampleRate.get() > WATCH_SR)
{
options.sampleRate.set(WATCH_SR);
}
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = WATCH_SR / options.sampleRate.get();
maxQueueSize = (int) (WATCH_SR * _frame.options.bufferSize.get());
minQueueSize = (int) (2 * samplingRatio);
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
// Get current sample values
currentHR = accessoryConsumer.hrQueue.peek();
currentRR = accessoryConsumer.rrQueue.peek();
// Check if queue is empty
if (currentHR != null && currentRR != null)
{
// Assign output values
out[0] = currentHR;
out[1] = currentRR;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
accessoryConsumer.hrQueue.poll();
accessoryConsumer.rrQueue.poll();
}
// Reset counters
if (currentIndex >= WATCH_SR)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = accessoryConsumer.hrQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
accessoryConsumer.hrQueue.poll();
accessoryConsumer.rrQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 2;
}
@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] = "HR BPM";
stream_out.desc[1] = "RR ms"; // RRs in milliseconds.
}
}
| 4,563 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SamsungWearable.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/samsung/SamsungWearable.java | /*
* SamsungWearable.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.samsung;
import android.os.SystemClock;
import com.samsung.android.sdk.accessory.SAAgentV2;
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.event.Event;
import hcm.ssj.core.option.OptionList;
/**
* Created by Michael Dietz on 04.06.2021.
*/
public class SamsungWearable extends Sensor implements SAAgentV2.RequestAgentCallback, SamsungAccessoryConsumer.AccessoryAnnotationListener
{
SamsungAccessoryConsumer accessoryConsumer;
public SamsungWearable()
{
_name = "SamsungWearable";
}
@Override
public OptionList getOptions()
{
return null;
}
@Override
public void onAgentAvailable(SAAgentV2 saAgentV2)
{
accessoryConsumer = (SamsungAccessoryConsumer) saAgentV2;
accessoryConsumer.setAnnotationListener(this);
}
@Override
public void onError(int errorCode, String message)
{
}
@Override
protected boolean connect() throws SSJFatalException
{
boolean connected = false;
// Wait for saAgent
if (accessoryConsumer == null)
{
SAAgentV2.requestAgent(SSJApplication.getAppContext(), SamsungAccessoryConsumer.class.getName(), this);
long startTime = SystemClock.elapsedRealtime();
while (!_terminate && accessoryConsumer == null && SystemClock.elapsedRealtime() - startTime < _frame.options.waitSensorConnect.get() * 1000 / 2)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException ignored)
{
}
}
}
if (accessoryConsumer != null)
{
accessoryConsumer.connect();
long startTime = SystemClock.elapsedRealtime();
while (!_terminate && !accessoryConsumer.isConnected() && SystemClock.elapsedRealtime() - startTime < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException ignored)
{
}
}
try
{
Thread.sleep(1000);
}
catch (InterruptedException ignored)
{
}
connected = accessoryConsumer.isConnected();
Log.i("Connected with wearable: " + connected);
if (!connected)
{
disconnect();
}
}
return connected;
}
@Override
protected void disconnect() throws SSJFatalException
{
if (accessoryConsumer != null)
{
accessoryConsumer.sendCommand(SamsungAccessoryConsumer.AccessoryCommand.PIPELINE_STOP);
try
{
Thread.sleep(1000);
}
catch (InterruptedException ignored)
{
}
accessoryConsumer.disconnect();
}
}
@Override
protected boolean checkConnection()
{
boolean connected = false;
if (accessoryConsumer != null)
{
connected = accessoryConsumer.isConnected();
}
return connected;
}
@Override
public void handleAnnotation(String data)
{
if (_evchannel_out != null)
{
Event ev = Event.create(Cons.Type.STRING);
ev.sender = "samsung-wearable";
ev.name = "annotation";
ev.time = (long) (_frame.getTimeMs() + 0.5);
ev.dur = 0;
ev.state = Event.State.COMPLETED;
ev.setData(data);
_evchannel_out.pushEvent(ev);
}
}
}
| 4,453 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SamsungAccessoryConsumer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/samsung/SamsungAccessoryConsumer.java | /*
* SamsungAccessoryProvider.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.samsung;
import android.content.Context;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.accessory.SA;
import com.samsung.android.sdk.accessory.SAAgent;
import com.samsung.android.sdk.accessory.SAAgentV2;
import com.samsung.android.sdk.accessory.SAPeerAgent;
import com.samsung.android.sdk.accessory.SASocket;
import java.io.IOException;
import java.util.ArrayDeque;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 02.06.2021.
*/
public class SamsungAccessoryConsumer extends SAAgentV2
{
public static final String TAG = SamsungAccessoryConsumer.class.getSimpleName();
public static final Class<ServiceConnection> SASOCKET_CLASS = ServiceConnection.class;
public static final int COMMAND_CHANNEL_ID = 1001;
public static final int ANNOTATION_CHANNEL_ID = 1002;
public static final int HR_CHANNEL_ID = 1003;
public static final int PPG_CHANNEL_ID = 1004;
public enum AccessoryCommand
{
SENSOR_HR("SENSOR_HR"),
SENSOR_PPG("SENSOR_PPG"),
PIPELINE_STOP("PIPELINE_STOP");
final String cmd;
AccessoryCommand(String command)
{
this.cmd = command;
}
}
public interface AccessoryAnnotationListener
{
void handleAnnotation(String data);
}
ArrayDeque<Float> hrQueue = new ArrayDeque<>();
ArrayDeque<Float> rrQueue = new ArrayDeque<>();
ArrayDeque<Float> ppgQueue = new ArrayDeque<>();
ServiceConnection connectionSocket = null;
boolean connected = false;
AccessoryAnnotationListener annotationListener = null;
public SamsungAccessoryConsumer(Context context)
{
super(TAG, context, SASOCKET_CLASS);
Log.i("Created SamsungAccessoryConsumer");
reset();
try
{
SA accessory = new SA();
accessory.initialize(context);
}
catch (SsdkUnsupportedException e)
{
// try to handle SsdkUnsupportedException
processUnsupportedException(e);
}
catch (Exception e1)
{
Log.e("Failed to initialize Samsung Accessory SDK", e1);
/*
* Your application can not use Samsung Accessory SDK. Your application should work smoothly
* without using this SDK, or you may want to notify user and close your application gracefully
* (release resources, stop Service threads, close UI thread, etc.)
*/
releaseAgent();
}
}
public void reset()
{
hrQueue.clear();
rrQueue.clear();
}
public void connect()
{
findPeerAgents();
}
public void disconnect()
{
if (connectionSocket != null)
{
connectionSocket.close();
connectionSocket = null;
updateStatus(false);
}
}
public boolean isConnected()
{
return connected;
}
private void updateStatus(boolean connected)
{
this.connected = connected;
}
public void setAnnotationListener(AccessoryAnnotationListener annotationListener)
{
this.annotationListener = annotationListener;
}
@Override
protected void onFindPeerAgentsResponse(SAPeerAgent[] peerAgents, int result)
{
if ((result == SAAgent.PEER_AGENT_FOUND) && (peerAgents != null))
{
for (SAPeerAgent peerAgent : peerAgents)
{
requestServiceConnection(peerAgent);
}
}
else if (result == SAAgent.FINDPEER_DEVICE_NOT_CONNECTED)
{
Log.e("Peer device not connected!");
updateStatus(false);
}
else if (result == SAAgent.FINDPEER_SERVICE_NOT_FOUND)
{
Log.e("Find peer result: service not found");
updateStatus(false);
}
else
{
Log.e("Find peer result: no peers have been found!");
}
}
@Override
protected void onPeerAgentsUpdated(SAPeerAgent[] peerAgents, int result)
{
if (result == PEER_AGENT_AVAILABLE)
{
if (!connected)
{
for (SAPeerAgent peerAgent : peerAgents)
{
requestServiceConnection(peerAgent);
}
}
}
else if (result == PEER_AGENT_UNAVAILABLE)
{
// Do nothing
}
}
@Override
protected void onServiceConnectionRequested(SAPeerAgent peerAgent)
{
if (peerAgent != null)
{
Log.i("Service connection accepted");
acceptServiceConnectionRequest(peerAgent);
}
}
@Override
protected void onServiceConnectionResponse(SAPeerAgent peerAgent, SASocket socket, int result)
{
if (result == SAAgentV2.CONNECTION_SUCCESS)
{
if (socket != null)
{
connectionSocket = (ServiceConnection) socket;
updateStatus(true);
}
}
else if (result == SAAgentV2.CONNECTION_ALREADY_EXIST)
{
Log.e("Service connection already exists");
updateStatus(true);
}
else
{
Log.e("Service connection with AccessoryProvider failed (code: " + result + ")");
}
}
public void sendCommand(final AccessoryCommand command)
{
if (connectionSocket != null)
{
Log.i("Sending command: " + command.cmd);
new Thread(() -> {
try
{
connectionSocket.send(COMMAND_CHANNEL_ID, command.cmd.getBytes());
}
catch (IOException e)
{
Log.e("Failed to send data to accessory device", e);
}
}).start();
}
}
public void sendData(final String data)
{
if (connectionSocket != null)
{
Log.i("Sending data: " + data);
new Thread(() -> {
try
{
connectionSocket.send(COMMAND_CHANNEL_ID, data.getBytes());
}
catch (IOException e)
{
Log.e("Failed to send data to accessory device", e);
}
}).start();
}
}
public class ServiceConnection extends SASocket
{
public ServiceConnection()
{
super(ServiceConnection.class.getName());
}
@Override
public void onError(int channelId, String errorMessage, int errorCode)
{
}
@Override
public void onReceive(int channelId, byte[] data)
{
if (connectionSocket == null)
{
return;
}
String dataConverted = new String(data);
if (channelId == COMMAND_CHANNEL_ID)
{
Log.d("Received command: " + dataConverted);
}
else if (channelId == ANNOTATION_CHANNEL_ID)
{
if (annotationListener != null)
{
Log.d("Received annotation: " + dataConverted);
annotationListener.handleAnnotation(dataConverted);
}
}
else if (channelId == HR_CHANNEL_ID)
{
String[] samples = dataConverted.split(",");
for (String sample : samples)
{
String[] sampleData = sample.split(";");
hrQueue.add(Float.parseFloat(sampleData[0]));
rrQueue.add(Float.parseFloat(sampleData[1]));
}
}
else if (channelId == PPG_CHANNEL_ID)
{
String[] samples = dataConverted.split(",");
for (String sample : samples)
{
ppgQueue.add(Float.parseFloat(sample));
}
}
}
@Override
protected void onServiceConnectionLost(int reason)
{
disconnect();
Log.i("Service Connection with AccessoryProvider has been terminated.");
}
}
private boolean processUnsupportedException(SsdkUnsupportedException e)
{
boolean unsupported = true;
Log.e("Unsupported exception", e);
int errType = e.getType();
if (errType == SsdkUnsupportedException.VENDOR_NOT_SUPPORTED || errType == SsdkUnsupportedException.DEVICE_NOT_SUPPORTED)
{
/*
* Your application can not use Samsung Accessory SDK. You application should work smoothly
* without using this SDK, or you may want to notify user and close your app gracefully (release
* resources, stop Service threads, close UI thread, etc.)
*/
releaseAgent();
}
else if (errType == SsdkUnsupportedException.LIBRARY_NOT_INSTALLED)
{
Log.e("You need to install Samsung Accessory SDK to use this application.");
}
else if (errType == SsdkUnsupportedException.LIBRARY_UPDATE_IS_REQUIRED)
{
Log.e("You need to update Samsung Accessory SDK to use this application.");
}
else if (errType == SsdkUnsupportedException.LIBRARY_UPDATE_IS_RECOMMENDED)
{
Log.e("We recommend that you update your Samsung Accessory SDK before using this application.");
unsupported = false;
}
return unsupported;
}
}
| 9,089 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SamsungPPGChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/samsung/SamsungPPGChannel.java | /*
* HRChannel.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.samsung;
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 11.06.2021.
*/
public class SamsungPPGChannel extends SensorChannel
{
public static final float WATCH_SR = 10;
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 10f, Float.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
SamsungAccessoryConsumer accessoryConsumer;
float samplingRatio;
float lastIndex;
float currentIndex;
int maxQueueSize;
int minQueueSize;
Float currentPPG;
public SamsungPPGChannel()
{
_name = "Samsung_PPG";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
accessoryConsumer = ((SamsungWearable) _sensor).accessoryConsumer;
accessoryConsumer.sendCommand(SamsungAccessoryConsumer.AccessoryCommand.SENSOR_PPG);
accessoryConsumer.ppgQueue.clear();
lastIndex = 0;
currentIndex = 0;
if (options.sampleRate.get() > WATCH_SR)
{
options.sampleRate.set(WATCH_SR);
}
// Get ratio between sensor sample rate and channel sample rate
samplingRatio = WATCH_SR / options.sampleRate.get();
maxQueueSize = (int) (WATCH_SR * _frame.options.bufferSize.get());
minQueueSize = (int) (2 * samplingRatio);
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
float[] out = stream_out.ptrF();
// Get current sample values
currentPPG = accessoryConsumer.ppgQueue.peek();
// Check if queue is empty
if (currentPPG != null)
{
// Assign output values
out[0] = currentPPG;
currentIndex += samplingRatio;
// Remove unused samples (due to sample rate) from queue
for (int i = (int) lastIndex; i < (int) currentIndex; i++)
{
accessoryConsumer.ppgQueue.poll();
}
// Reset counters
if (currentIndex >= WATCH_SR)
{
currentIndex = 0;
// Discard old samples from queue if buffer gets too full
int currentQueueSize = accessoryConsumer.ppgQueue.size();
// Log.d("Queue size: " + currentQueueSize);
if (currentQueueSize > maxQueueSize)
{
for (int i = currentQueueSize; i > minQueueSize; i--)
{
accessoryConsumer.ppgQueue.poll();
}
}
}
lastIndex = currentIndex;
return true;
}
return false;
}
@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] = "PPG LED"; // Led
}
}
| 4,314 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothChannel.java | /*
* BluetoothChannel.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.ioput;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
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.ImageStream;
import hcm.ssj.core.stream.Stream;
/**
* Created by Johnny on 05.03.2015.
*/
public class BluetoothChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> channel_id = new Option<>("channel_id", 0, Integer.class, "the channel index as defined by the order in which the streams were sent");
public final Option<Integer> bytes = new Option<>("bytes", 0, Integer.class, "");
public final Option<Integer> dim = new Option<>("dim", 0, Integer.class, "");
public final Option<Double> sr = new Option<>("sr", 0., Double.class, "");
public final Option<Integer> num = new Option<>("num", 1, Integer.class, "values >1 make buffer error handling less efficient");
public final Option<Cons.Type> type = new Option<>("type", Cons.Type.UNDEF, Cons.Type.class, "");
public final Option<Integer> imageWidth = new Option<>("imageWidth", 0, Integer.class, "image width in case of image stream");
public final Option<Integer> imageHeight = new Option<>("imageHeight", 0, Integer.class, "image height in case of image stream");
public final Option<Cons.ImageFormat> imageFormat = new Option<>("imageFormat", Cons.ImageFormat.NV21, Cons.ImageFormat.class, "color format in case of image stream");
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 BluetoothChannel()
{
_name = "BluetoothReader_Data";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (options.sr.get() == 0 || options.bytes.get() == 0 || options.dim.get() == 0 || options.type.get() == Cons.Type.UNDEF)
{
throw new SSJFatalException("input channel not configured");
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (!((BluetoothReader) _sensor).getConnection().isConnected())
{
return false;
}
byte[] data = ((BluetoothReader)_sensor).getData(options.channel_id.get());
if(data == null || data.length != stream_out.tot)
{
Log.w("data mismatch");
return false;
}
Util.arraycopy(data, 0, stream_out.ptr(), 0, stream_out.tot);
return true;
}
@Override
public int getSampleDimension()
{
return options.dim.get();
}
@Override
public double getSampleRate()
{
return options.sr.get();
}
@Override
public int getSampleBytes()
{
return options.bytes.get();
}
@Override
public int getSampleNumber()
{
return options.num.get();
}
@Override
public Cons.Type getSampleType()
{
return options.type.get();
}
@Override
public void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
if(options.outputClass.get() == null || stream_out.dim != options.outputClass.get().length)
{
Log.w("incomplete definition of output classes");
for(int i = 0; i < stream_out.desc.length; i++)
stream_out.desc[i] = "BluetoothData" + options.channel_id.get();
}
else
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
}
if(getSampleType() == Cons.Type.IMAGE)
{
((ImageStream) _stream_out).width = options.imageWidth.get();
((ImageStream) _stream_out).height = options.imageHeight.get();
((ImageStream) stream_out).format = options.imageFormat.get().val;
}
}
}
| 5,633 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SocketWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/SocketWriter.java | /*
* SocketWriter.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.ioput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
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;
/**
* Created by Johnny on 05.03.2015.
*/
public class SocketWriter extends Consumer {
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> port = new Option<>("port", 34300, Integer.class, "");
public final Option<String> ip = new Option<>("ip", "127.0.0.1", String.class, "");
public final Option<Cons.SocketType> type = new Option<>("type", Cons.SocketType.UDP, Cons.SocketType.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
private DatagramSocket _socket_udp;
private Socket _socket_tcp;
private InetAddress _addr;
private DataOutputStream _out;
private byte[] _data;
private boolean _connected = false;
public SocketWriter()
{
_name = "SocketWriter";
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
//start client
try {
_addr = InetAddress.getByName(options.ip.get());
switch(options.type.get()) {
case UDP:
_socket_udp = new DatagramSocket();
break;
case TCP:
_socket_tcp = new Socket(_addr, options.port.get());
_out = new DataOutputStream(_socket_tcp.getOutputStream());
break;
}
}
catch (IOException e)
{
throw new SSJFatalException("error in setting up connection", e);
}
_data = new byte[stream_in[0].tot];
Log.i("Streaming data to " + _addr.getHostName() +"@"+ options.port +"("+ options.type.get().toString() +")");
_connected = true;
}
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
if (!_connected)
{
return;
}
try {
switch(options.type.get()) {
case UDP:
Util.arraycopy(stream_in[0].ptr(), 0, _data, 0, _data.length);
DatagramPacket pack = new DatagramPacket(_data, _data.length, _addr, options.port.get());
_socket_udp.send(pack);
break;
case TCP:
Util.arraycopy(stream_in[0].ptr(), 0, _data, 0, _data.length);
_out.write(_data);
_out.flush();
break;
}
} catch (IOException e) {
Log.w("failed sending data", e);
}
}
public void flush(Stream[] stream_in) throws SSJFatalException
{
_connected = false;
try {
switch(options.type.get()) {
case UDP:
_socket_udp.close();
_socket_udp = null;
break;
case TCP:
_socket_tcp.close();
_socket_tcp = null;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 5,023 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GATTReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/GATTReader.java | /*
* GATTReader.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.ioput;
import android.os.Build;
import android.os.SystemClock;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
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 16.07.2021.
*/
public class GATTReader extends Sensor
{
public class Options extends OptionList
{
public final Option<String> macAddress = new Option<>("macAddress", "", String.class, "MAC address (in format '00:11:22:33:44:55')");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
GATTConnection connection;
public GATTReader()
{
_name = "GATTReader";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
protected void init() throws SSJException
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
connection = new GATTConnection();
}
}
@Override
protected boolean connect() throws SSJFatalException
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
connection.connect(options.macAddress.get());
// Wait until sensor is connected
long time = SystemClock.elapsedRealtime();
while (!connection.isConnected() && !_terminate && SystemClock.elapsedRealtime() - time < _frame.options.waitSensorConnect.get() * 1000)
{
try
{
Thread.sleep(Cons.SLEEP_IN_LOOP);
}
catch (InterruptedException ignored)
{
}
}
if (!connection.isConnected())
{
Log.w("Unable to connect to GATT sensor.");
disconnect();
return false;
}
return true;
}
return false;
}
@Override
protected void disconnect() throws SSJFatalException
{
Log.i("Disconnecting GATT Sensor");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
if (connection != null)
{
connection.disconnect();
connection.close();
}
}
}
@Override
protected boolean checkConnection()
{
boolean connected = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
if (connection != null)
{
connected = connection.isConnected();
}
}
return connected;
}
}
| 3,592 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothReader.java | /*
* BluetoothReader.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.ioput;
import android.bluetooth.BluetoothDevice;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.UUID;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
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 Johnny on 05.03.2015.
*/
public class BluetoothReader extends Sensor {
public class Options extends OptionList
{
public final Option<String> connectionName = new Option<>("connectionName", "SSJ", String.class, "must match that of the peer");
public final Option<String> serverName = new Option<>("serverName", "SSJ_BLServer", String.class, "");
public final Option<String> serverAddr = new Option<>("serverAddr", null, String.class, "if this is a client");
public final Option<Integer> numStreams = new Option<>("numStreams", null, Integer.class, "number of streams to be received (null = use number of defined SensorChannels)");
public final Option<BluetoothConnection.Type> connectionType = new Option<>("connectionType", BluetoothConnection.Type.SERVER, BluetoothConnection.Type.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
protected BluetoothConnection _conn;
protected byte[][] _recvData;
protected int numStreams;
public BluetoothReader() {
_name = "BluetoothReader";
}
@Override
public void init() throws SSJException
{
try {
switch(options.connectionType.get())
{
case SERVER:
_conn = new BluetoothServer(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get());
break;
case CLIENT:
_conn = new BluetoothClient(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get(), options.serverAddr.get());
break;
}
} catch (IOException e) {
throw new SSJException("error in setting up connection "+ options.connectionName, e);
}
}
@Override
public boolean connect() throws SSJFatalException
{
if (options.numStreams.get() == null || options.numStreams.get() == 0)
{
numStreams = _provider.size();
}
else
{
numStreams = options.numStreams.get();
}
if (numStreams < _provider.size())
{
throw new SSJFatalException("Invalid configuration. Expected incoming number of streams (" + numStreams + ") is smaller than number of defined channels (" + _provider.size() + ")");
}
else if (numStreams > _provider.size())
{
Log.w("Unusual configuration. Expected incoming number of streams (" + numStreams + ") is greater than number of defined channels (" + _provider.size() + ")");
}
Log.i("setting up sensor to receive " + numStreams + " streams");
_recvData = new byte[numStreams][];
for(int i=0; i< _provider.size(); ++i)
{
BluetoothChannel ch = (BluetoothChannel)_provider.get(i);
_recvData[ch.options.channel_id.get()] = new byte[ch.getOutputStream().tot];
}
//use object input streams if we expect more than one input
_conn.connect(numStreams > 1);
BluetoothDevice dev = _conn.getConnectedDevice();
Log.i("connected to " + dev.getName() + " @ " + dev.getAddress());
return true;
}
public void update() throws SSJFatalException
{
if (!_conn.isConnected())
{
return;
}
try
{
if(numStreams == 1)
{
((DataInputStream)_conn.input()).readFully(_recvData[0]);
}
else if(numStreams > 1)
{
Stream recvStreams[] = (Stream[]) ((ObjectInputStream)_conn.input()).readObject();
if (recvStreams.length != _recvData.length)
{
throw new IOException("unexpected amount of incoming streams");
}
for (int i = 0; i < recvStreams.length && i < _recvData.length; ++i)
{
Util.arraycopy(recvStreams[i].ptr(), 0, _recvData[i], 0, _recvData[i].length);
}
}
_conn.notifyDataTranferResult(true);
}
catch (IOException | ClassNotFoundException e)
{
Log.w("unable to read from data stream", e);
_conn.notifyDataTranferResult(false);
}
}
@Override
public void disconnect() throws SSJFatalException
{
try {
_conn.disconnect();
} catch (IOException e) {
Log.e("failed closing connection", e);
}
}
@Override
public void forcekill()
{
try {
_conn.disconnect();
} catch (Exception e) {
Log.e("error force killing thread", e);
}
super.forcekill();
}
public BluetoothConnection getConnection()
{
return _conn;
}
public byte[] getData(int channel_id)
{
if(channel_id >= _recvData.length)
return null;
return _recvData[channel_id];
}
@Override
public void clear()
{
_conn.clear();
_conn = null;
super.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 6,997 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothServer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothServer.java | /*
* BluetoothServer.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.ioput;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.UUID;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
/**
* Created by Johnny on 07.04.2015.
*/
public class BluetoothServer extends BluetoothConnection
{
BluetoothAdapter _adapter = null;
private BluetoothServerSocket _server = null;
private BluetoothSocket _socket = null;
private UUID _uuid;
private String _serverName;
public BluetoothServer(UUID connID, String serverName) throws IOException
{
_name = "BluetoothServer";
_adapter = BluetoothAdapter.getDefaultAdapter();
if (_adapter == null)
{
Log.e("Device does not support Bluetooth");
return;
}
if (!_adapter.isEnabled())
{
Log.e("Bluetooth not enabled");
return;
}
_serverName = serverName;
_uuid = connID;
Log.i("server connection on " + _adapter.getName() + " @ " + _adapter.getAddress() + " initialized");
}
public void run()
{
_adapter.cancelDiscovery();
while(!_terminate)
{
try
{
Log.i("setting up server on " + _adapter.getName() + " @ " + _adapter.getAddress() + ", conn = " + _uuid.toString());
_server = _adapter.listenUsingInsecureRfcommWithServiceRecord(_serverName, _uuid);
Log.i("waiting for clients...");
_socket = _server.accept();
if(_useObjectStreams)
{
_out = new ObjectOutputStream(_socket.getOutputStream());
_in = new ObjectInputStream(_socket.getInputStream());
}
else
{
_out = new DataOutputStream(_socket.getOutputStream());
_in = new DataInputStream(_socket.getInputStream());
}
}
catch (IOException e)
{
Log.w("failed to connect to client", e);
}
try {
Thread.sleep(Cons.WAIT_BL_CONNECT); //give BL adapter some time to establish connection ...
} catch (InterruptedException e) {}
if(_socket != null && _socket.isConnected())
{
Log.i("connected to client " + _socket.getRemoteDevice().getName() + ", conn = " + _uuid.toString());
setConnectedDevice(_socket.getRemoteDevice());
setConnectionStatus(true);
//wait as long as there is an active connection
waitForDisconnection();
}
close();
}
}
protected void close()
{
try
{
if(_server != null)
{
_server.close();
_server = null;
}
if(_socket != null)
{
_socket.close();
_socket = null;
}
}
catch (IOException e)
{
Log.e("failed to close sockets", e);
}
}
public BluetoothDevice getRemoteDevice()
{
if(_socket != null)
return _socket.getRemoteDevice();
return null;
}
}
| 4,915 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothEventReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothEventReader.java | /*
* BluetoothEventReader.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.ioput;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.PowerManager;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventHandler;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
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;
/**
* Bluetooth event reader - reads SSJ events from a bluetooth source
* Created by Johnny on 07.04.2015.
*/
public class BluetoothEventReader extends EventHandler
{
public class Options extends OptionList
{
public final Option<String> serverName = new Option<>("serverName", "SSJ_BLServer", String.class, "");
public final Option<String> connectionName = new Option<>("connectionName", "SSJ", String.class, "must match that of the peer");
public final Option<String> serverAddr = new Option<>("serverAddr", null, String.class, "if this is a client");
public final Option<BluetoothConnection.Type> connectionType = new Option<>("connectionType", BluetoothConnection.Type.SERVER, BluetoothConnection.Type.class, "");
public final Option<Boolean> parseXmlToEvent = new Option<>("parseXmlToEvent", true, Boolean.class, "attempt to convert the message to an SSJ event format");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
private final int MSG_HEADER_SIZE = 12;
private BluetoothConnection _conn;
boolean _connected = false;
byte[] _buffer;
XmlPullParser _parser;
PowerManager _mgr;
PowerManager.WakeLock _wakeLock;
public BluetoothEventReader()
{
_name = "BluetoothEventReader";
_doWakeLock = false; //disable SSJ's WL-manager, WL will be handled locally
_mgr = (PowerManager) SSJApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
_wakeLock = _mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this._name);
}
@Override
public void enter() throws SSJFatalException
{
try {
switch(options.connectionType.get())
{
case SERVER:
_conn = new BluetoothServer(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get());
_conn.connect(false);
break;
case CLIENT:
_conn = new BluetoothClient(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get(), options.serverAddr.get());
_conn.connect(false);
break;
}
} catch (Exception e)
{
throw new SSJFatalException("error in setting up connection", e);
}
BluetoothDevice dev = _conn.getRemoteDevice();
if(dev == null) {
throw new SSJFatalException("cannot retrieve remote device");
}
Log.i("connected to " + dev.getName() + " @ " + dev.getAddress());
if(!options.parseXmlToEvent.get())
{
_buffer = new byte[Cons.MAX_EVENT_SIZE];
}
else
{
try
{
_parser = Xml.newPullParser();
_parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
}
catch (XmlPullParserException e)
{
throw new SSJFatalException("unable to initialize parser", e);
}
}
_connected = true;
}
@Override
protected void process() throws SSJFatalException
{
if (!_connected || !_conn.isConnected())
{
return;
}
try
{
if (!options.parseXmlToEvent.get())
{
int len = _conn.input().read(_buffer);
_wakeLock.acquire();
Event ev = Event.create(Cons.Type.STRING);
ev.setData(new String(_buffer, 0, len));
_evchannel_out.pushEvent(ev);
}
else
{
_parser.setInput(new InputStreamReader(_conn.input()));
//first element must be <events>
_parser.next();
_wakeLock.acquire();
if (_parser.getEventType() != XmlPullParser.START_TAG || !_parser.getName().equalsIgnoreCase("events"))
{
Log.w("unknown or malformed bluetooth message");
return;
}
while (_parser.next() != XmlPullParser.END_DOCUMENT)
{
if (_parser.getEventType() == XmlPullParser.START_TAG && _parser.getName().equalsIgnoreCase("event"))
{
Event ev = Event.create(Cons.Type.STRING);
ev.name = _parser.getAttributeValue(null, "event");
ev.sender = _parser.getAttributeValue(null, "sender");
ev.time = Integer.valueOf(_parser.getAttributeValue(null, "from"));
ev.dur = Integer.valueOf(_parser.getAttributeValue(null, "dur"));
ev.state = Event.State.valueOf(_parser.getAttributeValue(null, "state"));
_parser.next();
ev.setData(Util.xmlToString(_parser));
_evchannel_out.pushEvent(ev);
}
if (_parser.getEventType() == XmlPullParser.END_TAG && _parser.getName().equalsIgnoreCase("events"))
{
break;
}
}
}
_conn.notifyDataTranferResult(true);
}
catch(IOException e)
{
Log.w("failed to receive BL data", e);
_conn.notifyDataTranferResult(false);
}
catch(XmlPullParserException e)
{
Log.w("failed to parse package", e);
}
finally
{
if (_wakeLock.isHeld())
{
_wakeLock.release();
}
}
}
@Override
public void flush() throws SSJFatalException
{
_connected = false;
try {
_conn.disconnect();
} catch (IOException e) {
Log.e("failed closing connection", e);
}
}
@Override
public void forcekill() {
try {
_conn.disconnect();
} catch (Exception e) {
Log.e("error force killing thread", e);
}
super.forcekill();
}
@Override
public void clear()
{
_conn.clear();
_conn = null;
super.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 8,443 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SocketEventReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/SocketEventReader.java | /*
* SocketEventReader.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.ioput;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventHandler;
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;
/**
* Audio Sensor - get data from audio interface and forwards it
* Created by Johnny on 05.03.2015.
*/
public class SocketEventReader extends EventHandler
{
final int MAX_MSG_SIZE = 4096;
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public Option<String> ip = new Option<>("ip", null, String.class, "");
public Option<Integer> port = new Option<>("port", 0, Integer.class, "");
public Option<Boolean> parseXmlToEvent = new Option<>("parseXmlToEvent", true, Boolean.class, "attempt to convert the message to an SSJ event format");
public Option<Boolean> overwriteEventTime = new Option<>("overwriteEventTime", false, Boolean.class, "overwrite event time with internal receive time");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
DatagramSocket _socket;
boolean _connected = false;
byte[] _buffer;
XmlPullParser _parser;
public SocketEventReader()
{
_name = "SocketEventReader";
_doWakeLock = true;
}
@Override
public void enter() throws SSJFatalException
{
if (options.ip.get() == null)
{
try
{
options.ip.set(Util.getIPAddress(true));
}
catch (SocketException e)
{
throw new SSJFatalException("Unable to determine local IP address", e);
}
}
try
{
_socket = new DatagramSocket(null);
_socket.setReuseAddress(true);
InetAddress addr = InetAddress.getByName(options.ip.get());
InetSocketAddress saddr = new InetSocketAddress(addr, options.port.get());
_socket.bind(saddr);
}
catch (IOException e)
{
throw new SSJFatalException("ERROR: cannot bind socket", e);
}
_buffer = new byte[MAX_MSG_SIZE];
if(options.parseXmlToEvent.get())
{
try
{
_parser = Xml.newPullParser();
_parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
}
catch (XmlPullParserException e)
{
throw new SSJFatalException("unable to initialize parser", e);
}
}
Log.i("Socket ready ("+options.ip.get() + "@" + options.port.get() +")");
_connected = true;
}
@Override
protected void process() throws SSJFatalException
{
if (!_connected)
{
return;
}
DatagramPacket packet = new DatagramPacket(_buffer, _buffer.length);
try
{
_socket.receive(packet);
}
catch (IOException e)
{
Log.w("Failed to receive packet", e);
return;
}
if(!options.parseXmlToEvent.get())
{
Event ev = Event.create(Cons.Type.STRING);
ev.setData(new String(_buffer, 0, packet.getLength()));
_evchannel_out.pushEvent(ev);
}
else
{
try
{
_parser.setInput(new ByteArrayInputStream(_buffer, 0, packet.getLength()), null);
//first element must be <events>
_parser.next();
if (_parser.getEventType() != XmlPullParser.START_TAG || !_parser.getName().equalsIgnoreCase("events"))
{
Log.w("unknown or malformed socket message");
return;
}
while (_parser.next() != XmlPullParser.END_DOCUMENT)
{
if (_parser.getEventType() == XmlPullParser.START_TAG && "event".equalsIgnoreCase(_parser.getName()))
{
String eventType = _parser.getAttributeValue(null, "type");
Event ev;
if ("map".equalsIgnoreCase(eventType))
{
ev = Event.create(Cons.Type.MAP);
}
else
{
ev = Event.create(Cons.Type.STRING);
}
ev.name = _parser.getAttributeValue(null, "event");
ev.sender = _parser.getAttributeValue(null, "sender");
ev.dur = Integer.valueOf(_parser.getAttributeValue(null, "dur"));
ev.state = Event.State.valueOf(_parser.getAttributeValue(null, "state").toUpperCase());
if (options.overwriteEventTime.get())
{
ev.time = _frame.getTimeMs();
}
else
{
ev.time = Integer.valueOf(_parser.getAttributeValue(null, "from"));
}
_parser.next();
if ("map".equalsIgnoreCase(eventType))
{
Map<String, String> map = new HashMap<>();
String key = null;
String value = null;
while (!(_parser.getEventType() == XmlPullParser.END_TAG && "event".equalsIgnoreCase(_parser.getName())))
{
if (_parser.getEventType() == XmlPullParser.START_TAG && "tuple".equalsIgnoreCase(_parser.getName()))
{
key = _parser.getAttributeValue(null, "string");
value = _parser.getAttributeValue(null, "value");
if (key != null && value != null)
{
map.put(key, value);
}
}
_parser.next();
}
ev.setData(map);
}
else
{
ev.setData(Util.xmlToString(_parser));
}
_evchannel_out.pushEvent(ev);
}
if (_parser.getEventType() == XmlPullParser.END_TAG && _parser.getName().equalsIgnoreCase("events"))
{
break;
}
}
}
catch (IOException | XmlPullParserException e)
{
Log.w("Failed to receive packet or parse xml", e);
return;
}
}
}
@Override
public void flush() throws SSJFatalException
{
_socket.close();
}
}
| 9,018 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SocketReader.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/SocketReader.java | /*
* SocketReader.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.ioput;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.Sensor;
import hcm.ssj.core.Util;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.option.OptionList;
/**
* Audio Sensor - get data from audio interface and forwards it
* Created by Johnny on 05.03.2015.
*/
public class SocketReader extends Sensor
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public Option<String> ip = new Option<>("ip", null, String.class, "");
public Option<Integer> port = new Option<>("port", 0, Integer.class, "");
public final Option<Cons.SocketType> type = new Option<>("type", Cons.SocketType.UDP, Cons.SocketType.class, "");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private DatagramSocket _socket_udp = null;
private ServerSocket _server_tcp = null;
private Socket _client_tcp = null;
private DataInputStream _in;
boolean _connected = false;
byte[] _buffer;
public SocketReader()
{
_name = "SocketReader";
}
@Override
public boolean connect() throws SSJFatalException
{
_connected = false;
_socket_udp = null;
_server_tcp = null;
_client_tcp = null;
Log.i("setting up socket ("+options.ip.get() + "@" + options.port.get() +" / "+ options.type.get().toString() +")");
if (options.ip.get() == null)
{
try
{
options.ip.set(Util.getIPAddress(true));
}
catch (SocketException e)
{
throw new SSJFatalException("unable to determine local IP address", e);
}
}
try
{
InetAddress addr = InetAddress.getByName(options.ip.get());
InetSocketAddress saddr = new InetSocketAddress(addr, options.port.get());
switch(options.type.get()) {
case UDP:
_socket_udp = new DatagramSocket(null);
_socket_udp.setReuseAddress(true);
_socket_udp.bind(saddr);
break;
case TCP:
_server_tcp = new ServerSocket(options.port.get());
Log.i("waiting for client ... ");
_client_tcp = _server_tcp.accept();
_in = new DataInputStream(_client_tcp.getInputStream());
break;
}
}
catch (IOException e)
{
throw new SSJFatalException("ERROR: cannot bind/connect socket", e);
}
_buffer = new byte[_provider.get(0).getOutputStream().tot];
_connected = true;
Log.i("socket connected");
return true;
}
@Override
protected void update() throws SSJFatalException
{
if (!_connected)
{
return;
}
try {
switch(options.type.get()) {
case UDP:
DatagramPacket packet = new DatagramPacket(_buffer, _buffer.length);
_socket_udp.receive(packet);
break;
case TCP:
_in.readFully(_buffer);
break;
}
} catch (IOException e) {
Log.w("failed receiving data", e);
}
}
@Override
public void disconnect() throws SSJFatalException
{
_connected = false;
try {
switch(options.type.get()) {
case UDP:
if(_socket_udp != null) {
_socket_udp.close();
_socket_udp = null;
}
break;
case TCP:
if(_client_tcp != null) {
_client_tcp.close();
_client_tcp = null;
}
if(_server_tcp != null) {
_server_tcp.close();
_server_tcp = null;
}
break;
}
} catch (Exception e) {
Log.w("failed closing socket", e);
}
}
public byte[] getData()
{
return _buffer;
}
}
| 6,064 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SocketEventWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/SocketEventWriter.java | /*
* SocketEventWriter.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.ioput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventHandler;
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.file.FileCons;
/**
* Created by Johnny on 05.03.2015.
*/
public class SocketEventWriter extends EventHandler
{
public final static int SOCKET_TYPE_UDP = 0;
public final static int SOCKET_TYPE_TCP = 1;
public class Options extends OptionList
{
public final Option<Integer> port = new Option<>("port", 34300, Integer.class, "port");
public final Option<Integer> type = new Option<>("type", SOCKET_TYPE_UDP, Integer.class, "connection type (0 = UDP, 1 = TCP)");
public final Option<String> ip = new Option<>("ip", "127.0.0.1", String.class, "remote ip address");
public final Option<Boolean> sendAsMap = new Option<>("sendAsMap", false, Boolean.class, "send values as map event");
public final Option<String> mapKeys = new Option<>("mapKeys", "", String.class, "key for each dimension separated by comma");
private Options()
{
addOptions();
}
}
public Options options = new Options();
private DatagramSocket _socket_udp;
private Socket _socket_tcp;
private InetAddress _addr;
private DataOutputStream _out;
StringBuilder _builder = new StringBuilder();
byte[] _buffer;
int _evID[];
String[] userMapKeys;
private boolean _connected = false;
public SocketEventWriter()
{
_name = "SocketEventWriter";
_doWakeLock = true;
}
@Override
public void enter() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new SSJFatalException("no incoming event channels defined");
}
//start client
String protocol = "";
try {
_addr = InetAddress.getByName(options.ip.get());
switch(options.type.get()) {
case SOCKET_TYPE_UDP:
_socket_udp = new DatagramSocket();
protocol = "UDP";
break;
case SOCKET_TYPE_TCP:
_socket_tcp = new Socket(_addr, options.port.get());
_out = new DataOutputStream(_socket_tcp.getOutputStream());
protocol = "TCP";
break;
}
}
catch (IOException e)
{
throw new SSJFatalException("error in setting up connection", e);
}
_buffer = new byte[Cons.MAX_EVENT_SIZE];
_evID = new int[_evchannel_in.size()];
Arrays.fill(_evID, 0);
if (options.sendAsMap.get() && options.mapKeys.get() != null && !options.mapKeys.get().equalsIgnoreCase(""))
{
userMapKeys = options.mapKeys.get().split(",");
}
Log.i("Streaming data to " + _addr.getHostName() +"@"+ options.port.get() +"("+ protocol +")");
_connected = true;
}
@Override
protected void process() throws SSJFatalException
{
if (!_connected)
{
return;
}
_builder.delete(0, _builder.length());
_builder.append("<events ssi-v=\"2\" ssj-v=\"");
_builder.append(_frame.getVersion());
_builder.append("\">");
int count = 0;
for(int i = 0; i < _evchannel_in.size(); ++i)
{
Event ev = _evchannel_in.get(i).getEvent(_evID[i], false);
if (ev == null)
{
continue;
}
count++;
_evID[i] = ev.id + 1;
//build event
Util.eventToXML(_builder, ev, options.sendAsMap.get(), userMapKeys);
_builder.append(FileCons.DELIMITER_LINE);
}
if(count > 0)
{
_builder.append( "</events>");
byte[] data;
try
{
switch(options.type.get()) {
case SOCKET_TYPE_UDP:
data = _builder.toString().getBytes();
DatagramPacket pack = new DatagramPacket(data, data.length, _addr, options.port.get());
_socket_udp.send(pack);
break;
case SOCKET_TYPE_TCP:
data = _builder.toString().getBytes();
_out.write(data);
_out.flush();
break;
}
}
catch (IOException e)
{
Log.w("failed sending data", e);
}
}
}
public void flush() throws SSJFatalException
{
_connected = false;
try {
switch(options.type.get()) {
case SOCKET_TYPE_UDP:
_socket_udp.close();
_socket_udp = null;
break;
case SOCKET_TYPE_TCP:
_socket_tcp.close();
_socket_tcp = null;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 6,915 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GATTConnection.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/GATTConnection.java | /*
* GATTConnection.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.ioput;
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.Build;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import androidx.annotation.RequiresApi;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJApplication;
/**
* Created by Michael Dietz on 16.07.2021.
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class GATTConnection extends BluetoothGattCallback
{
public static final String CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID = "00002902-0000-1000-8000-00805f9b34fb";
public static Map<String, CharacteristicDetails> GATT_DETAILS = new HashMap<>();
static {
// See Bluetooth GATT Specification Supplement for more details
// https://gist.github.com/sam016/4abe921b5a9ee27f67b3686910293026
GATT_DETAILS.put("00002a19-0000-1000-8000-00805f9b34fb", new CharacteristicDetails("Battery Level", BluetoothGattCharacteristic.FORMAT_UINT8, 0, Cons.Type.INT));
GATT_DETAILS.put("00002a6f-0000-1000-8000-00805f9b34fb", new CharacteristicDetails("Humidity", BluetoothGattCharacteristic.FORMAT_UINT16, -2, Cons.Type.FLOAT));
GATT_DETAILS.put("00002a6e-0000-1000-8000-00805f9b34fb", new CharacteristicDetails("Temperature", BluetoothGattCharacteristic.FORMAT_SINT16, -2, Cons.Type.FLOAT));
}
static class CharacteristicDetails
{
String name;
int readFormat;
int decimalOffset = 0;
Cons.Type outputFormat;
public CharacteristicDetails(String name, int readFormat, int decimalOffset, Cons.Type outputFormat)
{
this.name = name;
this.readFormat = readFormat;
this.decimalOffset = decimalOffset;
this.outputFormat = outputFormat;
}
}
enum GATTConnectionStatus {
CONNECTING,
CONNECTED,
DISCONNECTED;
}
BluetoothAdapter bluetoothAdapter = null;
BluetoothGatt bluetoothGatt = null;
String previousAddress = null;
GATTConnectionStatus connectionStatus;
Map<UUID, BluetoothGattCharacteristic> registeredCharacteristics = new HashMap<>();
Map<UUID, Object> characteristicValue = new HashMap<>();
Queue<Request> requests = new ArrayDeque<>();
public GATTConnection()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null)
{
Log.e("Device does not support Bluetooth");
return;
}
if (!bluetoothAdapter.isEnabled())
{
Log.e("Bluetooth not enabled");
return;
}
registeredCharacteristics.clear();
characteristicValue.clear();
connectionStatus = GATTConnectionStatus.DISCONNECTED;
}
public boolean connect(final String macAddress)
{
if (!BluetoothAdapter.checkBluetoothAddress(macAddress))
{
Log.e("Invalid MAC address: " + macAddress);
return false;
}
if (previousAddress != null && previousAddress.equalsIgnoreCase(macAddress) && bluetoothGatt != null)
{
Log.i("Trying to re-use existing gatt connection");
if (bluetoothGatt.connect())
{
connectionStatus = GATTConnectionStatus.CONNECTING;
return true;
}
else
{
return false;
}
}
final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
if (device == null)
{
Log.w("Device not found. Unable to connect.");
return false;
}
Log.i("Device name: " + device.getName());
Log.i("Trying to create a new connection");
bluetoothGatt = device.connectGatt(SSJApplication.getAppContext(), false, this);
previousAddress = macAddress;
connectionStatus = GATTConnectionStatus.CONNECTING;
return true;
}
public void disconnect()
{
if (bluetoothGatt != null)
{
for (BluetoothGattCharacteristic characteristic : registeredCharacteristics.values())
{
if (characteristic != null)
{
setCharacteristicNotification(characteristic, false);
}
}
bluetoothGatt.disconnect();
}
else
{
Log.w("Bluetooth adapter not initialized");
}
}
public void close()
{
if (bluetoothGatt != null)
{
bluetoothGatt.close();
}
}
public boolean isConnected()
{
return connectionStatus == GATTConnectionStatus.CONNECTED;
}
public void registerCharacteristic(UUID uuid)
{
registeredCharacteristics.put(uuid, null);
characteristicValue.put(uuid, null);
}
/**
* Reads a bt characteristic, result is reported in onCharacteristicRead() callback
* @param characteristic characteristic to read from
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic)
{
if (bluetoothGatt != null)
{
bluetoothGatt.readCharacteristic(characteristic);
}
}
public synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled)
{
if (bluetoothGatt != null)
{
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// Client Characteristic Configuration Descriptor
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID));
if (enabled)
{
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
}
else
{
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
bluetoothGatt.writeDescriptor(descriptor);
}
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if (newState == BluetoothProfile.STATE_CONNECTED)
{
Log.i("Connected to GATT server");
connectionStatus = GATTConnectionStatus.CONNECTED;
bluetoothGatt.discoverServices();
}
else if (newState == BluetoothProfile.STATE_DISCONNECTED)
{
Log.i("Disconnected from GATT server");
connectionStatus = GATTConnectionStatus.DISCONNECTED;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
// services discovered
Log.i("Services discovered!");
for (BluetoothGattService service : bluetoothGatt.getServices())
{
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics())
{
final UUID uuid = characteristic.getUuid();
if (registeredCharacteristics.containsKey(uuid))
{
registeredCharacteristics.put(uuid, characteristic);
requests.add(Request.newEnableNotificationsRequest(uuid));
}
}
}
nextRequest();
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
Log.i("Characteristic read: " + characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT16, 0));
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
{
final UUID uuid = characteristic.getUuid();
final CharacteristicDetails characteristicDetails = GATT_DETAILS.get(uuid.toString());
Object value = null;
if (characteristicDetails != null)
{
if (characteristicDetails.readFormat == BluetoothGattCharacteristic.FORMAT_UINT8
|| characteristicDetails.readFormat == BluetoothGattCharacteristic.FORMAT_UINT16
|| characteristicDetails.readFormat == BluetoothGattCharacteristic.FORMAT_SINT16)
{
value = characteristic.getIntValue(characteristicDetails.readFormat, 0) * ((float) Math.pow(10, characteristicDetails.decimalOffset));
}
}
else
{
value = characteristic.getValue();
}
// Log.i(characteristicDetails.name + ": " + value + " " + System.currentTimeMillis());
characteristicValue.put(uuid, value);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
Log.i("Writing characteristic: " + characteristic.getUuid());
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status)
{
// Log.i("Writing descriptor: " + descriptor.getCharacteristic().getUuid());
nextRequest();
}
public void nextRequest()
{
Request request = requests.poll();
if (request != null)
{
switch (request.type)
{
case ENABLE_NOTIFICATIONS:
setCharacteristicNotification(registeredCharacteristics.get(request.uuid), true);
break;
case DISABLE_NOTIFICATIONS:
setCharacteristicNotification(registeredCharacteristics.get(request.uuid), false);
break;
}
}
}
protected static final class Request
{
private enum Type
{
ENABLE_NOTIFICATIONS,
DISABLE_NOTIFICATIONS
}
private final Type type;
private final UUID uuid;
private Request(final Type type, final UUID uuid)
{
this.type = type;
this.uuid = uuid;
}
public static Request newEnableNotificationsRequest(final UUID uuid)
{
return new Request(Type.ENABLE_NOTIFICATIONS, uuid);
}
public static Request newDisableNotificationsRequest(final UUID uuid)
{
return new Request(Type.DISABLE_NOTIFICATIONS, uuid);
}
}
}
| 10,531 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothConnection.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothConnection.java | /*
* BluetoothConnection.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.ioput;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJApplication;
/**
* Created by Johnny on 07.04.2015.
*/
public abstract class BluetoothConnection extends BroadcastReceiver implements Runnable
{
public enum Type
{
CLIENT,
SERVER
}
protected String _name = "BluetoothConnection";
Pipeline pipe;
private long _firstError = 0;
protected BluetoothDevice _connectedDevice = null;
protected boolean _terminate = false;
protected boolean _isConnected = false;
protected final Object _newConnection = new Object();
protected final Object _newDisconnection = new Object();
protected InputStream _in;
protected OutputStream _out;
protected boolean _useObjectStreams = false;
public InputStream input() {return _in;}
public OutputStream output() {return _out;}
public BluetoothConnection()
{
pipe = Pipeline.getInstance();
//register listener for BL status changes
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
SSJApplication.getAppContext().registerReceiver(this, filter);
}
public void clear()
{
SSJApplication.getAppContext().unregisterReceiver(this);
}
public void connect(boolean useObjectStreams)
{
Log.i(_name + " connecting");
_useObjectStreams = useObjectStreams;
_isConnected = false;
_terminate = false;
pipe.executeRunnable(this);
waitForConnection();
Log.i(_name + " connected");
}
public void disconnect() throws IOException
{
Log.i(_name + " disconnecting");
_terminate = true;
_isConnected = false;
synchronized (_newConnection) {
_newConnection.notifyAll();
}
synchronized (_newDisconnection) {
_newDisconnection.notifyAll();
}
close();
Log.i(_name + " disconnected");
}
abstract BluetoothDevice getRemoteDevice();
public void onReceive(Context ctx, Intent intent) {
String action = intent.getAction();
Log.v("new bluetooth state: " + action);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
if (!device.equals(_connectedDevice))
{
Log.v("connected with " + device.getName() );
setConnectionStatus(true);
}
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
if (device.equals(_connectedDevice))
{
Log.w("disconnected from " + device.getName() );
setConnectionStatus(false);
}
}
else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
case BluetoothAdapter.STATE_TURNING_OFF:
setConnectionStatus(false);
break;
}
}
else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.ERROR);
BluetoothDevice device = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
if (device.equals(_connectedDevice)) {
switch (state) {
case BluetoothAdapter.STATE_DISCONNECTED:
case BluetoothAdapter.STATE_DISCONNECTING:
setConnectionStatus(false);
break;
case BluetoothAdapter.STATE_CONNECTED:
setConnectionStatus(true);
break;
}
}
}
}
public void waitForConnection()
{
while(!isConnected() && !_terminate)
{
try
{
synchronized (_newConnection)
{
_newConnection.wait();
}
}
catch (InterruptedException e) {}
}
}
public void waitForDisconnection()
{
while(isConnected() && !_terminate)
{
try
{
synchronized (_newDisconnection)
{
_newDisconnection.wait();
}
}
catch (InterruptedException e) {}
}
}
public boolean isConnected()
{
boolean value;
synchronized (this)
{
value = _connectedDevice != null && _isConnected;
}
return value;
}
public BluetoothDevice getConnectedDevice()
{
return _connectedDevice;
}
protected void setConnectedDevice(BluetoothDevice device)
{
synchronized (this) {
_connectedDevice = device;
}
}
protected void setConnectionStatus(boolean connected)
{
if(connected)
{
synchronized (this) {
_isConnected = true;
}
synchronized (_newConnection) {
_newConnection.notifyAll();
}
}
else
{
synchronized (this) {
_isConnected = false;
}
synchronized (_newDisconnection){
_newDisconnection.notifyAll();
}
}
}
protected void notifyDataTranferResult(boolean value)
{
if(!value)
{
if(_firstError == 0)
_firstError = System.currentTimeMillis();
else if (System.currentTimeMillis() - _firstError > Cons.WAIT_BL_DISCONNECT)
{
Log.w("connection interrupted");
setConnectionStatus(false);
}
}
else
_firstError = 0;
}
abstract protected void close();
}
| 8,361 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothClient.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothClient.java | /*
* BluetoothClient.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.ioput;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;
import java.util.UUID;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
/**
* Created by Johnny on 07.04.2015.
*/
public class BluetoothClient extends BluetoothConnection
{
private BluetoothSocket _socket = null;
private UUID _uuid;
BluetoothAdapter _adapter = null;
BluetoothDevice _server = null;
public BluetoothClient(UUID connID, String serverName, String serverAddr) throws IOException
{
_name = "BluetoothClient";
_adapter = BluetoothAdapter.getDefaultAdapter();
if (_adapter == null)
{
Log.e("Device does not support Bluetooth");
return;
}
if (!_adapter.isEnabled())
{
Log.e("Bluetooth not enabled");
return;
}
Log.i("searching for server " + serverName);
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(serverName))
{
serverAddr = d.getAddress();
_server = d;
}
}
}
//if we haven't found it
if(_server == null)
{
Log.i("not found, searching for server " + serverAddr);
if (!BluetoothAdapter.checkBluetoothAddress(serverAddr)) {
Log.e("invalid MAC address: " + serverAddr);
return;
}
_server = _adapter.getRemoteDevice(serverAddr);
}
_uuid = connID;
Log.i("client connection to " + _server.getName() + " initialized");
}
public void run()
{
_adapter.cancelDiscovery();
while(!_terminate)
{
try
{
Log.i("setting up connection to " + _server.getName() + ", conn = " + _uuid.toString());
_socket = _server.createRfcommSocketToServiceRecord(_uuid);
Log.i("waiting for server ...");
_socket.connect();
if(_useObjectStreams)
{
_out = new ObjectOutputStream(_socket.getOutputStream());
_in = new ObjectInputStream(_socket.getInputStream());
}
else
{
_out = new DataOutputStream(_socket.getOutputStream());
_in = new DataInputStream(_socket.getInputStream());
}
}
catch (IOException e)
{
Log.w("failed to connect to server", e);
}
try {
Thread.sleep(Cons.WAIT_BL_CONNECT); //give BL adapter some time to establish connection ...
} catch (InterruptedException e) {}
if(_socket != null && _socket.isConnected())
{
Log.i("connected to server " + _server.getName() + ", conn = " + _uuid.toString());
setConnectedDevice(_socket.getRemoteDevice());
setConnectionStatus(true);
//wait as long as there is an active connection
waitForDisconnection();
}
close();
}
}
protected void close()
{
try
{
if(_socket != null)
{
_socket.close();
_socket = null;
}
}
catch (IOException e)
{
Log.e("failed to close socket", e);
}
}
public BluetoothDevice getRemoteDevice()
{
if(_socket != null)
return _socket.getRemoteDevice();
return null;
}
}
| 5,500 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothEventWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothEventWriter.java | /*
* BluetoothEventWriter.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.ioput;
import android.bluetooth.BluetoothDevice;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.UUID;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventHandler;
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.file.FileCons;
/**
* Created by Johnny on 05.03.2015.
*/
public class BluetoothEventWriter extends EventHandler
{
public class Options extends OptionList
{
public final Option<String> serverName = new Option<>("serverName", "SSJ_BLServer", String.class, "");
public final Option<String> serverAddr = new Option<>("serverAddr", null, String.class, "we need an address if this is the first time these two devices connect");
public final Option<String> connectionName = new Option<>("connectionName", "SSJ", String.class, "must match that of the peer");
public final Option<BluetoothConnection.Type> connectionType = new Option<>("connectionType", BluetoothConnection.Type.CLIENT, BluetoothConnection.Type.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
private BluetoothConnection _conn;
private boolean _connected = false;
byte[] _buffer;
int _evID[];
StringBuilder _builder = new StringBuilder();
public BluetoothEventWriter() {
_name = "BluetoothEventWriter";
_doWakeLock = true;
}
@Override
public void enter() throws SSJFatalException
{
if (_evchannel_in == null || _evchannel_in.size() == 0)
{
throw new RuntimeException("no incoming event channels defined");
}
try {
switch(options.connectionType.get())
{
case SERVER:
_conn = new BluetoothServer(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get());
_conn.connect(false);
break;
case CLIENT:
_conn = new BluetoothClient(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get(), options.serverAddr.get());
_conn.connect(false);
break;
}
} catch (Exception e)
{
throw new SSJFatalException("error in setting up connection", e);
}
BluetoothDevice dev = _conn.getRemoteDevice();
if(dev == null) {
throw new SSJFatalException("cannot retrieve remote device");
}
Log.i("connected to " + dev.getName() + " @ " + dev.getAddress());
_buffer = new byte[Cons.MAX_EVENT_SIZE];
_evID = new int[_evchannel_in.size()];
_connected = true;
}
@Override
protected void process() throws SSJFatalException
{
if (!_connected || !_conn.isConnected())
{
return;
}
_builder.delete(0, _builder.length());
_builder.append("<events ssi-v=\"2\" ssj-v=\"");
_builder.append(_frame.getVersion());
_builder.append("\">");
int count = 0;
for(int i = 0; i < _evchannel_in.size(); ++i)
{
Event ev = _evchannel_in.get(i).getEvent(_evID[i], false);
if (ev == null)
{
continue;
}
_evID[i] = ev.id + 1;
count++;
//build event
Util.eventToXML(_builder, ev);
_builder.append(FileCons.DELIMITER_LINE);
}
if(count > 0)
{
_builder.append( "</events>");
ByteBuffer buf = ByteBuffer.wrap(_buffer);
buf.order(ByteOrder.BIG_ENDIAN);
//store event
buf.put(_builder.toString().getBytes());
try
{
_conn.output().write(_buffer, 0, buf.position());
_conn.output().flush();
_conn.notifyDataTranferResult(true);
}
catch (IOException e)
{
Log.w("failed sending data", e);
_conn.notifyDataTranferResult(false);
}
}
}
@Override
public void flush() throws SSJFatalException
{
_connected = false;
try {
_conn.disconnect();
} catch (IOException e) {
Log.e("failed closing connection", e);
}
}
@Override
public void forcekill() {
try {
_conn.disconnect();
} catch (Exception e) {
Log.e("error force killing thread", e);
}
super.forcekill();
}
@Override
public void clear()
{
_conn.clear();
_conn = null;
super.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 6,370 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SocketChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/SocketChannel.java | /*
* SocketChannel.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.ioput;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
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;
/**
* Created by Johnny on 05.03.2015.
*/
public class SocketChannel extends SensorChannel
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<Integer> bytes = new Option<>("bytes", 0, Integer.class, "");
public final Option<Integer> dim = new Option<>("dim", 0, Integer.class, "");
public final Option<Double> sr = new Option<>("sr", 0., Double.class, "");
public final Option<Integer> num = new Option<>("num", 1, Integer.class, "values >1 make buffer error handling less efficient");
public final Option<Cons.Type> type = new Option<>("type", Cons.Type.UNDEF, Cons.Type.class, "");
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 SocketChannel()
{
_name = "SocketReader_Data";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (options.sr.get() == 0 || options.bytes.get() == 0 || options.dim.get() == 0 || options.type.get() == Cons.Type.UNDEF)
{
Log.e("input channel not configured");
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
byte[] data = ((SocketReader)_sensor).getData();
if(data.length != stream_out.tot)
{
Log.w("data mismatch");
return false;
}
Util.arraycopy(data, 0, stream_out.ptr(), 0, stream_out.tot);
return true;
}
@Override
public int getSampleDimension()
{
return options.dim.get();
}
@Override
public double getSampleRate()
{
return options.sr.get();
}
@Override
public int getSampleBytes()
{
return options.bytes.get();
}
@Override
public int getSampleNumber()
{
return options.num.get();
}
@Override
public Cons.Type getSampleType()
{
return options.type.get();
}
@Override
public void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
if(options.outputClass.get() == null || stream_out.dim != options.outputClass.get().length)
{
Log.w("incomplete definition of output classes");
for(int i = 0; i < stream_out.desc.length; i++)
stream_out.desc[i] = "SocketData";
}
else
{
System.arraycopy(options.outputClass.get(), 0, stream_out.desc, 0, options.outputClass.get().length);
}
}
}
| 4,440 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GATTChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/GATTChannel.java | /*
* GATTChannel.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.ioput;
import android.os.Build;
import java.util.UUID;
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 16.07.2021.
*/
public class GATTChannel extends SensorChannel
{
public enum SupportedUUIDs
{
BATTERY_LEVEL("00002a19-0000-1000-8000-00805f9b34fb"),
HUMIDITY("00002a6f-0000-1000-8000-00805f9b34fb"),
TEMPERATURE("00002a6e-0000-1000-8000-00805f9b34fb");
UUID uuid;
SupportedUUIDs(String uuid)
{
this.uuid = UUID.fromString(uuid);
}
}
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 1.0f, Float.class, "samples per second");
public final Option<String> customUUID = new Option<>("customUUID", "", String.class, "manual UUID, overwrites supported UUID field");
public final Option<String> customName = new Option<>("customName", "", String.class, "data channel name");
public final Option<SupportedUUIDs> supportedUUID = new Option<>("supportedUUID", SupportedUUIDs.BATTERY_LEVEL, SupportedUUIDs.class, "");
private Options() {
addOptions();
}
}
public final Options options = new Options();
GATTConnection _connection;
UUID targetUUID;
public GATTChannel()
{
_name = "GATTChannel";
}
@Override
public OptionList getOptions()
{
return options;
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
_connection = ((GATTReader) _sensor).connection;
updateTargetUUID();
_connection.registerCharacteristic(targetUUID);
}
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
Float value = (Float) _connection.characteristicValue.get(targetUUID);
if (value != null)
{
float[] out = stream_out.ptrF();
out[0] = value;
return true;
}
}
return false;
}
@Override
protected double getSampleRate()
{
return options.sampleRate.get();
}
@Override
protected int getSampleDimension()
{
return 1;
}
@Override
protected Cons.Type getSampleType()
{
return Cons.Type.FLOAT;
}
private void updateTargetUUID()
{
String customUUID = options.customUUID.get();
if (customUUID != null && !customUUID.isEmpty())
{
targetUUID = UUID.fromString(customUUID);
}
else
{
targetUUID = options.supportedUUID.get().uuid;
}
}
@Override
protected void describeOutput(Stream stream_out)
{
stream_out.desc = new String[stream_out.dim];
stream_out.desc[0] = "GATT Value";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
{
updateTargetUUID();
if (targetUUID != null)
{
GATTConnection.CharacteristicDetails details = GATTConnection.GATT_DETAILS.get(targetUUID.toString());
if (details != null)
{
stream_out.desc[0] = details.name;
}
else
{
stream_out.desc[0] = options.customName.get();
}
}
}
}
}
| 4,543 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BluetoothWriter.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ioput/BluetoothWriter.java | /*
* BluetoothWriter.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.ioput;
import android.bluetooth.BluetoothDevice;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.UUID;
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;
/**
* Created by Johnny on 05.03.2015.
*/
public class BluetoothWriter extends Consumer {
public class Options extends OptionList
{
public final Option<String> serverName = new Option<>("serverName", "SSJ_BLServer", String.class, "");
public final Option<String> serverAddr = new Option<>("serverAddr", null, String.class, "if this is a client");
public final Option<String> connectionName = new Option<>("connectionName", "SSJ", String.class, "must match that of the peer");
public final Option<BluetoothConnection.Type> connectionType = new Option<>("connectionType", BluetoothConnection.Type.CLIENT, BluetoothConnection.Type.class, "");
/**
*
*/
private Options() {
addOptions();
}
}
public final Options options = new Options();
private BluetoothConnection _conn;
private byte[] _data;
private boolean _connected = false;
public BluetoothWriter() {
_name = "BluetoothWriter";
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
try {
switch(options.connectionType.get())
{
case SERVER:
_conn = new BluetoothServer(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get());
_conn.connect(stream_in.length > 1); //use object output streams if we are sending more than one stream
break;
case CLIENT:
_conn = new BluetoothClient(UUID.nameUUIDFromBytes(options.connectionName.get().getBytes()), options.serverName.get(), options.serverAddr.get());
_conn.connect(stream_in.length > 1); //use object output streams if we are sending more than one stream
break;
}
} catch (Exception e)
{
throw new SSJFatalException("error in setting up connection "+ options.connectionName, e);
}
BluetoothDevice dev = _conn.getRemoteDevice();
if(dev == null) {
Log.e("cannot retrieve remote device");
return;
}
if (stream_in.length == 1)
{
_data = new byte[stream_in[0].tot];
}
Log.i("connected to " + dev.getName() + " @ " + dev.getAddress());
_connected = true;
}
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
if (!_connected || !_conn.isConnected())
{
return;
}
try {
if(stream_in.length == 1)
{
Util.arraycopy(stream_in[0].ptr(), 0, _data, 0, _data.length);
_conn.output().write(_data);
}
else if(stream_in.length > 1)
{
((ObjectOutputStream)_conn.output()).reset();
((ObjectOutputStream)_conn.output()).writeObject(stream_in);
}
_conn.notifyDataTranferResult(true);
} catch (IOException e) {
Log.w("failed sending data", e);
_conn.notifyDataTranferResult(false);
}
}
public void flush(Stream[] stream_in) throws SSJFatalException
{
_connected = false;
try {
_conn.disconnect();
} catch (IOException e) {
Log.e("failed closing connection", e);
}
}
@Override
public void forcekill()
{
try {
_conn.disconnect();
} catch (IOException e) {
Log.e("failed closing connection", e);
}
super.forcekill();
}
@Override
public void clear()
{
_conn.clear();
_conn = null;
super.clear();
}
@Override
public OptionList getOptions()
{
return options;
}
}
| 5,587 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSI.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/mobileSSI/SSI.java | /*
* SSI.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.mobileSSI;
import hcm.ssj.core.Cons;
import hcm.ssj.core.stream.Stream;
import static java.lang.System.loadLibrary;
/**
* Interfaace for communication with SSI framework
* Created by Ionut Damian on 07.09.2017.
*/
public class SSI
{
static
{
loadLibrary("ssissjbridge");
}
public static native String getVersion();
public static native long create(String name, String libname, String libpath);
public static native boolean setOption(long ssiobj, String name, String value);
public static native void transformEnter(long ssiobj, Stream[] stream_in, Stream stream_out);
public static native void transform(long ssiobj, Stream[] stream_in, Stream stream_out);
public static native void transformFlush(long ssiobj, Stream[] stream_in, Stream stream_out);
public static native int getSampleNumberOut(long ssiobj, int sample_number_in);
public static native int getSampleDimensionOut(long ssiobj, int sample_dimension_in);
public static native int getSampleBytesOut(long ssiobj, int sample_bytes_in);
public static native int getSampleTypeOut(long ssiobj, Cons.Type sample_type_in);
public static native long clear();
public enum TransformerName
{
//TRANSFORMERS
AudioActivity("ssiaudio"),
AudioConvert("ssiaudio"),
AudioIntensity("ssiaudio"),
OSLpc("ssiaudio"),
AudioMono("ssiaudio"),
SNRatio("ssiaudio"),
ClassifierT("ssimodel"),
Bundle("ssisignal"),
Butfilt("ssisignal"),
ConvPower("ssisignal"),
Derivative("ssisignal"),
DownSample("ssisignal"),
Energy("ssisignal"),
Expression("ssisignal"),
FFTfeat("ssisignal"),
Functionals("ssisignal"),
Gate("ssisignal"),
IIR("ssisignal"),
Integral("ssisignal"),
Intensity("ssisignal"),
Limits("ssisignal"),
Mean("ssisignal"),
MFCC("ssisignal"),
MvgAvgVar("ssisignal"),
MvgConDiv("ssisignal"),
MvgDrvtv("ssisignal"),
MvgMedian("ssisignal"),
MvgMinMax("ssisignal"),
MvgNorm("ssisignal"),
MvgPeakGate("ssisignal"),
Noise("ssisignal"),
Normalize("ssisignal"),
Pulse("ssisignal"),
Relative("ssisignal"),
Spectrogram("ssisignal"),
Statistics("ssisignal"),
Sum("ssisignal"),
EmoVoiceFeat("ssiemovoice"),
EmoVoiceMFCC("ssiemovoice"),
EmoVoicePitch("ssiemovoice"),
EmoVoiceVAD("ssiemovoice");
public String lib;
TransformerName(String lib)
{
this.lib = lib;
}
}
}
| 3,678 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MobileSSIConsumer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/mobileSSI/MobileSSIConsumer.java | /*
* MobileSSIConsumer.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.mobileSSI;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
import hcm.ssj.core.SSJFatalException;
import hcm.ssj.core.event.Event;
import hcm.ssj.core.option.OptionList;
import hcm.ssj.core.stream.Stream;
import static java.lang.System.loadLibrary;
/**
* File writer for SSJ.<br>
* Created by Frank Gaibler on 20.08.2015.
*/
public class MobileSSIConsumer extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
*
*/
public class Options extends OptionList
{
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public MobileSSIConsumer()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length > 1 || stream_in.length < 1)
{
Log.e("stream count not supported");
return;
}
if (stream_in[0].type == Cons.Type.EMPTY || stream_in[0].type == Cons.Type.UNDEF)
{
Log.e("stream type not supported");
return;
}
start(stream_in[0]);
}
/**
* @param stream Stream
*/
private void start(Stream stream)
{
}
/**
* @param stream_in Stream[]
* @param trigger event trigger
*/
@Override
protected final void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
float[] floats = stream_in[0].ptrF();
stream_in[0].ptrF()[0]=0.5f;
//ssi_ssj_sensor
pushData(stream_in[0], getId());
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream stream_in[]) throws SSJFatalException
{
}
@Override
public final void init(Stream stream_in[]) throws SSJException
{
int t=0;
if (stream_in[0].type == Cons.Type.FLOAT)
{
t = 9;
}
setStreamOptions(getId(), stream_in[0].num, stream_in[0].dim, t, stream_in[0].sr);
}
public void setId(int _id)
{
id=_id;
}
public int getId()
{return id;}
static
{
loadLibrary("ssissjSensor");
}
public native void setSensor(Object sensor, Stream[] stream, int id);
public native void pushData(Stream stream, int id);
public native void setStreamOptions(int id, int num, int dim, int type, double sr);
private int id=0;
}
| 3,965 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSITransformer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/mobileSSI/SSITransformer.java | /*
* SSITransformer.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.mobileSSI;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.SSJException;
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;
import hcm.ssj.file.FileCons;
/**
* File writer for SSJ.<br>
* Created by Frank Gaibler on 20.08.2015.
*/
public class SSITransformer extends Transformer
{
@Override
public OptionList getOptions()
{
return options;
}
/**
*
*/
public class Options extends OptionList
{
public final Option<SSI.TransformerName> name = new Option<>("name", SSI.TransformerName.Mean, SSI.TransformerName.class, "name of the SSI transformer");
public final Option<String[]> ssioptions = new Option<>("ssioptions", null, String[].class, "options of the SSI transformer. Format: [name->value, name->value, ...]");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private long ssi_object = 0;
public SSITransformer()
{
_name = this.getClass().getSimpleName();
}
@Override
public void init(double frame, double delta) throws SSJException
{
Log.i("loading SSI libraries (" + SSI.getVersion()+ ")");
ssi_object = SSI.create(options.name.get().toString(), options.name.get().lib, FileCons.INTERNAL_LIB_DIR);
if(ssi_object == 0)
{
throw new SSJException("error creating SSI transformer");
}
//set options
if(options.ssioptions.get() != null)
{
for (String option : options.ssioptions.get())
{
String[] pair = option.split("->");
if (pair.length != 2)
{
Log.w("misformed ssi option: " + option + ". Should be 'name->pair'.");
continue;
}
if (!SSI.setOption(ssi_object, pair[0], pair[1]))
{
Log.w("unable to set option " + pair[0] + " to value " + pair[1]);
}
}
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (ssi_object != 0)
{
SSI.transformEnter(ssi_object, stream_in, stream_out);
}
}
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (ssi_object != 0)
{
SSI.transform(ssi_object, stream_in, stream_out);
}
}
/**
* @param stream_in Stream[]
*/
@Override
public final void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
if (ssi_object != 0)
{
SSI.transformFlush(ssi_object, stream_in, stream_out);
}
}
@Override
public int getSampleDimension(Stream[] stream_in)
{
if(ssi_object == 0)
{
Log.e("ssi interface not initialized");
return 0;
}
return SSI.getSampleDimensionOut(ssi_object, stream_in[0].dim);
}
@Override
public int getSampleBytes(Stream[] stream_in)
{
if(ssi_object == 0)
{
Log.e("ssi interface not initialized");
return 0;
}
return SSI.getSampleBytesOut(ssi_object, stream_in[0].bytes);
}
@Override
public Cons.Type getSampleType(Stream[] stream_in)
{
if(ssi_object == 0)
{
Log.e("ssi interface not initialized");
return null;
}
int type = SSI.getSampleTypeOut(ssi_object, stream_in[0].type);
switch(type)
{
default: //unsigned and unknown
case 0: //SSI_UNDEF
return Cons.Type.UNDEF;
case 1: //SSI_CHAR
return Cons.Type.BYTE;
case 3: //SSI_SHORT
return Cons.Type.SHORT;
case 5: //SSI_INT
return Cons.Type.INT;
case 7: //SSI_LONG
return Cons.Type.LONG;
case 9: //SSI_FLOAT
return Cons.Type.FLOAT;
case 10: //SSI_DOUBLE
return Cons.Type.DOUBLE;
case 13: //SSI_IMAGE
return Cons.Type.IMAGE;
case 14: //SSI_BOOL
return Cons.Type.BOOL;
}
}
@Override
public int getSampleNumber(int sampleNumber_in)
{
return SSI.getSampleNumberOut(ssi_object, sampleNumber_in);
}
@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] = "SSI_" + options.name.get() + "_" + i;
}
}
| 6,321 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AnchorOptions.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/AnchorOptions.java | /*
* AnchorOptions.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.ssd;
/**
* Created by Michael Dietz on 11.01.2021.
*/
public class AnchorOptions
{
public int numLayers = 4;
public float minScale = 0.1484375f;
public float maxScale = 0.75f;
public int inputSizeHeight = 128;
public int inputSizeWidth = 128;
public float anchorOffsetX = 0.5f;
public float anchorOffsetY = 0.5f;
public int[] strides = new int[] {8, 16, 16, 16};
public float[] aspectRatios = new float[] {1.0f};
public boolean fixedAnchorSize = true;
public boolean reduceBoxesInLowestLayer = false;
public float interpolatedScaleAspectRatio = 1.0f;
public int[] featureMapHeight = new int[] {};
public int[] featureMapWidth = new int[] {};
}
| 2,029 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Landmark.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/Landmark.java | /*
* Landmark.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.ssd;
/**
* Created by Michael Dietz on 12.01.2021.
*/
public class Landmark
{
public float x;
public float y;
public float z;
public float visibility;
public Landmark(float visibility)
{
this.visibility = visibility;
}
public Landmark(float x, float y)
{
this(x, y, 0.0f);
}
public Landmark(float x, float y, float z)
{
this(x, y, z, 1.0f);
}
public Landmark(float x, float y, float z, float visibility)
{
this.x = x;
this.y = y;
this.z = z;
this.visibility = visibility;
}
}
| 1,875 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SingleShotMultiBoxDetector.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/SingleShotMultiBoxDetector.java | /*
* SingleShotMultiBoxDetector.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.ssd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 07.11.2019.
*/
public class SingleShotMultiBoxDetector
{
private AnchorOptions anchorOptions;
private CalculatorOptions calculatorOptions;
private List<Anchor> anchorList;
private Comparator<Detection> detectionComparator;
public SingleShotMultiBoxDetector()
{
this(new AnchorOptions(), new CalculatorOptions());
}
public SingleShotMultiBoxDetector(AnchorOptions anchorOptions)
{
this(anchorOptions, new CalculatorOptions());
}
public SingleShotMultiBoxDetector(CalculatorOptions calculatorOptions)
{
this(new AnchorOptions(), calculatorOptions);
}
public SingleShotMultiBoxDetector(AnchorOptions anchorOptions, CalculatorOptions calculatorOptions)
{
this.anchorOptions = anchorOptions;
this.calculatorOptions = calculatorOptions;
anchorList = getAnchors();
detectionComparator = new Comparator<Detection>()
{
@Override
public int compare(Detection d1, Detection d2)
{
return Float.compare(d1.score, d2.score);
}
};
}
private float calculateScale(float minScale, float maxScale, float strideIndex, int numStrides)
{
return minScale + (maxScale - minScale) * 1.0f * strideIndex / (numStrides - 1.0f);
}
/**
* Calculates anchors.
*
* @link https://github.com/google/mediapipe/blob/master/mediapipe/calculators/tflite/ssd_anchors_calculator.cc
* @return
*/
private List<Anchor> getAnchors()
{
List<Anchor> anchors = new ArrayList<>();
if (anchorOptions.strides.length != anchorOptions.numLayers)
{
Log.e("Stride count and numLayers must be equal!");
return anchors;
}
int layerId = 0;
while (layerId < anchorOptions.strides.length)
{
List<Float> anchorHeight = new ArrayList<>();
List<Float> anchorWidth = new ArrayList<>();
List<Float> aspectRatios = new ArrayList<>();
List<Float> scales = new ArrayList<>();
// For same strides, we merge the anchors in the same order.
int lastSameStrideLayer = layerId;
while (lastSameStrideLayer < anchorOptions.strides.length && anchorOptions.strides[lastSameStrideLayer] == anchorOptions.strides[layerId])
{
final float scale = calculateScale(anchorOptions.minScale, anchorOptions.maxScale, lastSameStrideLayer, anchorOptions.strides.length);
if (lastSameStrideLayer == 0 && anchorOptions.reduceBoxesInLowestLayer)
{
// For first layer, it can be specified to use predefined anchors.
aspectRatios.add(1.0f);
aspectRatios.add(2.0f);
aspectRatios.add(0.5f);
scales.add(0.1f);
scales.add(scale);
scales.add(scale);
}
else
{
for (int aspectRatioId = 0; aspectRatioId < anchorOptions.aspectRatios.length; aspectRatioId++)
{
aspectRatios.add(anchorOptions.aspectRatios[aspectRatioId]);
scales.add(scale);
}
if (anchorOptions.interpolatedScaleAspectRatio > 0.0f)
{
final float scaleNext = lastSameStrideLayer == anchorOptions.strides.length - 1 ? 1.0f : calculateScale(anchorOptions.minScale, anchorOptions.maxScale, lastSameStrideLayer + 1, anchorOptions.strides.length);
aspectRatios.add(anchorOptions.interpolatedScaleAspectRatio);
scales.add((float) Math.sqrt(scale * scaleNext));
}
}
lastSameStrideLayer += 1;
}
for (int i = 0; i < aspectRatios.size(); i++)
{
final float ratioSqrts = (float) Math.sqrt(aspectRatios.get(i));
anchorHeight.add(scales.get(i) / ratioSqrts);
anchorWidth.add(scales.get(i) * ratioSqrts);
}
int stride = anchorOptions.strides[layerId];
int featureMapHeight = (int) Math.ceil(1.0 * anchorOptions.inputSizeHeight / stride);
int featureMapWidth = (int) Math.ceil(1.0 * anchorOptions.inputSizeWidth / stride);
if (anchorOptions.featureMapHeight.length > 0)
{
featureMapHeight = anchorOptions.featureMapHeight[layerId];
featureMapWidth = anchorOptions.featureMapWidth[layerId];
}
for (int y = 0; y < featureMapHeight; y++)
{
for (int x = 0; x < featureMapWidth; x++)
{
for (int anchorId = 0; anchorId < anchorHeight.size(); anchorId++)
{
final float xCenter = (x + anchorOptions.anchorOffsetX) * 1.0f / featureMapWidth;
final float yCenter = (y + anchorOptions.anchorOffsetY) * 1.0f / featureMapHeight;
Anchor anchor = new Anchor();
anchor.xCenter = xCenter;
anchor.yCenter = yCenter;
if (anchorOptions.fixedAnchorSize)
{
anchor.width = 1.0f;
anchor.height = 1.0f;
}
else
{
anchor.width = anchorWidth.get(anchorId);
anchor.height = anchorHeight.get(anchorId);
}
anchors.add(anchor);
}
}
}
layerId = lastSameStrideLayer;
}
return anchors;
}
public List<Detection> process(final float[][][] rawBoxes, final float[][][] rawScores)
{
List<Detection> detections = new ArrayList<>();
int candidateIndex = 0;
int highestScoreIndex = -1;
int largestAreaIndex = -1;
double largestArea = Double.MIN_VALUE;
double highestScore = Double.MIN_VALUE;
// Filter scores
for (int boxIndex = 0; boxIndex < calculatorOptions.numBoxes; boxIndex++)
{
double maxClassScore = Double.MIN_VALUE;
int classId = -1;
// Calculate max score across classes
for (int classIndex = 0; classIndex < calculatorOptions.numClasses; classIndex++)
{
double classScore = rawScores[0][boxIndex][classIndex];
if (calculatorOptions.sigmoidScore)
{
if (calculatorOptions.scoreClippingThresh > 0)
{
classScore = classScore < -calculatorOptions.scoreClippingThresh ? -calculatorOptions.scoreClippingThresh : classScore;
classScore = classScore > calculatorOptions.scoreClippingThresh ? calculatorOptions.scoreClippingThresh : classScore;
}
classScore = 1.0 / (1.0 + Math.exp(-classScore));
}
if (maxClassScore < classScore)
{
maxClassScore = classScore;
classId = classIndex;
}
}
if (maxClassScore >= calculatorOptions.minScoreThresh)
{
// Box candidate detected
Detection detection = decodeBox(candidateIndex, anchorList.get(boxIndex), rawBoxes[0][boxIndex], (float) maxClassScore, classId);
// For filter purposes
double area = detection.width * detection.height;
if (area > largestArea)
{
largestArea = area;
largestAreaIndex = candidateIndex;
}
if (detection.score > highestScore)
{
highestScore = detection.score;
highestScoreIndex = candidateIndex;
}
// Add detection to candidate list
detections.add(detection);
candidateIndex += 1;
}
}
if (detections.size() > 0)
{
switch (calculatorOptions.filterMethod)
{
case HIGHEST_SCORE:
Detection highestScoreDetection = detections.get(highestScoreIndex);
detections.clear();
detections.add(highestScoreDetection);
break;
case LARGEST_AREA:
Detection largestAreaDetection = detections.get(largestAreaIndex);
detections.clear();
detections.add(largestAreaDetection);
break;
case NON_MAX_SUPPRESSION:
detections = weightedNonMaxSuppression(detections);
break;
}
}
return detections;
}
private Detection decodeBox(int id, Anchor anchor, final float[] rawBoxValues, float score, int classId)
{
if (rawBoxValues.length != calculatorOptions.numCoords)
{
Log.e("rawBoxValues.length != calculatorOptions.numCoords");
}
final int boxOffset = calculatorOptions.boxCoordOffset;
float yCenter = rawBoxValues[boxOffset];
float xCenter = rawBoxValues[boxOffset + 1];
float height = rawBoxValues[boxOffset + 2];
float width = rawBoxValues[boxOffset + 3];
if (calculatorOptions.reverseOutputOrder)
{
xCenter = rawBoxValues[boxOffset];
yCenter = rawBoxValues[boxOffset + 1];
width = rawBoxValues[boxOffset + 2];
height = rawBoxValues[boxOffset + 3];
}
xCenter = xCenter / calculatorOptions.xScale * anchor.width + anchor.xCenter;
yCenter = yCenter / calculatorOptions.yScale * anchor.height + anchor.yCenter;
if (calculatorOptions.applyExponentialOnBoxSize)
{
height = (float) (Math.exp(height / calculatorOptions.hScale) * anchor.height);
width = (float) (Math.exp(width / calculatorOptions.wScale) * anchor.width);
}
else
{
height = height / calculatorOptions.hScale * anchor.height;
width = width / calculatorOptions.wScale * anchor.width;
}
final float yMin = yCenter - (height / 2.0f);
final float xMin = xCenter - (width / 2.0f);
final float yMax = yCenter + (height / 2.0f);
final float xMax = xCenter + (width / 2.0f);
Detection detection = new Detection();
detection.id = id;
detection.yMin = calculatorOptions.flipVertically ? 1.0f - yMax : yMin;
detection.xMin = xMin;
detection.width = xMax - xMin;
detection.height = yMax - yMin;
detection.score = score;
detection.classId = classId;
if (calculatorOptions.numKeypoints > 0)
{
List<Keypoint> keypoints = new ArrayList<>();
for (int keypointId = 0; keypointId < calculatorOptions.numKeypoints; keypointId++)
{
final int keypointOffset = boxOffset + calculatorOptions.keypointCoordOffset + keypointId * calculatorOptions.numValuesPerKeypoint;
float keypointY = rawBoxValues[keypointOffset];
float keypointX = rawBoxValues[keypointOffset + 1];
if (calculatorOptions.reverseOutputOrder)
{
keypointX = rawBoxValues[keypointOffset];
keypointY = rawBoxValues[keypointOffset + 1];
}
keypointX = keypointX / calculatorOptions.xScale * anchor.width + anchor.xCenter;
keypointY = keypointY / calculatorOptions.yScale * anchor.height + anchor.yCenter;
Keypoint keypoint = new Keypoint();
keypoint.x = keypointX;
keypoint.y = calculatorOptions.flipVertically ? 1.0f - keypointY : keypointY;
keypoints.add(keypoint);
}
detection.keypoints = keypoints;
}
return detection;
}
private List<Detection> weightedNonMaxSuppression(List<Detection> detections)
{
List<Detection> remaining = new ArrayList<>(detections);
List<Detection> picked = new ArrayList<>();
List<Detection> suppressed = new ArrayList<>();
// Sort list by score ascending
Collections.sort(remaining, detectionComparator);
int lastIndex;
Detection pick;
while (!remaining.isEmpty())
{
// Move last element (with highest score) into picked list
lastIndex = remaining.size() - 1;
pick = remaining.get(lastIndex);
picked.add(pick);
remaining.remove(pick);
// Compare overlap with all remaining detections
for (Detection remainingDetection : remaining)
{
// Remove detection if overlap with pick is bigger than threshold
if (pick.getOverlap(remainingDetection) > calculatorOptions.nmsThreshold)
{
suppressed.add(remainingDetection);
}
}
remaining.removeAll(suppressed);
suppressed.clear();
}
return picked;
}
}
| 12,338 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CalculatorOptions.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/CalculatorOptions.java | /*
* CalculatorOptions.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.ssd;
/**
* Created by Michael Dietz on 11.01.2021.
*/
public class CalculatorOptions
{
public int numClasses = 1;
public int numBoxes = 896;
public int numCoords = 16;
public int boxCoordOffset = 0;
public int keypointCoordOffset = 4;
public int numKeypoints = 6;
public int numValuesPerKeypoint = 2;
public boolean sigmoidScore = true;
public float scoreClippingThresh = 100;
public boolean reverseOutputOrder = true;
public float xScale = 128.0f;
public float yScale = 128.0f;
public float hScale = 128.0f;
public float wScale = 128.0f;
public double minScoreThresh = 0.75f;
public boolean applyExponentialOnBoxSize = false;
public boolean flipVertically = false;
public FilterMethod filterMethod = FilterMethod.HIGHEST_SCORE;
public float nmsThreshold = 0.3f;
}
| 2,159 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Keypoint.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/Keypoint.java | /*
* Keypoint.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.ssd;
/**
* Created by Michael Dietz on 11.01.2021.
*/
public class Keypoint
{
public float x;
public float y;
public Keypoint()
{
}
public Keypoint(float x, float y)
{
this.x = x;
this.y = y;
}
}
| 1,576 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Anchor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/Anchor.java | /*
* Anchor.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.ssd;
/**
* Created by Michael Dietz on 11.01.2021.
*/
class Anchor
{
public float xCenter;
public float yCenter;
public float width;
public float height;
}
| 1,523 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FilterMethod.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/FilterMethod.java | /*
* FilterMethod.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.ssd;
/**
* Created by Michael Dietz on 11.01.2021.
*/
public enum FilterMethod
{
HIGHEST_SCORE,
LARGEST_AREA,
NON_MAX_SUPPRESSION
}
| 1,504 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Detection.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ssd/Detection.java | /*
* Detection.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.ssd;
import java.util.ArrayList;
import java.util.List;
public class Detection
{
public int id;
public float yMin;
public float xMin;
public float width;
public float height;
public float score;
public int classId;
public List<Keypoint> keypoints = new ArrayList<>();
public float getArea()
{
return width * height;
}
public float getOverlap(Detection other)
{
float overlap = 0;
// Get top left coordinate of overlapping area
float overlapX1 = Math.max(xMin, other.xMin);
float overlapY1 = Math.max(yMin, other.yMin);
// Get bottom right coordinate of overlapping area
float overlapX2 = Math.min(xMin + width, other.xMin + other.width);
float overlapY2 = Math.min(yMin + height, other.yMin + other.height);
float overlapWidth = Math.max(0, overlapX2 - overlapX1);
float overlapHeight = Math.max(0, overlapY2 - overlapY1);
float overlapArea = overlapWidth * overlapHeight;
if (overlapArea > 0)
{
// Overlap value is calculated by dividing the intersection through the total area
overlap = overlapArea / (getArea() + other.getArea() - overlapArea);
}
return overlap;
}
}
| 2,493 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SVM.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/SVM.java | /*
* SVM.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.ml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.stream.Stream;
import libsvm.svm;
import libsvm.svm_model;
import libsvm.svm_node;
import libsvm.svm_problem;
/**
* Implements an SVM model using the libsvm library<br>
* Created by Ionut Damian
*/
public class SVM extends Model
{
/**
* All options for the transformer
*/
public class Options extends Model.Options
{
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private int n_features;
private double[] max = null;
private double[] min = null;
private svm_model model;
private svm_node[] nodes;
private svm_node[] usInstance;
private double[] prob_estimates;
private float[] probs;
private static final int SVM_SCALE_UPPER = 1;
private static final int SVM_SCALE_LOWER = -1;
/**
*
*/
public SVM()
{
_name = this.getClass().getSimpleName();
}
@Override
void init(int input_dim, int output_dim, String[] outputNames)
{
n_features = input_dim;
nodes = new svm_node[n_features+1];
for(int i = 0; i < nodes.length; i++)
nodes[i] = new svm_node();
usInstance = new svm_node[n_features+1];
for(int i = 0; i < usInstance.length; i++)
usInstance[i] = new svm_node();
prob_estimates = new double[output_dim];
probs = new float[output_dim];
}
@Override
public Model.Options getOptions()
{
return options;
}
/**
* @param stream Stream
* @return double[]
*/
protected float[] forward(Stream stream)
{
if (!isTrained)
{
Log.w("not trained");
return null;
}
if (stream.dim != n_features)
{
Log.w("feature dimension differs");
return null;
}
if (stream.type != Cons.Type.FLOAT) {
Log.w ("invalid stream type");
return null;
}
float[] ptr = stream.ptrF();
for (int i = 0; i < n_features; i++) {
nodes[i].index = i + 1;
nodes[i].value = ptr[i];
}
nodes[n_features].index=-1;
scale_instance (nodes, n_features);
svm.svm_predict_probability (model, nodes, prob_estimates);
//normalization
float sum = 0;
for (int i = 0; i < output_dim; i++) {
probs[model.label[i]] = (float) prob_estimates[i];
sum += probs[model.label[i]];
}
for (int j = 0; j < output_dim; j++) {
probs[j]/=sum;
}
return probs;
}
/**
* Load data from option file
*/
protected void loadOption(File file)
{
}
/**
* Load data from model file
*/
protected void loadModel(File file)
{
if (file == null)
{
Log.e("model file not set in options");
return;
}
BufferedReader reader = null;
try
{
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
//skip comments
String line;
do {
line = reader.readLine();
} while (line.startsWith("#") || line.charAt(0) == '\n');
//read num class and num features
String token[] = line.split("\t");
if (token.length > 0) {
int classNum = Integer.valueOf(token[0]);
if(classNum != output_dim)
Log.w("model definition (n_classes) mismatch between trainer and model file: " + classNum +" != "+ output_dim);
} else {
throw new IOException("can't read number of classes from classifier file " + file.getName() + "!");
}
if (token.length > 1) {
n_features = Integer.valueOf(token[1]);
} else {
throw new IOException("can't read feature dimension from classifier file " + file.getName() + "'!");
}
//skip comments
do {
line = reader.readLine();
} while (line.startsWith("#") || line.charAt(0) == '\n');
// read class names
String[] names = line.split(" ");
for(int i = 0; i < names.length; i++)
{
if (!names[i].equalsIgnoreCase(output_names[i]))
{
Log.w("model definition (name of class " + i + ") mismatch between trainer and model file:" + names[i] + " != " + output_names[i]);
output_names[i] = names[i];
}
}
max = new double[n_features];
min = new double[n_features];
if(scan(reader, "# Scaling: max\tmin") == null)
throw new IOException("can't read scaling information for SVM classifier from " + file.getName());
for (int i = 0; i < n_features; i++) {
line = reader.readLine();
token = line.split("\t");
if (token.length != 2) {
throw new IOException("misformed scaling information for SVM classifier from " + file.getName());
}
max[i] = Double.valueOf(token[0]);
min[i] = Double.valueOf(token[1]);
}
do {
line = reader.readLine();
} while (line.isEmpty() || line.startsWith("#") || line.charAt(0) == '\n');
//read SVM model
model = svm.svm_load_model(reader);
}
catch (FileNotFoundException e)
{
Log.e("file not found");
return;
}
catch (IOException e)
{
Log.e("error reading SVM model", e);
return;
}
finally {
try
{
reader.close();
}
catch(IOException | NullPointerException e)
{
Log.e("error closing reader", e);
}
}
isTrained = true;
}
/**
* @param reader BufferedReader
* @return String
*/
private String scan(BufferedReader reader, String msg)
{
String line;
try
{
do {
line = reader.readLine();
if (line.contains(msg))
return line;
} while(line != null);
}
catch (IOException e)
{
Log.e("could not read line");
}
return null;
}
void create_scaling (svm_problem problem, int n_features, double[] _max, double[] _min) {
int i,j, idx;
double temp;
for (i=0;i<n_features;i++){
_max[i]=-Double.MAX_VALUE;
_min[i]=Double.MAX_VALUE;
}
for (i=0;i<problem.l;i++) {
idx=0;
for (j=0;j<n_features;j++) {
if (problem.x[i][idx].index != j+1)
temp=0;
else {
temp=problem.x[i][idx].value;
idx++;
}
if (temp < _min[j])
_min[j] = temp;
if (temp > _max[j])
_max[j] = temp;
}
}
}
void scale_instance (svm_node[] instance, int n_features) {
int j=0, idx=0, n_idx=0;
double temp;
while (instance[j].index != -1) {
usInstance[j].index=instance[j].index;
usInstance[j].value=instance[j].value;
j++;
}
usInstance[j].index=-1;
for (j=0;j<n_features;j++) {
if (usInstance[idx].index != j+1)
temp=0;
else
temp=usInstance[idx++].value;
if (max[j]-min[j] != 0)
temp=SVM_SCALE_LOWER+(SVM_SCALE_UPPER-SVM_SCALE_LOWER)*(temp-min[j])/(max[j]-min[j]);
else
temp=SVM_SCALE_LOWER+(SVM_SCALE_UPPER-SVM_SCALE_LOWER)*(temp-min[j])/Float.MIN_VALUE;
if (temp != 0) {
instance[n_idx].index=j+1;
instance[n_idx++].value=temp;
}
}
instance[n_idx].index=-1;
}
}
| 10,035 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Model.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/Model.java | /*
* Model.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.ml;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import hcm.ssj.core.Annotation;
import hcm.ssj.core.Component;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJException;
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;
/**
* Generic model for machine learning
* Created by Ionut Damian on 10.10.2016.
*/
public abstract class Model extends Component
{
protected int[] select_dimensions = null;
protected String modelFileName;
protected String modelOptionFileName;
protected String dirPath = null;
protected int input_bytes = 0;
protected int input_dim = 0;
protected int input_num = 1;
protected double input_sr = 0;
protected Cons.Type input_type = Cons.Type.UNDEF;
protected boolean isTrained = false;
protected int output_dim = 0;
protected String[] output_names = null;
protected int output_heads = 0;
protected int[] output_dims = null;
public class Options extends OptionList
{
public final Option<FilePath> file = new Option<>("file", null, FilePath.class, "trainer file containing model information");
public Options()
{
super();
addOptions();
}
}
@Override
public void run()
{
Thread.currentThread().setName("SSJ_" + _name);
if(!_isSetup)
{
// pipe.error(_name, "not initialized", null);
Log.e("not initialized");
_safeToKill = true;
return;
}
try
{
load();
}
catch (IOException e)
{
Log.e("error loading model", e);
}
synchronized (this)
{
this.notifyAll();
}
_safeToKill = true;
}
public void waitUntilReady()
{
if(!isTrained())
{
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
// Do nothing
}
}
}
}
/**
* Called when model is added to the pipeline
*
* @throws SSJException When setup fails
*/
public void setup() throws SSJException
{
if (_isSetup)
{
return;
}
// Check if trainer file has been set
if (getOptions().file.get() != null && getOptions().file.get().value != null && !getOptions().file.get().value.isEmpty())
{
String trainerFile = getOptions().file.get().value;
String fileName = trainerFile.substring(trainerFile.lastIndexOf(File.separator)+1);
dirPath = trainerFile.substring(0, trainerFile.lastIndexOf(File.separator));
try
{
parseTrainerFile(FileUtils.getFile(dirPath, fileName));
}
catch (IOException | XmlPullParserException e)
{
throw new SSJException("error parsing trainer file", e);
}
init(input_dim, output_dim, output_names);
_isSetup = true;
}
else
{
Log.w("option file not defined");
}
}
public void setup(String[] classNames, int bytes_input, int dim_input, double sr_input, Cons.Type type_input)
{
this.input_bytes = bytes_input;
this.input_dim = dim_input;
this.input_sr = sr_input;
this.input_type = type_input;
this.output_names = classNames;
this.output_dim = classNames.length;
this.output_dims = new int[] { this.output_dim };
init(input_dim, this.output_dim, classNames);
_isSetup = true;
}
public String getName()
{
return _name;
}
public void load() throws IOException
{
loadModel(FileUtils.getFile(dirPath, modelFileName + "." + FileCons.FILE_EXTENSION_MODEL));
if (modelOptionFileName != null && !modelOptionFileName.isEmpty())
{
loadOption(FileUtils.getFile(dirPath, modelOptionFileName + "." + FileCons.FILE_EXTENSION_OPTION));
}
Log.d("model loaded (file: " + modelFileName + ")");
}
public void validateInput(Stream[] input) throws IOException
{
if (!isTrained())
{
throw new IOException("model not loaded or trained");
}
if (input[0].bytes != input_bytes || input[0].type != input_type)
{
throw new IOException("input stream (type=" + input[0].type + ", bytes=" + input[0].bytes
+ ") does not match model's expected input (type=" + input_type + ", bytes=" + input_bytes + ", sr=" + input_sr + ")");
}
if (input[0].sr != input_sr)
{
Log.w("input stream (sr=" + input[0].sr + ") may not be correct for model (sr=" + input_sr + ")");
}
if (input[0].dim != input_dim)
{
throw new IOException("input stream (dim=" + input[0].dim + ") does not match model (dim=" + input_dim + ")");
}
if (input[0].num > 1)
{
Log.w ("stream num > 1, only first sample is used");
}
}
private void parseTrainerFile(File file) throws XmlPullParserException, IOException, SSJException
{
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(new FileReader(file));
// <trainer> tag
parser.next();
if (parser.getEventType() != XmlPullParser.START_TAG || !parser.getName().equalsIgnoreCase("trainer"))
{
Log.w("unknown or malformed trainer file");
return;
}
List<String> outputNamesList = new ArrayList<>();
List<Integer> outputDimsList = new ArrayList<>();
while (parser.next() != XmlPullParser.END_DOCUMENT)
{
// <streams> tag
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("streams"))
{
// <item> tag
parser.nextTag();
// Currently only one input stream supported
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("item"))
{
input_bytes = Integer.parseInt(parser.getAttributeValue(null, "byte"));
input_dim = Integer.parseInt(parser.getAttributeValue(null, "dim"));
input_sr = Float.parseFloat(parser.getAttributeValue(null, "sr"));
input_type = Cons.Type.valueOf(parser.getAttributeValue(null, "type"));
String num = parser.getAttributeValue(null, "num");
if (num != null)
{
input_num = Integer.parseInt(num);
}
}
}
// <classes> tag
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("classes"))
{
output_heads = 1;
// <item> tag
parser.nextTag();
while (parser.getName().equalsIgnoreCase("item"))
{
if (parser.getEventType() == XmlPullParser.START_TAG)
{
outputNamesList.add(parser.getAttributeValue(null, "name"));
}
parser.nextTag();
}
}
// <outputs> tag
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("outputs"))
{
// <item> tag
parser.nextTag();
output_dim = 0;
output_heads = 0;
while (parser.getName().equalsIgnoreCase("item"))
{
if (parser.getEventType() == XmlPullParser.START_TAG)
{
String name = parser.getAttributeValue(null, "name");
String dimString = parser.getAttributeValue(null, "dim");
int dim = 1;
if (name == null)
{
name = "output" + output_heads;
}
if (dimString != null)
{
dim = Integer.parseInt(dimString);
for (int i = 0; i < dim; i++)
{
outputNamesList.add(name + "_" + i);
}
}
else
{
outputNamesList.add(name);
}
outputDimsList.add(dim);
output_dim += dim;
output_heads++;
}
parser.nextTag();
}
output_dims = new int[output_heads];
for (int i = 0; i < output_dims.length; i++)
{
output_dims[i] = outputDimsList.get(i);
}
}
// <select> tag
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("select"))
{
// <item> tag
parser.nextTag();
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("item"))
{
int stream_id = Integer.parseInt(parser.getAttributeValue(null, "stream"));
if (stream_id != 0)
{
Log.w("multiple input streams not supported");
}
String[] select = parser.getAttributeValue(null, "select").split(" ");
select_dimensions = new int[select.length];
for (int i = 0; i < select.length; i++)
{
select_dimensions[i] = Integer.parseInt(select[i]);
}
}
}
// <model> tag
if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equalsIgnoreCase("model"))
{
String expectedModel = parser.getAttributeValue(null, "create");
if(!_name.equals(expectedModel))
{
Log.w("trainer file demands a " + expectedModel + " model, we provide a " + _name + " model.");
}
modelFileName = parser.getAttributeValue(null, "path");
modelOptionFileName = parser.getAttributeValue(null, "option");
// Remove model file extension
if (modelFileName != null && modelFileName.endsWith("." + FileCons.FILE_EXTENSION_MODEL))
{
modelFileName = modelFileName.replaceFirst("(.*)\\." + FileCons.FILE_EXTENSION_MODEL + "$", "$1");
}
// Remove option file extension
if (modelOptionFileName != null && modelOptionFileName.endsWith("." + FileCons.FILE_EXTENSION_OPTION))
{
modelOptionFileName = modelOptionFileName.replaceFirst("(.*)\\." + FileCons.FILE_EXTENSION_OPTION + "$", "$1");
}
}
// <trainer> end tag
if (parser.getEventType() == XmlPullParser.END_TAG && parser.getName().equalsIgnoreCase("trainer"))
{
break;
}
}
if (outputNamesList.size() > 0)
{
output_names = outputNamesList.toArray(new String[0]);
if (output_dim == 0)
{
output_dim = output_names.length;
output_dims = new int[] { output_dim };
}
}
else
{
if (output_dim > 0)
{
output_names = new String[output_dim];
for (int i = 0; i < output_dim; i++)
{
output_names[i] = "out_" + i;
}
}
}
}
public void save(String path, String name) throws IOException
{
if (!_isSetup)
{
return;
}
File dir = Util.createDirectory(Util.parseWildcards(path));
if (dir == null)
{
return;
}
if (name.endsWith(FileCons.FILE_EXTENSION_TRAINER + FileCons.TAG_DATA_FILE))
{
name = name.substring(0, name.length()-2);
}
else if (!name.endsWith(FileCons.FILE_EXTENSION_TRAINER))
{
name += "." + FileCons.FILE_EXTENSION_TRAINER;
}
StringBuilder builder = new StringBuilder();
builder.append("<trainer ssi-v=\"5\" ssj-v=\"");
builder.append(Pipeline.getVersion());
builder.append("\">").append(FileCons.DELIMITER_LINE);
builder.append("<info trained=\"");
builder.append(isTrained());
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
builder.append("<streams>").append(FileCons.DELIMITER_LINE);
builder.append("<item byte=\"");
builder.append(input_bytes);
builder.append("\" dim=\"");
builder.append(input_dim);
builder.append("\" sr=\"");
builder.append(input_sr);
builder.append("\" type=\"");
builder.append(input_type);
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
builder.append("</streams>").append(FileCons.DELIMITER_LINE);
builder.append("<classes>").append(FileCons.DELIMITER_LINE);
for(String className : output_names)
{
builder.append("<item name=\"");
builder.append(className);
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
}
builder.append("</classes>").append(FileCons.DELIMITER_LINE);
builder.append("<users>").append(FileCons.DELIMITER_LINE);
builder.append("<item name=\"userLocal\"/>").append(FileCons.DELIMITER_LINE);
builder.append("</users>").append(FileCons.DELIMITER_LINE);
String modelFileName = name + "." + _name;
// String modelOptionFileName = name + "." + _name;
builder.append("<model create=\"");
builder.append(_name);
builder.append("\" stream=\"0\" path=\"");
builder.append(modelFileName);
//builder.append("\" option=\"");
//builder.append(modelOptionFileName);
builder.append("\"/>").append(FileCons.DELIMITER_LINE);
builder.append("</trainer>").append(FileCons.DELIMITER_LINE);
OutputStream ouputStream = new FileOutputStream(new File(dir, name));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ouputStream));
writer.write(builder.toString());
writer.flush();
writer.close();
saveModel(new File(dir, modelFileName + "." + FileCons.FILE_EXTENSION_MODEL));
}
public abstract Options getOptions();
/**
* forward data to the model for classification/inference
* @param stream Stream
* @return double[] classification/inference probabilities as outputed by the model
*/
abstract float[] forward(Stream stream);
/**
* Train model with one sample (incremental training)
* @param stream data of the sample to use for training
* @param label the label of the data, should match one of the model's classes
*/
void train(Stream stream, String label)
{
Log.e(_name + " does not supported training");
}
/**
* Train model with multiple samples (batch training)
* @param stream data from where to extract the samples
* @param anno annotation
*/
public void train(Stream stream, Annotation anno)
{
if(!_isSetup)
{
Log.e("model not initialized");
return;
}
for(Annotation.Entry e : anno.getEntries())
{
train(stream.substream(e.from, e.to), e.classlabel);
}
isTrained = true;
}
/**
* Load model from file
*
* @param file Model file
*/
abstract void loadModel(File file);
/**
* Load model options from file
*
* @param file Option file
*/
abstract void loadOption(File file);
/**
* Save model to file
*
* @param file Model file
*/
void saveModel(File file)
{
Log.e("save not supported");
}
/**
* Save model options to file
*/
void saveOption(File file) {};
/**
* Initialize model variables, called after model parameters have been set but before actually
* loading the model
*
* @param input_dim number of model inputs
* @param output_dim number of model outputs
* @param outputNames (optional) output names
*/
abstract void init(int input_dim, int output_dim, String[] outputNames);
public boolean isTrained()
{
return isTrained;
}
/**
* Set label count for the classifier.
*
* @param output_dim amount of object classes to recognize.
*/
public void setOutputDim(int output_dim)
{
this.output_dim = output_dim;
}
/**
* Set label strings for the classifier.
*
* @param classNames recognized object classes.
*/
public void setClassNames(String[] classNames)
{
this.output_names = classNames;
}
public int getOutputDim()
{
return output_dim;
}
public String[] getClassNames()
{
return output_names;
}
public int[] getInputDim()
{
return select_dimensions;
}
public double getInputSr()
{
return input_sr;
}
public Cons.Type getInputType()
{
return input_type;
}
}
| 19,911 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TFLiteWrapper.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/TFLiteWrapper.java | /*
* TFLiteWrapper.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.ml;
import android.graphics.Bitmap;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.gpu.CompatibilityList;
import org.tensorflow.lite.gpu.GpuDelegate;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.Map;
import hcm.ssj.core.Log;
/**
* Created by Michael Dietz on 03.02.2021.
*/
public class TFLiteWrapper
{
// An instance of the driver class to run model inference with Tensorflow Lite.
private Interpreter modelInterpreter;
// Optional GPU delegate for accleration.
private GpuDelegate gpuDelegate;
// GPU Compatibility
private boolean gpuSupported;
private boolean useGPU;
public TFLiteWrapper(boolean useGPU)
{
this.useGPU = useGPU;
}
public Interpreter.Options getInterpreterOptions()
{
// Check gpu compatibility
CompatibilityList compatList = new CompatibilityList();
gpuSupported = compatList.isDelegateSupportedOnThisDevice();
Log.i("GPU delegate supported: " + gpuSupported);
Interpreter.Options interpreterOptions = new Interpreter.Options();
// Initialize interpreter with GPU delegate
if (gpuSupported && useGPU)
{
// If the device has a supported GPU, add the GPU delegate
gpuDelegate = new GpuDelegate(compatList.getBestOptionsForThisDevice());
interpreterOptions.addDelegate(gpuDelegate);
}
else
{
// If the GPU is not supported, enable XNNPACK acceleration
interpreterOptions.setUseXNNPACK(true);
interpreterOptions.setNumThreads(Runtime.getRuntime().availableProcessors());
}
return interpreterOptions;
}
public void loadModel(File modelFile, Interpreter.Options interpreterOptions)
{
modelInterpreter = new Interpreter(modelFile, interpreterOptions);
}
public void loadModel(File modelFile)
{
loadModel(modelFile, getInterpreterOptions());
}
public void run(Object input, Object output)
{
if (modelInterpreter != null)
{
// Run inference
try
{
modelInterpreter.run(input, output);
}
catch (Exception e)
{
Log.e("Error while running tflite inference", e);
}
}
}
public void runMultiInputOutput(Object[] inputs, Map<Integer, Object> outputs)
{
if (modelInterpreter != null)
{
// Run inference
try
{
modelInterpreter.runForMultipleInputsOutputs(inputs, outputs);
}
catch (Exception e)
{
Log.e("Error while running TFLite inference", e);
}
}
}
public void convertBitmapToInputArray(Bitmap inputBitmap, int[] inputArray, ByteBuffer imgData)
{
convertBitmapToInputArray(inputBitmap, inputArray, imgData, 127.5f, 127.5f);
}
public void convertBitmapToInputArray(Bitmap inputBitmap, int[] inputArray, ByteBuffer imgData, float normShift, float normDiv)
{
// Get rgb pixel values as int array
inputBitmap.getPixels(inputArray, 0, inputBitmap.getWidth(), 0, 0, inputBitmap.getWidth(), inputBitmap.getHeight());
// Normalize resized image
imgData.rewind();
for (int i = 0; i < inputArray.length; ++i)
{
final int val = inputArray[i];
float r = (val >> 16) & 0xFF;
float g = (val >> 8) & 0xFF;
float b = (val & 0xFF);
r = (r - normShift) / normDiv;
g = (g - normShift) / normDiv;
b = (b - normShift) / normDiv;
// Fill byte buffer for model input
imgData.putFloat(r);
imgData.putFloat(g);
imgData.putFloat(b);
}
}
public void close()
{
// Clean up
if (modelInterpreter != null)
{
modelInterpreter.close();
}
if (gpuDelegate != null)
{
gpuDelegate.close();
}
}
}
| 4,823 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Trainer.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/Trainer.java | /*
* Trainer.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.ml;
import java.io.File;
import java.io.IOException;
import hcm.ssj.core.Cons;
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.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.signal.Merge;
import hcm.ssj.signal.Selector;
/**
* Generic classifier
*/
public class Trainer extends Consumer implements IModelHandler
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the consumer
*/
public class Options extends IModelHandler.Options
{
public final Option<Boolean> merge = new Option<>("merge", true, Boolean.class, "merge input streams");
public final Option<FolderPath> filePath = new Option<>("path", new FolderPath(FileCons.SSJ_EXTERNAL_STORAGE + File.separator + "[time]"), FolderPath.class, "where to save the model on pipeline stop");
public final Option<String> fileName = new Option<>("fileName", null, String.class, "model file name");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Selector selector = null;
private Stream[] stream_merged;
private Stream[] stream_selected;
private Merge merge = null;
private Model model = null;
public Trainer()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length > 1 && !options.merge.get())
{
throw new SSJFatalException("sources count not supported");
}
if (stream_in[0].type == Cons.Type.EMPTY || stream_in[0].type == Cons.Type.UNDEF)
{
throw new SSJFatalException("stream type not supported");
}
Log.d("waiting for model to become ready ...");
model.waitUntilReady();
Log.d("model ready");
Stream[] input = stream_in;
if(options.merge.get())
{
merge = new Merge();
stream_merged = new Stream[1];
stream_merged[0] = Stream.create(input[0].num, merge.getSampleDimension(input), input[0].sr, input[0].type);
merge.enter(stream_in, stream_merged[0]);
input = stream_merged;
}
try
{
model.validateInput(input);
}
catch (IOException e)
{
throw new SSJFatalException("model validation failed", e);
}
if(model.getInputDim() != null)
{
selector = new Selector();
selector.options.values.set(model.getInputDim());
stream_selected = new Stream[1];
stream_selected[0] = Stream.create(input[0].num, selector.options.values.get().length, input[0].sr, input[0].type);
selector.enter(input, stream_selected[0]);
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
public void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
if(trigger == null || trigger.type != Cons.Type.STRING)
throw new SSJFatalException("Event trigger missing or invalid. Make sure Trainer is setup to receive string events.");
Stream[] input = stream_in;
if(options.merge.get()) {
// since this is an event consumer, input num can change
stream_merged[0].adjust(input[0].num);
merge.transform(input, stream_merged[0]);
input = stream_merged;
}
if(selector != null) {
// since this is an event consumer, input num can change
stream_selected[0].adjust(input[0].num);
selector.transform(input, stream_selected[0]);
input = stream_selected;
}
model.train(input[0], trigger.ptrStr());
}
@Override
public void flush(Stream stream_in[]) throws SSJFatalException
{
if(options.fileName.get() != null && !options.fileName.get().isEmpty())
{
try
{
model.save(options.filePath.get().value, options.fileName.get());
}
catch (IOException e)
{
Log.e("error saving trained model", e);
}
}
}
@Override
public void setModel(Model model)
{
this.model = model;
}
@Override
public Model getModel()
{
return model;
}
}
| 6,074 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Classifier.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/Classifier.java | /*
* Classifier.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.ml;
import java.io.IOException;
import java.util.Locale;
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;
import hcm.ssj.signal.Merge;
import hcm.ssj.signal.Selector;
/**
* Generic classifier
*/
public class Classifier extends Consumer implements IModelHandler
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the consumer
*/
public class Options extends IModelHandler.Options
{
public final Option<Boolean> merge = new Option<>("merge", true, Boolean.class, "merge input streams");
public final Option<Boolean> bestMatchOnly = new Option<>("bestMatchOnly", true, Boolean.class, "print or send class with highest result only");
public final Option<Boolean> addClassNames = new Option<>("addClassNames", false, Boolean.class, "add class name to prediction result");
public final Option<Boolean> log = new Option<>("log", true, Boolean.class, "print results in log");
public final Option<String> sender = new Option<>("sender", "Classifier", String.class, "event sender name, written in every event");
public final Option<String> event = new Option<>("event", "Result", String.class, "event name (ignored if bestMatchOnly is true)");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Selector selector = null;
private Stream[] stream_merged;
private Stream[] stream_selected;
private Merge merge = null;
private Model model = null;
public Classifier()
{
_name = this.getClass().getSimpleName();
}
/**
* @param stream_in Stream[]
*/
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in.length > 1 && !options.merge.get())
{
throw new SSJFatalException("sources count not supported");
}
if (stream_in[0].type == Cons.Type.EMPTY || stream_in[0].type == Cons.Type.UNDEF)
{
throw new SSJFatalException("stream type not supported");
}
if (model == null)
{
throw new SSJFatalException("no model defined");
}
if (!model.isSetup())
{
throw new SSJFatalException("model not initialized.");
}
Log.d("waiting for model to become ready ...");
model.waitUntilReady();
Log.d("model ready");
Stream[] input = stream_in;
if(options.merge.get())
{
merge = new Merge();
stream_merged = new Stream[1];
stream_merged[0] = Stream.create(input[0].num, merge.getSampleDimension(input), input[0].sr, input[0].type);
merge.enter(stream_in, stream_merged[0]);
input = stream_merged;
}
try
{
model.validateInput(input);
}
catch (IOException e)
{
throw new SSJFatalException("model validation failed", e);
}
if(model.getInputDim() != null)
{
selector = new Selector();
selector.options.values.set(model.getInputDim());
stream_selected = new Stream[1];
stream_selected[0] = Stream.create(input[0].num, selector.options.values.get().length, input[0].sr, input[0].type);
selector.enter(input, stream_selected[0]);
}
}
/**
* @param stream_in Stream[]
* @param trigger Event trigger
*/
@Override
public void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
Stream[] input = stream_in;
if(options.merge.get()) {
merge.transform(input, stream_merged[0]);
input = stream_merged;
}
if(selector != null) {
selector.transform(input, stream_selected[0]);
input = stream_selected;
}
float[] probs = model.forward(input[0]);
if(options.bestMatchOnly.get())
{
// Get array index of element with largest probability.
int bestLabelIdx = Util.maxIndex(probs);
if (_evchannel_out != null)
{
Event ev = Event.create(Cons.Type.FLOAT);
ev.sender = options.sender.get();
ev.name = model.getClassNames()[bestLabelIdx];
ev.time = (int) (1000 * stream_in[0].time + 0.5);
double duration = stream_in[0].num / stream_in[0].sr;
ev.dur = (int) (1000 * duration + 0.5);
ev.state = Event.State.COMPLETED;
ev.setData(new float[]{probs[bestLabelIdx]});
_evchannel_out.pushEvent(ev);
}
if (options.log.get())
{
String bestMatch = String.format(Locale.GERMANY, "BEST MATCH: %s (%.2f%% likely)",
model.getClassNames()[bestLabelIdx],
probs[bestLabelIdx] * 100f);
Log.i(bestMatch);
}
}
else
{
if (_evchannel_out != null)
{
Event ev;
if (options.addClassNames.get())
{
String[] class_names = model.getClassNames();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < probs.length; i++)
{
stringBuilder.append(class_names[i]);
stringBuilder.append(": ");
stringBuilder.append(String.format(Locale.ENGLISH, "%.3f", probs[i]));
if (i < probs.length - 1)
{
stringBuilder.append(", ");
}
}
ev = Event.create(Cons.Type.STRING);
ev.setData(stringBuilder.toString());
}
else
{
ev = Event.create(Cons.Type.FLOAT);
ev.setData(probs);
}
ev.sender = options.sender.get();
ev.name = options.event.get();
ev.time = (int) (1000 * stream_in[0].time + 0.5);
double duration = stream_in[0].num / stream_in[0].sr;
ev.dur = (int) (1000 * duration + 0.5);
ev.state = Event.State.COMPLETED;
_evchannel_out.pushEvent(ev);
}
if (options.log.get())
{
String[] class_names = model.getClassNames();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < probs.length; i++)
{
stringBuilder.append(class_names[i]);
stringBuilder.append(" = ");
stringBuilder.append(probs[i]);
stringBuilder.append("; ");
}
Log.i(stringBuilder.toString());
}
}
}
@Override
public void setModel(Model model)
{
this.model = model;
}
@Override
public Model getModel()
{
return model;
}
}
| 8,917 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IModelHandler.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/IModelHandler.java | /*
* IModelHandler.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.ml;
import hcm.ssj.core.option.OptionList;
/**
* Interface for objects which work with models
*/
public interface IModelHandler
{
/**
* Standard options
*/
class Options extends OptionList
{}
void setModel(Model model);
Model getModel();
}
| 1,637 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TFLite.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/TFLite.java | /*
* TFLite.java
* Copyright (c) 2019
* 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.ml;
import android.util.Xml;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.gpu.CompatibilityList;
import org.tensorflow.lite.gpu.GpuDelegate;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.HashMap;
import java.util.Map;
import hcm.ssj.core.Log;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.stream.Stream;
/**
* Created by Michael Dietz on 28.10.2019.
*/
public class TFLite extends Model
{
public class Options extends Model.Options
{
//public final Option<long[]> shape = new Option<>("shape", new long[] {1, 224, 224, 3}, long[].class, "shape of the input tensor");
public final Option<Boolean> useGPU = new Option<>("useGPU", true, Boolean.class, "if true tries to use GPU for better performance");
private Options()
{
super();
addOptions();
}
}
public TFLite.Options options = new TFLite.Options();
private TFLiteWrapper tfLiteWrapper;
// ByteBuffer to hold input data (e.g., images), to be feed into Tensorflow Lite as inputs.
private ByteBuffer inputData = null;
// Map to hold output data
private Map<Integer, Object> outputs = null;
public TFLite()
{
_name = "TFLite";
}
@Override
public Options getOptions()
{
return options;
}
@Override
void init(int input_dim, int output_dim, String[] outputNames)
{
// For images width * height * channels * bytes per pixel (e.g., 4 for float)
inputData = ByteBuffer.allocateDirect(input_bytes * input_dim * input_num);
inputData.order(ByteOrder.nativeOrder());
outputs = new HashMap<>();
for (int i = 0; i < output_heads; i++)
{
outputs.put(i, FloatBuffer.allocate(output_dims[i]));
}
}
@Override
float[] forward(Stream stream)
{
if (!isTrained)
{
Log.w("not trained");
return null;
}
float[] floatValues = stream.ptrF();
return makePrediction(floatValues);
}
/**
* Makes prediction about the given image data.
*
* @param floatValues RGB float data.
* @return Probability array.
*/
private float[] makePrediction(float[] floatValues)
{
float[] prediction = new float[output_dim];
inputData.rewind();
for (Integer key : outputs.keySet())
{
((FloatBuffer) outputs.get(key)).rewind();
}
// Fill byte buffer
for (int i = 0; i < floatValues.length; i++)
{
inputData.putFloat(floatValues[i]);
}
// Run inference
tfLiteWrapper.runMultiInputOutput(new Object[] {inputData}, outputs);
int startPos = 0;
for (Integer key : outputs.keySet())
{
float[] outputArray = ((FloatBuffer) outputs.get(key)).array();
System.arraycopy(outputArray, 0, prediction, startPos, output_dims[key]);
startPos += output_dims[key];
}
return prediction;
}
@Override
void loadModel(File file)
{
tfLiteWrapper = new TFLiteWrapper(options.useGPU.get());
tfLiteWrapper.loadModel(file);
isTrained = true;
}
@Override
protected void loadOption(File file)
{
XmlPullParser parser = Xml.newPullParser();
try
{
parser.setInput(new FileReader(file));
parser.next();
int eventType = parser.getEventType();
// Check if option file is of the right format.
if (eventType != XmlPullParser.START_TAG || !parser.getName().equalsIgnoreCase("options"))
{
Log.w("unknown or malformed trainer file");
return;
}
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (parser.getName().equalsIgnoreCase("item"))
{
String optionName = parser.getAttributeValue(null, "name");
String optionValue = parser.getAttributeValue(null, "value");
Object currentValue = options.getOptionValue(optionName);
if(currentValue == null)
options.setOptionValue(optionName, optionValue);
}
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.e("Error while loading model option file", e);
}
}
@Override
public void close()
{
super.close();
// Clean up
if (tfLiteWrapper != null)
{
tfLiteWrapper.close();
}
}
}
| 5,485 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TensorFlow.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/TensorFlow.java | /*
* TensorFlow.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.ml;
import android.util.Xml;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.nio.FloatBuffer;
import java.util.Arrays;
import hcm.ssj.core.Log;
import hcm.ssj.core.option.Option;
import hcm.ssj.core.stream.Stream;
/**
* TensorFlow model.
* Supports prediction using tensor flow's Android API.
* Requires pre-trained frozen graph, e.g. using SSI.
*
* @author Vitaly Krumins
*/
public class TensorFlow extends Model
{
public class Options extends Model.Options
{
public final Option<String> inputNode = new Option<>("input", "input", String.class, "name of the input node");
public final Option<String> outputNode = new Option<>("output", "output", String.class, "name of the output node");
public final Option<long[]> shape = new Option<>("shape", null, long[].class, "shape of the input tensor");
private Options()
{
super();
addOptions();
}
}
public Options options = new Options();
private Graph graph;
private Session session;
static
{
System.loadLibrary("tensorflow_inference");
}
public TensorFlow()
{
_name = "TensorFlow";
}
@Override
public Model.Options getOptions()
{
return options;
}
@Override
void init(int input_dim, int output_dim, String[] outputNames)
{
}
@Override
protected float[] forward(Stream stream)
{
if (!isTrained)
{
Log.w("not trained");
return null;
}
float[] floatValues = stream.ptrF();
float[] probabilities = makePrediction(floatValues);
return probabilities;
}
@Override
protected void loadOption(File file)
{
XmlPullParser parser = Xml.newPullParser();
try
{
parser.setInput(new FileReader(file));
parser.next();
int eventType = parser.getEventType();
// Check if option file is of the right format.
if (eventType != XmlPullParser.START_TAG || !parser.getName().equalsIgnoreCase("options"))
{
Log.w("unknown or malformed trainer file");
return;
}
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (parser.getName().equalsIgnoreCase("item"))
{
String optionName = parser.getAttributeValue(null, "name");
String optionValue = parser.getAttributeValue(null, "value");
Object currentValue = options.getOptionValue(optionName);
if(currentValue == null)
options.setOptionValue(optionName, optionValue);
}
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.e(e.getMessage());
}
}
@Override
protected void loadModel(File file)
{
FileInputStream fileInputStream;
byte[] fileBytes = new byte[(int) file.length()];
try
{
fileInputStream = new FileInputStream(file);
fileInputStream.read(fileBytes);
fileInputStream.close();
graph = new Graph();
graph.importGraphDef(fileBytes);
session = new Session(graph);
}
catch (Exception e)
{
Log.e("Error while importing the model: " + e.getMessage());
return;
}
isTrained = true;
}
/**
* Makes prediction about the given image data.
*
* @param floatValues RGB float data.
* @return Probability array.
*/
private float[] makePrediction(float[] floatValues)
{
Tensor input = Tensor.create(options.shape.get(), FloatBuffer.wrap(floatValues));
Tensor result = session.runner()
.feed(options.inputNode.get(), input)
.fetch(options.outputNode.get())
.run().get(0);
long[] rshape = result.shape();
if (result.numDimensions() != 2 || rshape[0] != 1)
{
throw new RuntimeException(
String.format(
"Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
Arrays.toString(rshape)));
}
int nlabels = (int) rshape[1];
return result.copyTo(new float[1][nlabels])[0];
}
/**
* Parses string representation of input tensor shape.
*
* @param shape String that represents tensor shape.
* @return shape of the input tensor as a n-dimensional array.
*/
private long[] parseTensorShape(String shape)
{
// Delete square brackets and white spaces.
String formatted = shape.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "");
// Separate each dimension value.
String[] shapeArray = formatted.split(",");
long[] tensorShape = new long[shapeArray.length];
for (int i = 0; i < shapeArray.length; i++)
{
tensorShape[i] = Integer.parseInt(shapeArray[i]);
}
return tensorShape;
}
}
| 5,962 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
Session.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/Session.java | /*
* Session.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.ml;
import hcm.ssj.core.Annotation;
import hcm.ssj.core.stream.Stream;
/**
* Created by Ionut Damian on 30.11.2017.
*/
public class Session
{
public String name;
public String anno_path;
public String stream_path;
public Stream stream;
public Annotation anno;
}
| 1,635 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ClassifierT.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/ClassifierT.java | /*
* ClassifierT.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.ml;
import java.io.IOException;
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.Merge;
import hcm.ssj.signal.Selector;
/**
* Generic classifier
*/
public class ClassifierT extends Transformer implements IModelHandler
{
@Override
public OptionList getOptions()
{
return options;
}
/**
* All options for the transformer
*/
public class Options extends IModelHandler.Options
{
public final Option<Boolean> merge = new Option<>("merge", true, Boolean.class, "merge input streams");
private Options()
{
super();
addOptions();
}
}
public final Options options = new Options();
private Selector selector = null;
private Stream[] stream_merged;
private Stream[] stream_selected;
private Merge merge = null;
private Model model = null;
public ClassifierT()
{
_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 && !options.merge.get())
{
throw new SSJFatalException("sources count not supported");
}
if (stream_in[0].type == Cons.Type.EMPTY || stream_in[0].type == Cons.Type.UNDEF)
{
throw new SSJFatalException("stream type not supported");
}
if (!model.isSetup())
{
throw new SSJFatalException("model not initialized. Did you provide a trainer file?");
}
Log.d("waiting for model to become ready ...");
model.waitUntilReady();
Log.d("model ready");
Stream[] input = stream_in;
if(options.merge.get())
{
merge = new Merge();
stream_merged = new Stream[1];
stream_merged[0] = Stream.create(input[0].num, merge.getSampleDimension(input), input[0].sr, input[0].type);
merge.enter(stream_in, stream_merged[0]);
input = stream_merged;
}
try
{
model.validateInput(input);
}
catch (IOException e)
{
throw new SSJFatalException("model validation failed", e);
}
if(model.getInputDim() != null)
{
selector = new Selector();
selector.options.values.set(model.getInputDim());
stream_selected = new Stream[1];
stream_selected[0] = Stream.create(input[0].num, selector.options.values.get().length, input[0].sr, input[0].type);
selector.enter(input, stream_selected[0]);
}
}
/**
* @param stream_in Stream[]
* @param stream_out Stream
*/
@Override
public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException
{
Stream[] input = stream_in;
if(options.merge.get() && stream_in.length > 1) {
merge.transform(input, stream_merged[0]);
input = stream_merged;
}
if(selector != null) {
selector.transform(input, stream_selected[0]);
input = stream_selected;
}
float[] probs = model.forward(input[0]);
if (probs != null)
{
float[] out = stream_out.ptrF();
for (int i = 0; i < probs.length; i++)
{
out[i] = probs[i];
}
}
}
/**
* @param stream_in Stream[]
* @return int
*/
@Override
public int getSampleDimension(Stream[] stream_in)
{
if(model == null)
{
Log.e("model header not loaded, cannot determine num classes.");
return 0;
}
return model.getOutputDim();
}
/**
* @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;
}
@Override
public void setModel(Model model)
{
this.model = model;
}
@Override
public Model getModel()
{
return model;
}
/**
* @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(model != null)
{
//define output stream
if (model.getClassNames() != null)
System.arraycopy(model.getClassNames(), 0, stream_out.desc, 0, stream_out.desc.length);
}
else
{
for (int i = 0; i < overallDimension; i++)
{
stream_out.desc[i] = "class" + i;
}
}
}
}
| 6,810 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
NaiveBayes.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/NaiveBayes.java | /*
* NaiveBayes.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.ml;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import hcm.ssj.core.Log;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.SimpleXmlParser;
/**
* Created by Michael Dietz on 06.11.2017.
*/
public class NaiveBayes extends Model
{
/**
* All options for OnlineNaiveBayes
*/
public class Options extends Model.Options
{
/**
*
*/
private Options()
{
super();
addOptions();
}
}
private static final double NORMAL_CONSTANT = Math.sqrt(2 * Math.PI);
private static final double DEFAULT_SAMPLE_WEIGHT = 1.0;
private static final double INITIAL_MODEL_WEIGHT = 2.0;
private static final int SSI_FORMAT_LENGTH = 2;
private static final int SSJ_FORMAT_LENGTH = 4;
// Options loaded from file
private boolean logNormalDistribution = true;
private boolean usePriorProbability = true;
// Helper variables
private Map<String, Integer> classNameIndices = null;
private int classCount;
private int featureCount;
private float[] classProbabilities;
// Model values per class and per feature
private double[][] mean = null;
private double[][] varianceSum = null;
private double[][] weightSum = null;
private double[] classDistribution = null;
// Options instance
public final Options options = new Options();
public NaiveBayes()
{
_name = this.getClass().getSimpleName();
}
/**
* Calculates the standard deviation for a feature dimension from a certain class
*/
private double getStdDev(int classIndex, int featureIndex)
{
return Math.sqrt(getVariance(classIndex, featureIndex));
}
/**
* Variance is calculated between last and current mean value.
* Therefore only x-1 variance values exist between x mean values.
*/
private double getVariance(int classIndex, int featureIndex)
{
return weightSum[classIndex][featureIndex] > 1.0 ? varianceSum[classIndex][featureIndex] / (weightSum[classIndex][featureIndex] - 1.0) : 0.0;
}
@Override
public Model.Options getOptions()
{
return options;
}
@Override
public synchronized float[] forward(Stream stream)
{
if (!isTrained)
{
Log.w("Not trained");
return null;
}
if (stream.dim != featureCount)
{
Log.w("Feature dimension (" + featureCount + ") differs from input stream dimension (" + stream.dim + ")");
return null;
}
double classDistributionSum = getClassDistributionSum();
double probabilitySum = 0;
// Do prediction
if (logNormalDistribution)
{
for (int classIndex = 0; classIndex < classCount; classIndex++)
{
double probability = usePriorProbability ? naiveBayesLog(classDistribution[classIndex] / classDistributionSum) : 0;
for (int featureIndex = 0; featureIndex < featureCount; featureIndex++)
{
double stdDev = getStdDev(classIndex, featureIndex);
if (stdDev != 0)
{
probability += getProbabilityLog(getDoubleValue(stream, featureIndex), stdDev, mean[classIndex][featureIndex], weightSum[classIndex][featureIndex]);
}
}
classProbabilities[classIndex] = (float) Math.exp(probability / featureCount);
probabilitySum += classProbabilities[classIndex];
}
}
else
{
for (int classIndex = 0; classIndex < classCount; classIndex++)
{
double probability = usePriorProbability ? classDistribution[classIndex] / classDistributionSum : 0;
for (int featureIndex = 0; featureIndex < featureCount; featureIndex++)
{
probability *= getProbability(getDoubleValue(stream, featureIndex), getStdDev(classIndex, featureIndex), mean[classIndex][featureIndex], weightSum[classIndex][featureIndex]);
}
classProbabilities[classIndex] = (float) probability;
probabilitySum += classProbabilities[classIndex];
}
}
// Normalization
if (probabilitySum == 0)
{
Log.w("Probability sum == 0");
for (int i = 0; i < classCount; i++)
{
classProbabilities[i] = 1.0f / classCount;
}
}
else
{
for (int i = 0; i < classCount; i++)
{
classProbabilities[i] /= probabilitySum;
}
}
return classProbabilities;
}
private double getProbability(double featureValue, double stdDev, double mean, double weightSum)
{
double probability = 0;
if (weightSum > 0.0)
{
if (stdDev > 0.0)
{
double diff = featureValue - mean;
probability = (1.0 / (NORMAL_CONSTANT * stdDev)) * Math.exp(-(diff * diff / (2.0 * stdDev * stdDev)));
}
else
{
probability = featureValue == mean ? 1.0 : 0.0;
}
}
return probability;
}
private double getProbabilityLog(double featureValue, double stdDev, double mean, double weightSum)
{
double probability = 0;
if (stdDev != 0.0)
{
double diff = featureValue - mean;
probability = -naiveBayesLog(stdDev) - (diff * diff) / (2 * stdDev * stdDev);
}
return probability;
}
private double getClassDistributionSum()
{
double sum = 0;
for (double distributionValue : classDistribution)
{
sum += distributionValue;
}
return sum;
}
@Override
public void train(Stream stream, String label)
{
Log.i("training model with " + stream.num + " sample(s)");
if (classDistribution == null || classDistribution.length <= 0)
{
Log.w("Base model not loaded");
return;
}
if (stream.dim != featureCount)
{
Log.w("Feature dimension differs");
return;
}
if (!classNameIndices.containsKey(label))
{
Log.w("Class name (" + label + ") not found, data ignored!");
return;
}
int classIndex = classNameIndices.get(label);
double weight = DEFAULT_SAMPLE_WEIGHT;
for (int i = 0; i < stream.num; i++)
{
// Add to class distribution
classDistribution[classIndex] += weight;
// Train model for each feature dimension independently
for (int j = 0; j < stream.dim; j++)
{
trainOnSample(getDoubleValue(stream, i * stream.dim + j), j, classIndex, weight);
}
}
isTrained = true;
}
private void trainOnSample(double featureValue, int featureIndex, int classIndex, double weight)
{
if (Double.isInfinite(featureValue) || Double.isNaN(featureValue))
{
Log.w("Invalid featureValue[" + featureIndex + "] = " + featureValue + " ignored for training");
return;
}
if (weightSum[classIndex][featureIndex] > 0.0)
{
weightSum[classIndex][featureIndex] += weight;
double lastMean = mean[classIndex][featureIndex];
mean[classIndex][featureIndex] += weight * (featureValue - lastMean) / weightSum[classIndex][featureIndex];
varianceSum[classIndex][featureIndex] += weight * (featureValue - lastMean) * (featureValue - mean[classIndex][featureIndex]);
}
else
{
mean[classIndex][featureIndex] = featureValue;
weightSum[classIndex][featureIndex] = weight;
}
}
@Override
void init(int input_dim, int output_dim, String[] outputNames)
{
classCount = outputNames.length;
featureCount = input_dim;
// Initialize model variables
mean = new double[classCount][];
varianceSum = new double[classCount][];
weightSum = new double[classCount][];
classDistribution = new double[classCount];
for (int classIndex = 0; classIndex < classCount; classIndex++)
{
// Create arrays
mean[classIndex] = new double[featureCount];
varianceSum[classIndex] = new double[featureCount];
weightSum[classIndex] = new double[featureCount];
}
classProbabilities = new float[classCount];
// Store class indices for reverse lookup used in online learning
classNameIndices = new HashMap<>();
for (int i = 0; i < outputNames.length; i++)
{
classNameIndices.put(outputNames[i], i);
}
}
@Override
public void loadModel(File file)
{
BufferedReader reader;
try
{
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
}
catch (FileNotFoundException e)
{
Log.e("File not found");
return;
}
// Skip first comments
String line;
do
{
line = readLine(reader);
}
while (line.startsWith("#"));
// Parse number of classes
String token[] = line.split("\t");
if (token.length > 0)
{
int classNum = Integer.valueOf(token[0]);
if (classNum != output_dim)
{
Log.w("Model definition (n_classes) mismatch between trainer and model file: " + classNum + " != " + output_dim);
}
classCount = output_dim;
}
else
{
Log.w("Can't read number of classes from classifier file " + file.getName() + "!");
return;
}
// Parse number of features
if (token.length > 1)
{
featureCount = Integer.valueOf(token[1]);
}
else
{
Log.w("Can't read feature dimension from classifier file " + file.getName() + "'!");
return;
}
for (int classIndex = 0; classIndex < classCount; classIndex++)
{
// Load model values
do
{
line = readLine(reader);
}
while (line.isEmpty() || line.startsWith("#"));
token = line.split("\t");
// Get class name
String name = token[0];
if (!name.equalsIgnoreCase(output_names[classIndex]))
{
Log.w("Model definition (name of class " + classIndex + ") mismatch between trainer and model file:" + name + " != " + output_names[classIndex]);
// Overwrite class name
output_names[classIndex] = name;
}
// Get class distribution
classDistribution[classIndex] = Double.valueOf(token[1]);
// Load feature values
for (int featureIndex = 0; featureIndex < featureCount; featureIndex++)
{
line = readLine(reader);
token = line.split("\t");
if (token.length == SSI_FORMAT_LENGTH)
{
// Model is in offline (SSI) format with mean and std deviation
mean[classIndex][featureIndex] = Double.valueOf(token[0]);
varianceSum[classIndex][featureIndex] = Math.pow(Double.valueOf(token[1]), 2) * (INITIAL_MODEL_WEIGHT - 1);
weightSum[classIndex][featureIndex] = INITIAL_MODEL_WEIGHT;
}
else if (token.length == SSJ_FORMAT_LENGTH)
{
// Model is in online format with mean, variance sum and weight sum
mean[classIndex][featureIndex] = Double.valueOf(token[0]);
varianceSum[classIndex][featureIndex] = Double.valueOf(token[2]);
weightSum[classIndex][featureIndex] = Double.valueOf(token[3]);
}
else
{
Log.e("Unknown model format");
}
}
}
// Close model file
try
{
reader.close();
}
catch (IOException e)
{
Log.e("Could not close reader");
}
isTrained = true;
}
/**
* Load data from option file
*/
@Override
public void loadOption(File file)
{
if (file == null)
{
Log.w("Option file not set in options");
return;
}
SimpleXmlParser simpleXmlParser = new SimpleXmlParser();
try
{
SimpleXmlParser.XmlValues xmlValues = simpleXmlParser.parse(
new FileInputStream(file),
new String[]{"options", "item"},
new String[]{"name", "value"}
);
ArrayList<String[]> foundAttributes = xmlValues.foundAttributes;
for (String[] strings : foundAttributes)
{
if (strings[0].equals("log"))
{
logNormalDistribution = strings[1].equals("true");
}
else if (strings[0].equals("prior"))
{
usePriorProbability = strings[1].equals("true");
}
}
}
catch (Exception e)
{
e.printStackTrace();
Log.e("File could not be parsed", e);
}
}
@Override
public void saveModel(File file)
{
if (file == null)
{
Log.e("Model file not set in options");
return;
}
BufferedWriter writer;
try
{
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
writer = new BufferedWriter(outputStreamWriter);
}
catch (FileNotFoundException e)
{
Log.e("File not found");
return;
}
try
{
// Write model header
String header = "# Classifier type:\tnaive_bayes\n# number of classes\tfeature space dimension\n" + classCount + "\t" + featureCount + "\n\n# class\tprior class probability\n# mean\tstandard deviation\tvariance sum\tweight sum\n";
writer.write(header);
double classDistributionSum = getClassDistributionSum();
for (int classIndex = 0; classIndex < classCount; classIndex++)
{
// Write class name and distribution
writer.write(output_names[classIndex] + "\t" + classDistribution[classIndex] / classDistributionSum + "\n");
// Write feature values
for (int featureIndex = 0; featureIndex < featureCount; featureIndex++)
{
writer.write(mean[classIndex][featureIndex] + "\t" + getStdDev(classIndex, featureIndex) + "\t" + varianceSum[classIndex][featureIndex] + "\t" + weightSum[classIndex][featureIndex] + "\n");
}
writer.write("\n");
}
}
catch (IOException e)
{
Log.e("Error while writing to file " + file.getAbsolutePath());
}
// Close model file
try
{
writer.close();
}
catch (IOException e)
{
Log.e("Could not close reader");
}
}
/**
* Helper function to read a line from the model file
*/
private String readLine(BufferedReader reader)
{
String line = null;
if (reader != null)
{
try
{
line = reader.readLine();
}
catch (IOException e)
{
Log.e("could not read line");
}
}
return line;
}
/**
* Calculates the log value
*/
private double naiveBayesLog(double x)
{
return x > (1e-20) ? Math.log(x) : -46; // Smallest log value
}
private double getDoubleValue(Stream stream, int pos)
{
switch (stream.type)
{
case CHAR:
return stream.ptrC()[pos];
case SHORT:
return stream.ptrS()[pos];
case INT:
return stream.ptrI()[pos];
case LONG:
return stream.ptrL()[pos];
case FLOAT:
return stream.ptrF()[pos];
case DOUBLE:
return stream.ptrD()[pos];
default:
Log.e("invalid input stream type");
return 0;
}
}
}
| 15,407 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
NaiveBayesOld.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/ml/NaiveBayesOld.java | /*
* NaiveBayesOld.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.ml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import hcm.ssj.core.Log;
import hcm.ssj.core.stream.Stream;
import hcm.ssj.file.SimpleXmlParser;
/**
* Evaluates live data depending on the naive bayes classifier files of SSI.<br>
* Created by Frank Gaibler on 22.09.2015.
*/
@Deprecated
public class NaiveBayesOld extends Model
{
/**
* All options for the transformer
*/
public class Options extends Model.Options
{
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
//file options
private boolean userLogNormalDistribution = true;
private boolean usePriorProbability = false;
//helper variables
private int n_features;
private double[] class_probs = null;
private double[][] means = null;
private double[][] std_dev = null;
private float[] probs;
private double[] data;
/**
*
*/
public NaiveBayesOld()
{
_name = "NaiveBayes";
}
@Override
void init(int input_dim, int output_dim, String[] outputNames)
{
probs = new float[output_dim];
_isSetup = true;
}
@Override
public Model.Options getOptions()
{
return options;
}
/**
* @param stream Stream
* @return double[]
*/
public float[] forward(Stream stream)
{
if (!isTrained || class_probs == null || class_probs.length <= 0)
{
Log.w("not trained");
return null;
}
if (stream.dim != n_features)
{
Log.w("feature dimension differs");
return null;
}
double sum = 0;
boolean prior = usePriorProbability;
if (userLogNormalDistribution)
{
for (int nclass = 0; nclass < output_dim; nclass++)
{
double prob = prior ? naiveBayesLog(class_probs[nclass]) : 0;
double[] ptr = getValuesAsDouble(stream);
double temp;
for (int nfeat = 0, t = 0; nfeat < n_features; nfeat++)
{
if (std_dev[nclass][nfeat] == 0)
{
t++;
continue;
}
double sqr = std_dev[nclass][nfeat] * std_dev[nclass][nfeat];
temp = ptr[t++] - means[nclass][nfeat];
if (sqr != 0)
{
prob += -naiveBayesLog(std_dev[nclass][nfeat]) - (temp * temp) / (2 * sqr);
} else
{
prob += -naiveBayesLog(std_dev[nclass][nfeat]) - (temp * temp) / (2 * Double.MIN_VALUE);
}
}
probs[nclass] = (float)Math.exp(prob / n_features);
sum += probs[nclass];
}
} else
{
for (int nclass = 0; nclass < output_dim; nclass++)
{
double norm_const = Math.sqrt(2.0 * Math.PI);
double prob = prior ? class_probs[nclass] : 0;
double[] ptr = getValuesAsDouble(stream);
for (int nfeat = 0, t = 0; nfeat < n_features; nfeat++)
{
double diff = ptr[t++] - means[nclass][nfeat];
double stddev = std_dev[nclass][nfeat];
if (stddev == 0)
{
stddev = Double.MIN_VALUE;
}
double temp = (1 / (norm_const * stddev)) * Math.exp(-((diff * diff) / (2 * (stddev * stddev))));
prob *= temp;
}
probs[nclass] = (float)prob;
sum += probs[nclass];
}
}
//normalisation
if (sum == 0)
{
Log.w("sum == 0");
for (int j = 0; j < output_dim; j++)
{
probs[j] = 1.0f / output_dim;
}
} else
{
for (int j = 0; j < output_dim; j++)
{
probs[j] /= sum;
}
}
return probs;
}
/**
* Load data from option file
*/
public void loadOption(File file)
{
if (file == null)
{
Log.w("option file not set in options");
return;
}
SimpleXmlParser simpleXmlParser = new SimpleXmlParser();
try
{
SimpleXmlParser.XmlValues xmlValues = simpleXmlParser.parse(
new FileInputStream(file),
new String[]{"options", "item"},
new String[]{"name", "value"}
);
ArrayList<String[]> foundAttributes = xmlValues.foundAttributes;
for (String[] strings : foundAttributes)
{
if (strings[0].equals("log"))
{
userLogNormalDistribution = strings[1].equals("true");
} else if (strings[0].equals("prior"))
{
usePriorProbability = strings[1].equals("true");
}
}
} catch (Exception e)
{
e.printStackTrace();
Log.e("file could not be parsed", e);
}
}
/**
* Load data from model file
*/
public void loadModel(File file)
{
if (file == null)
{
Log.e("model file not set in options");
return;
}
BufferedReader reader;
try
{
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
} catch (FileNotFoundException e)
{
Log.e("file not found");
return;
}
String line;
do
{
line = readLine(reader);
} while (line.startsWith("#"));
String token[] = line.split("\t");
if (token.length > 0)
{
int classNum = Integer.valueOf(token[0]);
if(classNum != output_dim)
Log.w("model definition (n_classes) mismatch between trainer and model file: " + classNum +" != "+ output_dim);
}
else
{
Log.w("can't read number of classes from classifier file " + file.getName() + "!");
return;
}
if (token.length > 1)
{
n_features = Integer.valueOf(token[1]);
} else
{
Log.w("can't read feature dimension from classifier file " + file.getName() + "'!");
return;
}
class_probs = new double[output_dim];
means = new double[output_dim][];
std_dev = new double[output_dim][];
for (int nclass = 0; nclass < output_dim; nclass++)
{
means[nclass] = new double[n_features];
std_dev[nclass] = new double[n_features];
for (int nfeat = 0; nfeat < n_features; nfeat++)
{
means[nclass][nfeat] = 0;
std_dev[nclass][nfeat] = 0;
}
class_probs[nclass] = 0;
}
for (int nclass = 0; nclass < output_dim; nclass++)
{
do
{
line = readLine(reader);
} while (line.isEmpty() || line.startsWith("#"));
token = line.split("\t");
String name = token[0];
if(!name.equalsIgnoreCase(output_names[nclass]))
{
Log.w("model definition (name of class " + nclass + ") mismatch between trainer and model file:" + name + " != " + output_names[nclass]);
output_names[nclass] = name;
}
class_probs[nclass] = Double.valueOf(token[1]);
for (int nfeat = 0; nfeat < n_features; nfeat++)
{
line = readLine(reader);
token = line.split("\t");
means[nclass][nfeat] = Double.valueOf(token[0]);
std_dev[nclass][nfeat] = Double.valueOf(token[1]);
}
}
try
{
reader.close();
} catch (IOException e)
{
Log.e("could not close reader");
}
isTrained = true;
}
/**
* @param reader BufferedReader
* @return String
*/
private String readLine(BufferedReader reader)
{
String line = null;
if (reader != null)
{
try
{
line = reader.readLine();
} catch (IOException e)
{
Log.e("could not read line");
}
}
return line;
}
/**
* @param x double
* @return double
*/
private double naiveBayesLog(double x)
{
return x > (1e-20) ? Math.log(x) : -46;
}
/**
* Transforms an input array of a stream into a double array and returns it.
*
* @param stream Stream
* @return double[]
*/
private double[] getValuesAsDouble(Stream stream)
{
if(data == null)
data = new double[stream.num * stream.dim];
switch (stream.type)
{
case CHAR:
char[] chars = stream.ptrC();
for (int i = 0; i < data.length; i++)
{
data[i] = (double) chars[i];
}
break;
case SHORT:
short[] shorts = stream.ptrS();
for (int i = 0; i < data.length; i++)
{
data[i] = (double) shorts[i];
}
break;
case INT:
int[] ints = stream.ptrI();
for (int i = 0; i < data.length; i++)
{
data[i] = (double) ints[i];
}
break;
case LONG:
long[] longs = stream.ptrL();
for (int i = 0; i < data.length; i++)
{
data[i] = (double) longs[i];
}
break;
case FLOAT:
float[] floats = stream.ptrF();
for (int i = 0; i < data.length; i++)
{
data[i] = (double) floats[i];
}
break;
case DOUBLE:
return stream.ptrD();
default:
Log.e("invalid input stream type");
break;
}
return data;
}
}
| 12,266 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ThresholdEventSender.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/event/ThresholdEventSender.java | /*
* ThresholdEventSender.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.event;
import hcm.ssj.core.Cons;
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;
public class ThresholdEventSender extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", null, String.class, "name of event sender");
public final Option<String> event = new Option<>("event", "event", String.class, "name of event");
public final Option<float[]> thresin = new Option<>("threshold_in", null, float[].class, "thresholds (one per dimension) for starting the event.");
public final Option<float[]> thresout = new Option<>("threshold_out", null, float[].class, "thresholds (one per dimension) for finishing the event (leave empty if same as threshold_in)");
public final Option<Integer> hangin = new Option<>("hangin", 0, Integer.class, "number of samples over threshold_in to wait until starting event");
public final Option<Integer> hangout = new Option<>("hangout", 0, Integer.class, "number of samples under threshold_out to wait until finishing event");
public final Option<Double> loffset = new Option<>("loffset", 0., Double.class, "lower offset in seconds (will be substracted from event start time)");
public final Option<Double> uoffset = new Option<>("uoffset", 0., Double.class, "upper offset in seconds (will be added to event end time)");
public final Option<Double> maxdur = new Option<>("maxdur", 2., Double.class, "maximum duration of event (longer events will be split unless skip is true)");
public final Option<Double> mindur = new Option<>("mindur", 0., Double.class, "minimum duration of event (shorter events will be ignored)");
public final Option<Boolean> hard = new Option<>("hard", true, Boolean.class, "all dimensions must respect thresholds");
public final Option<Boolean> skip = new Option<>("skip", false, Boolean.class, "ignore event if max duration is exceeded");
public final Option<Boolean> eager = new Option<>("eager", false, Boolean.class, "send an event when the observation begins");
public final Option<Boolean> eall = new Option<>("eall", true, Boolean.class, "forward incomplete events to event board, otherwise only complete events are sent");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
boolean _trigger_on;
double _trigger_start = 0, _trigger_stop = 0;
int _hangover_in = 0, _hangover_out = 0, _counter_in = 0, _counter_out = 0;
int _samples_max_dur = 0, _counter_max_dur = 0;
double _loffset = 0, _uoffset = 0;
boolean _skip_on_max_dur = false;
public ThresholdEventSender()
{
_name = "ThresholdEventSender";
options.sender.set(_name);
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
int totaldim = 0;
for(Stream s : stream_in)
{
totaldim += s.dim;
}
if(options.thresin.get() == null || options.thresin.get().length != totaldim)
{
throw new SSJFatalException("invalid threshold list. Expecting " + totaldim + " thresholds");
}
if(options.thresout.get() == null)
{
Log.w("thresout undefined, using thresin");
options.thresout.set(options.thresin.get());
}
_trigger_on = false;
_hangover_in = options.hangin.get();
_hangover_out = options.hangout.get();
_counter_in = _hangover_in;
_counter_out = _hangover_out;
_loffset = options.loffset.get();
_uoffset = options.uoffset.get();
_skip_on_max_dur = options.skip.get();
_samples_max_dur = (int) (options.maxdur.get() * stream_in[0].sr);
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
double time = stream_in[0].time;
double timeStep = 1 / stream_in[0].sr;
boolean found_event;
for (int i = 0; i < stream_in[0].num; i++) {
//differentiate between onset and offset threshold
float[] threshold = (!_trigger_on) ? options.thresin.get() : options.thresout.get();
found_event = options.hard.get();
int thresId = 0;
for (int j = 0; j < stream_in.length; j++) {
for (int k = 0; k < stream_in[j].dim; k++)
{
int position = i * stream_in[j].dim + k;
boolean result = false;
switch(stream_in[j].type)
{
case BYTE:
result = (float)stream_in[j].ptrB()[ position ] > threshold[thresId];
break;
case FLOAT:
result = stream_in[j].ptrF()[ position ] > threshold[thresId];
break;
case DOUBLE:
result = (float)stream_in[j].ptrD()[ position ] > threshold[thresId];
break;
case SHORT:
result = stream_in[j].ptrS()[ position ] > (double)threshold[thresId];
break;
case INT:
result = (float)stream_in[j].ptrI()[ position ] > threshold[thresId];
break;
case LONG:
result = stream_in[j].ptrL()[ position ] > (long)threshold[thresId];
break;
default:
Log.e("unsupported input type");
break;
}
if (options.hard.get())
{
found_event = found_event && result;
}
else
{
found_event = found_event || result;
}
thresId++;
}
}
if (!_trigger_on) {
if (found_event) {
// possible start of a new event
if (_counter_in == _hangover_in) {
// store start time and init max dur counter
_trigger_start = time + i * timeStep;
}
// check if event start is proved
if (_counter_in-- == 0) {
// signal that event start is now proved and init hangout and max counter
_trigger_on = true;
_counter_out = _hangover_out;
_counter_max_dur = _samples_max_dur - _hangover_in;
if (options.eager.get()) {
Event ev = Event.create(Cons.Type.EMPTY); //empty event
ev.name = options.event.get();
ev.sender = options.sender.get();
ev.time = (int)(1000 * _trigger_start + 0.5);
ev.dur = 0;
ev.state = Event.State.CONTINUED;
_evchannel_out.pushEvent(ev);
}
Log.ds("event started at " + _trigger_start);
}
} else {
// re-init hangin counter
_counter_in = _hangover_in;
}
} else if (_trigger_on) {
// check if max dur is reached
if (--_counter_max_dur == 0) {
// send event and reset start/stop time amd max counter
_trigger_stop = time + i * timeStep;
update (_trigger_start, _trigger_stop - _trigger_start, Event.State.CONTINUED);
_trigger_start = _trigger_stop;
_counter_max_dur = _samples_max_dur;
}
if (!found_event) {
// possible end of a new event
if (_counter_out == _hangover_out) {
// store end time
_trigger_stop = time + i * timeStep;
}
// check if event end is proved
if (_counter_out-- == 0) {
// event end is now proved and event is sent
update(_trigger_start, _trigger_stop - _trigger_start,
Event.State.COMPLETED);
// signal end of event and init hangin counter
_trigger_on = false;
_counter_in = _hangover_in;
Log.ds("event stopped at " + _trigger_stop);
}
} else {
// re-init hangin counter
_counter_out = _hangover_out;
}
}
}
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{}
boolean update (double time, double dur, Event.State state)
{
if (dur < options.mindur.get() || dur <= 0.0) {
Log.ds("skip event because duration too short " + dur + "@" + time);
return false;
}
if (dur > options.maxdur.get() + 0.000000001) {
if (_skip_on_max_dur) {
Log.ds("skip event because duration too long " + dur + "@" + time);
return false;
}
Log.w("crop duration from " + dur +" to " + options.maxdur.get());
time += dur - options.maxdur.get();
dur = options.maxdur.get();
}
if (options.eall.get() || state == Event.State.COMPLETED) {
Event ev = Event.create(Cons.Type.EMPTY); //empty event
ev.name = options.event.get();
ev.sender = options.sender.get();
ev.time = Math.max (0, (int)(1000 * (time - _loffset) + 0.5));
ev.dur = Math.max (0, (int)(1000 * (dur + _uoffset) + 0.5));
ev.state = state;
_evchannel_out.pushEvent(ev);
}
return true;
}
}
| 11,982 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ValueEventSender.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/event/ValueEventSender.java | /*
* ValueEventSender.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.event;
import java.util.EnumSet;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
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 Michael Dietz on 07.07.2016.
*/
public class ValueEventSender extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", null, String.class, "");
public final Option<String> event = new Option<>("event", "event", String.class, "");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public ValueEventSender()
{
_name = "ValueEventSender";
options.sender.set(_name);
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (!EnumSet.of(Cons.Type.BYTE, Cons.Type.CHAR, Cons.Type.SHORT, Cons.Type.INT, Cons.Type.LONG, Cons.Type.FLOAT, Cons.Type.DOUBLE, Cons.Type.BOOL).contains(stream_in[0].type))
{
throw new SSJFatalException("type "+ stream_in[0].type +" not supported");
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
Event ev = Event.create(stream_in[0].type);
ev.name = options.event.get();
ev.sender = options.sender.get();
ev.time = (int) (1000 * stream_in[0].time + 0.5);
ev.dur = (int) (1000 * (stream_in[0].num / stream_in[0].sr) + 0.5);
ev.state = Event.State.COMPLETED;
ev.setData(stream_in[0].ptr());
_evchannel_out.pushEvent(ev);
}
} | 3,020 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FloatsEventSender.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/event/FloatsEventSender.java | /*
* FloatsEventSender.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.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
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;
public class FloatsEventSender extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", null, String.class, "");
public final Option<String> event = new Option<>("event", "event", String.class, "");
public final Option<Boolean> mean = new Option<>("mean", true, Boolean.class, "send mean values");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public FloatsEventSender()
{
_name = "FloatsEventSender";
options.sender.set(_name);
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in[0].type != Cons.Type.FLOAT) {
throw new SSJFatalException("type "+ stream_in[0].type +" not supported");
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
float ptr[] = stream_in[0].ptrF();
Event ev = Event.create(Cons.Type.FLOAT);
ev.name = options.event.get();
ev.sender = options.sender.get();
ev.time = (int)(1000 * stream_in[0].time + 0.5);
ev.dur = (int)(1000 * (stream_in[0].num / stream_in[0].sr) + 0.5);
ev.state = Event.State.COMPLETED;
if (options.mean.get()) {
float[] avg = new float[stream_in[0].dim];
Arrays.fill(avg, 0);
for (int j = 0; j < stream_in[0].dim; j++) {
for (int i = 0; i < stream_in[0].num; i++) {
avg[j] += ptr[i * stream_in[0].dim + j];
}
avg[j] /= stream_in[0].num;
}
ev.setData(avg);
}
else {
ev.setData(ptr);
}
_evchannel_out.pushEvent(ev);
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{}
}
| 3,687 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
ThresholdClassEventSender.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/event/ThresholdClassEventSender.java | /*
* ThresholdClassEventSender.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.event;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import hcm.ssj.core.Cons;
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;
public class ThresholdClassEventSender extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", null, String.class, "name of event sender");
public final Option<String[]> classes = new Option<>("classes", new String[]{"low", "medium", "high"}, String[].class, "classes for threshold values (eventnames)");
public final Option<float[]> thresholds = new Option<>("thresholds", new float[]{0f, 1f, 2f}, float[].class, "thresholds for input");
public final Option<Float> minDiff = new Option<>("minDiff", 0.1f, Float.class, "minimum difference to previous value");
public final Option<Boolean> mean = new Option<>("mean", false, Boolean.class, "classify based on mean value of entire frame");
public final Option<Double> maxDur = new Option<>("maxDur", 2., Double.class, "maximum delay before continued events will be sent");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
private List<SimpleEntry<Float, String>> thresholdList;
private float lastValue = Float.NEGATIVE_INFINITY;
private Map.Entry<Float, String> lastClass = null;
private int samplesMaxDur;
private double lastTriggerTime;
public ThresholdClassEventSender()
{
_name = "ThresholdClassEventSender";
options.sender.set(_name);
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in[0].dim != 1)
{
throw new SSJFatalException("Dimension != 1 unsupported");
}
makeThresholdList();
samplesMaxDur = (int) (options.maxDur.get() * stream_in[0].sr);
}
private void makeThresholdList() throws SSJFatalException
{
String[] classes = options.classes.get();
float[] thresholds = options.thresholds.get();
if (classes == null || thresholds == null)
{
throw new SSJFatalException("classes and thresholds not correctly set");
}
if (classes.length != thresholds.length)
{
throw new SSJFatalException("number of classes do not match number of thresholds");
}
thresholdList = new ArrayList<>();
for (int i = 0; i < classes.length; ++i)
{
thresholdList.add(new SimpleEntry<Float, String>(thresholds[i], classes[i]));
}
Collections.sort(thresholdList, new ThresholdListComparator());
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
makeThresholdList();
double time = stream_in[0].time;
double timeStep = 1 / stream_in[0].sr;
float sum = 0;
for (int i = 0; i < stream_in[0].num; i++)
{
float value = 0;
switch (stream_in[0].type)
{
case BYTE:
value = (float) stream_in[0].ptrB()[i];
break;
case FLOAT:
value = stream_in[0].ptrF()[i];
break;
case DOUBLE:
value = (float) stream_in[0].ptrD()[i];
break;
case SHORT:
value = stream_in[0].ptrS()[i];
break;
case INT:
value = (float) stream_in[0].ptrI()[i];
break;
case LONG:
value = stream_in[0].ptrL()[i];
break;
default:
Log.e("unsupported input type");
break;
}
if (options.mean.get())
{
sum += value;
}
else
{
processValue(value, time, stream_in[0].sr, 1);
}
time += timeStep;
}
if (options.mean.get())
{
processValue(sum / stream_in[0].num, time, stream_in[0].sr, stream_in[0].num);
}
}
private void processValue(float value, double time, double sampleRate, int numberOfSamples)
{
SimpleEntry<Float, String> newClass = classify(value);
samplesMaxDur -= numberOfSamples;
if (newClass == null)
{
return;
}
if (isEqualLastClass(newClass))
{
if (samplesMaxDur <= 0)
{
lastValue = value;
sendEvent(newClass, lastTriggerTime, time - lastTriggerTime, Event.State.CONTINUED);
samplesMaxDur = (int) (options.maxDur.get() * sampleRate);
}
}
else if (valueDiffersEnoughFromLast(value))
{
if (lastClass != null)
{
sendEvent(lastClass, lastTriggerTime, time - lastTriggerTime, Event.State.COMPLETED);
}
sendEvent(newClass, time, 0, Event.State.CONTINUED);
lastTriggerTime = time;
lastValue = value;
lastClass = newClass;
samplesMaxDur = (int) (options.maxDur.get() * sampleRate);
}
}
private boolean isEqualLastClass(SimpleEntry<Float, String> newClass)
{
return newClass.equals(lastClass);
}
private boolean valueDiffersEnoughFromLast(float value)
{
return Math.abs(value - lastValue) > options.minDiff.get();
}
private SimpleEntry<Float, String> classify(float value)
{
SimpleEntry<Float, String> foundClass = null;
for (SimpleEntry<Float, String> thresholdClass : thresholdList)
{
float classValue = thresholdClass.getKey();
if (value > classValue)
{
return thresholdClass;
}
}
return foundClass;
}
private void sendEvent(Map.Entry<Float, String> thresholdClass, double time, double duration, Event.State state)
{
Event event = Event.create(Cons.Type.EMPTY);
event.name = thresholdClass.getValue();
event.sender = options.sender.get();
event.time = Math.max(0, (int) (1000 * time + 0.5));
event.dur = Math.max(0, (int) (1000 * duration + 0.5));
event.state = state;
_evchannel_out.pushEvent(event);
}
private class ThresholdListComparator implements Comparator<SimpleEntry<Float, String>>
{
@Override
public int compare(SimpleEntry<Float, String> o1, SimpleEntry<Float, String> o2)
{
// Note: this comparator imposes orderings that are inconsistent with equals.
// Order is descending.
if (o1.getKey() > o2.getKey())
{
return -1;
}
if (o1.getKey() < o2.getKey())
{
return 1;
}
return 0;
}
}
}
| 7,511 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FloatSegmentEventSender.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/event/FloatSegmentEventSender.java | /*
* FloatSegmentEventSender.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.event;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Consumer;
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;
public class FloatSegmentEventSender extends Consumer
{
@Override
public OptionList getOptions()
{
return options;
}
public class Options extends OptionList
{
public final Option<String> sender = new Option<>("sender", null, String.class, "");
public final Option<String> event = new Option<>("event", "event", String.class, "");
public final Option<Boolean> mean = new Option<>("mean", true, Boolean.class, "send mean values");
/**
*
*/
private Options()
{
addOptions();
}
}
public final Options options = new Options();
public FloatSegmentEventSender()
{
_name = "FloatSegmentEventSender";
options.sender.set(_name);
}
@Override
public void enter(Stream[] stream_in) throws SSJFatalException
{
if (stream_in[0].type != Cons.Type.FLOAT) {
throw new SSJFatalException("type "+ stream_in[0].type +" not supported");
}
}
@Override
protected void consume(Stream[] stream_in, Event trigger) throws SSJFatalException
{
float ptr[] = stream_in[0].ptrF();
Event ev = Event.create(Cons.Type.STRING);
ev.name = options.event.get();
ev.sender = options.sender.get();
ev.time = (int)(1000 * stream_in[0].time + 0.5);
ev.dur = (int)(1000 * (stream_in[0].num / stream_in[0].sr) + 0.5);
ev.state = Event.State.COMPLETED;
String msg = "";
if (options.mean.get()) {
float sum;
for (int j = 0; j < stream_in[0].dim; j++)
{
sum = 0;
for (int i = 0; i < stream_in[0].num; i++)
{
sum += ptr[i * stream_in[0].dim + j];
}
msg += String.valueOf(sum / stream_in[0].num) + " ";
}
}
else {
for (int i = 0; i < stream_in[0].num; i++) {
for (int j = 0; j < stream_in[0].dim; j++)
{
msg += String.valueOf(ptr[i * stream_in[0].dim + j]) + " ";
}
}
}
ev.setData(msg);
_evchannel_out.pushEvent(ev);
}
@Override
public void flush(Stream[] stream_in) throws SSJFatalException
{}
}
| 3,934 | 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/angelsensor/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.angelsensor;
/*
* 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,512 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AngelSensorListener.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/angelsensor/AngelSensorListener.java | /*
* AngelSensorListener.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.angelsensor;
import android.content.Context;
import android.os.Handler;
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;
import java.util.Vector;
import hcm.ssj.core.SSJApplication;
/**
* Created by simon on 17.06.16.
*/
public class AngelSensorListener
{
private BleDevice mBleDevice;
private Handler mHandler;
private Vector<Integer> opticalGreenLED;
private Vector<Integer> opticalBlueLED;
//private Vector<Tupel<float, float, float>> acceleration;
public AngelSensorListener()
{
reset();
}
public void reset()
{
if (opticalGreenLED == null)
{
opticalGreenLED = new Vector<Integer>();
}
else
{
opticalGreenLED.removeAllElements();
}
if (opticalBlueLED == null)
{
opticalBlueLED = new Vector<Integer>();
}
else
{
opticalBlueLED.removeAllElements();
}
}
private final BleCharacteristic.ValueReadyCallback<ChAccelerationWaveform.AccelerationWaveformValue> mAccelerationWaveformListener = new BleCharacteristic.ValueReadyCallback<ChAccelerationWaveform.AccelerationWaveformValue>()
{
@Override
public void onValueReady(ChAccelerationWaveform.AccelerationWaveformValue accelerationWaveformValue)
{
if (accelerationWaveformValue != null && accelerationWaveformValue.wave != null)
{
for (Integer item : accelerationWaveformValue.wave)
{
//mAccelerationWaveformView.addValue(item);
//vector push
//provide()
}
}
}
};
public void connect(String deviceAddress)
{
// A device has been chosen from the list. Create an instance of BleDevice,
// populate it with interesting services and then connect
if (mBleDevice != null)
{
mBleDevice.disconnect();
}
Context context = SSJApplication.getAppContext();
mHandler = new Handler(context.getMainLooper());
mBleDevice = new BleDevice(context, mDeviceLifecycleCallback, mHandler);
try
{
mBleDevice.registerServiceClass(SrvWaveformSignal.class);
mBleDevice.registerServiceClass(SrvHeartRate.class);
mBleDevice.registerServiceClass(SrvHealthThermometer.class);
mBleDevice.registerServiceClass(SrvBattery.class);
mBleDevice.registerServiceClass(SrvActivityMonitoring.class);
}
catch (NoSuchMethodException e)
{
throw new AssertionError();
}
catch (IllegalAccessException e)
{
throw new AssertionError();
}
catch (InstantiationException e)
{
throw new AssertionError();
}
mBleDevice.connect(deviceAddress);
}
private final BleCharacteristic.ValueReadyCallback<ChOpticalWaveform.OpticalWaveformValue> mOpticalWaveformListener = new BleCharacteristic.ValueReadyCallback<ChOpticalWaveform.OpticalWaveformValue>()
{
@Override
public void onValueReady(ChOpticalWaveform.OpticalWaveformValue opticalWaveformValue)
{
if (opticalWaveformValue != null && opticalWaveformValue.wave != null)
{
for (ChOpticalWaveform.OpticalSample item : opticalWaveformValue.wave)
{
opticalGreenLED.add(item.green);
opticalBlueLED.add(item.blue);
//mBlueOpticalWaveformView.addValue(item.blue);
}
}
}
};
private final BleDevice.LifecycleCallback mDeviceLifecycleCallback = new BleDevice.LifecycleCallback()
{
@Override
public void onBluetoothServicesDiscovered(BleDevice bleDevice)
{
bleDevice.getService(SrvWaveformSignal.class).getAccelerationWaveform().enableNotifications(mAccelerationWaveformListener);
bleDevice.getService(SrvWaveformSignal.class).getOpticalWaveform().enableNotifications(mOpticalWaveformListener);
}
@Override
public void onBluetoothDeviceDisconnected()
{
}
@Override
public void onReadRemoteRssi(int i)
{
}
};
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;
}
}
};
| 5,578 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AngelSensor.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/angelsensor/AngelSensor.java | /*
* AngelSensor.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.angelsensor;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import com.angel.sdk.BleScanner;
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;
public class AngelSensor extends Sensor
{
private Handler handler;
protected boolean angelInitialized;
protected AngelSensorListener listener;
BleScanner.ScanCallback mScanCallback = new BleScanner.ScanCallback()
{
@Override
public void onBluetoothDeviceFound(BluetoothDevice device)
{
if (device.getName() != null)
{
Log.i("Bluetooth LE device found: " + device.getName());
//mBleScanner.stopScan();
if (device.getName() != null && device.getName().startsWith("Angel"))
{
bluetoothDevice = device;
//mBleScanner.stop();
mBleScanner.stopScan();
listener.connect(device.getAddress());
Log.i("connected to device " + device.getName());
}
}
}
};
public AngelSensor()
{
_name = "AngelSensor";
angelInitialized = false;
}
@Override
public boolean connect() throws SSJFatalException
{
listener = new AngelSensorListener();
try
{
if (mBleScanner == null)
{
//bluetoothAdapter = BleUtils.getBluetoothAdapter(ctx);
mBleScanner = new BleScanner(SSJApplication.getAppContext(), mScanCallback);
}
}
catch (Exception e)
{
Log.e("Exception:", e);
}
mBleScanner.startScan();
//mBleScanner.setScanPeriod(1000);
//mBleScanner.start();
return true;
}
@Override
public void disconnect() throws SSJFatalException
{
}
public void didDiscoverDevice(BluetoothDevice bluetoothDevice, int rssi, boolean allowed)
{
}
private BleScanner mBleScanner;
private BluetoothAdapter bluetoothAdapter;
BluetoothDevice bluetoothDevice;
@Override
public OptionList getOptions()
{
return null;
}
}
| 3,325 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
BVPAngelChannel.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/main/java/hcm/ssj/angelsensor/BVPAngelChannel.java | /*
* BVPAngelChannel.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.angelsensor;
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 BVPAngelChannel extends SensorChannel
{
public class Options extends OptionList
{
public final Option<Float> sampleRate = new Option<>("sampleRate", 100f, Float.class, "sensor sample rate");
private Options()
{
addOptions();
}
}
public final Options options = new Options();
protected AngelSensorListener _listener;
public BVPAngelChannel()
{
_name = "Angel_BVP";
}
@Override
public void enter(Stream stream_out) throws SSJFatalException
{
_listener = ((AngelSensor)_sensor).listener;
}
@Override
protected boolean process(Stream stream_out) throws SSJFatalException
{
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,784 | 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/angelsensor/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.angelsensor;
/*
*
* 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,784 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FFMPEGTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FFMPEGTest.java | /*
* FFMPEGTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.camera.CameraChannel;
import hcm.ssj.camera.CameraSensor;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Pipeline;
import hcm.ssj.ffmpeg.FFMPEGWriter;
/**
* Created by Michael Dietz on 04.09.2017.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FFMPEGTest
{
int width = 640;
int height = 480;
int frameRate = 15;
@Test
public void testFFMPEGWriter() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
CameraSensor cameraSensor = new CameraSensor();
cameraSensor.options.cameraType.set(Cons.CameraType.BACK_CAMERA);
cameraSensor.options.width.set(width);
cameraSensor.options.height.set(height);
cameraSensor.options.previewFpsRangeMin.set(frameRate * 1000);
cameraSensor.options.previewFpsRangeMax.set(frameRate * 1000);
// Sensor channel
CameraChannel cameraChannel = new CameraChannel();
cameraChannel.options.sampleRate.set((double) frameRate);
frame.addSensor(cameraSensor, cameraChannel);
// Consumer
FFMPEGWriter ffmpegWriter = new FFMPEGWriter();
ffmpegWriter.options.fileName.set("test.mp4");
frame.addConsumer(ffmpegWriter, cameraChannel, 1.0 / frameRate);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
}
}
| 2,933 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSIXmlPipeTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SSIXmlPipeTest.java | /*
* MobileSSITest.java
* Copyright (c) 2017
* 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;
import android.content.res.AssetManager;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.core.Pipeline;
import hcm.ssj.mobileSSI.MobileSSIConsumer;
import hcm.ssj.test.Logger;
import static java.lang.System.loadLibrary;
/**
* Tests all classes in the android sensor package.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SSIXmlPipeTest
{
public native void startSSI(String path, AssetManager am, boolean extractFiles);
public native void stopSSI();
/**
* @throws Exception
*/
@Test
public void testSensors() throws Exception
{
loadLibrary("ssiframe");
loadLibrary("ssievent");
loadLibrary("ssiioput");
loadLibrary("ssiandroidsensors");
loadLibrary("ssimodel");
loadLibrary("ssisignal");
loadLibrary("ssissjSensor");
loadLibrary("android_xmlpipe");
// Test for every sensor type
SensorType acc = SensorType.GYROSCOPE;
SensorType mag = SensorType.ACCELEROMETER;
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
AndroidSensor sensor = new AndroidSensor();
AndroidSensor s2 = new AndroidSensor();
// Channel
AndroidSensorChannel sensorChannel = new AndroidSensorChannel();
sensorChannel.options.sensorType.set(acc);
AndroidSensorChannel sensorPmag = new AndroidSensorChannel();
sensorPmag.options.sensorType.set(mag);
frame.addSensor(sensor, sensorChannel);
frame.addSensor(s2, sensorPmag);
// Logger
Logger log = new Logger();
frame.addConsumer(log, sensorChannel, 1, 0);
frame.addConsumer(log, sensorPmag, 1, 0);
MobileSSIConsumer mobileSSI2 = new MobileSSIConsumer();
MobileSSIConsumer mobileSSI = new MobileSSIConsumer();
mobileSSI.setId(1);
mobileSSI2.setId(2);
frame.addConsumer(mobileSSI, sensorChannel, 1, 0);
frame.addConsumer(mobileSSI2, sensorPmag, 1, 0);
// Start framework
startSSI("/sdcard/android_xmlpipe", null, false);
Thread.sleep(3100);
frame.start();
mobileSSI.setSensor(sensorChannel, null, mobileSSI.getId());
mobileSSI2.setSensor(sensorPmag, null, mobileSSI2.getId());
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
stopSSI();
frame.stop();
frame.release();
}
}
| 3,921 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AnnotationTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/AnnotationTest.java | /*
* AnnotationTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.core.Annotation;
import hcm.ssj.core.Cons;
/**
* Created by Michael Dietz on 07.11.2017.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class AnnotationTest
{
private String trainerFileName = "activity.NaiveBayes.trainer";
private String modelPath = "/sdcard/SSJ/Creator/res";
// Helper variables
private String modelFileName;
private String modelOptionFileName;
private int[] select_dimensions;
private String[] classNames;
private int bytes;
private int dim;
private float sr;
private Cons.Type type;
@Test
public void LoadSaveTest() throws Exception
{
Annotation anno = new Annotation();
anno.load("/sdcard/SSJ/mouse.annotation");
anno.save("/sdcard/SSJ", "mouse2.annotation");
anno.convertToFrames(1.0, "xx", 0, 0.5);
anno.save("/sdcard/SSJ", "mouse_cont.annotation");
return;
}
}
| 2,352 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
TestHelper.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/TestHelper.java | /*
* TestHelper.java
* Copyright (c) 2017
* 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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
/**
* Created by Johnny on 04.05.2017.
*/
public class TestHelper
{
public static final int DUR_TEST_LONG = 2 * 60 * 1000;
public static final int DUR_TEST_NORMAL = 30 * 1000;
public static final int DUR_TEST_SHORT = 10 * 1000;
public static void copyAssetToFile(String assetName, File dst) throws IOException
{
InputStream in = getInstrumentation().getContext().getResources().getAssets().open(assetName);
OutputStream out = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
}
}
| 2,222 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FacialLandmarkTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FacialLandmarkTest.java | /*
* FacialLandmarkTest.java
* Copyright (c) 2019
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.camera.CameraChannel;
import hcm.ssj.camera.CameraSensor;
import hcm.ssj.camera.ImageResizer;
import hcm.ssj.camera.NV21ToRGBDecoder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Pipeline;
import hcm.ssj.landmark.FaceLandmarks;
import hcm.ssj.test.Logger;
/**
* Created by Michael Dietz on 29.01.2019.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FacialLandmarkTest
{
@Test
public void testFacialLandmarks() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Option parameters for camera sensor
double sampleRate = 1;
int width = 640;
int height = 480;
// Instantiate camera sensor and set options
CameraSensor cameraSensor = new CameraSensor();
cameraSensor.options.cameraType.set(Cons.CameraType.FRONT_CAMERA);
cameraSensor.options.width.set(width);
cameraSensor.options.height.set(height);
cameraSensor.options.previewFpsRangeMin.set(15);
cameraSensor.options.previewFpsRangeMax.set(15);
// Add sensor to the pipeline
CameraChannel cameraChannel = new CameraChannel();
cameraChannel.options.sampleRate.set(sampleRate);
frame.addSensor(cameraSensor, cameraChannel);
// Set up a NV21 decoder
NV21ToRGBDecoder decoder = new NV21ToRGBDecoder();
frame.addTransformer(decoder, cameraChannel, 1, 0);
// Add landmark detector
FaceLandmarks landmarkTransformer = new FaceLandmarks();
landmarkTransformer.options.rotation.set(-90);
landmarkTransformer.options.useLegacyModel.set(true);
frame.addTransformer(landmarkTransformer, decoder, 1, 0);
// Add logger
Logger logger = new Logger();
frame.addConsumer(logger, landmarkTransformer, 1, 0);
// Start pipeline
frame.start();
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
frame.release();
}
}
| 3,388 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileDownloadTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FileDownloadTest.java | /*
* FileDownloadTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import hcm.ssj.core.Pipeline;
import hcm.ssj.file.FileCons;
import static org.junit.Assert.assertTrue;
/**
* Downloads necessary files for inference with Inception and tests whether
* they all are on SD card thereafter.
*
* @author Vitaly
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FileDownloadTest
{
private static final String assetsURL = "https://raw.githubusercontent.com/hcmlab/ssj/syncHost/models";
private static final String trainer = "inception.trainer";
private static final String model = "inception.model";
private static final String option = "inception.option";
@Test
public void downloadTrainerFile()
{
File file = null;
try
{
Pipeline.getInstance().download(trainer, assetsURL, FileCons.DOWNLOAD_DIR, true);
}
catch (IOException e)
{
e.printStackTrace();
}
file = new File(FileCons.DOWNLOAD_DIR, trainer);
assertTrue(file.exists());
}
@Test
public void downloadModelFile()
{
File file = null;
try
{
Pipeline.getInstance().download(model, assetsURL, FileCons.DOWNLOAD_DIR, true);
}
catch (IOException e)
{
e.printStackTrace();
}
file = new File(FileCons.DOWNLOAD_DIR, model);
assertTrue(file.exists());
}
@Test
public void downloadOptionFile()
{
File file = null;
try
{
Pipeline.getInstance().download(option, assetsURL, FileCons.DOWNLOAD_DIR, true);
}
catch (IOException e)
{
e.printStackTrace();
}
file = new File(FileCons.DOWNLOAD_DIR, option);
assertTrue(file.exists());
}
}
| 3,076 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
NV21ToRGBDecoderTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/NV21ToRGBDecoderTest.java | /*
* NV21ToRGBDecoderTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.camera.CameraChannel;
import hcm.ssj.camera.CameraSensor;
import hcm.ssj.camera.ImageResizer;
import hcm.ssj.camera.NV21ToRGBDecoder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Pipeline;
import hcm.ssj.test.Logger;
/**
* @author Vitaly
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class NV21ToRGBDecoderTest
{
@Test
public void decodeNV21() throws Exception
{
final float BUFFER_SIZE = 10f;
final int CROP_SIZE = 224;
final int MIN_FPS = 15;
final int MAX_FPS = 15;
final int DATA_WINDOW_SIZE = 1;
final int DATA_OVERLAP = 0;
// Option parameters for camera sensor
double sampleRate = 1;
int width = 320;
int height = 240;
// Get pipeline instance
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(BUFFER_SIZE);
// Instantiate camera sensor and set options
CameraSensor cameraSensor = new CameraSensor();
cameraSensor.options.cameraType.set(Cons.CameraType.BACK_CAMERA);
cameraSensor.options.width.set(width);
cameraSensor.options.height.set(height);
cameraSensor.options.previewFpsRangeMin.set(MIN_FPS);
cameraSensor.options.previewFpsRangeMax.set(MAX_FPS);
// Add sensor to the pipeline
CameraChannel cameraChannel = new CameraChannel();
cameraChannel.options.sampleRate.set(sampleRate);
frame.addSensor(cameraSensor, cameraChannel);
// Set up a NV21 decoder
NV21ToRGBDecoder decoder = new NV21ToRGBDecoder();
frame.addTransformer(decoder, cameraChannel, DATA_WINDOW_SIZE, DATA_OVERLAP);
ImageResizer resizer = new ImageResizer();
resizer.options.size.set(CROP_SIZE);
frame.addTransformer(resizer, decoder, DATA_WINDOW_SIZE, DATA_OVERLAP);
// Add consumer to the pipeline
Logger logger = new Logger();
frame.addConsumer(logger, resizer, 1.0 / sampleRate, DATA_OVERLAP);
// Start pipeline
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_SHORT);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
frame.release();
}
}
| 3,525 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
UtilTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/UtilTest.java | /*
* UtilTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import android.util.Xml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xmlpull.v1.XmlPullParser;
import java.io.StringReader;
import java.util.Arrays;
import hcm.ssj.core.Log;
import hcm.ssj.core.Util;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class UtilTest
{
@Test
public void test() throws Exception
{
int[] x = new int[]{0, 2, 9, -20};
byte[] y = new byte[1024];
int[] z = new int[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void test2() throws Exception
{
long[] x = new long[]{0, 2, 9, -20};
byte[] y = new byte[1024];
long[] z = new long[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void test3() throws Exception
{
short[] x = new short[]{0, 2, 9, -20};
byte[] y = new byte[1024];
short[] z = new short[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void test4() throws Exception
{
int ITER = 20;
long start, delta, ff = 0, fb = 0, bf = 0;
for (int i = 0; i < ITER; i++)
{
float[] x = new float[48000];
for (int j = 0; j < x.length; ++j)
{
x[j] = (float) Math.random();
}
byte[] y = new byte[48000 * 4];
float[] z = new float[48000];
start = System.nanoTime();
Util.arraycopy(x, 0, z, 0, x.length * Util.sizeOf(z[0]));
delta = System.nanoTime() - start;
Log.i("float-float copy: " + delta + "ns");
ff += delta;
start = System.nanoTime();
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
delta = System.nanoTime() - start;
Log.i("float-byte copy: " + delta + "ns");
fb += delta;
Arrays.fill(x, (float) 0);
start = System.nanoTime();
Util.arraycopy(y, 0, x, 0, x.length * Util.sizeOf(x[0]));
delta = System.nanoTime() - start;
Log.i("byte-float copy: " + delta + "ns");
bf += delta;
Thread.sleep(1000);
}
Log.i("avg float-float copy: " + ff / ITER + "ns");
Log.i("avg float-byte copy: " + fb / ITER + "ns");
Log.i("avg byte-float copy: " + bf / ITER + "ns");
}
@Test
public void test5() throws Exception
{
double[] x = new double[]{0.7985, 2, 9, -20.556999};
byte[] y = new byte[1024];
double[] z = new double[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void test6() throws Exception
{
char[] x = new char[]{0, 2, 9};
byte[] y = new byte[1024];
char[] z = new char[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void test7() throws Exception
{
boolean[] x = new boolean[]{true, false, true, true};
byte[] y = new byte[1024];
boolean[] z = new boolean[1024];
Util.arraycopy(x, 0, y, 0, x.length * Util.sizeOf(x[0]));
Util.arraycopy(y, 0, z, 0, x.length * Util.sizeOf(z[0]));
for (int i = 0; i < x.length; i++)
{
if (x[i] != z[i])
{
throw new RuntimeException();
}
}
}
@Test
public void testXmlToStr() throws Exception
{
String str = "<ssj><test attr=\"val\">text</test><test attr=\"val2\">text2</test></ssj>";
Log.i("input: " + str);
XmlPullParser xml = Xml.newPullParser();
xml.setInput(new StringReader(str));
xml.next();
Log.i("output: " + Util.xmlToString(xml));
}
} | 5,514 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
EstimoteBeaconTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/EstimoteBeaconTest.java | /*
* EstimoteBeaconTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.Provider;
import hcm.ssj.estimote.BeaconChannel;
import hcm.ssj.estimote.EstimoteBeacon;
import hcm.ssj.signal.Butfilt;
import hcm.ssj.signal.Merge;
import hcm.ssj.test.Logger;
/**
* Created by Michael Dietz on 08.03.2017.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class EstimoteBeaconTest
{
@Test
public void testBeacons() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
frame.options.logtimeout.set(0.2);
// Sensor
EstimoteBeacon sensor = new EstimoteBeacon();
sensor.options.uuid.set("B9407F30-F5F8-466E-AFF9-25556B57FE6D");
sensor.options.major.set(1337);
// Channel
BeaconChannel channel = new BeaconChannel();
channel.options.identifier.set("B9407F30-F5F8-466E-AFF9-25556B57FE6D:1337:1000");
frame.addSensor(sensor, channel);
// Transformer
Butfilt filter = new Butfilt();
filter.options.zero.set(true);
filter.options.norm.set(false);
filter.options.low.set(0.3);
filter.options.order.set(1);
filter.options.type.set(Butfilt.Type.LOW);
frame.addTransformer(filter, channel, 0.2, 0);
Merge merge = new Merge();
frame.addTransformer(merge, new Provider[]{channel, filter}, 0.2, 0);
// Consumer
Logger log = new Logger();
frame.addConsumer(log, merge, 0.2, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.clear();
}
}
| 3,089 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
CameraTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/CameraTest.java | /*
* CameraTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import android.view.SurfaceView;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import hcm.ssj.camera.CameraChannel;
import hcm.ssj.camera.CameraPainter;
import hcm.ssj.camera.CameraSensor;
import hcm.ssj.camera.CameraWriter;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Pipeline;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
/**
* Tests all camera sensor, channel and consumer.<br>
* Created by Frank Gaibler on 28.01.2016.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class CameraTest
{
/**
* Test types
*/
private enum Type
{
WRITER, PAINTER
}
@Test
public void testCameraWriter() throws Throwable
{
buildPipe(Type.WRITER);
}
@Test
public void testCameraPainter() throws Throwable
{
buildPipe(Type.PAINTER);
}
private void buildPipe(Type type) throws Exception
{
// Small values because of memory usage
int frameRate = 10;
int width = 176;
int height = 144;
// Resources
File file = null;
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
CameraSensor cameraSensor = new CameraSensor();
cameraSensor.options.cameraType.set(Cons.CameraType.FRONT_CAMERA);
cameraSensor.options.width.set(width);
cameraSensor.options.height.set(height);
cameraSensor.options.previewFpsRangeMin.set(4 * 1000);
cameraSensor.options.previewFpsRangeMax.set(16 * 1000);
// Channel
CameraChannel cameraChannel = new CameraChannel();
cameraChannel.options.sampleRate.set((double) frameRate);
frame.addSensor(cameraSensor, cameraChannel);
// Consumer
switch (type)
{
case WRITER:
{
//file
File dir = getInstrumentation().getContext().getFilesDir();
String fileName = getClass().getSimpleName() + "." + getClass().getSimpleName();
//
CameraWriter cameraWriter = new CameraWriter();
cameraWriter.options.filePath.setValue(dir.getPath());
cameraWriter.options.fileName.set(fileName);
cameraWriter.options.width.set(width);
cameraWriter.options.height.set(height);
frame.addConsumer(cameraWriter, cameraChannel, 1.0 / frameRate, 0);
break;
}
case PAINTER:
{
CameraPainter cameraPainter = new CameraPainter();
cameraPainter.options.surfaceView.set(new SurfaceView(getInstrumentation().getContext()));
frame.addConsumer(cameraPainter, cameraChannel, 1 / frameRate, 0);
break;
}
}
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
// Cleanup
switch (type)
{
case WRITER:
{
Assert.assertTrue(file.length() > 1000);
if (file.exists())
{
if (!file.delete())
{
throw new RuntimeException("File could not be deleted");
}
}
break;
}
}
}
}
| 4,398 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GPSTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/GPSTest.java | /*
* GPSTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.core.Pipeline;
import hcm.ssj.gps.GPSChannel;
import hcm.ssj.gps.GPSSensor;
import hcm.ssj.test.Logger;
/**
* Created by Michael Dietz on 05.07.2016.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class GPSTest
{
@Test
public void testSensors() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
GPSSensor sensor = new GPSSensor();
// Channel
GPSChannel sensorChannel = new GPSChannel();
frame.addSensor(sensor, sensorChannel);
// Logger
Logger log = new Logger();
frame.addConsumer(log, sensorChannel, 1, 0);
// start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// stop framework
frame.stop();
frame.clear();
}
}
| 2,360 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
GlassTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/GlassTest.java | /*
* GlassTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.core.Pipeline;
import hcm.ssj.glass.BlinkDetection;
import hcm.ssj.glass.InfraredChannel;
import hcm.ssj.glass.InfraredSensor;
import hcm.ssj.test.Logger;
/**
* Tests all classes in the glass package.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class GlassTest
{
@Test
public void testInfrared() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
InfraredSensor sensor = new InfraredSensor();
// Channel
InfraredChannel sensorChannel = new InfraredChannel();
frame.addSensor(sensor, sensorChannel);
// Transformer
BlinkDetection transformer = new BlinkDetection();
frame.addTransformer(transformer, sensorChannel, 1, 0);
// Logger
Logger log = new Logger();
frame.addConsumer(log, sensorChannel, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
}
}
| 2,614 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SSITest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SSITest.java | /*
* SSITest.java
* Copyright (c) 2017
* 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;
import android.os.Environment;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.Provider;
import hcm.ssj.mobileSSI.SSI;
import hcm.ssj.mobileSSI.SSITransformer;
import hcm.ssj.signal.AvgVar;
import hcm.ssj.signal.Median;
import hcm.ssj.signal.Merge;
import hcm.ssj.signal.MinMax;
import hcm.ssj.signal.Progress;
import hcm.ssj.test.Logger;
/**
* Tests all classes in the android sensor package.<br>
* Created by Frank Gaibler on 13.08.2015.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SSITest
{
@Test
public void testTransformer() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
AndroidSensor sensor = new AndroidSensor();
AndroidSensorChannel channel = new AndroidSensorChannel();
channel.options.sensorType.set(SensorType.ACCELEROMETER);
frame.addSensor(sensor, channel);
SSITransformer transf = new SSITransformer();
transf.options.name.set(SSI.TransformerName.Butfilt);
transf.options.ssioptions.set(new String[]{"low->0.01"});
frame.addTransformer(transf, channel, 1);
// Logger
Logger log = new Logger();
frame.addConsumer(log, transf, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
}
@Test
public void testClassifierT() throws Exception
{
//setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
//sensor
AndroidSensor sensor = new AndroidSensor();
AndroidSensorChannel acc = new AndroidSensorChannel();
acc.options.sensorType.set(SensorType.ACCELEROMETER);
frame.addSensor(sensor, acc);
AndroidSensorChannel gyr = new AndroidSensorChannel();
gyr.options.sensorType.set(SensorType.GYROSCOPE);
frame.addSensor(sensor, gyr);
AndroidSensorChannel mag = new AndroidSensorChannel();
mag.options.sensorType.set(SensorType.MAGNETIC_FIELD);
frame.addSensor(sensor, mag);
Progress prog = new Progress();
frame.addTransformer(prog, new Provider[]{acc, gyr, mag}, 1.0, 0);
AvgVar avg = new AvgVar();
avg.options.avg.set(true);
avg.options.var.set(true);
frame.addTransformer(avg, prog, 1.0, 0);
MinMax minmax = new MinMax();
frame.addTransformer(minmax, prog, 1.0, 0);
Median med = new Median();
frame.addTransformer(med, prog, 1.0, 0);
Merge merge = new Merge();
frame.addTransformer(merge, new Provider[]{avg, med, minmax}, 1.0, 0);
SSITransformer transf = new SSITransformer();
transf.options.name.set(SSI.TransformerName.ClassifierT);
transf.options.ssioptions.set(new String[]{"trainer->" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/SSJ/Creator/res/activity.NaiveBayes.trainer"});
frame.addTransformer(transf, merge, 1);
// Logger
Logger log = new Logger();
frame.addConsumer(log, transf, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
}
}
| 4,812 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SignalTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SignalTest.java | /*
* SignalTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.biosig.HRVSpectral;
import hcm.ssj.core.Pipeline;
import hcm.ssj.file.FileReader;
import hcm.ssj.file.FileReaderChannel;
import hcm.ssj.signal.Derivative;
import hcm.ssj.signal.FFTfeat;
import hcm.ssj.signal.Functionals;
import hcm.ssj.signal.PSD;
import hcm.ssj.signal.Spectrogram;
import hcm.ssj.test.Logger;
import static androidx.test.InstrumentationRegistry.getContext;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SignalTest
{
@Test
public void testFFT() throws Exception
{
String[] files = null;
files = getInstrumentation().getContext().getResources().getAssets().list("");
File dir = getContext().getFilesDir();
String fileName = "audio.stream";
File header = new File(dir, fileName);
TestHelper.copyAssetToFile(fileName, header);
File data = new File(dir, fileName + "~");
TestHelper.copyAssetToFile(fileName + "data", data); //android does not support "~" in asset files
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
frame.options.countdown.set(0);
// Sensor
FileReader file = new FileReader();
file.options.file.setValue(dir.getAbsolutePath() + File.separator + fileName);
FileReaderChannel channel = new FileReaderChannel();
channel.setWatchInterval(0);
channel.setSyncInterval(0);
frame.addSensor(file, channel);
// Transformer
FFTfeat fft = new FFTfeat();
frame.addTransformer(fft, channel, 512.0 / channel.getSampleRate(), 0);
Logger log = new Logger();
frame.addConsumer(log, fft, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.clear();
header.delete();
data.delete();
}
@Test
public void testDerivative() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
frame.options.countdown.set(0);
// Sensor
AndroidSensor sensor = new AndroidSensor();
AndroidSensorChannel channel = new AndroidSensorChannel();
channel.options.sensorType.set(SensorType.ACCELEROMETER);
channel.options.sampleRate.set(40);
frame.addSensor(sensor, channel);
// Transformer
Derivative deriv = new Derivative();
frame.addTransformer(deriv, channel, 1, 0);
Logger log = new Logger();
frame.addConsumer(log, deriv, 1, 0);
// start framework
frame.start();
// Run test
long end = System.currentTimeMillis() + TestHelper.DUR_TEST_SHORT;
try
{
while (System.currentTimeMillis() < end)
{
Thread.sleep(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.clear();
}
@Test
public void testFunctionals() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
AndroidSensor sensor = new AndroidSensor();
// Channel
AndroidSensorChannel sensorChannel = new AndroidSensorChannel();
sensorChannel.options.sensorType.set(SensorType.ACCELEROMETER);
frame.addSensor(sensor, sensorChannel);
// Transformer
Functionals transformer = new Functionals();
frame.addTransformer(transformer, sensorChannel, 1, 0);
// Logger
Logger log = new Logger();
frame.addConsumer(log, transformer, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_SHORT);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
}
@Test
public void testSpectrogram() throws Exception
{
File dir = getContext().getFilesDir();
String fileName = "audio.stream";
File header = new File(dir, fileName);
TestHelper.copyAssetToFile(fileName, header);
File data = new File(dir, fileName + "~");
TestHelper.copyAssetToFile(fileName + "data", data); //android does not support "~" in asset files
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
frame.options.countdown.set(0);
frame.options.log.set(true);
// Sensor
FileReader file = new FileReader();
file.options.file.setValue(dir.getAbsolutePath() + File.separator + fileName);
FileReaderChannel channel = new FileReaderChannel();
channel.options.chunk.set(0.032);
channel.setWatchInterval(0);
channel.setSyncInterval(0);
frame.addSensor(file, channel);
// Transformer
Spectrogram spectrogram = new Spectrogram();
spectrogram.options.banks.set("0.003 0.040, 0.040 0.150, 0.150 0.400");
spectrogram.options.nbanks.set(3);
spectrogram.options.nfft.set(1024);
spectrogram.options.dopower.set(true);
spectrogram.options.dolog.set(false);
frame.addTransformer(spectrogram, channel, 0.1, 0);
HRVSpectral feat = new HRVSpectral();
frame.addTransformer(feat, spectrogram, 0.1, 0);
Logger log = new Logger();
frame.addConsumer(log, feat, 0.1, 0);
// start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// stop framework
frame.stop();
frame.clear();
}
@Test
public void testPSD() throws Exception
{
//setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
//sensor
AndroidSensor sensor = new AndroidSensor();
//channel
AndroidSensorChannel sensorChannel = new AndroidSensorChannel();
sensorChannel.options.sensorType.set(SensorType.LIGHT);
frame.addSensor(sensor, sensorChannel);
//transformer
PSD transformer = new PSD();
transformer.options.entropy.set(false);
transformer.options.normalize.set(false);
frame.addTransformer(transformer, sensorChannel, 1, 0);
//logger
Logger log = new Logger();
frame.addConsumer(log, transformer, 1, 0);
//start framework
frame.start();
//run test
long end = System.currentTimeMillis() + TestHelper.DUR_TEST_NORMAL;
try
{
while (System.currentTimeMillis() < end)
{
Thread.sleep(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
frame.release();
}
}
| 7,853 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FileTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FileTest.java | /*
* FileTest.java
* Copyright (c) 2017
* 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;
import android.os.Environment;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.core.Pipeline;
import hcm.ssj.file.FileCons;
import hcm.ssj.file.FileReader;
import hcm.ssj.file.FileReaderChannel;
import hcm.ssj.file.FileWriter;
import hcm.ssj.file.SimpleXmlParser;
import hcm.ssj.test.Logger;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
/**
* Tests all classes in the logging package.<br>
* Created by Frank Gaibler on 09.09.2015.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FileTest
{
/**
* @throws Exception
*/
@Test
public void testInternalStorage() throws Exception
{
testWriteRead(true);
}
/**
* @throws Exception
*/
@Test
public void testExternalStorage() throws Exception
{
testWriteRead(false);
}
/**
* @throws Exception
*/
@Test
public void testXmlParserTag() throws Exception
{
String xmlString = "<?xml version=\"1.0\" ?>\n"
+ "<foo>My name is Molly!</foo>";
SimpleXmlParser xmlParser = new SimpleXmlParser();
SimpleXmlParser.XmlValues xmlValues = xmlParser.parse(new ByteArrayInputStream(xmlString.getBytes(Charset.forName("UTF-8"))),
new String[]{"foo"},
null
);
ArrayList<String> foundTag = xmlValues.foundTag;
ArrayList<String[]> foundAttributes = xmlValues.foundAttributes;
if (!foundAttributes.isEmpty())
{
throw new RuntimeException("attributes should be empty");
}
if (foundTag.size() != 1
|| !foundTag.get(0).equals("My name is Molly!"))
{
throw new RuntimeException("tag not found");
}
}
/**
* @throws Exception
*/
@Test
public void testXmlParserAttribute() throws Exception
{
String xmlString = "<?xml version=\"1.0\" ?>"
+ "<options>"
+ " <foo>My name is Molly!</foo>"
+ " <item name=\"log\" type=\"BOOL\" num=\"1\" value=\"true\" help=\"user log normal distribution\" />"
+ " <item name=\"prior\" type=\"BOOL\" num=\"1\" value=\"false\" help=\"use prior probability\" />"
+ "</options>";
SimpleXmlParser xmlParser = new SimpleXmlParser();
SimpleXmlParser.XmlValues xmlValues = xmlParser.parse(new ByteArrayInputStream(xmlString.getBytes(Charset.forName("UTF-8"))),
new String[]{"options", "item"},
new String[]{"name", "value"}
);
ArrayList<String> foundTag = xmlValues.foundTag;
ArrayList<String[]> foundAttributes = xmlValues.foundAttributes;
if (!foundTag.isEmpty())
{
throw new RuntimeException("tag should be empty");
}
if (foundAttributes.size() != 2
|| !foundAttributes.get(0)[0].equals("log")
|| !foundAttributes.get(0)[1].equals("true")
|| !foundAttributes.get(1)[0].equals("prior")
|| !foundAttributes.get(1)[1].equals("false"))
{
throw new RuntimeException("attribute not found");
}
}
/**
* @param internalStorage boolean
* @throws Exception
*/
private void testWriteRead(boolean internalStorage) throws Exception
{
File dir = internalStorage ? getInstrumentation().getContext().getFilesDir()
: Environment.getExternalStorageDirectory();
String fileName = getClass().getSimpleName() + "." + getClass().getSimpleName();
File fileHeader = new File(dir, fileName);
//write
buildPipeline(fileHeader, true);
//read
buildPipeline(fileHeader, false);
//cleanup
if (fileHeader.exists())
{
if (!fileHeader.delete())
{
throw new RuntimeException("Header file could not be deleted");
}
File fileReal = new File(dir, fileName + FileCons.FILE_EXTENSION_STREAM);
if (fileReal.exists())
{
if (!fileReal.delete())
{
throw new RuntimeException("Real file could not be deleted");
}
}
}
}
/**
* @param file File
* @param write boolean
* @throws Exception
*/
private void buildPipeline(File file, boolean write) throws Exception
{
//setup
Pipeline framework = Pipeline.getInstance();
framework.options.bufferSize.set(10.0f);
if (write)
{
write(framework, file);
}
else
{
read(framework, file);
}
//start framework
framework.start();
//run for two minutes
long end = System.currentTimeMillis() + TestHelper.DUR_TEST_NORMAL;
try
{
while (System.currentTimeMillis() < end)
{
Thread.sleep(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
framework.stop();
framework.release();
}
/**
* @param frame TheFramework
* @param file File
* @throws Exception
*/
private void write(Pipeline frame, File file) throws Exception
{
//sensor
AndroidSensor sensorConnection = new AndroidSensor();
//channel
AndroidSensorChannel sensorConnectionChannel = new AndroidSensorChannel();
sensorConnectionChannel.options.sensorType.set(SensorType.ACCELEROMETER);
frame.addSensor(sensorConnection, sensorConnectionChannel);
//consumer
FileWriter fileWriter = new FileWriter();
fileWriter.options.filePath.setValue(file.getParent());
fileWriter.options.fileName.set(file.getName());
frame.addConsumer(fileWriter, sensorConnectionChannel, 0.25, 0);
}
/**
* @param frame TheFramework
* @param file File
* @throws Exception
*/
private void read(Pipeline frame, File file) throws Exception
{
//sensor
FileReader fileReader = new FileReader();
fileReader.options.file.setValue(file.getParent() + File.separator + file.getName());
fileReader.options.loop.set(true);
//channel
FileReaderChannel fileReaderChannel = new FileReaderChannel();
frame.addSensor(fileReader, fileReaderChannel);
//logger
Logger log = new Logger();
frame.addConsumer(log, fileReaderChannel, 0.25, 0);
}
} | 7,282 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
IOputTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/IOputTest.java | /*
* IOputTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.audio.AudioChannel;
import hcm.ssj.audio.Intensity;
import hcm.ssj.audio.Microphone;
import hcm.ssj.core.Cons;
import hcm.ssj.core.EventChannel;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.Provider;
import hcm.ssj.event.FloatsEventSender;
import hcm.ssj.ioput.BluetoothChannel;
import hcm.ssj.ioput.BluetoothConnection;
import hcm.ssj.ioput.BluetoothEventReader;
import hcm.ssj.ioput.BluetoothEventWriter;
import hcm.ssj.ioput.BluetoothReader;
import hcm.ssj.ioput.BluetoothWriter;
import hcm.ssj.ioput.SocketChannel;
import hcm.ssj.ioput.SocketEventWriter;
import hcm.ssj.ioput.SocketReader;
import hcm.ssj.test.EventLogger;
import hcm.ssj.test.Logger;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class IOputTest
{
@Test
public void testBLClient() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
AndroidSensor sensor = new AndroidSensor();
AndroidSensorChannel acc = new AndroidSensorChannel();
acc.options.sensorType.set(SensorType.ACCELEROMETER);
acc.options.sampleRate.set(50);
frame.addSensor(sensor, acc);
AndroidSensor sensor2 = new AndroidSensor();
AndroidSensorChannel gyr = new AndroidSensorChannel();
gyr.options.sensorType.set(SensorType.GRAVITY);
gyr.options.sampleRate.set(50);
frame.addSensor(sensor2, gyr);
Logger dummy = new Logger();
dummy.options.reduceNum.set(true);
frame.addConsumer(dummy, acc, 1.0, 0);
Logger dummy2 = new Logger();
dummy2.options.reduceNum.set(true);
frame.addConsumer(dummy2, gyr, 1.0, 0);
BluetoothWriter blw = new BluetoothWriter();
blw.options.connectionType.set(BluetoothConnection.Type.CLIENT);
blw.options.serverName.set("HCM-Johnny-Phone");
blw.options.connectionName.set("stream");
frame.addConsumer(blw, new Provider[]{acc, gyr}, 1.0, 0);
FloatsEventSender fes = new FloatsEventSender();
frame.addConsumer(fes, acc, 1.0, 0);
EventChannel ch = fes.getEventChannelOut();
BluetoothEventWriter blew = new BluetoothEventWriter();
blew.options.connectionType.set(BluetoothConnection.Type.CLIENT);
blew.options.serverName.set("HCM-Johnny-Phone");
blew.options.connectionName.set("event");
frame.registerEventListener(blew, ch);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_LONG);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
Log.i("test finished");
}
@Test
public void testBLServer() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
BluetoothReader blr = new BluetoothReader();
blr.options.connectionType.set(BluetoothConnection.Type.SERVER);
blr.options.connectionName.set("stream");
BluetoothChannel acc = new BluetoothChannel();
acc.options.channel_id.set(0);
acc.options.dim.set(3);
acc.options.bytes.set(4);
acc.options.type.set(Cons.Type.FLOAT);
acc.options.sr.set(50.);
acc.options.num.set(50);
frame.addSensor(blr, acc);
BluetoothChannel gyr = new BluetoothChannel();
gyr.options.channel_id.set(1);
gyr.options.dim.set(3);
gyr.options.bytes.set(4);
gyr.options.type.set(Cons.Type.FLOAT);
gyr.options.sr.set(50.);
gyr.options.num.set(50);
frame.addSensor(blr, gyr);
Logger dummy = new Logger();
dummy.options.reduceNum.set(true);
frame.addConsumer(dummy, acc, 1.0, 0);
Logger dummy2 = new Logger();
dummy2.options.reduceNum.set(true);
frame.addConsumer(dummy2, gyr, 1.0, 0);
BluetoothEventReader bler = new BluetoothEventReader();
bler.options.connectionType.set(BluetoothConnection.Type.SERVER);
bler.options.connectionName.set("event");
EventChannel ch = frame.registerEventProvider(bler);
EventLogger evlog = new EventLogger();
frame.registerEventListener(evlog, ch);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_LONG);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
Log.i("test finished");
}
@Test
public void testSocketEventWriter() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
Microphone mic = new Microphone();
AudioChannel audio = new AudioChannel();
audio.options.sampleRate.set(16000);
audio.options.scale.set(true);
frame.addSensor(mic, audio);
Intensity energy = new Intensity();
frame.addTransformer(energy, audio, 1.0, 0);
FloatsEventSender evs = new FloatsEventSender();
evs.options.mean.set(true);
frame.addConsumer(evs, energy, 1.0, 0);
EventChannel channel = evs.getEventChannelOut();
EventLogger log = new EventLogger();
frame.registerEventListener(log, channel);
SocketEventWriter sock = new SocketEventWriter();
sock.options.port.set(34300);
sock.options.ip.set("192.168.0.101");
frame.registerEventListener(sock, channel);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_SHORT);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
frame.clear();
}
@Test
public void testSocketReader() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
SocketReader sock = new SocketReader();
sock.options.port.set(7777);
sock.options.ip.set("192.168.0.104");
sock.options.type.set(Cons.SocketType.TCP);
SocketChannel data = new SocketChannel();
data.options.dim.set(2);
data.options.bytes.set(4);
data.options.type.set(Cons.Type.FLOAT);
data.options.sr.set(50.);
data.options.num.set(10);
frame.addSensor(sock, data);
Logger log = new Logger();
frame.addConsumer(log, data, 0.2, 0);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_LONG);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
frame.clear();
}
} | 7,456 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
AudioTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/AudioTest.java | /*
* AudioTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import hcm.ssj.audio.AudioChannel;
import hcm.ssj.audio.AudioWriter;
import hcm.ssj.audio.Intensity;
import hcm.ssj.audio.Microphone;
import hcm.ssj.audio.Pitch;
import hcm.ssj.core.EventChannel;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.Provider;
import hcm.ssj.event.ThresholdEventSender;
import hcm.ssj.signal.Avg;
import hcm.ssj.test.EventLogger;
import static androidx.test.InstrumentationRegistry.getContext;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class AudioTest
{
@Test
public void testWriter() throws Exception
{
// Resources
File dir = getContext().getFilesDir();
String fileName = getClass().getSimpleName() + ".test";
File file = new File(dir, fileName);
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
Microphone microphone = new Microphone();
AudioChannel audio = new AudioChannel();
audio.options.sampleRate.set(8000);
audio.options.scale.set(true);
frame.addSensor(microphone, audio);
// Consumer
AudioWriter audioWriter = new AudioWriter();
audioWriter.options.filePath.setValue(dir.getPath());
audioWriter.options.fileName.set(fileName);
frame.addConsumer(audioWriter, audio, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.release();
// Verify test
Assert.assertTrue(file.exists());
Assert.assertTrue(file.length() > 1000); //1Kb
// Cleanup
if (file.exists())
{
if (!file.delete())
{
throw new RuntimeException("File could not be deleted");
}
}
}
@Test
public void testSpeechrate() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
frame.options.log.set(true);
Microphone mic = new Microphone();
AudioChannel audio = new AudioChannel();
audio.options.sampleRate.set(8000);
audio.options.scale.set(true);
audio.options.chunk.set(0.1);
frame.addSensor(mic, audio);
Pitch pitch = new Pitch();
pitch.options.detector.set(Pitch.YIN);
pitch.options.computeVoicedProb.set(true);
frame.addTransformer(pitch, audio, 0.1, 0);
Avg pitch_env = new Avg();
frame.addTransformer(pitch_env, pitch, 0.1, 0);
Intensity energy = new Intensity();
frame.addTransformer(energy, audio, 1.0, 0);
//VAD
ThresholdEventSender vad = new ThresholdEventSender();
vad.options.thresin.set(new float[]{50.0f}); //SPL
vad.options.mindur.set(1.0);
vad.options.maxdur.set(9.0);
vad.options.hangin.set(3);
vad.options.hangout.set(5);
Provider[] vad_in = {energy};
frame.addConsumer(vad, vad_in, 1.0, 0);
EventChannel vad_channel = vad.getEventChannelOut();
hcm.ssj.audio.SpeechRate sr = new hcm.ssj.audio.SpeechRate();
sr.options.thresholdVoicedProb.set(0.3f);
Provider[] sr_in = {energy, pitch_env};
frame.addConsumer(sr, sr_in, vad_channel);
EventChannel sr_channel = frame.registerEventProvider(sr);
EventLogger log = new EventLogger();
frame.registerEventListener(log, sr_channel);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
}
} | 4,843 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
StandardTestSuite.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/StandardTestSuite.java | /*
* StandardTestSuite.java
* Copyright (c) 2017
* 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;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Runs all tests which do not require advanced setup (e.g. special hardware)
* Created by Johnny on 04.05.2017.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
AndroidSensorTest.class,
AudioTest.class,
BodyTest.class,
EventTest.class,
FileTest.class,
SignalTest.class,
SvmTest.class,
SSITest.class,
UtilTest.class,
NaiveBayesTest.class})
public class StandardTestSuite
{}
| 1,837 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
MyoTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/MyoTest.java | /*
* MyoTest.java
* Copyright (c) 2017
* 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;
import android.os.Handler;
import android.os.Looper;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.thalmic.myo.AbstractDeviceListener;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import org.junit.Test;
import org.junit.runner.RunWith;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.myo.AccelerationChannel;
import hcm.ssj.myo.DynAccelerationChannel;
import hcm.ssj.myo.EMGChannel;
import hcm.ssj.myo.Vibrate2Command;
import hcm.ssj.test.Logger;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
/**
* Created by Michael Dietz on 02.04.2015.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class MyoTest
{
@Test
public void testChannels() throws Exception
{
// Setup
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
// Sensor
hcm.ssj.myo.Myo sensor = new hcm.ssj.myo.Myo();
AccelerationChannel accelerationChannel = new AccelerationChannel();
frame.addSensor(sensor, accelerationChannel);
DynAccelerationChannel dynAccelerationChannel = new DynAccelerationChannel();
frame.addSensor(sensor, dynAccelerationChannel);
EMGChannel emgChannel = new EMGChannel();
frame.addSensor(sensor, emgChannel);
// Loggers
Logger accLogger = new Logger();
frame.addConsumer(accLogger, accelerationChannel, 1, 0);
Logger dynAccLogger = new Logger();
frame.addConsumer(dynAccLogger, dynAccelerationChannel, 1, 0);
Logger emgLogger = new Logger();
frame.addConsumer(emgLogger, emgChannel, 1, 0);
// Start framework
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
// Stop framework
frame.stop();
frame.clear();
}
/**
* Method to test the vibrate2-functionality of myo
*/
@Test
public void testVibrate()
{
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{
public void run()
{
final Hub hub = Hub.getInstance();
if (!hub.init(getInstrumentation().getContext(), getInstrumentation().getContext().getPackageName()))
{
Log.e("error");
}
hub.setLockingPolicy(Hub.LockingPolicy.NONE);
// Disable usage data sending
hub.setSendUsageData(false);
Log.i("attaching...");
hub.attachByMacAddress("F3:41:FA:27:EB:08");
Log.i("attached...");
hub.addListener(new AbstractDeviceListener()
{
@Override
public void onConnect(Myo myo, long timestamp)
{
super.onAttach(myo, timestamp);
startVibrate(myo, hub);
}
});
}
}, 1);
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
handler.postDelayed(new Runnable()
{
public void run()
{
final Hub hub = Hub.getInstance();
hub.shutdown();
}
}, 1);
}
private void startVibrate(Myo myo, Hub hub)
{
Log.i("connected");
try
{
Vibrate2Command vibrate2Command = new Vibrate2Command(hub);
Log.i("vibrate 1...");
myo.vibrate(Myo.VibrationType.MEDIUM);
Thread.sleep(3000);
Log.i("vibrate 2...");
//check strength 50
vibrate2Command.vibrate(myo, 1000, (byte) 50);
Thread.sleep(3000);
Log.i("vibrate 3 ...");
//check strength 100
vibrate2Command.vibrate(myo, 1000, (byte) 100);
Thread.sleep(3000);
Log.i("vibrate 4 ...");
//check strength 100
vibrate2Command.vibrate(myo, 1000, (byte) 150);
Thread.sleep(3000);
Log.i("vibrate 5...");
//check strength 250
vibrate2Command.vibrate(myo, 1000, (byte) 200);
Thread.sleep(3000);
Log.i("vibrate 6...");
//check strength 250
vibrate2Command.vibrate(myo, 1000, (byte) 250);
Thread.sleep(3000);
Log.i("vibrate pattern...");
//check vibrate pattern
vibrate2Command.vibrate(myo, new int[]{500, 500, 500, 500, 500, 500}, new byte[]{25, 50, 100, (byte) 150, (byte) 200, (byte) 250});
Thread.sleep(3000);
}
catch (Exception e)
{
Log.e("exception in vibrate test", e);
}
}
}
| 5,445 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
SendImageTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SendImageTest.java | /*
* IOputTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import hcm.ssj.camera.CameraChannel;
import hcm.ssj.camera.CameraSensor;
import hcm.ssj.camera.ImageNormalizer;
import hcm.ssj.camera.ImageResizer;
import hcm.ssj.camera.NV21ToRGBDecoder;
import hcm.ssj.core.Cons;
import hcm.ssj.core.Log;
import hcm.ssj.core.Pipeline;
import hcm.ssj.ioput.BluetoothChannel;
import hcm.ssj.ioput.BluetoothConnection;
import hcm.ssj.ioput.BluetoothReader;
import hcm.ssj.ioput.BluetoothWriter;
import hcm.ssj.ml.Classifier;
import hcm.ssj.ml.TensorFlow;
import hcm.ssj.test.Logger;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SendImageTest
{
private int width = 320 * 2;
private int height = 240 * 2;
private float frameSize = 1;
private int delta = 0;
@Test
public void testBluetoothClient() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
int minFps = 15;
int maxFps = 15;
double sampleRate = 1;
String serverName = "Hcm Lab (Galaxy S5)";
CameraSensor cameraSensor = new CameraSensor();
cameraSensor.options.cameraType.set(Cons.CameraType.BACK_CAMERA);
cameraSensor.options.width.set(width);
cameraSensor.options.height.set(height);
cameraSensor.options.previewFpsRangeMin.set(minFps);
cameraSensor.options.previewFpsRangeMax.set(maxFps);
CameraChannel cameraChannel = new CameraChannel();
cameraChannel.options.sampleRate.set(sampleRate);
frame.addSensor(cameraSensor, cameraChannel);
BluetoothWriter bluetoothWriter = new BluetoothWriter();
bluetoothWriter.options.connectionType.set(BluetoothConnection.Type.CLIENT);
bluetoothWriter.options.serverName.set(serverName);
bluetoothWriter.options.connectionName.set("stream");
frame.addConsumer(bluetoothWriter, cameraChannel, frameSize, delta);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
Log.i("test finished");
}
@Test
public void testBluetoothServer() throws Exception
{
Pipeline frame = Pipeline.getInstance();
frame.options.bufferSize.set(10.0f);
String trainerName = "inception.trainer";
String trainerURL = "https://raw.githubusercontent.com/hcmlab/ssj/syncHost/models";
BluetoothReader bluetoothReader = new BluetoothReader();
bluetoothReader.options.connectionType.set(BluetoothConnection.Type.SERVER);
bluetoothReader.options.connectionName.set("stream");
BluetoothChannel bluetoothChannel = new BluetoothChannel();
bluetoothChannel.options.channel_id.set(0);
bluetoothChannel.options.dim.set((int) (width * height * 1.5));
bluetoothChannel.options.bytes.set(1);
bluetoothChannel.options.type.set(Cons.Type.IMAGE);
bluetoothChannel.options.sr.set(1.0);
bluetoothChannel.options.num.set(1);
bluetoothChannel.options.imageHeight.set(height);
bluetoothChannel.options.imageWidth.set(width);
bluetoothChannel.options.imageFormat.set(Cons.ImageFormat.NV21);
bluetoothChannel.setSyncInterval(20);
bluetoothChannel.setWatchInterval(10);
frame.addSensor(bluetoothReader, bluetoothChannel);
NV21ToRGBDecoder decoder = new NV21ToRGBDecoder();
frame.addTransformer(decoder, bluetoothChannel, frameSize, delta);
ImageResizer resizer = new ImageResizer();
resizer.options.maintainAspect.set(true);
resizer.options.size.set(224);
resizer.options.savePreview.set(true);
frame.addTransformer(resizer, decoder, frameSize, delta);
// Add image pixel value normalizer to the pipeline
ImageNormalizer imageNormalizer = new ImageNormalizer();
imageNormalizer.options.imageMean.set(127.5f);
imageNormalizer.options.imageStd.set(1f);
frame.addTransformer(imageNormalizer, resizer, frameSize, delta);
TensorFlow tf = new TensorFlow();
tf.options.file.setValue(trainerURL + File.separator + trainerName);
frame.addModel(tf);
Classifier classifier = new Classifier();
classifier.options.merge.set(false);
classifier.options.log.set(true);
classifier.setModel(tf);
frame.addConsumer(classifier, imageNormalizer, frameSize, delta);
Logger logger = new Logger();
frame.addConsumer(logger, bluetoothChannel);
frame.start();
// Wait duration
try
{
Thread.sleep(TestHelper.DUR_TEST_NORMAL);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.stop();
Log.i("test finished");
}
}
| 5,844 | Java | .java | hcmlab/ssj | 31 | 12 | 1 | 2016-02-22T15:23:28Z | 2023-06-28T11:01:08Z |
FeedbackCollectionTest.java | /FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FeedbackCollectionTest.java | /*
* FeedbackCollectionTest.java
* Copyright (c) 2017
* 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;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.Map;
import hcm.ssj.androidSensor.AndroidSensor;
import hcm.ssj.androidSensor.AndroidSensorChannel;
import hcm.ssj.androidSensor.SensorType;
import hcm.ssj.body.OverallActivation;
import hcm.ssj.core.Pipeline;
import hcm.ssj.core.SSJException;
import hcm.ssj.event.FloatsEventSender;
import hcm.ssj.feedback.AndroidTactileFeedback;
import hcm.ssj.feedback.Feedback;
import hcm.ssj.feedback.FeedbackCollection;
import hcm.ssj.signal.MvgAvgVar;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class FeedbackCollectionTest
{
private Pipeline pipeline;
private FeedbackCollection feedbackCollection;
private List<Map<Feedback, FeedbackCollection.LevelBehaviour>> feedbackList;
@Before
public void prepareEnvironment() throws SSJException
{
pipeline = Pipeline.getInstance();
pipeline.options.countdown.set(0);
AndroidSensor sensor = new AndroidSensor();
AndroidSensorChannel sensorChannel = new AndroidSensorChannel();
sensorChannel.options.sensorType.set(SensorType.LINEAR_ACCELERATION);
pipeline.addSensor(sensor, sensorChannel);
OverallActivation overallActivation = new OverallActivation();
pipeline.addTransformer(overallActivation, sensorChannel);
MvgAvgVar mvgAvgVar = new MvgAvgVar();
mvgAvgVar.options.window.set(0.05);
pipeline.addTransformer(mvgAvgVar, overallActivation);
FloatsEventSender floatsEventSender = new FloatsEventSender();
pipeline.addConsumer(floatsEventSender, mvgAvgVar);
feedbackCollection = new FeedbackCollection();
feedbackCollection.options.progression.set(1.0f);
feedbackCollection.options.regression.set(1.5f);
pipeline.registerEventListener(feedbackCollection, floatsEventSender);
// LEVEL 0
AndroidTactileFeedback androidTactileFeedback1 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback1, feedbackCollection, 0, FeedbackCollection.LevelBehaviour.Regress);
AndroidTactileFeedback androidTactileFeedback2 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback2, feedbackCollection, 0, FeedbackCollection.LevelBehaviour.Neutral);
AndroidTactileFeedback androidTactileFeedback3 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback3, feedbackCollection, 0, FeedbackCollection.LevelBehaviour.Progress);
// LEVEL 1
AndroidTactileFeedback androidTactileFeedback4 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback4, feedbackCollection, 1, FeedbackCollection.LevelBehaviour.Regress);
AndroidTactileFeedback androidTactileFeedback5 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback5, feedbackCollection, 1, FeedbackCollection.LevelBehaviour.Neutral);
AndroidTactileFeedback androidTactileFeedback6 = new AndroidTactileFeedback();
pipeline.registerInFeedbackCollection(androidTactileFeedback6, feedbackCollection, 1, FeedbackCollection.LevelBehaviour.Progress);
feedbackList = feedbackCollection.getFeedbackList();
}
@Test
public void testNoProgression()
{
try
{
pipeline.start();
Thread.sleep((int) ((feedbackCollection.options.progression.get() * 1000) * 1.5));
pipeline.stop();
pipeline.release();
}
catch (Exception e)
{
e.printStackTrace();
}
checkLevelActive(0);
}
@Test
public void testProgression()
{
for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackList.get(0).entrySet())
{
if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Regress) ||
feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Neutral))
{
((AndroidTactileFeedback) feedbackLevelBehaviourEntry.getKey()).options.lock.set((int) (feedbackCollection.options.progression.get() * 1000) * 2);
}
}
try
{
pipeline.start();
Thread.sleep((int) ((feedbackCollection.options.progression.get() * 1000) * 1.5));
pipeline.stop();
pipeline.release();
}
catch (Exception e)
{
e.printStackTrace();
}
checkLevelActive(1);
}
@Test
public void testNoRegression()
{
for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackList.get(0).entrySet())
{
if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Regress) ||
feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Neutral))
{
((AndroidTactileFeedback) feedbackLevelBehaviourEntry.getKey()).options.lock.set((int) (feedbackCollection.options.progression.get() * 1000) * 2);
}
}
try
{
pipeline.start();
Thread.sleep((int) ((feedbackCollection.options.progression.get() * 1000) * 1.5));
checkLevelActive(1);
Thread.sleep((int) ((feedbackCollection.options.regression.get() * 1000) * 1.5));
pipeline.stop();
pipeline.release();
}
catch (Exception e)
{
e.printStackTrace();
}
checkLevelActive(1);
}
@Test
public void testRegression()
{
for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackList.get(0).entrySet())
{
if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Regress) ||
feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Neutral))
{
((AndroidTactileFeedback) feedbackLevelBehaviourEntry.getKey()).options.lock.set((int) (feedbackCollection.options.progression.get() * 1000) * 2);
}
}
for (Map.Entry<Feedback, FeedbackCollection.LevelBehaviour> feedbackLevelBehaviourEntry : feedbackList.get(1).entrySet())
{
if (feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Progress) ||
feedbackLevelBehaviourEntry.getValue().equals(FeedbackCollection.LevelBehaviour.Neutral))
{
((AndroidTactileFeedback) feedbackLevelBehaviourEntry.getKey()).options.lock.set((int) (feedbackCollection.options.regression.get() * 1000) * 2);
}
}
try
{
pipeline.start();
Thread.sleep((int) (feedbackCollection.options.progression.get() * 1000) + 200);
checkLevelActive(1);
Thread.sleep((int) (feedbackCollection.options.regression.get() * 1000) + 200);
pipeline.stop();
pipeline.release();
}
catch (Exception e)
{
e.printStackTrace();
}
checkLevelActive(0);
}
private void checkLevelActive(int level)
{
for (int i = 0; i < feedbackList.size(); i++)
{
for (Feedback feedback : feedbackList.get(i).keySet())
{
if (i == level)
{
assertTrue(feedback.isActive());
}
else
{
assertFalse(feedback.isActive());
}
}
}
}
@After
public void clearPipeline()
{
Pipeline.getInstance().clear();
}
}
| 8,444 | 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.