repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
difi/datahotel
src/test/java/no/difi/datahotel/resources/DatahotelExceptionMapperTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // } // // Path: src/main/java/no/difi/datahotel/util/Formater.java // public enum Formater { // // XML("xml", "text/xml", new XMLFormater()), // CSV("csv", "text/plain", new CSVFormater()), // CSVCORRECT(null, "text/csv", new CSVFormater()), // JSON("json", "application/json", new JSONFormater()), // JSONP("jsonp", "application/json", new JSONPFormater()), // YAML("yaml", "text/plain", new YAMLFormater()); // // private static Logger logger = Logger.getLogger(Formater.class.getSimpleName()); // // private String type; // private String mime; // private FormaterInterface cls; // // private Formater(String type, String mime, FormaterInterface cls) { // this.type = type; // this.mime = mime; // this.cls = cls; // } // // /** // * Gets a new dataformat based on a mime type. // * @param type Mime type (ie. json) // * @return Returns a new DataFormat enum. // */ // public static Formater get(String type) { // for (Formater t : Formater.values()) // if (type.equals(t.type)) // return t; // // throw new DatahotelException(404, "Format not found."); // } // // /** // * Gets the type of this DataFormat. // * @return Returns the type of this DataFormat. // */ // public String getType() { // return this.type; // } // // /** // * Gets the correct Mime type for this DataFormat. // * @return Returns the correct Mime type for this DataFormat. // */ // public String getMime() { // return this.mime + ";charset=UTF-8"; // } // // /** // * Formats an object if support for it has been implemented. // * @param object Object to format. // * @param context Context. // * @return Returns a string representation of the object supplied. // */ // public String format(Object object, RequestContext context) { // try // { // return cls.format(object, context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return formatError(e, context); // } // } // // /** // * Formats an object into an error. // * @param exception // * @param context // * @return // */ // public String formatError(Exception exception, RequestContext context) { // try // { // return cls.format(new SimpleError(exception.getMessage()), context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return "Error"; // } // } // }
import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.DatahotelException; import no.difi.datahotel.util.Formater; import org.junit.Assert; import org.junit.Test; import javax.ws.rs.core.Response;
package no.difi.datahotel.resources; public class DatahotelExceptionMapperTest extends BaseTest { private DatahotelExceptionMapper mapper = new DatahotelExceptionMapper(); @Test public void testNotModified() {
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // } // // Path: src/main/java/no/difi/datahotel/util/Formater.java // public enum Formater { // // XML("xml", "text/xml", new XMLFormater()), // CSV("csv", "text/plain", new CSVFormater()), // CSVCORRECT(null, "text/csv", new CSVFormater()), // JSON("json", "application/json", new JSONFormater()), // JSONP("jsonp", "application/json", new JSONPFormater()), // YAML("yaml", "text/plain", new YAMLFormater()); // // private static Logger logger = Logger.getLogger(Formater.class.getSimpleName()); // // private String type; // private String mime; // private FormaterInterface cls; // // private Formater(String type, String mime, FormaterInterface cls) { // this.type = type; // this.mime = mime; // this.cls = cls; // } // // /** // * Gets a new dataformat based on a mime type. // * @param type Mime type (ie. json) // * @return Returns a new DataFormat enum. // */ // public static Formater get(String type) { // for (Formater t : Formater.values()) // if (type.equals(t.type)) // return t; // // throw new DatahotelException(404, "Format not found."); // } // // /** // * Gets the type of this DataFormat. // * @return Returns the type of this DataFormat. // */ // public String getType() { // return this.type; // } // // /** // * Gets the correct Mime type for this DataFormat. // * @return Returns the correct Mime type for this DataFormat. // */ // public String getMime() { // return this.mime + ";charset=UTF-8"; // } // // /** // * Formats an object if support for it has been implemented. // * @param object Object to format. // * @param context Context. // * @return Returns a string representation of the object supplied. // */ // public String format(Object object, RequestContext context) { // try // { // return cls.format(object, context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return formatError(e, context); // } // } // // /** // * Formats an object into an error. // * @param exception // * @param context // * @return // */ // public String formatError(Exception exception, RequestContext context) { // try // { // return cls.format(new SimpleError(exception.getMessage()), context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return "Error"; // } // } // } // Path: src/test/java/no/difi/datahotel/resources/DatahotelExceptionMapperTest.java import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.DatahotelException; import no.difi.datahotel.util.Formater; import org.junit.Assert; import org.junit.Test; import javax.ws.rs.core.Response; package no.difi.datahotel.resources; public class DatahotelExceptionMapperTest extends BaseTest { private DatahotelExceptionMapper mapper = new DatahotelExceptionMapper(); @Test public void testNotModified() {
Response response = mapper.toResponse(new DatahotelException(304, "Not modified").setFormater(Formater.XML));
difi/datahotel
src/test/java/no/difi/datahotel/resources/DatahotelExceptionMapperTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // } // // Path: src/main/java/no/difi/datahotel/util/Formater.java // public enum Formater { // // XML("xml", "text/xml", new XMLFormater()), // CSV("csv", "text/plain", new CSVFormater()), // CSVCORRECT(null, "text/csv", new CSVFormater()), // JSON("json", "application/json", new JSONFormater()), // JSONP("jsonp", "application/json", new JSONPFormater()), // YAML("yaml", "text/plain", new YAMLFormater()); // // private static Logger logger = Logger.getLogger(Formater.class.getSimpleName()); // // private String type; // private String mime; // private FormaterInterface cls; // // private Formater(String type, String mime, FormaterInterface cls) { // this.type = type; // this.mime = mime; // this.cls = cls; // } // // /** // * Gets a new dataformat based on a mime type. // * @param type Mime type (ie. json) // * @return Returns a new DataFormat enum. // */ // public static Formater get(String type) { // for (Formater t : Formater.values()) // if (type.equals(t.type)) // return t; // // throw new DatahotelException(404, "Format not found."); // } // // /** // * Gets the type of this DataFormat. // * @return Returns the type of this DataFormat. // */ // public String getType() { // return this.type; // } // // /** // * Gets the correct Mime type for this DataFormat. // * @return Returns the correct Mime type for this DataFormat. // */ // public String getMime() { // return this.mime + ";charset=UTF-8"; // } // // /** // * Formats an object if support for it has been implemented. // * @param object Object to format. // * @param context Context. // * @return Returns a string representation of the object supplied. // */ // public String format(Object object, RequestContext context) { // try // { // return cls.format(object, context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return formatError(e, context); // } // } // // /** // * Formats an object into an error. // * @param exception // * @param context // * @return // */ // public String formatError(Exception exception, RequestContext context) { // try // { // return cls.format(new SimpleError(exception.getMessage()), context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return "Error"; // } // } // }
import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.DatahotelException; import no.difi.datahotel.util.Formater; import org.junit.Assert; import org.junit.Test; import javax.ws.rs.core.Response;
package no.difi.datahotel.resources; public class DatahotelExceptionMapperTest extends BaseTest { private DatahotelExceptionMapper mapper = new DatahotelExceptionMapper(); @Test public void testNotModified() {
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // } // // Path: src/main/java/no/difi/datahotel/util/Formater.java // public enum Formater { // // XML("xml", "text/xml", new XMLFormater()), // CSV("csv", "text/plain", new CSVFormater()), // CSVCORRECT(null, "text/csv", new CSVFormater()), // JSON("json", "application/json", new JSONFormater()), // JSONP("jsonp", "application/json", new JSONPFormater()), // YAML("yaml", "text/plain", new YAMLFormater()); // // private static Logger logger = Logger.getLogger(Formater.class.getSimpleName()); // // private String type; // private String mime; // private FormaterInterface cls; // // private Formater(String type, String mime, FormaterInterface cls) { // this.type = type; // this.mime = mime; // this.cls = cls; // } // // /** // * Gets a new dataformat based on a mime type. // * @param type Mime type (ie. json) // * @return Returns a new DataFormat enum. // */ // public static Formater get(String type) { // for (Formater t : Formater.values()) // if (type.equals(t.type)) // return t; // // throw new DatahotelException(404, "Format not found."); // } // // /** // * Gets the type of this DataFormat. // * @return Returns the type of this DataFormat. // */ // public String getType() { // return this.type; // } // // /** // * Gets the correct Mime type for this DataFormat. // * @return Returns the correct Mime type for this DataFormat. // */ // public String getMime() { // return this.mime + ";charset=UTF-8"; // } // // /** // * Formats an object if support for it has been implemented. // * @param object Object to format. // * @param context Context. // * @return Returns a string representation of the object supplied. // */ // public String format(Object object, RequestContext context) { // try // { // return cls.format(object, context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return formatError(e, context); // } // } // // /** // * Formats an object into an error. // * @param exception // * @param context // * @return // */ // public String formatError(Exception exception, RequestContext context) { // try // { // return cls.format(new SimpleError(exception.getMessage()), context); // } catch (Exception e) // { // logger.log(Level.WARNING, e.getMessage() + " - Format: " + type + " - " + e.getClass().getSimpleName() + " - " + e.getStackTrace()[0].toString()); // return "Error"; // } // } // } // Path: src/test/java/no/difi/datahotel/resources/DatahotelExceptionMapperTest.java import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.DatahotelException; import no.difi.datahotel.util.Formater; import org.junit.Assert; import org.junit.Test; import javax.ws.rs.core.Response; package no.difi.datahotel.resources; public class DatahotelExceptionMapperTest extends BaseTest { private DatahotelExceptionMapper mapper = new DatahotelExceptionMapper(); @Test public void testNotModified() {
Response response = mapper.toResponse(new DatahotelException(304, "Not modified").setFormater(Formater.XML));
difi/datahotel
src/test/java/no/difi/datahotel/util/formater/CSVFormaterTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Result.java // public class Result implements Serializable { // // private static final long serialVersionUID = -8412531397903068046L; // private List<Map<String, String>> entries; // private Long page = 0L, pages = 0L, posts = 0L; // // public Result() { // this.setEntries(new ArrayList<Map<String, String>>()); // } // // /** // * Creates a new CSVData object with the specified list of hashmaps. // * // * @param entries // * A list of hashmaps. Each entry in the arraylist must be a line // * in the CSV File, each entry in the hashmap must be column // * header and respective value. // */ // public Result(List<Map<String, String>> entries) { // this.setEntries(entries); // } // // /** // * Sets the CSV data. // * // * @param entries // * CSV data. // */ // public void setEntries(List<Map<String, String>> entries) { // this.entries = entries != null ? entries : new ArrayList<Map<String, String>>(); // } // // /** // * Gets the CSV data. // * // * @return Returns the CSV data. // */ // public List<Map<String, String>> getEntries() { // return entries; // } // // public Long getPosts() { // return posts; // } // // public void setPosts(long posts) { // this.posts = posts; // this.pages = ((posts - (posts % 100)) / 100) + (posts % 100 == 0 ? 0 : 1); // } // // public Long getPages() { // return pages; // } // // public Long getPage() { // return page; // } // // public void setPage(long page) { // this.page = page; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/CSVFormater.java // public class CSVFormater implements FormaterInterface { // // public String format(Object object, RequestContext context) throws Exception { // if (object instanceof Result) { // List<Map<String, String>> data = ((Result) object).getEntries(); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // CSVWriter writer = new CSVWriter(baos); // // writer.writeHeader(data.get(0).keySet().toArray(new String[0])); // for (Map<String, String> row : data) // writer.write(row.values().toArray(new String[0])); // // writer.close(); // // return baos.toString("UTF-8"); // } // // throw new Exception("Unable to parse content."); // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Result; import no.difi.datahotel.util.formater.CSVFormater; import static org.junit.Assert.*; import org.junit.Test;
package no.difi.datahotel.util.formater; public class CSVFormaterTest extends BaseTest { @Test public void testCSVData() throws Exception { ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> element; element = new HashMap<String, String>(); element.put("id", "1"); element.put("name", "Ole"); data.add(element); element = new HashMap<String, String>(); element.put("id", "2"); element.put("name", "Per"); data.add(element);
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Result.java // public class Result implements Serializable { // // private static final long serialVersionUID = -8412531397903068046L; // private List<Map<String, String>> entries; // private Long page = 0L, pages = 0L, posts = 0L; // // public Result() { // this.setEntries(new ArrayList<Map<String, String>>()); // } // // /** // * Creates a new CSVData object with the specified list of hashmaps. // * // * @param entries // * A list of hashmaps. Each entry in the arraylist must be a line // * in the CSV File, each entry in the hashmap must be column // * header and respective value. // */ // public Result(List<Map<String, String>> entries) { // this.setEntries(entries); // } // // /** // * Sets the CSV data. // * // * @param entries // * CSV data. // */ // public void setEntries(List<Map<String, String>> entries) { // this.entries = entries != null ? entries : new ArrayList<Map<String, String>>(); // } // // /** // * Gets the CSV data. // * // * @return Returns the CSV data. // */ // public List<Map<String, String>> getEntries() { // return entries; // } // // public Long getPosts() { // return posts; // } // // public void setPosts(long posts) { // this.posts = posts; // this.pages = ((posts - (posts % 100)) / 100) + (posts % 100 == 0 ? 0 : 1); // } // // public Long getPages() { // return pages; // } // // public Long getPage() { // return page; // } // // public void setPage(long page) { // this.page = page; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/CSVFormater.java // public class CSVFormater implements FormaterInterface { // // public String format(Object object, RequestContext context) throws Exception { // if (object instanceof Result) { // List<Map<String, String>> data = ((Result) object).getEntries(); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // CSVWriter writer = new CSVWriter(baos); // // writer.writeHeader(data.get(0).keySet().toArray(new String[0])); // for (Map<String, String> row : data) // writer.write(row.values().toArray(new String[0])); // // writer.close(); // // return baos.toString("UTF-8"); // } // // throw new Exception("Unable to parse content."); // } // } // Path: src/test/java/no/difi/datahotel/util/formater/CSVFormaterTest.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Result; import no.difi.datahotel.util.formater.CSVFormater; import static org.junit.Assert.*; import org.junit.Test; package no.difi.datahotel.util.formater; public class CSVFormaterTest extends BaseTest { @Test public void testCSVData() throws Exception { ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> element; element = new HashMap<String, String>(); element.put("id", "1"); element.put("name", "Ole"); data.add(element); element = new HashMap<String, String>(); element.put("id", "2"); element.put("name", "Per"); data.add(element);
CSVFormater parser = new CSVFormater();
difi/datahotel
src/test/java/no/difi/datahotel/util/formater/CSVFormaterTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Result.java // public class Result implements Serializable { // // private static final long serialVersionUID = -8412531397903068046L; // private List<Map<String, String>> entries; // private Long page = 0L, pages = 0L, posts = 0L; // // public Result() { // this.setEntries(new ArrayList<Map<String, String>>()); // } // // /** // * Creates a new CSVData object with the specified list of hashmaps. // * // * @param entries // * A list of hashmaps. Each entry in the arraylist must be a line // * in the CSV File, each entry in the hashmap must be column // * header and respective value. // */ // public Result(List<Map<String, String>> entries) { // this.setEntries(entries); // } // // /** // * Sets the CSV data. // * // * @param entries // * CSV data. // */ // public void setEntries(List<Map<String, String>> entries) { // this.entries = entries != null ? entries : new ArrayList<Map<String, String>>(); // } // // /** // * Gets the CSV data. // * // * @return Returns the CSV data. // */ // public List<Map<String, String>> getEntries() { // return entries; // } // // public Long getPosts() { // return posts; // } // // public void setPosts(long posts) { // this.posts = posts; // this.pages = ((posts - (posts % 100)) / 100) + (posts % 100 == 0 ? 0 : 1); // } // // public Long getPages() { // return pages; // } // // public Long getPage() { // return page; // } // // public void setPage(long page) { // this.page = page; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/CSVFormater.java // public class CSVFormater implements FormaterInterface { // // public String format(Object object, RequestContext context) throws Exception { // if (object instanceof Result) { // List<Map<String, String>> data = ((Result) object).getEntries(); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // CSVWriter writer = new CSVWriter(baos); // // writer.writeHeader(data.get(0).keySet().toArray(new String[0])); // for (Map<String, String> row : data) // writer.write(row.values().toArray(new String[0])); // // writer.close(); // // return baos.toString("UTF-8"); // } // // throw new Exception("Unable to parse content."); // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Result; import no.difi.datahotel.util.formater.CSVFormater; import static org.junit.Assert.*; import org.junit.Test;
package no.difi.datahotel.util.formater; public class CSVFormaterTest extends BaseTest { @Test public void testCSVData() throws Exception { ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> element; element = new HashMap<String, String>(); element.put("id", "1"); element.put("name", "Ole"); data.add(element); element = new HashMap<String, String>(); element.put("id", "2"); element.put("name", "Per"); data.add(element); CSVFormater parser = new CSVFormater();
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Result.java // public class Result implements Serializable { // // private static final long serialVersionUID = -8412531397903068046L; // private List<Map<String, String>> entries; // private Long page = 0L, pages = 0L, posts = 0L; // // public Result() { // this.setEntries(new ArrayList<Map<String, String>>()); // } // // /** // * Creates a new CSVData object with the specified list of hashmaps. // * // * @param entries // * A list of hashmaps. Each entry in the arraylist must be a line // * in the CSV File, each entry in the hashmap must be column // * header and respective value. // */ // public Result(List<Map<String, String>> entries) { // this.setEntries(entries); // } // // /** // * Sets the CSV data. // * // * @param entries // * CSV data. // */ // public void setEntries(List<Map<String, String>> entries) { // this.entries = entries != null ? entries : new ArrayList<Map<String, String>>(); // } // // /** // * Gets the CSV data. // * // * @return Returns the CSV data. // */ // public List<Map<String, String>> getEntries() { // return entries; // } // // public Long getPosts() { // return posts; // } // // public void setPosts(long posts) { // this.posts = posts; // this.pages = ((posts - (posts % 100)) / 100) + (posts % 100 == 0 ? 0 : 1); // } // // public Long getPages() { // return pages; // } // // public Long getPage() { // return page; // } // // public void setPage(long page) { // this.page = page; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/CSVFormater.java // public class CSVFormater implements FormaterInterface { // // public String format(Object object, RequestContext context) throws Exception { // if (object instanceof Result) { // List<Map<String, String>> data = ((Result) object).getEntries(); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // CSVWriter writer = new CSVWriter(baos); // // writer.writeHeader(data.get(0).keySet().toArray(new String[0])); // for (Map<String, String> row : data) // writer.write(row.values().toArray(new String[0])); // // writer.close(); // // return baos.toString("UTF-8"); // } // // throw new Exception("Unable to parse content."); // } // } // Path: src/test/java/no/difi/datahotel/util/formater/CSVFormaterTest.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Result; import no.difi.datahotel.util.formater.CSVFormater; import static org.junit.Assert.*; import org.junit.Test; package no.difi.datahotel.util.formater; public class CSVFormaterTest extends BaseTest { @Test public void testCSVData() throws Exception { ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> element; element = new HashMap<String, String>(); element.put("id", "1"); element.put("name", "Ole"); data.add(element); element = new HashMap<String, String>(); element.put("id", "2"); element.put("name", "Per"); data.add(element); CSVFormater parser = new CSVFormater();
String result = parser.format(new Result(data), null);
difi/datahotel
src/test/java/no/difi/datahotel/BaseTest.java
// Path: src/test/java/no/difi/datahotel/logic/ChunkBeanTest.java // public class ChunkBeanTest extends BaseTest { // // private ChunkBean chunkBean; // // static MetadataLogger logger; // static Metadata metadata; // // @Before // public void before() throws Exception { // chunkBean = new ChunkBean(); // logger = Mockito.mock(MetadataLogger.class); // // metadata = new Metadata(); // metadata.setUpdated(System.currentTimeMillis()); // metadata.setLogger(logger); // } // // @Test // public void testUpdate() { // metadata.setLocation("difi/test/simple"); // metadata.setShortName("simple"); // // chunkBean.update(metadata); // // assertTrue(Filesystem.getFile(FOLDER_CACHE_CHUNK, "difi", "test", "simple", "dataset-1.csv").exists()); // assertTrue(Filesystem.getFile(FOLDER_CACHE_CHUNK, "difi", "test", "simple", "dataset-2.csv").exists()); // } // // @Test // public void testUpdateError() { // metadata.setLocation("difi/test/simple-not-here"); // metadata.setShortName("simple-not-here"); // // chunkBean.update(metadata); // // // TODO Fikse verifisert bruk av logger // // Mockito.verify(logger).log(Level.WARNING, null); // } // // @Test // public void testGet() throws Exception { // metadata.setLocation("difi/test/simple"); // metadata.setShortName("simple"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(19, chunkBean.get(metadata, 2).getEntries().size()); // // assertEquals(0, chunkBean.get(metadata, 3).getEntries().size()); // // metadata.setLocation("difi/test/simple2"); // assertEquals(0, chunkBean.get(metadata, 1).getEntries().size()); // // // Thread.sleep(1000); // // // chunkEJB.delete("difi", "test", "simple2"); // } // // @Test // public void testOneHundred() throws Exception { // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(0, chunkBean.get(metadata, 2).getEntries().size()); // // assertEquals(new Long(100), chunkBean.get(metadata, 1).getPosts()); // // metadata.setLocation("difi/test/hundred200"); // assertEquals(new Long(0), chunkBean.get(metadata, 1).getPosts()); // // // Thread.sleep(1000); // // // chunkEJB.delete("difi", "test", "hundred"); // // assertFalse(Filesystem.getFolderPathF("chunk", "difi", "test", // // "hundred").exists()); // } // // @Test // public void testNoNeed() throws Exception { // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(0, chunkBean.get(metadata, 2).getEntries().size()); // long ts = Filesystem.getFile(FOLDER_CACHE_CHUNK, metadata.getLocation(), "timestamp").lastModified(); // // Thread.sleep(1000); // // chunkBean.update(metadata); // long ts2 = Filesystem.getFile(FOLDER_CACHE_CHUNK, metadata.getLocation(), "timestamp").lastModified(); // assertEquals(ts, ts2); // // // chunkEJB.delete("difi", "test", "hundred"); // // assertFalse(Filesystem.getFolderPathF("chunk", "difi", "test", // // "hundred").exists()); // } // // @Test // public void testReplaceGoal() throws Exception { // File folder = Filesystem.getFolder(Filesystem.FOLDER_CACHE_CHUNK, "difi/test/hundred", "secret"); // assertTrue(folder.exists()); // // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertFalse(folder.exists()); // } // }
import no.difi.datahotel.logic.ChunkBeanTest; import org.junit.BeforeClass; import java.io.File;
package no.difi.datahotel; public class BaseTest { @BeforeClass public static void beforeClass() throws Exception {
// Path: src/test/java/no/difi/datahotel/logic/ChunkBeanTest.java // public class ChunkBeanTest extends BaseTest { // // private ChunkBean chunkBean; // // static MetadataLogger logger; // static Metadata metadata; // // @Before // public void before() throws Exception { // chunkBean = new ChunkBean(); // logger = Mockito.mock(MetadataLogger.class); // // metadata = new Metadata(); // metadata.setUpdated(System.currentTimeMillis()); // metadata.setLogger(logger); // } // // @Test // public void testUpdate() { // metadata.setLocation("difi/test/simple"); // metadata.setShortName("simple"); // // chunkBean.update(metadata); // // assertTrue(Filesystem.getFile(FOLDER_CACHE_CHUNK, "difi", "test", "simple", "dataset-1.csv").exists()); // assertTrue(Filesystem.getFile(FOLDER_CACHE_CHUNK, "difi", "test", "simple", "dataset-2.csv").exists()); // } // // @Test // public void testUpdateError() { // metadata.setLocation("difi/test/simple-not-here"); // metadata.setShortName("simple-not-here"); // // chunkBean.update(metadata); // // // TODO Fikse verifisert bruk av logger // // Mockito.verify(logger).log(Level.WARNING, null); // } // // @Test // public void testGet() throws Exception { // metadata.setLocation("difi/test/simple"); // metadata.setShortName("simple"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(19, chunkBean.get(metadata, 2).getEntries().size()); // // assertEquals(0, chunkBean.get(metadata, 3).getEntries().size()); // // metadata.setLocation("difi/test/simple2"); // assertEquals(0, chunkBean.get(metadata, 1).getEntries().size()); // // // Thread.sleep(1000); // // // chunkEJB.delete("difi", "test", "simple2"); // } // // @Test // public void testOneHundred() throws Exception { // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(0, chunkBean.get(metadata, 2).getEntries().size()); // // assertEquals(new Long(100), chunkBean.get(metadata, 1).getPosts()); // // metadata.setLocation("difi/test/hundred200"); // assertEquals(new Long(0), chunkBean.get(metadata, 1).getPosts()); // // // Thread.sleep(1000); // // // chunkEJB.delete("difi", "test", "hundred"); // // assertFalse(Filesystem.getFolderPathF("chunk", "difi", "test", // // "hundred").exists()); // } // // @Test // public void testNoNeed() throws Exception { // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertEquals(100, chunkBean.get(metadata, 1).getEntries().size()); // assertEquals(0, chunkBean.get(metadata, 2).getEntries().size()); // long ts = Filesystem.getFile(FOLDER_CACHE_CHUNK, metadata.getLocation(), "timestamp").lastModified(); // // Thread.sleep(1000); // // chunkBean.update(metadata); // long ts2 = Filesystem.getFile(FOLDER_CACHE_CHUNK, metadata.getLocation(), "timestamp").lastModified(); // assertEquals(ts, ts2); // // // chunkEJB.delete("difi", "test", "hundred"); // // assertFalse(Filesystem.getFolderPathF("chunk", "difi", "test", // // "hundred").exists()); // } // // @Test // public void testReplaceGoal() throws Exception { // File folder = Filesystem.getFolder(Filesystem.FOLDER_CACHE_CHUNK, "difi/test/hundred", "secret"); // assertTrue(folder.exists()); // // metadata.setLocation("difi/test/hundred"); // metadata.setShortName("hundred"); // // chunkBean.update(metadata); // // assertFalse(folder.exists()); // } // } // Path: src/test/java/no/difi/datahotel/BaseTest.java import no.difi.datahotel.logic.ChunkBeanTest; import org.junit.BeforeClass; import java.io.File; package no.difi.datahotel; public class BaseTest { @BeforeClass public static void beforeClass() throws Exception {
System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel");
difi/datahotel
src/main/java/no/difi/datahotel/util/MetadataLogger.java
// Path: src/main/java/no/difi/datahotel/model/Metadata.java // @XmlRootElement // public class Metadata implements Comparable<Metadata>, Light<MetadataLight> { // // private String location = ""; // private List<Metadata> children = new ArrayList<Metadata>(); // private boolean active = true; // private boolean dataset = false; // private Metadata parent; // private MetadataLogger logger = new MetadataLogger(this); // private Long version; // // // Values for users // private String shortName; // private String name; // private String description; // private String url; // private Long updated; // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Long getUpdated() { // return updated; // } // // public void setUpdated(Long updated) { // this.updated = updated; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // @XmlTransient // public List<Metadata> getChildren() { // return children; // } // // public void addChild(Metadata child) { // this.children.add(child); // child.parent = this; // // if (child.isActive() && child.updated != null) // if (this.updated == null || this.updated < child.updated) // this.updated = child.updated; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // // public boolean isDataset() { // return dataset; // } // // public void setDataset(boolean dataset) { // this.dataset = dataset; // } // // @XmlTransient // public MetadataLogger getLogger() { // return logger; // } // // public void setLogger(MetadataLogger logger) { // this.logger = logger; // } // // @XmlTransient // public Metadata getParent() { // return parent; // } // // public void setParent(Metadata parent) { // this.parent = parent; // } // // public Long getVersion() { // return version; // } // // public void setVersion(Long version) { // this.version = version; // } // // public MetadataLight light() { // return new MetadataLight(this); // } // // public void save() throws Exception { // Disk.save(Filesystem.getFile(Filesystem.FOLDER_SLAVE, location, Filesystem.FILE_METADATA), this); // } // // public static Metadata read(String location) { // File folder = Filesystem.getFolder(FOLDER_SLAVE, location); // Metadata metadata = (Metadata) Disk.read(Metadata.class, Filesystem.getFile(folder, FILE_METADATA)); // metadata.setLocation(location); // metadata.setShortName(folder.getName()); // metadata.setDataset(Filesystem.getFile(folder, FILE_DATASET).exists()); // // return metadata; // } // // public static String getLocation(String... dir) { // String location = dir[0]; // for (int i = 1; i < dir.length; i++) // location += "/" + dir[i]; // return location; // } // // @Override // public int compareTo(Metadata other) { // return String.valueOf(name).compareTo(String.valueOf(other.name)); // } // }
import no.difi.datahotel.model.Metadata; import java.util.logging.Level; import java.util.logging.Logger;
package no.difi.datahotel.util; public class MetadataLogger { private static Logger logger = Logger.getLogger(MetadataLogger.class.getSimpleName());
// Path: src/main/java/no/difi/datahotel/model/Metadata.java // @XmlRootElement // public class Metadata implements Comparable<Metadata>, Light<MetadataLight> { // // private String location = ""; // private List<Metadata> children = new ArrayList<Metadata>(); // private boolean active = true; // private boolean dataset = false; // private Metadata parent; // private MetadataLogger logger = new MetadataLogger(this); // private Long version; // // // Values for users // private String shortName; // private String name; // private String description; // private String url; // private Long updated; // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public Long getUpdated() { // return updated; // } // // public void setUpdated(Long updated) { // this.updated = updated; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // @XmlTransient // public List<Metadata> getChildren() { // return children; // } // // public void addChild(Metadata child) { // this.children.add(child); // child.parent = this; // // if (child.isActive() && child.updated != null) // if (this.updated == null || this.updated < child.updated) // this.updated = child.updated; // } // // public boolean isActive() { // return active; // } // // public void setActive(boolean active) { // this.active = active; // } // // public boolean isDataset() { // return dataset; // } // // public void setDataset(boolean dataset) { // this.dataset = dataset; // } // // @XmlTransient // public MetadataLogger getLogger() { // return logger; // } // // public void setLogger(MetadataLogger logger) { // this.logger = logger; // } // // @XmlTransient // public Metadata getParent() { // return parent; // } // // public void setParent(Metadata parent) { // this.parent = parent; // } // // public Long getVersion() { // return version; // } // // public void setVersion(Long version) { // this.version = version; // } // // public MetadataLight light() { // return new MetadataLight(this); // } // // public void save() throws Exception { // Disk.save(Filesystem.getFile(Filesystem.FOLDER_SLAVE, location, Filesystem.FILE_METADATA), this); // } // // public static Metadata read(String location) { // File folder = Filesystem.getFolder(FOLDER_SLAVE, location); // Metadata metadata = (Metadata) Disk.read(Metadata.class, Filesystem.getFile(folder, FILE_METADATA)); // metadata.setLocation(location); // metadata.setShortName(folder.getName()); // metadata.setDataset(Filesystem.getFile(folder, FILE_DATASET).exists()); // // return metadata; // } // // public static String getLocation(String... dir) { // String location = dir[0]; // for (int i = 1; i < dir.length; i++) // location += "/" + dir[i]; // return location; // } // // @Override // public int compareTo(Metadata other) { // return String.valueOf(name).compareTo(String.valueOf(other.name)); // } // } // Path: src/main/java/no/difi/datahotel/util/MetadataLogger.java import no.difi.datahotel.model.Metadata; import java.util.logging.Level; import java.util.logging.Logger; package no.difi.datahotel.util; public class MetadataLogger { private static Logger logger = Logger.getLogger(MetadataLogger.class.getSimpleName());
private Metadata metadata;
difi/datahotel
src/test/java/no/difi/datahotel/model/DefinitionTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Definition.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.NONE) // public class Definition implements Comparable<Definition>, Light<DefinitionLight> { // @XmlElement // private String name; // // @XmlElement // private String shortName; // // @XmlElement // private String description; // // private List<Field> fields = new ArrayList<Field>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = "".equals(description) ? null : description; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getShortName() { // return shortName; // } // // public List<Field> getFields() { // return fields; // } // // public void addField(Field field) { // fields.add(field); // field.setDefinition(this); // } // // public void removeField(Field field) { // fields.remove(field); // } // // public DefinitionLight light() { // return new DefinitionLight(this); // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof Definition)) // return false; // // return String.valueOf(shortName).compareTo(String.valueOf(((Definition) o).shortName)) == 0; // } // // @Override // public int compareTo(Definition other) { // return name.compareTo(other.name); // } // } // // Path: src/main/java/no/difi/datahotel/model/DefinitionLight.java // @XmlRootElement // public class DefinitionLight implements Comparable<DefinitionLight> { // // private String name; // private String shortName; // private String description; // // public DefinitionLight(Definition definition) { // name = definition.getName(); // shortName = definition.getShortName(); // description = definition.getDescription(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int compareTo(DefinitionLight other) { // return name.compareTo(other.name); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Definition; import no.difi.datahotel.model.DefinitionLight; import org.junit.Test;
package no.difi.datahotel.model; public class DefinitionTest extends BaseTest { @Test public void testSetGet() throws Exception {
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Definition.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.NONE) // public class Definition implements Comparable<Definition>, Light<DefinitionLight> { // @XmlElement // private String name; // // @XmlElement // private String shortName; // // @XmlElement // private String description; // // private List<Field> fields = new ArrayList<Field>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = "".equals(description) ? null : description; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getShortName() { // return shortName; // } // // public List<Field> getFields() { // return fields; // } // // public void addField(Field field) { // fields.add(field); // field.setDefinition(this); // } // // public void removeField(Field field) { // fields.remove(field); // } // // public DefinitionLight light() { // return new DefinitionLight(this); // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof Definition)) // return false; // // return String.valueOf(shortName).compareTo(String.valueOf(((Definition) o).shortName)) == 0; // } // // @Override // public int compareTo(Definition other) { // return name.compareTo(other.name); // } // } // // Path: src/main/java/no/difi/datahotel/model/DefinitionLight.java // @XmlRootElement // public class DefinitionLight implements Comparable<DefinitionLight> { // // private String name; // private String shortName; // private String description; // // public DefinitionLight(Definition definition) { // name = definition.getName(); // shortName = definition.getShortName(); // description = definition.getDescription(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int compareTo(DefinitionLight other) { // return name.compareTo(other.name); // } // } // Path: src/test/java/no/difi/datahotel/model/DefinitionTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Definition; import no.difi.datahotel.model.DefinitionLight; import org.junit.Test; package no.difi.datahotel.model; public class DefinitionTest extends BaseTest { @Test public void testSetGet() throws Exception {
Definition d = new Definition();
difi/datahotel
src/test/java/no/difi/datahotel/model/DefinitionTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Definition.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.NONE) // public class Definition implements Comparable<Definition>, Light<DefinitionLight> { // @XmlElement // private String name; // // @XmlElement // private String shortName; // // @XmlElement // private String description; // // private List<Field> fields = new ArrayList<Field>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = "".equals(description) ? null : description; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getShortName() { // return shortName; // } // // public List<Field> getFields() { // return fields; // } // // public void addField(Field field) { // fields.add(field); // field.setDefinition(this); // } // // public void removeField(Field field) { // fields.remove(field); // } // // public DefinitionLight light() { // return new DefinitionLight(this); // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof Definition)) // return false; // // return String.valueOf(shortName).compareTo(String.valueOf(((Definition) o).shortName)) == 0; // } // // @Override // public int compareTo(Definition other) { // return name.compareTo(other.name); // } // } // // Path: src/main/java/no/difi/datahotel/model/DefinitionLight.java // @XmlRootElement // public class DefinitionLight implements Comparable<DefinitionLight> { // // private String name; // private String shortName; // private String description; // // public DefinitionLight(Definition definition) { // name = definition.getName(); // shortName = definition.getShortName(); // description = definition.getDescription(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int compareTo(DefinitionLight other) { // return name.compareTo(other.name); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Definition; import no.difi.datahotel.model.DefinitionLight; import org.junit.Test;
package no.difi.datahotel.model; public class DefinitionTest extends BaseTest { @Test public void testSetGet() throws Exception { Definition d = new Definition(); assertNull(d.getName()); assertNull(d.getShortName()); assertNull(d.getDescription()); d.setName("Organisasjonsnummer"); d.setShortName("orgnr"); d.setDescription("Identifikator i brreg."); assertEquals("Organisasjonsnummer", d.getName()); assertEquals("orgnr", d.getShortName()); assertEquals("Identifikator i brreg.", d.getDescription());
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/model/Definition.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.NONE) // public class Definition implements Comparable<Definition>, Light<DefinitionLight> { // @XmlElement // private String name; // // @XmlElement // private String shortName; // // @XmlElement // private String description; // // private List<Field> fields = new ArrayList<Field>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = "".equals(description) ? null : description; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getShortName() { // return shortName; // } // // public List<Field> getFields() { // return fields; // } // // public void addField(Field field) { // fields.add(field); // field.setDefinition(this); // } // // public void removeField(Field field) { // fields.remove(field); // } // // public DefinitionLight light() { // return new DefinitionLight(this); // } // // @Override // public boolean equals(Object o) { // if (o == null || !(o instanceof Definition)) // return false; // // return String.valueOf(shortName).compareTo(String.valueOf(((Definition) o).shortName)) == 0; // } // // @Override // public int compareTo(Definition other) { // return name.compareTo(other.name); // } // } // // Path: src/main/java/no/difi/datahotel/model/DefinitionLight.java // @XmlRootElement // public class DefinitionLight implements Comparable<DefinitionLight> { // // private String name; // private String shortName; // private String description; // // public DefinitionLight(Definition definition) { // name = definition.getName(); // shortName = definition.getShortName(); // description = definition.getDescription(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public int compareTo(DefinitionLight other) { // return name.compareTo(other.name); // } // } // Path: src/test/java/no/difi/datahotel/model/DefinitionTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import no.difi.datahotel.BaseTest; import no.difi.datahotel.model.Definition; import no.difi.datahotel.model.DefinitionLight; import org.junit.Test; package no.difi.datahotel.model; public class DefinitionTest extends BaseTest { @Test public void testSetGet() throws Exception { Definition d = new Definition(); assertNull(d.getName()); assertNull(d.getShortName()); assertNull(d.getDescription()); d.setName("Organisasjonsnummer"); d.setShortName("orgnr"); d.setDescription("Identifikator i brreg."); assertEquals("Organisasjonsnummer", d.getName()); assertEquals("orgnr", d.getShortName()); assertEquals("Identifikator i brreg.", d.getDescription());
DefinitionLight dl = d.light();
difi/datahotel
src/main/java/no/difi/datahotel/util/RequestContext.java
// Path: src/main/java/no/difi/datahotel/model/FieldLight.java // @XmlRootElement // public class FieldLight { // // private String name; // private String shortName; // private boolean groupable; // private boolean searchable; // private boolean indexPrimaryKey; // private String description; // private String definition; // // public FieldLight(Field field) { // name = field.getName(); // shortName = field.getShortName(); // groupable = field.getGroupable(); // searchable = field.getSearchable(); // indexPrimaryKey = field.getIndexPrimaryKey(); // description = field.getContent(); // definition = field.getDefShort(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public boolean getGroupable() { // return groupable; // } // // public void setGroupable(boolean groupable) { // this.groupable = groupable; // } // // public boolean getSearchable() { // return searchable; // } // // public void setSearchable(boolean searchable) { // this.searchable = searchable; // } // // public boolean getIndexPrimaryKey() { // return indexPrimaryKey; // } // // public void setIndexPrimaryKey(boolean indexPrimaryKey) { // this.indexPrimaryKey = indexPrimaryKey; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDefinition() { // return definition; // } // // public void setDefinition(String definition) { // this.definition = definition; // } // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import no.difi.datahotel.model.FieldLight;
package no.difi.datahotel.util; public class RequestContext { private int page = 1; private String query = null; private Map<String, String> lookup = new HashMap<String, String>(); private String callback; public RequestContext() { } public RequestContext(UriInfo uriInfo) { this(uriInfo, null); }
// Path: src/main/java/no/difi/datahotel/model/FieldLight.java // @XmlRootElement // public class FieldLight { // // private String name; // private String shortName; // private boolean groupable; // private boolean searchable; // private boolean indexPrimaryKey; // private String description; // private String definition; // // public FieldLight(Field field) { // name = field.getName(); // shortName = field.getShortName(); // groupable = field.getGroupable(); // searchable = field.getSearchable(); // indexPrimaryKey = field.getIndexPrimaryKey(); // description = field.getContent(); // definition = field.getDefShort(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShortName() { // return shortName; // } // // public void setShortName(String shortName) { // this.shortName = shortName; // } // // public boolean getGroupable() { // return groupable; // } // // public void setGroupable(boolean groupable) { // this.groupable = groupable; // } // // public boolean getSearchable() { // return searchable; // } // // public void setSearchable(boolean searchable) { // this.searchable = searchable; // } // // public boolean getIndexPrimaryKey() { // return indexPrimaryKey; // } // // public void setIndexPrimaryKey(boolean indexPrimaryKey) { // this.indexPrimaryKey = indexPrimaryKey; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getDefinition() { // return definition; // } // // public void setDefinition(String definition) { // this.definition = definition; // } // // } // Path: src/main/java/no/difi/datahotel/util/RequestContext.java import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import no.difi.datahotel.model.FieldLight; package no.difi.datahotel.util; public class RequestContext { private int page = 1; private String query = null; private Map<String, String> lookup = new HashMap<String, String>(); private String callback; public RequestContext() { } public RequestContext(UriInfo uriInfo) { this(uriInfo, null); }
public RequestContext(UriInfo uriInfo, List<FieldLight> fields) {
difi/datahotel
src/test/java/no/difi/datahotel/logic/MetadataBeanTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/Filesystem.java // public class Filesystem { // // private static final String HOME = "datahotel"; // // public static final String FOLDER_MASTER = "master"; // public static final String FOLDER_MASTER_DEFINITION = FOLDER_MASTER + File.separator + "definition"; // public static final String FOLDER_SLAVE = "slave"; // public static final String FOLDER_CACHE = "cache"; // public static final String FOLDER_CACHE_CHUNK = FOLDER_CACHE + File.separator + "chunk"; // public static final String FOLDER_CACHE_INDEX = FOLDER_CACHE + File.separator + "index"; // // public static final String FILE_DATASET = "dataset.csv"; // public static final String FILE_DATASET_ORIGINAL = "original.csv"; // public static final String FILE_FIELDS = "fields.xml"; // public static final String FILE_DEFINITIONS = "definitions.xml"; // public static final String FILE_METADATA = "meta.xml"; // public static final String FILE_VERSION = "version.xml"; // // private static String home; // // public static String getHome() { // if (home != null) // return home; // // String dir; // // try { // Context initCtx = new InitialContext(); // Context envCtx = (Context) initCtx.lookup("java:comp/env"); // // dir = envCtx.lookup("datahotel.home") + File.separator; // } catch (NamingException e) { // if (System.getProperty("datahotel.home") != null) // dir = System.getProperty("datahotel.home") + File.separator; // else // dir = System.getProperty("user.home") + File.separator + HOME + File.separator; // } // // dir = dir.replace(File.separator + File.separator, File.separator); // new File(dir).mkdirs(); // // home = dir; // return dir; // } // // public static File getFolderPath(String... folder) { // String dir = getHome(); // for (String f : folder) // if (!"".equals(f)) // dir += f.replace("/", File.separator) + File.separator; // return new File(dir); // } // // public static File getFolder(String... folder) { // File dir = getFolderPath(folder); // // if (!dir.exists()) // dir.mkdirs(); // // return dir; // } // // public static File getFile(String... uri) { // String[] dir = new String[uri.length - 1]; // for (int i = 0; i < uri.length - 1; i++) // dir[i] = uri[i]; // // return new File(getFolder(dir).toString() + File.separator + uri[uri.length - 1]); // } // // public static File getFile(File folder, String... uri) { // String path = folder.toString(); // for (int i = 0; i < uri.length - 1; i++) // path += uri[i].replace("/", File.separator) + File.separator; // // return new File(path + File.separator + uri[uri.length - 1]); // } // // public static void delete(String folder, String location) { // delete(getFolder(folder, location)); // } // // public static void delete(String folder) { // delete(getFolder(folder)); // } // // public static void delete(File folder) { // for (File f : folder.listFiles()) { // if (f.isDirectory()) // delete(f); // else // f.delete(); // } // folder.delete(); // } // }
import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.Filesystem; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify;
public MetadataBean getMetadataBean() throws Exception { dataBean = new DataBean(); logger = Mockito.mock(Logger.class); MetadataBean m = new MetadataBean(); m.setDataEJB(dataBean); m.setUpdateEJB(Mockito.mock(UpdateBean.class)); Field settingsLoggerField = MetadataBean.class.getDeclaredField("logger"); settingsLoggerField.setAccessible(true); settingsLoggerField.set(m, logger); return m; } @Test public void testReading() { metadataBean.update(); assertEquals(1, dataBean.getChildren().size()); assertEquals("http://www.difi.no/", dataBean.getChild("difi").getUrl()); assertEquals(5, dataBean.getDatasets().size()); assertEquals(null, dataBean.getChildren("not/seen/here")); assertEquals(2, dataBean.getChild("difi", "geo").getChildren().size()); } @Test public void testError() throws IOException {
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/Filesystem.java // public class Filesystem { // // private static final String HOME = "datahotel"; // // public static final String FOLDER_MASTER = "master"; // public static final String FOLDER_MASTER_DEFINITION = FOLDER_MASTER + File.separator + "definition"; // public static final String FOLDER_SLAVE = "slave"; // public static final String FOLDER_CACHE = "cache"; // public static final String FOLDER_CACHE_CHUNK = FOLDER_CACHE + File.separator + "chunk"; // public static final String FOLDER_CACHE_INDEX = FOLDER_CACHE + File.separator + "index"; // // public static final String FILE_DATASET = "dataset.csv"; // public static final String FILE_DATASET_ORIGINAL = "original.csv"; // public static final String FILE_FIELDS = "fields.xml"; // public static final String FILE_DEFINITIONS = "definitions.xml"; // public static final String FILE_METADATA = "meta.xml"; // public static final String FILE_VERSION = "version.xml"; // // private static String home; // // public static String getHome() { // if (home != null) // return home; // // String dir; // // try { // Context initCtx = new InitialContext(); // Context envCtx = (Context) initCtx.lookup("java:comp/env"); // // dir = envCtx.lookup("datahotel.home") + File.separator; // } catch (NamingException e) { // if (System.getProperty("datahotel.home") != null) // dir = System.getProperty("datahotel.home") + File.separator; // else // dir = System.getProperty("user.home") + File.separator + HOME + File.separator; // } // // dir = dir.replace(File.separator + File.separator, File.separator); // new File(dir).mkdirs(); // // home = dir; // return dir; // } // // public static File getFolderPath(String... folder) { // String dir = getHome(); // for (String f : folder) // if (!"".equals(f)) // dir += f.replace("/", File.separator) + File.separator; // return new File(dir); // } // // public static File getFolder(String... folder) { // File dir = getFolderPath(folder); // // if (!dir.exists()) // dir.mkdirs(); // // return dir; // } // // public static File getFile(String... uri) { // String[] dir = new String[uri.length - 1]; // for (int i = 0; i < uri.length - 1; i++) // dir[i] = uri[i]; // // return new File(getFolder(dir).toString() + File.separator + uri[uri.length - 1]); // } // // public static File getFile(File folder, String... uri) { // String path = folder.toString(); // for (int i = 0; i < uri.length - 1; i++) // path += uri[i].replace("/", File.separator) + File.separator; // // return new File(path + File.separator + uri[uri.length - 1]); // } // // public static void delete(String folder, String location) { // delete(getFolder(folder, location)); // } // // public static void delete(String folder) { // delete(getFolder(folder)); // } // // public static void delete(File folder) { // for (File f : folder.listFiles()) { // if (f.isDirectory()) // delete(f); // else // f.delete(); // } // folder.delete(); // } // } // Path: src/test/java/no/difi/datahotel/logic/MetadataBeanTest.java import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.Filesystem; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; public MetadataBean getMetadataBean() throws Exception { dataBean = new DataBean(); logger = Mockito.mock(Logger.class); MetadataBean m = new MetadataBean(); m.setDataEJB(dataBean); m.setUpdateEJB(Mockito.mock(UpdateBean.class)); Field settingsLoggerField = MetadataBean.class.getDeclaredField("logger"); settingsLoggerField.setAccessible(true); settingsLoggerField.set(m, logger); return m; } @Test public void testReading() { metadataBean.update(); assertEquals(1, dataBean.getChildren().size()); assertEquals("http://www.difi.no/", dataBean.getChild("difi").getUrl()); assertEquals(5, dataBean.getDatasets().size()); assertEquals(null, dataBean.getChildren("not/seen/here")); assertEquals(2, dataBean.getChild("difi", "geo").getChildren().size()); } @Test public void testError() throws IOException {
File folder = Filesystem.getFolder(Filesystem.FOLDER_SLAVE, "google");
difi/datahotel
src/main/java/no/difi/datahotel/util/formater/JSONFormater.java
// Path: src/main/java/no/difi/datahotel/util/FormaterInterface.java // public interface FormaterInterface { // public String format(Object object, RequestContext context) throws Exception; // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // }
import no.difi.datahotel.util.FormaterInterface; import no.difi.datahotel.util.RequestContext; import com.google.gson.Gson;
package no.difi.datahotel.util.formater; /** * Class representing JSON. */ public class JSONFormater implements FormaterInterface { private static Gson gson; public JSONFormater() { gson = new Gson(); } @Override
// Path: src/main/java/no/difi/datahotel/util/FormaterInterface.java // public interface FormaterInterface { // public String format(Object object, RequestContext context) throws Exception; // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // Path: src/main/java/no/difi/datahotel/util/formater/JSONFormater.java import no.difi.datahotel.util.FormaterInterface; import no.difi.datahotel.util.RequestContext; import com.google.gson.Gson; package no.difi.datahotel.util.formater; /** * Class representing JSON. */ public class JSONFormater implements FormaterInterface { private static Gson gson; public JSONFormater() { gson = new Gson(); } @Override
public String format(Object object, RequestContext context) {
difi/datahotel
src/test/java/no/difi/datahotel/model/FieldsTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/Filesystem.java // public class Filesystem { // // private static final String HOME = "datahotel"; // // public static final String FOLDER_MASTER = "master"; // public static final String FOLDER_MASTER_DEFINITION = FOLDER_MASTER + File.separator + "definition"; // public static final String FOLDER_SLAVE = "slave"; // public static final String FOLDER_CACHE = "cache"; // public static final String FOLDER_CACHE_CHUNK = FOLDER_CACHE + File.separator + "chunk"; // public static final String FOLDER_CACHE_INDEX = FOLDER_CACHE + File.separator + "index"; // // public static final String FILE_DATASET = "dataset.csv"; // public static final String FILE_DATASET_ORIGINAL = "original.csv"; // public static final String FILE_FIELDS = "fields.xml"; // public static final String FILE_DEFINITIONS = "definitions.xml"; // public static final String FILE_METADATA = "meta.xml"; // public static final String FILE_VERSION = "version.xml"; // // private static String home; // // public static String getHome() { // if (home != null) // return home; // // String dir; // // try { // Context initCtx = new InitialContext(); // Context envCtx = (Context) initCtx.lookup("java:comp/env"); // // dir = envCtx.lookup("datahotel.home") + File.separator; // } catch (NamingException e) { // if (System.getProperty("datahotel.home") != null) // dir = System.getProperty("datahotel.home") + File.separator; // else // dir = System.getProperty("user.home") + File.separator + HOME + File.separator; // } // // dir = dir.replace(File.separator + File.separator, File.separator); // new File(dir).mkdirs(); // // home = dir; // return dir; // } // // public static File getFolderPath(String... folder) { // String dir = getHome(); // for (String f : folder) // if (!"".equals(f)) // dir += f.replace("/", File.separator) + File.separator; // return new File(dir); // } // // public static File getFolder(String... folder) { // File dir = getFolderPath(folder); // // if (!dir.exists()) // dir.mkdirs(); // // return dir; // } // // public static File getFile(String... uri) { // String[] dir = new String[uri.length - 1]; // for (int i = 0; i < uri.length - 1; i++) // dir[i] = uri[i]; // // return new File(getFolder(dir).toString() + File.separator + uri[uri.length - 1]); // } // // public static File getFile(File folder, String... uri) { // String path = folder.toString(); // for (int i = 0; i < uri.length - 1; i++) // path += uri[i].replace("/", File.separator) + File.separator; // // return new File(path + File.separator + uri[uri.length - 1]); // } // // public static void delete(String folder, String location) { // delete(getFolder(folder, location)); // } // // public static void delete(String folder) { // delete(getFolder(folder)); // } // // public static void delete(File folder) { // for (File f : folder.listFiles()) { // if (f.isDirectory()) // delete(f); // else // f.delete(); // } // folder.delete(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.Filesystem; import org.junit.Test;
package no.difi.datahotel.model; public class FieldsTest extends BaseTest { @Test public void testSaveRead() throws Exception { Fields f = new Fields(); List<Field> fields = new ArrayList<Field>(); fields.add(new Field("id", false)); fields.add(new Field("name", true)); f.setFields(fields); f.save("difi", "test", "people");
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/Filesystem.java // public class Filesystem { // // private static final String HOME = "datahotel"; // // public static final String FOLDER_MASTER = "master"; // public static final String FOLDER_MASTER_DEFINITION = FOLDER_MASTER + File.separator + "definition"; // public static final String FOLDER_SLAVE = "slave"; // public static final String FOLDER_CACHE = "cache"; // public static final String FOLDER_CACHE_CHUNK = FOLDER_CACHE + File.separator + "chunk"; // public static final String FOLDER_CACHE_INDEX = FOLDER_CACHE + File.separator + "index"; // // public static final String FILE_DATASET = "dataset.csv"; // public static final String FILE_DATASET_ORIGINAL = "original.csv"; // public static final String FILE_FIELDS = "fields.xml"; // public static final String FILE_DEFINITIONS = "definitions.xml"; // public static final String FILE_METADATA = "meta.xml"; // public static final String FILE_VERSION = "version.xml"; // // private static String home; // // public static String getHome() { // if (home != null) // return home; // // String dir; // // try { // Context initCtx = new InitialContext(); // Context envCtx = (Context) initCtx.lookup("java:comp/env"); // // dir = envCtx.lookup("datahotel.home") + File.separator; // } catch (NamingException e) { // if (System.getProperty("datahotel.home") != null) // dir = System.getProperty("datahotel.home") + File.separator; // else // dir = System.getProperty("user.home") + File.separator + HOME + File.separator; // } // // dir = dir.replace(File.separator + File.separator, File.separator); // new File(dir).mkdirs(); // // home = dir; // return dir; // } // // public static File getFolderPath(String... folder) { // String dir = getHome(); // for (String f : folder) // if (!"".equals(f)) // dir += f.replace("/", File.separator) + File.separator; // return new File(dir); // } // // public static File getFolder(String... folder) { // File dir = getFolderPath(folder); // // if (!dir.exists()) // dir.mkdirs(); // // return dir; // } // // public static File getFile(String... uri) { // String[] dir = new String[uri.length - 1]; // for (int i = 0; i < uri.length - 1; i++) // dir[i] = uri[i]; // // return new File(getFolder(dir).toString() + File.separator + uri[uri.length - 1]); // } // // public static File getFile(File folder, String... uri) { // String path = folder.toString(); // for (int i = 0; i < uri.length - 1; i++) // path += uri[i].replace("/", File.separator) + File.separator; // // return new File(path + File.separator + uri[uri.length - 1]); // } // // public static void delete(String folder, String location) { // delete(getFolder(folder, location)); // } // // public static void delete(String folder) { // delete(getFolder(folder)); // } // // public static void delete(File folder) { // for (File f : folder.listFiles()) { // if (f.isDirectory()) // delete(f); // else // f.delete(); // } // folder.delete(); // } // } // Path: src/test/java/no/difi/datahotel/model/FieldsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.Filesystem; import org.junit.Test; package no.difi.datahotel.model; public class FieldsTest extends BaseTest { @Test public void testSaveRead() throws Exception { Fields f = new Fields(); List<Field> fields = new ArrayList<Field>(); fields.add(new Field("id", false)); fields.add(new Field("name", true)); f.setFields(fields); f.save("difi", "test", "people");
assertTrue(Filesystem.getFile(Filesystem.FOLDER_SLAVE, "difi", "test", "people", Filesystem.FILE_FIELDS).exists());
difi/datahotel
src/main/java/no/difi/datahotel/resources/DatahotelExceptionMapper.java
// Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // }
import no.difi.datahotel.util.DatahotelException; import org.springframework.stereotype.Component; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider;
package no.difi.datahotel.resources; @Provider @Component
// Path: src/main/java/no/difi/datahotel/util/DatahotelException.java // @SuppressWarnings("serial") // public class DatahotelException extends RuntimeException { // // private int status = 500; // private Formater formater = JSON; // // public DatahotelException(String message) { // super(message); // } // // public DatahotelException(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // // public Formater getFormater() { // return formater; // } // // public DatahotelException setFormater(Formater formater) { // this.formater = formater; // return this; // } // } // Path: src/main/java/no/difi/datahotel/resources/DatahotelExceptionMapper.java import no.difi.datahotel.util.DatahotelException; import org.springframework.stereotype.Component; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; package no.difi.datahotel.resources; @Provider @Component
public class DatahotelExceptionMapper implements ExceptionMapper<DatahotelException> {
difi/datahotel
src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java
// Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // }
import no.difi.datahotel.util.RequestContext;
package no.difi.datahotel.util.formater; /** * Class representing an JSONP. */ public class JSONPFormater extends JSONFormater { @Override
// Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // Path: src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java import no.difi.datahotel.util.RequestContext; package no.difi.datahotel.util.formater; /** * Class representing an JSONP. */ public class JSONPFormater extends JSONFormater { @Override
public String format(Object object, RequestContext context) {
kijiproject/kiji-mapreduce
kiji-mapreduce/src/main/java/org/kiji/mapreduce/tools/KijiPivot.java
// Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/MapReduceJobOutput.java // @ApiAudience.Public // @ApiStability.Stable // @Inheritance.Sealed // public abstract class MapReduceJobOutput { // /** // * Initializes the job output from command-line parameters. // * // * @param params Initialization parameters. // * @throws IOException on I/O error. // */ // public abstract void initialize(Map<String, String> params) throws IOException; // // /** // * Configures the output for a MapReduce job. // * // * @param job The job to configure. // * @throws IOException If there is an error. // */ // public void configure(Job job) throws IOException { // job.setOutputFormatClass(getOutputFormatClass()); // } // // /** // * Gets the Hadoop MapReduce output format class. // * // * @return The job output format class. // */ // protected abstract Class<? extends OutputFormat> getOutputFormatClass(); // }
import java.io.IOException; import java.util.List; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.kiji.annotations.ApiAudience; import org.kiji.common.flags.Flag; import org.kiji.mapreduce.MapReduceJobInput; import org.kiji.mapreduce.MapReduceJobOutput; import org.kiji.mapreduce.input.KijiTableMapReduceJobInput; import org.kiji.mapreduce.output.DirectKijiTableMapReduceJobOutput; import org.kiji.mapreduce.output.HFileMapReduceJobOutput; import org.kiji.mapreduce.output.KijiTableMapReduceJobOutput; import org.kiji.mapreduce.pivot.KijiPivotJobBuilder; import org.kiji.mapreduce.pivot.impl.KijiPivoters; import org.kiji.mapreduce.tools.framework.KijiJobTool; import org.kiji.mapreduce.tools.framework.MapReduceJobInputFactory; import org.kiji.mapreduce.tools.framework.MapReduceJobOutputFactory; import org.kiji.schema.Kiji; import org.kiji.schema.KijiTable; import org.kiji.schema.tools.KijiToolLauncher; import org.kiji.schema.tools.RequiredFlagException; import org.kiji.schema.util.ResourceUtils;
/** * (c) Copyright 2012 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.tools; /** * Runs a KijiPivoter a Kiji table. * * <p> * Here is an example of command-line to launch a KijiPivoter named {@code package.SomePivoter} * on the rows from an input table {@code kiji://.env/input_instance/input_table} * while writing cells to another output table {@code kiji://.env/output_instance/output_table}: * <pre><blockquote> * $ kiji pivot \ * --pivoter='package.SomePivoter' \ * --input="format=kiji table=kiji://.env/default/input_table" \ * --output="format=kiji table=kiji://.env/default/output_table nsplits=5" \ * --lib=/path/to/libdir/ * </blockquote></pre> * </p> */ @ApiAudience.Private public final class KijiPivot extends KijiJobTool<KijiPivotJobBuilder> { private static final Logger LOG = LoggerFactory.getLogger(KijiPivot.class); @Flag(name="pivoter", usage="KijiPivoter class to run over the table.") private String mPivoter= ""; /** {@inheritDoc} */ @Override public String getName() { return "pivot"; } /** {@inheritDoc} */ @Override public String getDescription() { return "Run a pivoter over a Kiji table."; } /** {@inheritDoc} */ @Override public String getCategory() { return "MapReduce"; } /** Kiji instance where the output table lives. */ private Kiji mKiji; /** KijiTable to import data into. */ private KijiTable mTable; /** Job output. */ private KijiTableMapReduceJobOutput mOutput; /** {@inheritDoc} */ @Override protected void validateFlags() throws Exception { // Parse --input and --output flags: // --input is guaranteed to be a Kiji table, --output is not. super.validateFlags(); if (mInputFlag.isEmpty()) { throw new RequiredFlagException("input"); } if (mPivoter.isEmpty()) { throw new RequiredFlagException("pivoter"); } if (mOutputFlag.isEmpty()) { throw new RequiredFlagException("output"); }
// Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/MapReduceJobOutput.java // @ApiAudience.Public // @ApiStability.Stable // @Inheritance.Sealed // public abstract class MapReduceJobOutput { // /** // * Initializes the job output from command-line parameters. // * // * @param params Initialization parameters. // * @throws IOException on I/O error. // */ // public abstract void initialize(Map<String, String> params) throws IOException; // // /** // * Configures the output for a MapReduce job. // * // * @param job The job to configure. // * @throws IOException If there is an error. // */ // public void configure(Job job) throws IOException { // job.setOutputFormatClass(getOutputFormatClass()); // } // // /** // * Gets the Hadoop MapReduce output format class. // * // * @return The job output format class. // */ // protected abstract Class<? extends OutputFormat> getOutputFormatClass(); // } // Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/tools/KijiPivot.java import java.io.IOException; import java.util.List; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.kiji.annotations.ApiAudience; import org.kiji.common.flags.Flag; import org.kiji.mapreduce.MapReduceJobInput; import org.kiji.mapreduce.MapReduceJobOutput; import org.kiji.mapreduce.input.KijiTableMapReduceJobInput; import org.kiji.mapreduce.output.DirectKijiTableMapReduceJobOutput; import org.kiji.mapreduce.output.HFileMapReduceJobOutput; import org.kiji.mapreduce.output.KijiTableMapReduceJobOutput; import org.kiji.mapreduce.pivot.KijiPivotJobBuilder; import org.kiji.mapreduce.pivot.impl.KijiPivoters; import org.kiji.mapreduce.tools.framework.KijiJobTool; import org.kiji.mapreduce.tools.framework.MapReduceJobInputFactory; import org.kiji.mapreduce.tools.framework.MapReduceJobOutputFactory; import org.kiji.schema.Kiji; import org.kiji.schema.KijiTable; import org.kiji.schema.tools.KijiToolLauncher; import org.kiji.schema.tools.RequiredFlagException; import org.kiji.schema.util.ResourceUtils; /** * (c) Copyright 2012 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.tools; /** * Runs a KijiPivoter a Kiji table. * * <p> * Here is an example of command-line to launch a KijiPivoter named {@code package.SomePivoter} * on the rows from an input table {@code kiji://.env/input_instance/input_table} * while writing cells to another output table {@code kiji://.env/output_instance/output_table}: * <pre><blockquote> * $ kiji pivot \ * --pivoter='package.SomePivoter' \ * --input="format=kiji table=kiji://.env/default/input_table" \ * --output="format=kiji table=kiji://.env/default/output_table nsplits=5" \ * --lib=/path/to/libdir/ * </blockquote></pre> * </p> */ @ApiAudience.Private public final class KijiPivot extends KijiJobTool<KijiPivotJobBuilder> { private static final Logger LOG = LoggerFactory.getLogger(KijiPivot.class); @Flag(name="pivoter", usage="KijiPivoter class to run over the table.") private String mPivoter= ""; /** {@inheritDoc} */ @Override public String getName() { return "pivot"; } /** {@inheritDoc} */ @Override public String getDescription() { return "Run a pivoter over a Kiji table."; } /** {@inheritDoc} */ @Override public String getCategory() { return "MapReduce"; } /** Kiji instance where the output table lives. */ private Kiji mKiji; /** KijiTable to import data into. */ private KijiTable mTable; /** Job output. */ private KijiTableMapReduceJobOutput mOutput; /** {@inheritDoc} */ @Override protected void validateFlags() throws Exception { // Parse --input and --output flags: // --input is guaranteed to be a Kiji table, --output is not. super.validateFlags(); if (mInputFlag.isEmpty()) { throw new RequiredFlagException("input"); } if (mPivoter.isEmpty()) { throw new RequiredFlagException("pivoter"); } if (mOutputFlag.isEmpty()) { throw new RequiredFlagException("output"); }
final MapReduceJobOutput mrJobOutput =
kijiproject/kiji-mapreduce
kiji-mapreduce/src/main/java/org/kiji/mapreduce/gather/impl/GatherMapper.java
// Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/gather/GathererContext.java // @ApiAudience.Public // @ApiStability.Stable // @Inheritance.Sealed // public interface GathererContext<K, V> extends KijiContext { // /** // * Emits a key/value pair. // * // * @param key Emit this key. // * @param value Emit this value. // * @throws IOException on I/O error. // */ // void write(K key, V value) throws IOException; // }
import org.kiji.mapreduce.avro.AvroValueWriter; import org.kiji.mapreduce.framework.JobHistoryCounters; import org.kiji.mapreduce.framework.KijiConfKeys; import org.kiji.mapreduce.gather.GathererContext; import org.kiji.mapreduce.gather.KijiGatherer; import org.kiji.mapreduce.impl.KijiTableMapper; import org.kiji.schema.KijiDataRequest; import org.kiji.schema.KijiRowData; import java.io.IOException; import com.google.common.base.Preconditions; import org.apache.avro.Schema; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.kiji.annotations.ApiAudience; import org.kiji.mapreduce.avro.AvroKeyWriter;
/** * (c) Copyright 2012 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.gather.impl; /** * Mapper that executes a gatherer over the rows of a Kiji table. * * @param <K> The type of the MapReduce output key. * @param <V> The type of the MapReduce output value. */ @ApiAudience.Private public final class GatherMapper<K, V> extends KijiTableMapper<K, V> implements AvroKeyWriter, AvroValueWriter { private static final Logger LOG = LoggerFactory.getLogger(GatherMapper.class); /** The gatherer to execute. */ private KijiGatherer<K, V> mGatherer; /** * The context object that allows the gatherer to interact with MapReduce, * KVStores, etc. */
// Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/gather/GathererContext.java // @ApiAudience.Public // @ApiStability.Stable // @Inheritance.Sealed // public interface GathererContext<K, V> extends KijiContext { // /** // * Emits a key/value pair. // * // * @param key Emit this key. // * @param value Emit this value. // * @throws IOException on I/O error. // */ // void write(K key, V value) throws IOException; // } // Path: kiji-mapreduce/src/main/java/org/kiji/mapreduce/gather/impl/GatherMapper.java import org.kiji.mapreduce.avro.AvroValueWriter; import org.kiji.mapreduce.framework.JobHistoryCounters; import org.kiji.mapreduce.framework.KijiConfKeys; import org.kiji.mapreduce.gather.GathererContext; import org.kiji.mapreduce.gather.KijiGatherer; import org.kiji.mapreduce.impl.KijiTableMapper; import org.kiji.schema.KijiDataRequest; import org.kiji.schema.KijiRowData; import java.io.IOException; import com.google.common.base.Preconditions; import org.apache.avro.Schema; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.kiji.annotations.ApiAudience; import org.kiji.mapreduce.avro.AvroKeyWriter; /** * (c) Copyright 2012 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.gather.impl; /** * Mapper that executes a gatherer over the rows of a Kiji table. * * @param <K> The type of the MapReduce output key. * @param <V> The type of the MapReduce output value. */ @ApiAudience.Private public final class GatherMapper<K, V> extends KijiTableMapper<K, V> implements AvroKeyWriter, AvroValueWriter { private static final Logger LOG = LoggerFactory.getLogger(GatherMapper.class); /** The gatherer to execute. */ private KijiGatherer<K, V> mGatherer; /** * The context object that allows the gatherer to interact with MapReduce, * KVStores, etc. */
private GathererContext<K, V> mGathererContext;
kijiproject/kiji-mapreduce
kiji-mapreduce/src/test/java/org/kiji/mapreduce/input/TestKijiTableMapReduceJobInput.java
// Path: kiji-mapreduce/src/test/java/org/kiji/mapreduce/KijiMRTestLayouts.java // public final class KijiMRTestLayouts { // // /** // * Alias for KijiTableLayouts.getLayout(resource). // * // * @param resourcePath Path of the resource to load the JSON descriptor from. // * @return the decoded TableLayoutDesc. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getLayout(String resourcePath) throws IOException { // return KijiTableLayouts.getLayout(resourcePath); // } // // /** Generic test layout with user info, all primitive types, a map-type family of strings. */ // public static final String TEST_LAYOUT = "org/kiji/mapreduce/layout/test.json"; // /** Multiple locality group test layout. */ // public static final String LG_TEST_LAYOUT = "org/kiji/mapreduce/layout/lgtest.json"; // // /** // * @return a generic test layout. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getTestLayout() throws IOException { // return getLayout(TEST_LAYOUT); // } // // /** // * @param tableName For the table name in the layout. // * @return a generic test layout. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getTestLayout(String tableName) throws IOException { // final TableLayoutDesc desc = getLayout(TEST_LAYOUT); // desc.setName(tableName); // return desc; // } // // /** Utility class cannot be instantiated. */ // private KijiMRTestLayouts() { // } // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SerializationUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kiji.mapreduce.KijiMRTestLayouts; import org.kiji.mapreduce.MapReduceJobInput; import org.kiji.mapreduce.framework.KijiConfKeys; import org.kiji.schema.EntityId; import org.kiji.schema.HBaseEntityId; import org.kiji.schema.KijiClientTest; import org.kiji.schema.KijiDataRequest; import org.kiji.schema.KijiDataRequestBuilder; import org.kiji.schema.KijiTable; import org.kiji.schema.KijiURI; import org.kiji.schema.filter.KijiRowFilter; import org.kiji.schema.filter.StripValueRowFilter; import org.kiji.schema.util.ResourceUtils; import org.kiji.schema.util.TestingFileUtils;
/** * (c) Copyright 2013 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.input; public class TestKijiTableMapReduceJobInput extends KijiClientTest { private File mTempDir; private Path mTempPath; private KijiTable mTable; @Before public void setUp() throws Exception { mTempDir = TestingFileUtils.createTempDir("test", "dir"); mTempPath = new Path("file://" + mTempDir); getConf().set("fs.defaultFS", mTempPath.toString()); getConf().set("fs.default.name", mTempPath.toString());
// Path: kiji-mapreduce/src/test/java/org/kiji/mapreduce/KijiMRTestLayouts.java // public final class KijiMRTestLayouts { // // /** // * Alias for KijiTableLayouts.getLayout(resource). // * // * @param resourcePath Path of the resource to load the JSON descriptor from. // * @return the decoded TableLayoutDesc. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getLayout(String resourcePath) throws IOException { // return KijiTableLayouts.getLayout(resourcePath); // } // // /** Generic test layout with user info, all primitive types, a map-type family of strings. */ // public static final String TEST_LAYOUT = "org/kiji/mapreduce/layout/test.json"; // /** Multiple locality group test layout. */ // public static final String LG_TEST_LAYOUT = "org/kiji/mapreduce/layout/lgtest.json"; // // /** // * @return a generic test layout. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getTestLayout() throws IOException { // return getLayout(TEST_LAYOUT); // } // // /** // * @param tableName For the table name in the layout. // * @return a generic test layout. // * @throws IOException on I/O error. // */ // public static TableLayoutDesc getTestLayout(String tableName) throws IOException { // final TableLayoutDesc desc = getLayout(TEST_LAYOUT); // desc.setName(tableName); // return desc; // } // // /** Utility class cannot be instantiated. */ // private KijiMRTestLayouts() { // } // } // Path: kiji-mapreduce/src/test/java/org/kiji/mapreduce/input/TestKijiTableMapReduceJobInput.java import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SerializationUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kiji.mapreduce.KijiMRTestLayouts; import org.kiji.mapreduce.MapReduceJobInput; import org.kiji.mapreduce.framework.KijiConfKeys; import org.kiji.schema.EntityId; import org.kiji.schema.HBaseEntityId; import org.kiji.schema.KijiClientTest; import org.kiji.schema.KijiDataRequest; import org.kiji.schema.KijiDataRequestBuilder; import org.kiji.schema.KijiTable; import org.kiji.schema.KijiURI; import org.kiji.schema.filter.KijiRowFilter; import org.kiji.schema.filter.StripValueRowFilter; import org.kiji.schema.util.ResourceUtils; import org.kiji.schema.util.TestingFileUtils; /** * (c) Copyright 2013 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.mapreduce.input; public class TestKijiTableMapReduceJobInput extends KijiClientTest { private File mTempDir; private Path mTempPath; private KijiTable mTable; @Before public void setUp() throws Exception { mTempDir = TestingFileUtils.createTempDir("test", "dir"); mTempPath = new Path("file://" + mTempDir); getConf().set("fs.defaultFS", mTempPath.toString()); getConf().set("fs.default.name", mTempPath.toString());
getKiji().createTable(KijiMRTestLayouts.getTestLayout());
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/generic/GenericJSONClient.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import java.nio.charset.Charset; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection;
/* * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.automation.test.utils.generic; public class GenericJSONClient { public static final Log log = LogFactory.getLog(GenericJSONClient.class); public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/generic/GenericJSONClient.java import java.nio.charset.Charset; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /* * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.automation.test.utils.generic; public class GenericJSONClient { public static final Log log = LogFactory.getLog(GenericJSONClient.class); public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
public JSONObject doGet(String endpoint, String query, String contentType) throws AutomationFrameworkException, IOException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/JMeterTestManager.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jmeter.JMeter; import org.apache.jmeter.engine.StandardJMeterEngine; import org.apache.jmeter.util.ShutdownClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern;
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.automation.extensions.jmeter; public class JMeterTestManager { private static final Pattern PAT_ERROR = Pattern.compile(".*\\s+ERROR\\s+.*"); private static final Log log = LogFactory.getLog(JMeterTestManager.class); private String jmeterLogLevel = "INFO"; private File testFile = null; private File jmeterHome = null; private File jmeterLogFile = null; private DateFormat fmt = new SimpleDateFormat("yyMMdd-HH-mm-ss"); private File jmeterProps = null; public void runTest(JMeterTest jMeterTest)
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/JMeterTestManager.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jmeter.JMeter; import org.apache.jmeter.engine.StandardJMeterEngine; import org.apache.jmeter.util.ShutdownClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; /* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.automation.extensions.jmeter; public class JMeterTestManager { private static final Pattern PAT_ERROR = Pattern.compile(".*\\s+ERROR\\s+.*"); private static final Log log = LogFactory.getLog(JMeterTestManager.class); private String jmeterLogLevel = "INFO"; private File testFile = null; private File jmeterHome = null; private File jmeterLogFile = null; private DateFormat fmt = new SimpleDateFormat("yyMMdd-HH-mm-ss"); private File jmeterProps = null; public void runTest(JMeterTest jMeterTest)
throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/context/beans/User.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // }
import org.wso2.carbon.automation.engine.FrameworkConstants; import java.util.ArrayList; import java.util.List;
} public String getKey() { return key; } public String getUserName() { return userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserNameWithoutDomain() { if (userName.contains("@")) { return userName.substring(0, userName.lastIndexOf("@")); } else { return userName; } } public String getUserDomain() { if(userName.contains("@")) { return userName.substring(userName.lastIndexOf("@") + 1); } else {
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // } // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/context/beans/User.java import org.wso2.carbon.automation.engine.FrameworkConstants; import java.util.ArrayList; import java.util.List; } public String getKey() { return key; } public String getUserName() { return userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserNameWithoutDomain() { if (userName.contains("@")) { return userName.substring(0, userName.lastIndexOf("@")); } else { return userName; } } public String getUserDomain() { if(userName.contains("@")) { return userName.substring(userName.lastIndexOf("@") + 1); } else {
return FrameworkConstants.SUPER_TENANT_DOMAIN_NAME;
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSTopicMessagePublisher.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Properties;
public void disconnect() { if (publisher != null) { try { publisher.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * this will publish the message to given topic * * @param messageContent * @throws AutomationFrameworkException */
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSTopicMessagePublisher.java import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Properties; public void disconnect() { if (publisher != null) { try { publisher.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * this will publish the message to given topic * * @param messageContent * @throws AutomationFrameworkException */
public void publish(String messageContent) throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/http/client/HttpRequestUtil.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.*; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
Iterator<String> itr = conn.getHeaderFields().keySet().iterator(); Map<String, String> headers = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { headers.put(key, conn.getHeaderField(key)); } } return new HttpResponse(sb.toString(), conn.getResponseCode(), headers); } finally { if (conn != null) { conn.disconnect(); } } } /** * Reads data from the data reader and posts it to a server via POST request. * data - The data you want to send * endpoint - The server's address * output - writes the server's response to output * * @param data Data to be sent * @param endpoint The endpoint to which the data has to be POSTed * @param output Output * @throws AutomationFrameworkException If an error occurs while POSTing */
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/http/client/HttpRequestUtil.java import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.*; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Iterator; import java.util.Map; Iterator<String> itr = conn.getHeaderFields().keySet().iterator(); Map<String, String> headers = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { headers.put(key, conn.getHeaderField(key)); } } return new HttpResponse(sb.toString(), conn.getResponseCode(), headers); } finally { if (conn != null) { conn.disconnect(); } } } /** * Reads data from the data reader and posts it to a server via POST request. * data - The data you want to send * endpoint - The server's address * output - writes the server's response to output * * @param data Data to be sent * @param endpoint The endpoint to which the data has to be POSTed * @param output Output * @throws AutomationFrameworkException If an error occurs while POSTing */
public static void sendPostRequest(Reader data, URL endpoint, Writer output) throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSTopicMessageConsumer.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.ArrayList; import java.util.List; import java.util.Properties;
public void stopConsuming() { if (consumer != null) { try { consumer.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * this will returns all the message received from the topic after the subscription * * @return * @throws AutomationFrameworkException */
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSTopicMessageConsumer.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.ArrayList; import java.util.List; import java.util.Properties; public void stopConsuming() { if (consumer != null) { try { consumer.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * this will returns all the message received from the topic after the subscription * * @return * @throws AutomationFrameworkException */
public List<String> getMessages() throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/JMeterInstallationProvider.java
// Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/util/Utils.java // public class Utils { // public static void copyFromClassPath(String fileName, File destination) throws IOException { // // BufferedWriter out = null; // try { // // out = new BufferedWriter // (new OutputStreamWriter(new FileOutputStream(destination), Charset.defaultCharset())); // // IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName), out); // // // } catch (IOException e) { // throw new IOException("Could not create temporary saveservice.properties", e); // } finally { // if (out != null) { // out.flush(); // out.close(); // } // } // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.extensions.jmeter.util.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties;
//creating jmeter directory jMeterHome = new File(targetDir, "jmeter"); if (!jMeterHome.mkdirs()) { log.error("Unable to create jmeter directory"); throw new RuntimeException("Unable to create jmeter directory"); } reportDir = new File(jMeterHome, "reports"); // now create lib dir for jmeter fallback mode libDir = new File(jMeterHome + File.separator + "lib"); createLibDirectory(libDir); binDir = new File(jMeterHome + File.separator + "bin"); if (!binDir.exists()) { if (!binDir.mkdirs()) { log.error("unable to create bin directory"); throw new RuntimeException("unable to create bin dir for Jmeter"); } } //saving properties file in bin directory saveServiceProps = new File(binDir, "saveservice.properties"); upgradeProps = new File(binDir, "upgrade.properties"); jmeterPropertyFile = new File(binDir, "jmeter.properties"); jmeterPropertyFileTemp = new File(binDir, "jmeterTemp.properties"); //copying saveservice.properties from classpath try {
// Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/util/Utils.java // public class Utils { // public static void copyFromClassPath(String fileName, File destination) throws IOException { // // BufferedWriter out = null; // try { // // out = new BufferedWriter // (new OutputStreamWriter(new FileOutputStream(destination), Charset.defaultCharset())); // // IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName), out); // // // } catch (IOException e) { // throw new IOException("Could not create temporary saveservice.properties", e); // } finally { // if (out != null) { // out.flush(); // out.close(); // } // } // } // } // Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/jmeter/JMeterInstallationProvider.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.extensions.jmeter.util.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; //creating jmeter directory jMeterHome = new File(targetDir, "jmeter"); if (!jMeterHome.mkdirs()) { log.error("Unable to create jmeter directory"); throw new RuntimeException("Unable to create jmeter directory"); } reportDir = new File(jMeterHome, "reports"); // now create lib dir for jmeter fallback mode libDir = new File(jMeterHome + File.separator + "lib"); createLibDirectory(libDir); binDir = new File(jMeterHome + File.separator + "bin"); if (!binDir.exists()) { if (!binDir.mkdirs()) { log.error("unable to create bin directory"); throw new RuntimeException("unable to create bin dir for Jmeter"); } } //saving properties file in bin directory saveServiceProps = new File(binDir, "saveservice.properties"); upgradeProps = new File(binDir, "upgrade.properties"); jmeterPropertyFile = new File(binDir, "jmeter.properties"); jmeterPropertyFileTemp = new File(binDir, "jmeterTemp.properties"); //copying saveservice.properties from classpath try {
Utils.copyFromClassPath("bin/saveservice.properties", saveServiceProps);
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // } // // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/enums/OperatingSystems.java // public enum OperatingSystems { // WINDOWS, // MAC, // UNIX, // SOLARIS // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.frameworkutils.enums.OperatingSystems; import java.io.File;
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; public class FrameworkPathUtil { public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); public static String getSystemResourceLocation() { String resourceLocation;
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // } // // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/enums/OperatingSystems.java // public enum OperatingSystems { // WINDOWS, // MAC, // UNIX, // SOLARIS // } // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.frameworkutils.enums.OperatingSystems; import java.io.File; /* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; public class FrameworkPathUtil { public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); public static String getSystemResourceLocation() { String resourceLocation;
if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME)
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // } // // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/enums/OperatingSystems.java // public enum OperatingSystems { // WINDOWS, // MAC, // UNIX, // SOLARIS // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.frameworkutils.enums.OperatingSystems; import java.io.File;
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; public class FrameworkPathUtil { public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); public static String getSystemResourceLocation() { String resourceLocation; if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME)
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/FrameworkConstants.java // public class FrameworkConstants { // public static final String SYSTEM_PROPERTY_SETTINGS_LOCATION = "automation.settings.location"; // public static final String SYSTEM_PROPERTY_BASEDIR_LOCATION = "basedir"; // public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; // public static final String SYSTEM_PROPERTY_CARBON_ZIP_LOCATION = "carbon.zip"; // public static final String SYSTEM_PROPERTY_SEC_VERIFIER_DIRECTORY = "sec.verifier.dir"; // public static final int DEFAULT_CARBON_PORT_OFFSET = 0; // public static final String SERVICE_FILE_SEC_VERIFIER = "SecVerifier.aar"; // public static final String LIST_SUPPORTED_DATABASES = "mysql,oracle,derby,h2"; // public static final String SEVER_STARTUP_SCRIPT_NAME = "wso2server"; // public static final String SERVER_STARTUP_PORT_OFFSET_COMMAND = "-DportOffset"; // public static final String SERVER_DEFAULT_HTTPS_PORT = "9443"; // public static final String SERVER_DEFAULT_HTTP_PORT = "9763"; // public static final String SUPER_TENANT_DOMAIN_NAME = "carbon.super"; // public static final String ADMIN_ROLE = "admin"; // public static final String DEFAULT_KEY_STORE = "wso2"; // public static final String TENANT_USAGE_PLAN_DEMO = "demo"; // public static final String AUTOMATION_SCHEMA_NAME = "automationXMLSchema.xsd"; // public static final String LISTENER_INIT_METHOD = "initiate"; // public static final String LISTENER_EXECUTE_METHOD = "execution"; // public static final String DEFAULT_BACKEND_URL = "https://localhost:9443/services/"; // public static final String AUTHENTICATE_ADMIN_SERVICE_NAME = "AuthenticationAdmin"; // public static final String CONFIGURATION_FILE_NAME = "automation.xml"; // public static final String MAPPING_FILE_NAME = "automation_mapping.xsd"; // public static final String DEFAULT_PRODUCT_GROUP = "default.product.group"; // public static final String EXECUTION_MODE = "framework.execution.mode"; // public static final String ENVIRONMENT_STANDALONE = "standalone"; // public static final String ENVIRONMENT_PLATFORM = "platform"; // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // public static final String SUPER_TENANT_KEY = "superTenant"; // public static final String SUPER_TENANT_ADMIN = "superAdmin"; // public static final String CARBON_HOME = "carbon.home"; // public static final String JACOCO_AGENT_JAR_NAME = "jacocoagent.jar"; // public static final String CLASS_FILE_PATTERN = "**/*.class"; // // } // // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/enums/OperatingSystems.java // public enum OperatingSystems { // WINDOWS, // MAC, // UNIX, // SOLARIS // } // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.frameworkutils.enums.OperatingSystems; import java.io.File; /* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; public class FrameworkPathUtil { public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); public static String getSystemResourceLocation() { String resourceLocation; if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME)
.toLowerCase().contains(OperatingSystems.WINDOWS.name().toLowerCase())) {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/axis2client/AxisServiceClientUtils.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.AxisFault; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import javax.xml.stream.XMLStreamException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import static org.testng.Assert.assertFalse; import static org.testng.Assert.fail;
} catch (IOException e) { return false; } finally { if (in != null) { in.close(); } } } return false; } public static void waitForServiceDeployment(String serviceUrl) throws IOException { int serviceTimeOut = 0; while (!isServiceAvailable(serviceUrl)) { if (serviceTimeOut == 0) { } else if (serviceTimeOut > 100) { //Check for the service for 100 seconds // if Service not available assertfalse; fail(serviceUrl + " service is not found"); break; } try { Thread.sleep(500); serviceTimeOut++; } catch (InterruptedException ignored) { } } } public static void sendRequest(String eprUrl, String operation, String payload, int numberOfInstances, List<String> expectedStrings,
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/axis2client/AxisServiceClientUtils.java import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.AxisFault; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import javax.xml.stream.XMLStreamException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import static org.testng.Assert.assertFalse; import static org.testng.Assert.fail; } catch (IOException e) { return false; } finally { if (in != null) { in.close(); } } } return false; } public static void waitForServiceDeployment(String serviceUrl) throws IOException { int serviceTimeOut = 0; while (!isServiceAvailable(serviceUrl)) { if (serviceTimeOut == 0) { } else if (serviceTimeOut > 100) { //Check for the service for 100 seconds // if Service not available assertfalse; fail(serviceUrl + " service is not found"); break; } try { Thread.sleep(500); serviceTimeOut++; } catch (InterruptedException ignored) { } } } public static void sendRequest(String eprUrl, String operation, String payload, int numberOfInstances, List<String> expectedStrings,
boolean twoWay) throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/TestCoverageGenerator.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.File; import java.io.IOException;
/* *Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; /** * Coverage generator class for multi module test project. * This class traverse though all Jacoco data dump files in multiple modules and then merge the result * into one file. This file will be used to generate aggregated coverage report. */ public class TestCoverageGenerator { private static final Log log = LogFactory.getLog(TestCoverageGenerator.class); private static String carbonZip;
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/TestCoverageGenerator.java import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import java.io.File; import java.io.IOException; /* *Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.frameworkutils; /** * Coverage generator class for multi module test project. * This class traverse though all Jacoco data dump files in multiple modules and then merge the result * into one file. This file will be used to generate aggregated coverage report. */ public class TestCoverageGenerator { private static final Log log = LogFactory.getLog(TestCoverageGenerator.class); private static String carbonZip;
public static void main(String[] args) throws AutomationFrameworkException, IOException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/axis2client/ConfigurationContextProvider.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java // public class FrameworkPathUtil { // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); // // public static String getSystemResourceLocation() { // String resourceLocation; // if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME) // .toLowerCase().contains(OperatingSystems.WINDOWS.name().toLowerCase())) { // resourceLocation = System.getProperty // (SYSTEM_ARTIFACT_RESOURCE_LOCATION).replace("/", "\\"); // } else { // resourceLocation = System.getProperty // (SYSTEM_ARTIFACT_RESOURCE_LOCATION).replace("/", "/"); // } // return resourceLocation; // } // // public static String getSystemSettingsLocation() { // String settingsLocation; // if (System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION) != null) { // if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME) // .toLowerCase().contains(OperatingSystems.WINDOWS.name().toLowerCase())) { // settingsLocation = System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION).replace("/", "\\"); // } else { // settingsLocation = System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION).replace("/", "/"); // } // } else { // settingsLocation = getSystemResourceLocation(); // } // return settingsLocation; // } // // public static String getReportLocation() { // String reportLocation; // reportLocation = (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_BASEDIR_LOCATION, ".")) + // File.separator + "target"; // return reportLocation; // } // // public static String getCarbonZipLocation() { // return System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_CARBON_ZIP_LOCATION); // } // // public static String getCarbonTempLocation() { // String extractDir = "carbontmp" + System.currentTimeMillis(); // String baseDir = (System.getProperty("basedir", ".")) + File.separator + "target"; // return new File(baseDir).getAbsolutePath() + File.separator + extractDir; // } // // public static String getCarbonServerAxisServiceDirectory() { // return getCarbonHome() + File.separator + "repository" + File.separator // + "deployment" + File.separator + "server" + File.separator + "axis2services"; // } // // public static String getCarbonServerLibLocation() { // return getCarbonHome() + File.separator + "repository" + File.separator + "components" + // File.separator + "lib"; // } // // public static String getCarbonServerConfLocation() { // return getCarbonHome() + File.separator + "repository" + File.separator + "conf"; // } // // public static String getCoverageDirPath() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + // "jacoco" + File.separator + "coverage"; // } // // public static String getJacocoCoverageHome() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + // "jacoco"; // } // // public static String getTargetDirectory() { // return System.getProperty("basedir") + File.separator + "target"; // } // // public static String getCoverageDumpFilePath() { // return getJacocoCoverageHome() + File.separator + "jacoco" + System.currentTimeMillis() + ".exec"; // } // // public static String getCoverageMergeFilePath() { // return getJacocoCoverageHome() + File.separator + "jacoco-data-merge" + ".exec"; // } // // public static String getJarExtractedFilePath() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + "jar"; // } // // public static String getCarbonHome() { // if (System.getProperty(FrameworkConstants.CARBON_HOME) != null) { // return System.getProperty(FrameworkConstants.CARBON_HOME); // } else { // log.error("Cannot read carbon.home property "); // return null; // } // } // }
import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import java.io.File;
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.test.utils.axis2client; public class ConfigurationContextProvider { private static final Log log = LogFactory.getLog(ConfigurationContextProvider.class); private static ConfigurationContext configurationContext = null; private static ConfigurationContextProvider instance = new ConfigurationContextProvider(); private ConfigurationContextProvider() { try { PoolingHttpClientConnectionManager poolingHttpClientConnectionManager; configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/frameworkutils/FrameworkPathUtil.java // public class FrameworkPathUtil { // public static final String SYSTEM_ARTIFACT_RESOURCE_LOCATION = "framework.resource.location"; // private static final Log log = LogFactory.getLog(FrameworkPathUtil.class); // // public static String getSystemResourceLocation() { // String resourceLocation; // if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME) // .toLowerCase().contains(OperatingSystems.WINDOWS.name().toLowerCase())) { // resourceLocation = System.getProperty // (SYSTEM_ARTIFACT_RESOURCE_LOCATION).replace("/", "\\"); // } else { // resourceLocation = System.getProperty // (SYSTEM_ARTIFACT_RESOURCE_LOCATION).replace("/", "/"); // } // return resourceLocation; // } // // public static String getSystemSettingsLocation() { // String settingsLocation; // if (System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION) != null) { // if (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_OS_NAME) // .toLowerCase().contains(OperatingSystems.WINDOWS.name().toLowerCase())) { // settingsLocation = System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION).replace("/", "\\"); // } else { // settingsLocation = System.getProperty // (FrameworkConstants.SYSTEM_PROPERTY_SETTINGS_LOCATION).replace("/", "/"); // } // } else { // settingsLocation = getSystemResourceLocation(); // } // return settingsLocation; // } // // public static String getReportLocation() { // String reportLocation; // reportLocation = (System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_BASEDIR_LOCATION, ".")) + // File.separator + "target"; // return reportLocation; // } // // public static String getCarbonZipLocation() { // return System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_CARBON_ZIP_LOCATION); // } // // public static String getCarbonTempLocation() { // String extractDir = "carbontmp" + System.currentTimeMillis(); // String baseDir = (System.getProperty("basedir", ".")) + File.separator + "target"; // return new File(baseDir).getAbsolutePath() + File.separator + extractDir; // } // // public static String getCarbonServerAxisServiceDirectory() { // return getCarbonHome() + File.separator + "repository" + File.separator // + "deployment" + File.separator + "server" + File.separator + "axis2services"; // } // // public static String getCarbonServerLibLocation() { // return getCarbonHome() + File.separator + "repository" + File.separator + "components" + // File.separator + "lib"; // } // // public static String getCarbonServerConfLocation() { // return getCarbonHome() + File.separator + "repository" + File.separator + "conf"; // } // // public static String getCoverageDirPath() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + // "jacoco" + File.separator + "coverage"; // } // // public static String getJacocoCoverageHome() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + // "jacoco"; // } // // public static String getTargetDirectory() { // return System.getProperty("basedir") + File.separator + "target"; // } // // public static String getCoverageDumpFilePath() { // return getJacocoCoverageHome() + File.separator + "jacoco" + System.currentTimeMillis() + ".exec"; // } // // public static String getCoverageMergeFilePath() { // return getJacocoCoverageHome() + File.separator + "jacoco-data-merge" + ".exec"; // } // // public static String getJarExtractedFilePath() { // return System.getProperty("basedir") + File.separator + "target" + File.separator + "jar"; // } // // public static String getCarbonHome() { // if (System.getProperty(FrameworkConstants.CARBON_HOME) != null) { // return System.getProperty(FrameworkConstants.CARBON_HOME); // } else { // log.error("Cannot read carbon.home property "); // return null; // } // } // } // Path: test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/axis2client/ConfigurationContextProvider.java import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import java.io.File; /* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.test.utils.axis2client; public class ConfigurationContextProvider { private static final Log log = LogFactory.getLog(ConfigurationContextProvider.class); private static ConfigurationContext configurationContext = null; private static ConfigurationContextProvider instance = new ConfigurationContextProvider(); private ConfigurationContextProvider() { try { PoolingHttpClientConnectionManager poolingHttpClientConnectionManager; configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
FrameworkPathUtil.getSystemResourceLocation() + File.separator + "client", null);
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/http/client/HttpClientUtil.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import java.net.URL; import java.nio.charset.Charset; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException;
/* * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.automation.test.utils.http.client; public class HttpClientUtil { private static final Log log = LogFactory.getLog(HttpClientUtil.class); private static final int connectionTimeOut = 30000;
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.test.utils/src/main/java/org/wso2/carbon/automation/test/utils/http/client/HttpClientUtil.java import java.net.URL; import java.nio.charset.Charset; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; /* * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.automation.test.utils.http.client; public class HttpClientUtil { private static final Log log = LogFactory.getLog(HttpClientUtil.class); private static final int connectionTimeOut = 30000;
public OMElement get(String endpoint) throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSQueueMessageProducer.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Properties;
public void disconnect() { if (producer != null) { try { producer.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * This will send the message to the destination Queue * * @param messageContent returns the message contents * @throws AutomationFrameworkException */
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.extensions/src/main/java/org/wso2/carbon/automation/extensions/servers/jmsserver/client/JMSQueueMessageProducer.java import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.extensions.servers.jmsserver.controller.config.JMSBrokerConfiguration; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Properties; public void disconnect() { if (producer != null) { try { producer.close(); } catch (JMSException e) { //ignore } } if (session != null) { try { session.close(); } catch (JMSException e) { //ignore } } if (connection != null) { try { connection.close(); } catch (JMSException e) { //ignore } } } /** * This will send the message to the destination Queue * * @param messageContent returns the message contents * @throws AutomationFrameworkException */
public void pushMessage(String messageContent) throws AutomationFrameworkException {
wso2/carbon-platform-integration
test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/extensions/ExecutionListenerExtension.java
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.extensions; public abstract class ExecutionListenerExtension extends ListenerExtension { private final Log log = LogFactory.getLog(getClass()); private final static String XPATH_TO_CLASS = "//listenerExtensions/platformExecutionManager/extentionClasses/class/name"; public ExecutionListenerExtension() { super(); try { setParameterMap(XPATH_TO_CLASS, getClass().getName()); } catch (Exception e) { log.warn("Failed to initializing the Extension Class"); log.error("Error initializing the Automation Context", e); } }
// Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/exceptions/AutomationFrameworkException.java // public class AutomationFrameworkException extends Exception { // public AutomationFrameworkException(String message) { // super(message); // } // // public AutomationFrameworkException(String message, Throwable e) { // super(message, e); // } // // public AutomationFrameworkException(Throwable e) { // super(e); // } // } // Path: test-automation-framework/org.wso2.carbon.automation.engine/src/main/java/org/wso2/carbon/automation/engine/extensions/ExecutionListenerExtension.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; /* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.automation.engine.extensions; public abstract class ExecutionListenerExtension extends ListenerExtension { private final Log log = LogFactory.getLog(getClass()); private final static String XPATH_TO_CLASS = "//listenerExtensions/platformExecutionManager/extentionClasses/class/name"; public ExecutionListenerExtension() { super(); try { setParameterMap(XPATH_TO_CLASS, getClass().getName()); } catch (Exception e) { log.warn("Failed to initializing the Extension Class"); log.error("Error initializing the Automation Context", e); } }
public abstract void initiate() throws AutomationFrameworkException;
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa;
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa;
private final Normalizer normalizer;
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final double[] breakpoints; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSize the size of the alphabet used to discretise the values */ public SymbolicAggregateApproximation(int segments, int alphabetSize) {
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final double[] breakpoints; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSize the size of the alphabet used to discretise the values */ public SymbolicAggregateApproximation(int segments, int alphabetSize) {
this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), new NormalDistributionDivider().getBreakpoints(alphabetSize));
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final double[] breakpoints; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSize the size of the alphabet used to discretise the values */ public SymbolicAggregateApproximation(int segments, int alphabetSize) {
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Symbolic Aggregate Approximation (SAX) algorithm. * <p> * Reference: * Jessica L., Keogh E., Lonardi S., Chiu B. (2003) * <i>A symbolic representation of time series, with implications for streaming algorithms</i> * </p> * * @since 0.5 */ public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = -2951279057715694424L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final double[] breakpoints; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSize the size of the alphabet used to discretise the values */ public SymbolicAggregateApproximation(int segments, int alphabetSize) {
this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), new NormalDistributionDivider().getBreakpoints(alphabetSize));
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/normalization/ZNormalizerTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.normalization; @RunWith(MockitoJUnitRunner.class) public class ZNormalizerTest { @InjectMocks private ZNormalizer normalizer; @Mock private Mean mean; @Mock private StandardDeviation standardDeviation; @Test public void testCalls() throws Exception { Mockito.when(mean.evaluate(ArgumentMatchers.any(double[].class))).thenReturn(3.0); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; normalizer.normalize(v); Mockito.verify(mean).evaluate(v); Mockito.verify(standardDeviation).evaluate(v, 3.0); } @Test public void testNormalize() throws Exception { normalizer = new ZNormalizer(); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; double aux = FastMath.sqrt(2); double[] expected = {-2 / aux, -1 / aux, 0, 1 / aux, 2 / aux}; double[] out = normalizer.normalize(v);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/normalization/ZNormalizerTest.java import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.normalization; @RunWith(MockitoJUnitRunner.class) public class ZNormalizerTest { @InjectMocks private ZNormalizer normalizer; @Mock private Mean mean; @Mock private StandardDeviation standardDeviation; @Test public void testCalls() throws Exception { Mockito.when(mean.evaluate(ArgumentMatchers.any(double[].class))).thenReturn(3.0); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; normalizer.normalize(v); Mockito.verify(mean).evaluate(v); Mockito.verify(standardDeviation).evaluate(v, 3.0); } @Test public void testNormalize() throws Exception { normalizer = new ZNormalizer(); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; double aux = FastMath.sqrt(2); double[] expected = {-2 / aux, -1 / aux, 0, 1 / aux, 2 / aux}; double[] out = normalizer.normalize(v);
Assert.assertArrayEquals(expected, out, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/exception/NumberIsNotDivisibleExceptionTest.java
// Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximation.java // public class PiecewiseAggregateApproximation implements GenericTransformer<double[], double[]> { // private static final long serialVersionUID = -8199587096227874425L; // private final int segments; // // /** // * Creates a new instance of this class. // * // * @param segments the number of segments // * @throws NumberIsTooSmallException if segments lower than 1 // */ // public PiecewiseAggregateApproximation(int segments) { // if (segments < 1) { // throw new NumberIsTooSmallException(segments, 1, true); // } // // this.segments = segments; // } // // @Override // public double[] transform(double[] values) { // int len = values.length; // if (len < segments) { // throw new ArrayLengthIsTooSmallException(len, segments, true); // } // // int modulo = len % segments; // double[] reducedValues = new double[segments]; // if (modulo == 0) { // int segmentSize = len / segments; // double sum = 0; // int n = 0; // for (int i = 0; i < len; i++) { // sum += values[i]; // if ((i + 1) % segmentSize == 0) { // reducedValues[n++] = sum / segmentSize; // if (n == segments) break; // sum = 0; // } // } // } else { // double segmentSize = len * 1.0 / segments; // int k = 0; // double sum = 0; // for (int i = 0; i < segments - 1; i++) { // double x = (i + 1) * segmentSize - 1; // // for (; k < x; k++) { // sum += values[k]; // } // // double delta = x - (int) x; // sum += delta * values[k]; // reducedValues[i] = sum / segmentSize; // // sum = (1 - delta) * values[k]; // k++; // } // // for (; k < len; k++) { // sum += values[k]; // } // reducedValues[segments - 1] = sum / segmentSize; // } // // return reducedValues; // } // // public int getSegments() { // return segments; // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.representation.PiecewiseAggregateApproximation;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; public class NumberIsNotDivisibleExceptionTest { @Test public void testGetFactor() throws Exception { try {
// Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximation.java // public class PiecewiseAggregateApproximation implements GenericTransformer<double[], double[]> { // private static final long serialVersionUID = -8199587096227874425L; // private final int segments; // // /** // * Creates a new instance of this class. // * // * @param segments the number of segments // * @throws NumberIsTooSmallException if segments lower than 1 // */ // public PiecewiseAggregateApproximation(int segments) { // if (segments < 1) { // throw new NumberIsTooSmallException(segments, 1, true); // } // // this.segments = segments; // } // // @Override // public double[] transform(double[] values) { // int len = values.length; // if (len < segments) { // throw new ArrayLengthIsTooSmallException(len, segments, true); // } // // int modulo = len % segments; // double[] reducedValues = new double[segments]; // if (modulo == 0) { // int segmentSize = len / segments; // double sum = 0; // int n = 0; // for (int i = 0; i < len; i++) { // sum += values[i]; // if ((i + 1) % segmentSize == 0) { // reducedValues[n++] = sum / segmentSize; // if (n == segments) break; // sum = 0; // } // } // } else { // double segmentSize = len * 1.0 / segments; // int k = 0; // double sum = 0; // for (int i = 0; i < segments - 1; i++) { // double x = (i + 1) * segmentSize - 1; // // for (; k < x; k++) { // sum += values[k]; // } // // double delta = x - (int) x; // sum += delta * values[k]; // reducedValues[i] = sum / segmentSize; // // sum = (1 - delta) * values[k]; // k++; // } // // for (; k < len; k++) { // sum += values[k]; // } // reducedValues[segments - 1] = sum / segmentSize; // } // // return reducedValues; // } // // public int getSegments() { // return segments; // } // } // Path: src/test/java/ro/hasna/ts/math/exception/NumberIsNotDivisibleExceptionTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.representation.PiecewiseAggregateApproximation; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; public class NumberIsNotDivisibleExceptionTest { @Test public void testGetFactor() throws Exception { try {
PiecewiseAggregateApproximation paa = new PiecewiseAggregateApproximation(4);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/StampTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class StampTransformerTest { @Test public void transform_withoutNormalization() { StampTransformer transformer = new StampTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/StampTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class StampTransformerTest { @Test public void transform_withoutNormalization() { StampTransformer transformer = new StampTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
MatrixProfile transform = transformer.transform(v);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/StampTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class StampTransformerTest { @Test public void transform_withoutNormalization() { StampTransformer transformer = new StampTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/StampTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class StampTransformerTest { @Test public void transform_withoutNormalization() { StampTransformer transformer = new StampTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage;
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage;
private final Normalizer normalizer;
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage; private final Normalizer normalizer; public DynamicTimeWarpingDistance() {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage; private final Normalizer normalizer; public DynamicTimeWarpingDistance() {
this(0.05, new ZNormalizer());
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // }
import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage; private final Normalizer normalizer; public DynamicTimeWarpingDistance() { this(0.05, new ZNormalizer()); } /** * Creates a new instance of this class with * * @param radiusPercentage Sakoe-Chiba Band width used to constraint the warping window * @param normalizer the normalizer (it can be null if the values were normalized) * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] */ public DynamicTimeWarpingDistance(double radiusPercentage, Normalizer normalizer) { if (radiusPercentage < 0 || radiusPercentage > 1) {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/DynamicTimeWarpingDistance.java import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.util.LocalizableMessages; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import java.util.Deque; import java.util.LinkedList; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Dynamic Time Warping. * <p> * Reference: * Wikipedia https://en.wikipedia.org/wiki/Dynamic_time_warping * </p> * * @since 0.10 */ public class DynamicTimeWarpingDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 1154818905340336905L; private final double radiusPercentage; private final Normalizer normalizer; public DynamicTimeWarpingDistance() { this(0.05, new ZNormalizer()); } /** * Creates a new instance of this class with * * @param radiusPercentage Sakoe-Chiba Band width used to constraint the warping window * @param normalizer the normalizer (it can be null if the values were normalized) * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] */ public DynamicTimeWarpingDistance(double radiusPercentage, Normalizer normalizer) { if (radiusPercentage < 0 || radiusPercentage > 1) {
throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/distribution/UniformDistributionDividerTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class UniformDistributionDividerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private UniformDistributionDivider divider; @Before public void setUp() throws Exception { divider = new UniformDistributionDivider(-1, 1); } @After public void tearDown() throws Exception { divider = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooLargeException.class); thrown.expectMessage("4 is larger than the maximum (3)"); new UniformDistributionDivider(4, 3); } @Test public void testGetBreakpointsWithException() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("1 is smaller than the minimum (2)"); divider.getBreakpoints(1); } @Test public void testGetBreakpoints1() throws Exception { double[] expected = {-1.0 / 3, 1.0 / 3}; double[] v = divider.getBreakpoints(3);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/distribution/UniformDistributionDividerTest.java import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class UniformDistributionDividerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private UniformDistributionDivider divider; @Before public void setUp() throws Exception { divider = new UniformDistributionDivider(-1, 1); } @After public void tearDown() throws Exception { divider = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooLargeException.class); thrown.expectMessage("4 is larger than the maximum (3)"); new UniformDistributionDivider(4, 3); } @Test public void testGetBreakpointsWithException() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("1 is smaller than the minimum (2)"); divider.getBreakpoints(1); } @Test public void testGetBreakpoints1() throws Exception { double[] expected = {-1.0 / 3, 1.0 / 3}; double[] v = divider.getBreakpoints(3);
Assert.assertArrayEquals(expected, v, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/SaxEuclideanDistance.java
// Path: src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java // public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { // private static final long serialVersionUID = -2951279057715694424L; // private final PiecewiseAggregateApproximation paa; // private final Normalizer normalizer; // private final double[] breakpoints; // // /** // * Creates a new instance of this class with a given number of segments and // * the size of the alphabet. // * // * @param segments the number of segments // * @param alphabetSize the size of the alphabet used to discretise the values // */ // public SymbolicAggregateApproximation(int segments, int alphabetSize) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), new NormalDistributionDivider().getBreakpoints(alphabetSize)); // } // // /** // * Creates a new instance of this class with a given number of segments and // * the breakpoints used to divide the distribution of the values. // * // * @param segments the number of segments // * @param breakpoints the list of values that divide the distribution of the values // * in equal areas of probability // */ // public SymbolicAggregateApproximation(int segments, double[] breakpoints) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), breakpoints); // } // // /** // * Creates a new instance of this class with a given PAA and normalizer algorithm and // * the breakpoints used to divide the distribution of the values. // * // * @param paa the Piecewise Aggregate Approximation algorithm // * @param normalizer the normalizer (it can be null if the values were normalized) // * @param breakpoints the list of values that divide the distribution of the values // * in equal areas of probability // */ // public SymbolicAggregateApproximation(PiecewiseAggregateApproximation paa, Normalizer normalizer, double[] breakpoints) { // this.paa = paa; // this.normalizer = normalizer; // this.breakpoints = breakpoints; // } // // /** // * Transform a given sequence of values using the SAX algorithm. // * // * @param values the sequence of values // * @return the result of the transformation // */ // public int[] transform(double[] values) { // double[] copy = paa.transform(values); // // // NOTE: mathematically the order of PAA and normalisation doesn't matter, the result is the same, // // but comparing the speed, running PAA and then normalisation is faster than in the reverse order // if (normalizer != null) { // copy = normalizer.normalize(copy); // } // // int n = 0; // int[] result = new int[copy.length]; // for (double item : copy) { // boolean found = false; // for (int i = 0; i < breakpoints.length && !found; i++) { // double breakpoint = breakpoints[i]; // if (breakpoint > item) { // result[n] = i; // found = true; // } // } // if (!found) { // result[n] = breakpoints.length; // } // n++; // } // // return result; // } // // public double[] getBreakpoints() { // return breakpoints; // } // }
import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.representation.SymbolicAggregateApproximation;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the L<sub>2</sub> (Euclidean) distance between two vectors using the SAX representation. * * @since 0.7 */ public class SaxEuclideanDistance implements GenericDistanceMeasure<int[]> { private static final long serialVersionUID = -2580188567848020545L;
// Path: src/main/java/ro/hasna/ts/math/representation/SymbolicAggregateApproximation.java // public class SymbolicAggregateApproximation implements GenericTransformer<double[], int[]> { // private static final long serialVersionUID = -2951279057715694424L; // private final PiecewiseAggregateApproximation paa; // private final Normalizer normalizer; // private final double[] breakpoints; // // /** // * Creates a new instance of this class with a given number of segments and // * the size of the alphabet. // * // * @param segments the number of segments // * @param alphabetSize the size of the alphabet used to discretise the values // */ // public SymbolicAggregateApproximation(int segments, int alphabetSize) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), new NormalDistributionDivider().getBreakpoints(alphabetSize)); // } // // /** // * Creates a new instance of this class with a given number of segments and // * the breakpoints used to divide the distribution of the values. // * // * @param segments the number of segments // * @param breakpoints the list of values that divide the distribution of the values // * in equal areas of probability // */ // public SymbolicAggregateApproximation(int segments, double[] breakpoints) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), breakpoints); // } // // /** // * Creates a new instance of this class with a given PAA and normalizer algorithm and // * the breakpoints used to divide the distribution of the values. // * // * @param paa the Piecewise Aggregate Approximation algorithm // * @param normalizer the normalizer (it can be null if the values were normalized) // * @param breakpoints the list of values that divide the distribution of the values // * in equal areas of probability // */ // public SymbolicAggregateApproximation(PiecewiseAggregateApproximation paa, Normalizer normalizer, double[] breakpoints) { // this.paa = paa; // this.normalizer = normalizer; // this.breakpoints = breakpoints; // } // // /** // * Transform a given sequence of values using the SAX algorithm. // * // * @param values the sequence of values // * @return the result of the transformation // */ // public int[] transform(double[] values) { // double[] copy = paa.transform(values); // // // NOTE: mathematically the order of PAA and normalisation doesn't matter, the result is the same, // // but comparing the speed, running PAA and then normalisation is faster than in the reverse order // if (normalizer != null) { // copy = normalizer.normalize(copy); // } // // int n = 0; // int[] result = new int[copy.length]; // for (double item : copy) { // boolean found = false; // for (int i = 0; i < breakpoints.length && !found; i++) { // double breakpoint = breakpoints[i]; // if (breakpoint > item) { // result[n] = i; // found = true; // } // } // if (!found) { // result[n] = breakpoints.length; // } // n++; // } // // return result; // } // // public double[] getBreakpoints() { // return breakpoints; // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/SaxEuclideanDistance.java import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.representation.SymbolicAggregateApproximation; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the L<sub>2</sub> (Euclidean) distance between two vectors using the SAX representation. * * @since 0.7 */ public class SaxEuclideanDistance implements GenericDistanceMeasure<int[]> { private static final long serialVersionUID = -2580188567848020545L;
private final SymbolicAggregateApproximation sax;
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
thrown.expect(ArrayLengthIsTooSmallException.class);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseAggregateApproximation paa = new PiecewiseAggregateApproximation(4); double[] v = {1, 2, 3}; paa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseAggregateApproximation paa = new PiecewiseAggregateApproximation(2); double[] v = {1, 2, 3, 4, 5, 6}; double[] expected = {2.0, 5.0}; double[] result = paa.transform(v);
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseAggregateApproximation paa = new PiecewiseAggregateApproximation(4); double[] v = {1, 2, 3}; paa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseAggregateApproximation paa = new PiecewiseAggregateApproximation(2); double[] v = {1, 2, 3, 4, 5, 6}; double[] expected = {2.0, 5.0}; double[] result = paa.transform(v);
Assert.assertArrayEquals(expected, result, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseCurveFitterApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); private AbstractCurveFitter curveFitter; private static void assertMatrixEquals(double[][] expected, double[][] actual, double precision) { Assert.assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; i++) { Assert.assertArrayEquals(expected[i], actual[i], precision); } } @Before public void setUp() throws Exception { curveFitter = PolynomialCurveFitter.create(0).withMaxIterations(2); } @After public void tearDown() throws Exception { curveFitter = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseCurveFitterApproximation(0, curveFitter); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseCurveFitterApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); private AbstractCurveFitter curveFitter; private static void assertMatrixEquals(double[][] expected, double[][] actual, double precision) { Assert.assertEquals(expected.length, actual.length); for (int i = 0; i < expected.length; i++) { Assert.assertArrayEquals(expected[i], actual[i], precision); } } @Before public void setUp() throws Exception { curveFitter = PolynomialCurveFitter.create(0).withMaxIterations(2); } @After public void tearDown() throws Exception { curveFitter = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseCurveFitterApproximation(0, curveFitter); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
thrown.expect(ArrayLengthIsTooSmallException.class);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
curveFitter = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseCurveFitterApproximation(0, curveFitter); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseCurveFitterApproximation pcfa = new PiecewiseCurveFitterApproximation(4, curveFitter); double[] v = {1, 2, 3}; pcfa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseCurveFitterApproximation pcfa = new PiecewiseCurveFitterApproximation(2, curveFitter); double[] v = {1, 2, 3, 4, 5, 6}; double[][] expected = {{2.0}, {5.0}}; double[][] result = pcfa.transform(v);
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; curveFitter = null; } @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseCurveFitterApproximation(0, curveFitter); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseCurveFitterApproximation pcfa = new PiecewiseCurveFitterApproximation(4, curveFitter); double[] v = {1, 2, 3}; pcfa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseCurveFitterApproximation pcfa = new PiecewiseCurveFitterApproximation(2, curveFitter); double[] v = {1, 2, 3, 4, 5, 6}; double[][] expected = {{2.0}, {5.0}}; double[][] result = pcfa.transform(v);
assertMatrixEquals(expected, result, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
thrown.expect(ArrayLengthIsTooSmallException.class);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3}; plaa.transform(v); } @Test public void testTransformSegmentsNotDivisible() throws Exception {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3}; plaa.transform(v); } @Test public void testTransformSegmentsNotDivisible() throws Exception {
thrown.expect(ArrayLengthIsNotDivisibleException.class);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3}; plaa.transform(v); } @Test public void testTransformSegmentsNotDivisible() throws Exception { thrown.expect(ArrayLengthIsNotDivisibleException.class); thrown.expectMessage("5 is not divisible with 4"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3, 4, 5}; plaa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(2); double[] v = {1, 2, 3, 3, 2, 1};
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // } // Path: src/test/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class PiecewiseLinearAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new PiecewiseLinearAggregateApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3}; plaa.transform(v); } @Test public void testTransformSegmentsNotDivisible() throws Exception { thrown.expect(ArrayLengthIsNotDivisibleException.class); thrown.expectMessage("5 is not divisible with 4"); PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(4); double[] v = {1, 2, 3, 4, 5}; plaa.transform(v); } @Test public void testTransformStrict() throws Exception { PiecewiseLinearAggregateApproximation plaa = new PiecewiseLinearAggregateApproximation(2); double[] v = {1, 2, 3, 3, 2, 1};
MeanSlopePair[] expected = {new MeanSlopePair(2.0, 1.0), new MeanSlopePair(2.0, -1.0)};
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/IndexableSaxEuclideanDistance.java
// Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java // public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { // private static final long serialVersionUID = -1652621695908903282L; // private final PiecewiseAggregateApproximation paa; // private final Normalizer normalizer; // private final DistributionDivider distributionDivider; // private final int[] alphabetSizes; // // /** // * Creates a new instance of this class with a given number of segments and // * the size of the alphabet. // * // * @param segments the number of segments // * @param alphabetSizes the size of the alphabet used to discretise the values for every segment // */ // public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), alphabetSizes, new NormalDistributionDivider()); // } // // // /** // * Creates a new instance of this class with a given PAA and normalizer algorithm and // * the breakpoints used to divide the distribution of the values. // * // * @param paa the Piecewise Aggregate Approximation algorithm // * @param normalizer the normalizer (it can be null if the values were normalized) // * @param alphabetSizes the size of the alphabet used to discretise the values for every segment // * @param distributionDivider the divider that gets the list of breakpoints (values that divide a // * distribution in equal areas of probability) // * @throws DimensionMismatchException if the number of segments is different than the length of alphabetSizes // */ // public IndexableSymbolicAggregateApproximation(PiecewiseAggregateApproximation paa, Normalizer normalizer, // int[] alphabetSizes, DistributionDivider distributionDivider) { // if (paa.getSegments() != alphabetSizes.length) { // throw new DimensionMismatchException(alphabetSizes.length, paa.getSegments()); // } // // this.paa = paa; // this.normalizer = normalizer; // this.alphabetSizes = alphabetSizes; // this.distributionDivider = distributionDivider; // } // // /** // * Transform a given sequence of values using the iSAX algorithm. // * // * @param values the sequence of values // * @return the result of the transformation // */ // public SaxPair[] transform(double[] values) { // double[] copy = paa.transform(values); // // // NOTE: mathematically the order of PAA and normalisation doesn't matter, the result is the same, // // but comparing the speed, running PAA and then normalisation is faster than in the reverse order // if (normalizer != null) { // copy = normalizer.normalize(copy); // } // // int n = 0; // int segments = copy.length; // SaxPair[] result = new SaxPair[segments]; // for (int i = 0; i < segments; i++) { // double item = copy[i]; // int alphabetSize = alphabetSizes[i]; // double[] breakpoints = distributionDivider.getBreakpoints(alphabetSize); // boolean found = false; // for (int j = 0; j < breakpoints.length && !found; j++) { // double breakpoint = breakpoints[j]; // if (breakpoint > item) { // result[n] = new SaxPair(j, alphabetSize); // found = true; // } // } // if (!found) { // result[n] = new SaxPair(breakpoints.length, alphabetSize); // } // n++; // } // // return result; // } // // public double[] getBreakpoints(int areas) { // return distributionDivider.getBreakpoints(areas); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.representation.IndexableSymbolicAggregateApproximation; import ro.hasna.ts.math.type.SaxPair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the L<sub>2</sub> (Euclidean) distance between two vectors using the iSAX representation. * * @since 0.7 */ public class IndexableSaxEuclideanDistance implements GenericDistanceMeasure<SaxPair[]> { private static final long serialVersionUID = -4740907293933039859L;
// Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java // public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { // private static final long serialVersionUID = -1652621695908903282L; // private final PiecewiseAggregateApproximation paa; // private final Normalizer normalizer; // private final DistributionDivider distributionDivider; // private final int[] alphabetSizes; // // /** // * Creates a new instance of this class with a given number of segments and // * the size of the alphabet. // * // * @param segments the number of segments // * @param alphabetSizes the size of the alphabet used to discretise the values for every segment // */ // public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) { // this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), alphabetSizes, new NormalDistributionDivider()); // } // // // /** // * Creates a new instance of this class with a given PAA and normalizer algorithm and // * the breakpoints used to divide the distribution of the values. // * // * @param paa the Piecewise Aggregate Approximation algorithm // * @param normalizer the normalizer (it can be null if the values were normalized) // * @param alphabetSizes the size of the alphabet used to discretise the values for every segment // * @param distributionDivider the divider that gets the list of breakpoints (values that divide a // * distribution in equal areas of probability) // * @throws DimensionMismatchException if the number of segments is different than the length of alphabetSizes // */ // public IndexableSymbolicAggregateApproximation(PiecewiseAggregateApproximation paa, Normalizer normalizer, // int[] alphabetSizes, DistributionDivider distributionDivider) { // if (paa.getSegments() != alphabetSizes.length) { // throw new DimensionMismatchException(alphabetSizes.length, paa.getSegments()); // } // // this.paa = paa; // this.normalizer = normalizer; // this.alphabetSizes = alphabetSizes; // this.distributionDivider = distributionDivider; // } // // /** // * Transform a given sequence of values using the iSAX algorithm. // * // * @param values the sequence of values // * @return the result of the transformation // */ // public SaxPair[] transform(double[] values) { // double[] copy = paa.transform(values); // // // NOTE: mathematically the order of PAA and normalisation doesn't matter, the result is the same, // // but comparing the speed, running PAA and then normalisation is faster than in the reverse order // if (normalizer != null) { // copy = normalizer.normalize(copy); // } // // int n = 0; // int segments = copy.length; // SaxPair[] result = new SaxPair[segments]; // for (int i = 0; i < segments; i++) { // double item = copy[i]; // int alphabetSize = alphabetSizes[i]; // double[] breakpoints = distributionDivider.getBreakpoints(alphabetSize); // boolean found = false; // for (int j = 0; j < breakpoints.length && !found; j++) { // double breakpoint = breakpoints[j]; // if (breakpoint > item) { // result[n] = new SaxPair(j, alphabetSize); // found = true; // } // } // if (!found) { // result[n] = new SaxPair(breakpoints.length, alphabetSize); // } // n++; // } // // return result; // } // // public double[] getBreakpoints(int areas) { // return distributionDivider.getBreakpoints(areas); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/IndexableSaxEuclideanDistance.java import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.representation.IndexableSymbolicAggregateApproximation; import ro.hasna.ts.math.type.SaxPair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the L<sub>2</sub> (Euclidean) distance between two vectors using the iSAX representation. * * @since 0.7 */ public class IndexableSaxEuclideanDistance implements GenericDistanceMeasure<SaxPair[]> { private static final long serialVersionUID = -4740907293933039859L;
private final IndexableSymbolicAggregateApproximation isax;
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/type/TesparSymbolTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NotPositiveException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class TesparSymbolTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructorException() throws Exception { thrown.expect(NotPositiveException.class); thrown.expectMessage("-5.5 is smaller than the minimum (0)"); new TesparSymbol(10, 3, -5.5); } @Test public void testGetters() throws Exception { TesparSymbol symbol = new TesparSymbol(10, 3, 5.5); Assert.assertEquals(10, symbol.getDuration()); Assert.assertEquals(3, symbol.getShape());
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/type/TesparSymbolTest.java import org.apache.commons.math3.exception.NotPositiveException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.type; public class TesparSymbolTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructorException() throws Exception { thrown.expect(NotPositiveException.class); thrown.expectMessage("-5.5 is smaller than the minimum (0)"); new TesparSymbol(10, 3, -5.5); } @Test public void testGetters() throws Exception { TesparSymbol symbol = new TesparSymbol(10, 3, 5.5); Assert.assertEquals(10, symbol.getDuration()); Assert.assertEquals(3, symbol.getShape());
Assert.assertEquals(5.5, symbol.getAmplitude(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/StampTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import org.apache.commons.math3.complex.Complex; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STAMP algorithm to compute the self join matrix profile. * <p> * Reference: * Yeh C. C. M., Zhu Y., Ulanova L., Begum N., Ding Y., Dau H. A., Keogh E. (2016, December) * <i>Matrix profile I: all pairs similarity joins for time series: a unifying view that includes motifs, discords and shapelets</i> * </p> * * @since 0.17 */ public class StampTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 5919724985496947961L; public StampTransformer(int window) { super(window); } public StampTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/StampTransformer.java import org.apache.commons.math3.complex.Complex; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STAMP algorithm to compute the self join matrix profile. * <p> * Reference: * Yeh C. C. M., Zhu Y., Ulanova L., Begum N., Ding Y., Dau H. A., Keogh E. (2016, December) * <i>Matrix profile I: all pairs similarity joins for time series: a unifying view that includes motifs, discords and shapelets</i> * </p> * * @since 0.17 */ public class StampTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 5919724985496947961L; public StampTransformer(int window) { super(window); } public StampTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/StampTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import org.apache.commons.math3.complex.Complex; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; int[] indices = generateRandomIndices(n); for (int i = 0; i < n; i++) { int index = indices[i]; computeDistanceProfileWithProductSums(input, index, input, skip, n, distanceProfile); updateMatrixProfileFromDistanceProfile(distanceProfile, n, index, mp, callback); } updateMatrixProfileWithSqrt(mp); return mp; } protected void computeDistanceProfileWithProductSums(double[] a, int i, double[] b, int skip, int nb, double[] distanceProfile) { for (int j = 0; j < nb; j++) { if (inExclusionZone(i, j, skip)) { distanceProfile[j] = Double.POSITIVE_INFINITY; } else { double distance = 0; for (int k = 0; k < window; k++) { distance += (a[k + i] - b[k + j]) * (a[k + i] - b[k + j]); } distanceProfile[j] = distance; } } } protected void computeNormalizedDistanceProfileWithFft(double[] a, int i, double[] b, int skip, int nb, double[] distanceProfile) {
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/StampTransformer.java import org.apache.commons.math3.complex.Complex; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; int[] indices = generateRandomIndices(n); for (int i = 0; i < n; i++) { int index = indices[i]; computeDistanceProfileWithProductSums(input, index, input, skip, n, distanceProfile); updateMatrixProfileFromDistanceProfile(distanceProfile, n, index, mp, callback); } updateMatrixProfileWithSqrt(mp); return mp; } protected void computeDistanceProfileWithProductSums(double[] a, int i, double[] b, int skip, int nb, double[] distanceProfile) { for (int j = 0; j < nb; j++) { if (inExclusionZone(i, j, skip)) { distanceProfile[j] = Double.POSITIVE_INFINITY; } else { double distance = 0; for (int k = 0; k < window; k++) { distance += (a[k + i] - b[k + j]) * (a[k + i] - b[k + j]); } distanceProfile[j] = distance; } } } protected void computeNormalizedDistanceProfileWithFft(double[] a, int i, double[] b, int skip, int nb, double[] distanceProfile) {
BothWaySummaryStatistics first = new BothWaySummaryStatistics();
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/UniformScalingDistance.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.util.TimeSeriesPrecision;
this.minScalingFactor = minScalingFactor; if (maxScalingFactor < minScalingFactor) { throw new NumberIsTooSmallException(maxScalingFactor, minScalingFactor, true); } this.maxScalingFactor = maxScalingFactor; if (steps < 1) { throw new NumberIsTooSmallException(steps, 1, true); } this.steps = steps; this.distance = distance; } @Override public double compute(double[] a, double[] b) { return compute(a, b, Double.POSITIVE_INFINITY); } @Override public double compute(double[] a, double[] b, double cutOffValue) { double min = Double.POSITIVE_INFINITY; double[] aux = new double[a.length]; if (steps == 1) { double scalingFactor = (minScalingFactor + maxScalingFactor) / 2; return computeDistance(a, b, aux, scalingFactor, cutOffValue); } double interval = (maxScalingFactor - minScalingFactor) / (steps - 1);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/UniformScalingDistance.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.util.TimeSeriesPrecision; this.minScalingFactor = minScalingFactor; if (maxScalingFactor < minScalingFactor) { throw new NumberIsTooSmallException(maxScalingFactor, minScalingFactor, true); } this.maxScalingFactor = maxScalingFactor; if (steps < 1) { throw new NumberIsTooSmallException(steps, 1, true); } this.steps = steps; this.distance = distance; } @Override public double compute(double[] a, double[] b) { return compute(a, b, Double.POSITIVE_INFINITY); } @Override public double compute(double[] a, double[] b, double cutOffValue) { double min = Double.POSITIVE_INFINITY; double[] aux = new double[a.length]; if (steps == 1) { double scalingFactor = (minScalingFactor + maxScalingFactor) / 2; return computeDistance(a, b, aux, scalingFactor, cutOffValue); } double interval = (maxScalingFactor - minScalingFactor) / (steps - 1);
if (Precision.equals(interval, 0.0, TimeSeriesPrecision.EPSILON)) {
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/filter/MovingAverageFilterTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.filter; public class MovingAverageFilterTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor1() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("0 != 5"); new MovingAverageFilter(2, true, new double[]{}); } @Test public void testConstructor2() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("0 != 2"); new MovingAverageFilter(2, false, new double[]{}); } @Test public void testFilterSymmetricWithoutWeights() throws Exception { double[] v = {1, 1, 2, 2, 3, 3, 4, 4, 5}; double[] expected = {1, 1, 1.8, 2.2, 2.8, 3.2, 3.8, 4, 5}; Filter filter = new MovingAverageFilter(2); double[] result = filter.filter(v);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/filter/MovingAverageFilterTest.java import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.filter; public class MovingAverageFilterTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor1() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("0 != 5"); new MovingAverageFilter(2, true, new double[]{}); } @Test public void testConstructor2() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("0 != 2"); new MovingAverageFilter(2, false, new double[]{}); } @Test public void testFilterSymmetricWithoutWeights() throws Exception { double[] v = {1, 1, 2, 2, 3, 3, 4, 4, 5}; double[] expected = {1, 1, 1.8, 2.2, 2.8, 3.2, 3.8, 4, 5}; Filter filter = new MovingAverageFilter(2); double[] result = filter.filter(v);
Assert.assertArrayEquals(expected, result, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa;
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa;
private final Normalizer normalizer;
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer;
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer;
private final DistributionDivider distributionDivider;
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final DistributionDivider distributionDivider; private final int[] alphabetSizes; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSizes the size of the alphabet used to discretise the values for every segment */ public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) {
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final DistributionDivider distributionDivider; private final int[] alphabetSizes; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSizes the size of the alphabet used to discretise the values for every segment */ public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) {
this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), alphabetSizes, new NormalDistributionDivider());
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final DistributionDivider distributionDivider; private final int[] alphabetSizes; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSizes the size of the alphabet used to discretise the values for every segment */ public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) {
// Path: src/main/java/ro/hasna/ts/math/distribution/DistributionDivider.java // public interface DistributionDivider extends Serializable { // /** // * Get the breakpoints for dividing the distribution in equal areas of probability. // * NOTE: the breakpoints are in ascending order. // * // * @param areas the number of areas // * @return the list of breakpoints // * @throws NumberIsTooSmallException if areas is smaller than 2 // */ // double[] getBreakpoints(int areas); // } // // Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/Normalizer.java // public interface Normalizer extends Serializable { // /** // * Normalize the sequence of values. // * NOTE: The length of the output array should be equal to the input array. // * // * @param values the sequence of values // * @return the normalized sequence // */ // double[] normalize(double[] values); // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/main/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximation.java import org.apache.commons.math3.exception.DimensionMismatchException; import ro.hasna.ts.math.distribution.DistributionDivider; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.Normalizer; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Indexable Symbolic Aggregate Approximation (iSAX) algorithm. * <p> * Reference: * Camerra A., Palpanas T., Shieh J., Keogh E. (2010) * <i>iSAX 2.0: Indexing and mining one billion time series</i> * </p> * * @since 0.7 */ public class IndexableSymbolicAggregateApproximation implements GenericTransformer<double[], SaxPair[]> { private static final long serialVersionUID = -1652621695908903282L; private final PiecewiseAggregateApproximation paa; private final Normalizer normalizer; private final DistributionDivider distributionDivider; private final int[] alphabetSizes; /** * Creates a new instance of this class with a given number of segments and * the size of the alphabet. * * @param segments the number of segments * @param alphabetSizes the size of the alphabet used to discretise the values for every segment */ public IndexableSymbolicAggregateApproximation(int segments, int[] alphabetSizes) {
this(new PiecewiseAggregateApproximation(segments), new ZNormalizer(), alphabetSizes, new NormalDistributionDivider());
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/TesparDzCoding.java
// Path: src/main/java/ro/hasna/ts/math/type/TesparSymbol.java // @Data // public class TesparSymbol { // private final int duration; // private final int shape; // private final double amplitude; // // /** // * Create a TESPAR symbol. // * // * @param duration the number of samples between two successive real zeros (one epoch) // * @param shape the number of local minimums (for a positive epoch) or // * the number of local maximums (for a negative epoch) // * @param amplitude the amplitude of the epoch // */ // public TesparSymbol(int duration, int shape, double amplitude) { // this.duration = duration; // this.shape = shape; // if (amplitude < 0) { // throw new NotPositiveException(amplitude); // } // this.amplitude = amplitude; // } // }
import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.type.TesparSymbol;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Time Encoding Signal Processing and Recognition (TESPAR) coding method. * <p> * Reference: * King R.A., Phipps T.C. (1998) * <i>Shannon, TESPAR And Approximation Strategies</i> * </p> * * @since 0.7 */ public class TesparDzCoding implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = 7734158131264856074L; @Override public int[] transform(double[] values) {
// Path: src/main/java/ro/hasna/ts/math/type/TesparSymbol.java // @Data // public class TesparSymbol { // private final int duration; // private final int shape; // private final double amplitude; // // /** // * Create a TESPAR symbol. // * // * @param duration the number of samples between two successive real zeros (one epoch) // * @param shape the number of local minimums (for a positive epoch) or // * the number of local maximums (for a negative epoch) // * @param amplitude the amplitude of the epoch // */ // public TesparSymbol(int duration, int shape, double amplitude) { // this.duration = duration; // this.shape = shape; // if (amplitude < 0) { // throw new NotPositiveException(amplitude); // } // this.amplitude = amplitude; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/TesparDzCoding.java import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.type.TesparSymbol; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Time Encoding Signal Processing and Recognition (TESPAR) coding method. * <p> * Reference: * King R.A., Phipps T.C. (1998) * <i>Shannon, TESPAR And Approximation Strategies</i> * </p> * * @since 0.7 */ public class TesparDzCoding implements GenericTransformer<double[], int[]> { private static final long serialVersionUID = 7734158131264856074L; @Override public int[] transform(double[] values) {
TesparSymbol[] symbols = getTesparSymbols(values);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/DiscreteHaarWaveletTransformTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class DiscreteHaarWaveletTransformTest { private DiscreteHaarWaveletTransform waveletTransform; @Before public void setUp() throws Exception { waveletTransform = new DiscreteHaarWaveletTransform(); } @After public void tearDown() throws Exception { waveletTransform = null; } @Test public void testTransform() throws Exception { double[] v = {1, 2, 1, 0, -1, -2, -1, 0}; double[] result = waveletTransform.transform(v); double[] expected = {0, 8, 2, -2, -1, 1, 1, -1};
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/DiscreteHaarWaveletTransformTest.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class DiscreteHaarWaveletTransformTest { private DiscreteHaarWaveletTransform waveletTransform; @Before public void setUp() throws Exception { waveletTransform = new DiscreteHaarWaveletTransform(); } @After public void tearDown() throws Exception { waveletTransform = null; } @Test public void testTransform() throws Exception { double[] v = {1, 2, 1, 0, -1, -2, -1, 0}; double[] result = waveletTransform.transform(v); double[] expected = {0, 8, 2, -2, -1, 1, 1, -1};
Assert.assertArrayEquals(expected, result, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/exception/NumberIsNotDivisibleException.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // }
import org.apache.commons.math3.exception.MathIllegalNumberException; import org.apache.commons.math3.exception.util.Localizable; import ro.hasna.ts.math.exception.util.LocalizableMessages;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; /** * Exception to be thrown when a number is not divisible with a given factor. * * @since 0.3 */ public class NumberIsNotDivisibleException extends MathIllegalNumberException { private static final long serialVersionUID = -3573144648031073903L; /** * The factor for the number. */ private final Integer factor; /** * Construct the exception. * * @param wrong Value that is not divisible with the factor. * @param factor The factor. */ public NumberIsNotDivisibleException(Number wrong, Integer factor) {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // Path: src/main/java/ro/hasna/ts/math/exception/NumberIsNotDivisibleException.java import org.apache.commons.math3.exception.MathIllegalNumberException; import org.apache.commons.math3.exception.util.Localizable; import ro.hasna.ts.math.exception.util.LocalizableMessages; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; /** * Exception to be thrown when a number is not divisible with a given factor. * * @since 0.3 */ public class NumberIsNotDivisibleException extends MathIllegalNumberException { private static final long serialVersionUID = -3573144648031073903L; /** * The factor for the number. */ private final Integer factor; /** * Construct the exception. * * @param wrong Value that is not divisible with the factor. * @param factor The factor. */ public NumberIsNotDivisibleException(Number wrong, Integer factor) {
this(LocalizableMessages.NUMBER_NOT_DIVISIBLE_WITH, wrong, factor);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Aggregate Approximation (PAA) algorithm. * <p> * Reference: * Keogh E., Chakrabarti K., Pazzani M., Mehrotra S. (2001) * <i>Locally Adaptive Dimensionality Reduction for Indexing Large Time Series Databases </i> * </p> * * @since 0.5 */ public class PiecewiseAggregateApproximation implements GenericTransformer<double[], double[]> { private static final long serialVersionUID = -8199587096227874425L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } @Override public double[] transform(double[] values) { int len = values.length; if (len < segments) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseAggregateApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Aggregate Approximation (PAA) algorithm. * <p> * Reference: * Keogh E., Chakrabarti K., Pazzani M., Mehrotra S. (2001) * <i>Locally Adaptive Dimensionality Reduction for Indexing Large Time Series Databases </i> * </p> * * @since 0.5 */ public class PiecewiseAggregateApproximation implements GenericTransformer<double[], double[]> { private static final long serialVersionUID = -8199587096227874425L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } @Override public double[] transform(double[] values) { int len = values.length; if (len < segments) {
throw new ArrayLengthIsTooSmallException(len, segments, true);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class MatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new MatrixProfileTransformer(0); } @Test public void transform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).transform(new double[5], new double[3]); } @Test public void fullJoinTransform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).fullJoinTransform(new double[5], new double[3]); } @Test public void transform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18};
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class MatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new MatrixProfileTransformer(0); } @Test public void transform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).transform(new double[5], new double[3]); } @Test public void fullJoinTransform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).fullJoinTransform(new double[5], new double[3]); } @Test public void transform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18};
MatrixProfile transform = transformer.transform(v, v2);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class MatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new MatrixProfileTransformer(0); } @Test public void transform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).transform(new double[5], new double[3]); } @Test public void fullJoinTransform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).fullJoinTransform(new double[5], new double[3]); } @Test public void transform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {1.4142135623730951, 46.05431575867782, 3.1622776601683795, 3.3166247903554}; int[] expectedIp = {0, 0, 6, 7};
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class MatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new MatrixProfileTransformer(0); } @Test public void transform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).transform(new double[5], new double[3]); } @Test public void fullJoinTransform_withSmallInput() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new MatrixProfileTransformer(4).fullJoinTransform(new double[5], new double[3]); } @Test public void transform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {1.4142135623730951, 46.05431575867782, 3.1622776601683795, 3.3166247903554}; int[] expectedIp = {0, 0, 6, 7};
Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {1.4142135623730951, 46.05431575867782, 3.1622776601683795, 3.3166247903554}; int[] expectedIp = {0, 0, 6, 7}; Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON); Assert.assertArrayEquals(expectedIp, transform.getIndexProfile()); } @Test public void transform_withNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {0.5257667760397134, 0.0970386144176177, 0.12392968870054807, 0.16907943342270723}; int[] expectedIp = {1, 1, 6, 7}; Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON); Assert.assertArrayEquals(expectedIp, transform.getIndexProfile()); } @Test public void fullJoinTransform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18};
// Path: src/main/java/ro/hasna/ts/math/type/FullMatrixProfile.java // @Data // public class FullMatrixProfile { // private final MatrixProfile leftMatrixProfile; // private final MatrixProfile rightMatrixProfile; // // public FullMatrixProfile(MatrixProfile leftMatrixProfile, MatrixProfile rightMatrixProfile) { // this.leftMatrixProfile = leftMatrixProfile; // this.rightMatrixProfile = rightMatrixProfile; // } // // public FullMatrixProfile(int leftSize, int rightSize) { // this(new MatrixProfile(leftSize), new MatrixProfile(rightSize)); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/MatrixProfileTransformerTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.FullMatrixProfile; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {1.4142135623730951, 46.05431575867782, 3.1622776601683795, 3.3166247903554}; int[] expectedIp = {0, 0, 6, 7}; Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON); Assert.assertArrayEquals(expectedIp, transform.getIndexProfile()); } @Test public void transform_withNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18}; MatrixProfile transform = transformer.transform(v, v2); double[] expectedMp = {0.5257667760397134, 0.0970386144176177, 0.12392968870054807, 0.16907943342270723}; int[] expectedIp = {1, 1, 6, 7}; Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON); Assert.assertArrayEquals(expectedIp, transform.getIndexProfile()); } @Test public void fullJoinTransform_withoutNormalization() throws Exception { MatrixProfileTransformer transformer = new MatrixProfileTransformer(4, 0, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 49, 25, 19}; double[] v2 = {1, 2, 2, 5, 50, 25, 18};
FullMatrixProfile transform = transformer.fullJoinTransform(v, v2);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/StompTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java // public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { // private static final long serialVersionUID = 4542559569313251930L; // private final double epsilon; // private final double radiusPercentage; // // /** // * Creates a new instance of this class with // * // * @param epsilon the maximum absolute difference between two values that are considered equal // * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window // * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] // */ // public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { // this.epsilon = epsilon; // if (radiusPercentage < 0 || radiusPercentage > 1) { // throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1); // } // // this.radiusPercentage = radiusPercentage; // } // // @Override // public double compute(double[] a, double[] b) { // return compute(a, b, Double.POSITIVE_INFINITY); // } // // @Override // public double compute(double[] a, double[] b, double cutOffValue) { // int n = a.length; // int radius = (int) (n * radiusPercentage); // double min = -1; // if (cutOffValue < 1) { // min = n * (1 - cutOffValue); // } // // int lcs = computeLcs(a, b, n, radius, min); // if (lcs == -1) { // return Double.POSITIVE_INFINITY; // } // // return 1 - lcs * 1.0 / n; // } // // private int computeLcs(double[] a, double[] b, int n, int radius, double min) { // min = min - n + 1; // // int w = 2 * radius + 1; // int[] prev = new int[w]; // int[] current = new int[w]; // int start, end, x, y, k = 0; // for (int i = 0; i < n; i++) { // k = FastMath.max(0, radius - i); // start = FastMath.max(0, i - radius); // end = FastMath.min(n - 1, i + radius); // for (int j = start; j <= end; j++, k++) { // if (Precision.equals(a[i], b[j], epsilon)) { // current[k] = prev[k] + 1; // } else { // if (k - 1 >= 0) x = current[k - 1]; // else x = 0; // // if (k + 1 < w) y = prev[k + 1]; // else y = 0; // // current[k] = FastMath.max(x, y); // } // } // // if (current[k - 1] - i <= min) { // return -1; // } // // System.arraycopy(current, 0, prev, 0, w); // } // // return current[k - 1]; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.ml.distance.LongestCommonSubsequenceDistance; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Locale; import java.util.Scanner;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * @since 0.17 */ public class StompTransformerTest { @Test public void transform_withoutNormalization() { StompTransformer transformer = new StompTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
// Path: src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java // public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { // private static final long serialVersionUID = 4542559569313251930L; // private final double epsilon; // private final double radiusPercentage; // // /** // * Creates a new instance of this class with // * // * @param epsilon the maximum absolute difference between two values that are considered equal // * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window // * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] // */ // public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { // this.epsilon = epsilon; // if (radiusPercentage < 0 || radiusPercentage > 1) { // throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1); // } // // this.radiusPercentage = radiusPercentage; // } // // @Override // public double compute(double[] a, double[] b) { // return compute(a, b, Double.POSITIVE_INFINITY); // } // // @Override // public double compute(double[] a, double[] b, double cutOffValue) { // int n = a.length; // int radius = (int) (n * radiusPercentage); // double min = -1; // if (cutOffValue < 1) { // min = n * (1 - cutOffValue); // } // // int lcs = computeLcs(a, b, n, radius, min); // if (lcs == -1) { // return Double.POSITIVE_INFINITY; // } // // return 1 - lcs * 1.0 / n; // } // // private int computeLcs(double[] a, double[] b, int n, int radius, double min) { // min = min - n + 1; // // int w = 2 * radius + 1; // int[] prev = new int[w]; // int[] current = new int[w]; // int start, end, x, y, k = 0; // for (int i = 0; i < n; i++) { // k = FastMath.max(0, radius - i); // start = FastMath.max(0, i - radius); // end = FastMath.min(n - 1, i + radius); // for (int j = start; j <= end; j++, k++) { // if (Precision.equals(a[i], b[j], epsilon)) { // current[k] = prev[k] + 1; // } else { // if (k - 1 >= 0) x = current[k - 1]; // else x = 0; // // if (k + 1 < w) y = prev[k + 1]; // else y = 0; // // current[k] = FastMath.max(x, y); // } // } // // if (current[k - 1] - i <= min) { // return -1; // } // // System.arraycopy(current, 0, prev, 0, w); // } // // return current[k - 1]; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/StompTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.ml.distance.LongestCommonSubsequenceDistance; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Locale; import java.util.Scanner; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * @since 0.17 */ public class StompTransformerTest { @Test public void transform_withoutNormalization() { StompTransformer transformer = new StompTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
MatrixProfile transform = transformer.transform(v);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/StompTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java // public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { // private static final long serialVersionUID = 4542559569313251930L; // private final double epsilon; // private final double radiusPercentage; // // /** // * Creates a new instance of this class with // * // * @param epsilon the maximum absolute difference between two values that are considered equal // * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window // * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] // */ // public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { // this.epsilon = epsilon; // if (radiusPercentage < 0 || radiusPercentage > 1) { // throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1); // } // // this.radiusPercentage = radiusPercentage; // } // // @Override // public double compute(double[] a, double[] b) { // return compute(a, b, Double.POSITIVE_INFINITY); // } // // @Override // public double compute(double[] a, double[] b, double cutOffValue) { // int n = a.length; // int radius = (int) (n * radiusPercentage); // double min = -1; // if (cutOffValue < 1) { // min = n * (1 - cutOffValue); // } // // int lcs = computeLcs(a, b, n, radius, min); // if (lcs == -1) { // return Double.POSITIVE_INFINITY; // } // // return 1 - lcs * 1.0 / n; // } // // private int computeLcs(double[] a, double[] b, int n, int radius, double min) { // min = min - n + 1; // // int w = 2 * radius + 1; // int[] prev = new int[w]; // int[] current = new int[w]; // int start, end, x, y, k = 0; // for (int i = 0; i < n; i++) { // k = FastMath.max(0, radius - i); // start = FastMath.max(0, i - radius); // end = FastMath.min(n - 1, i + radius); // for (int j = start; j <= end; j++, k++) { // if (Precision.equals(a[i], b[j], epsilon)) { // current[k] = prev[k] + 1; // } else { // if (k - 1 >= 0) x = current[k - 1]; // else x = 0; // // if (k + 1 < w) y = prev[k + 1]; // else y = 0; // // current[k] = FastMath.max(x, y); // } // } // // if (current[k - 1] - i <= min) { // return -1; // } // // System.arraycopy(current, 0, prev, 0, w); // } // // return current[k - 1]; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.ml.distance.LongestCommonSubsequenceDistance; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Locale; import java.util.Scanner;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * @since 0.17 */ public class StompTransformerTest { @Test public void transform_withoutNormalization() { StompTransformer transformer = new StompTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
// Path: src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java // public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { // private static final long serialVersionUID = 4542559569313251930L; // private final double epsilon; // private final double radiusPercentage; // // /** // * Creates a new instance of this class with // * // * @param epsilon the maximum absolute difference between two values that are considered equal // * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window // * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] // */ // public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { // this.epsilon = epsilon; // if (radiusPercentage < 0 || radiusPercentage > 1) { // throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1); // } // // this.radiusPercentage = radiusPercentage; // } // // @Override // public double compute(double[] a, double[] b) { // return compute(a, b, Double.POSITIVE_INFINITY); // } // // @Override // public double compute(double[] a, double[] b, double cutOffValue) { // int n = a.length; // int radius = (int) (n * radiusPercentage); // double min = -1; // if (cutOffValue < 1) { // min = n * (1 - cutOffValue); // } // // int lcs = computeLcs(a, b, n, radius, min); // if (lcs == -1) { // return Double.POSITIVE_INFINITY; // } // // return 1 - lcs * 1.0 / n; // } // // private int computeLcs(double[] a, double[] b, int n, int radius, double min) { // min = min - n + 1; // // int w = 2 * radius + 1; // int[] prev = new int[w]; // int[] current = new int[w]; // int start, end, x, y, k = 0; // for (int i = 0; i < n; i++) { // k = FastMath.max(0, radius - i); // start = FastMath.max(0, i - radius); // end = FastMath.min(n - 1, i + radius); // for (int j = start; j <= end; j++, k++) { // if (Precision.equals(a[i], b[j], epsilon)) { // current[k] = prev[k] + 1; // } else { // if (k - 1 >= 0) x = current[k - 1]; // else x = 0; // // if (k + 1 < w) y = prev[k + 1]; // else y = 0; // // current[k] = FastMath.max(x, y); // } // } // // if (current[k - 1] - i <= min) { // return -1; // } // // System.arraycopy(current, 0, prev, 0, w); // } // // return current[k - 1]; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/StompTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.ml.distance.LongestCommonSubsequenceDistance; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Locale; import java.util.Scanner; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * @since 0.17 */ public class StompTransformerTest { @Test public void transform_withoutNormalization() { StompTransformer transformer = new StompTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/DiscreteFourierTransformTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision;
} @Test public void testTransformSineWave() throws Exception { double signalFrequency = 100; double amplitude = 30; double displacement = 17; double samplingFrequency = signalFrequency * 8; //it should be at least double (Shannon Theorem) int len = 1000; double[] v = new double[len]; for (int i = 0; i < len; i++) { v[i] = amplitude * Math.sin(2 * Math.PI * signalFrequency * i / samplingFrequency) + displacement; } double[] result = new DiscreteFourierTransform().transform(v); double max = 0; int pos = 0; for (int i = 1; i < result.length; i++) { if (max < result[i]) { max = result[i]; pos = i; } } int powerOfTwo = Integer.highestOneBit(len); if (len != powerOfTwo) { powerOfTwo = powerOfTwo << 1; }
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/DiscreteFourierTransformTest.java import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision; } @Test public void testTransformSineWave() throws Exception { double signalFrequency = 100; double amplitude = 30; double displacement = 17; double samplingFrequency = signalFrequency * 8; //it should be at least double (Shannon Theorem) int len = 1000; double[] v = new double[len]; for (int i = 0; i < len; i++) { v[i] = amplitude * Math.sin(2 * Math.PI * signalFrequency * i / samplingFrequency) + displacement; } double[] result = new DiscreteFourierTransform().transform(v); double max = 0; int pos = 0; for (int i = 1; i < result.length; i++) { if (max < result[i]) { max = result[i]; pos = i; } } int powerOfTwo = Integer.highestOneBit(len); if (len != powerOfTwo) { powerOfTwo = powerOfTwo << 1; }
Assert.assertEquals(amplitude, max, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.ArrayList; import java.util.List;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements Piecewise Approximation using a curve fitting function (ex: linear = PLA, quadratic = PQA etc.). * An optimised implementation for the mean function is the class {@code PiecewiseAggregateApproximation}. * * @since 0.10 */ public class PiecewiseCurveFitterApproximation implements GenericTransformer<double[], double[][]> { private static final long serialVersionUID = -410430777798956046L; private final int segments; private final AbstractCurveFitter curveFitter; /** * Creates a new instance of this class. * * @param segments the number of segments * @param curveFitter the curve fitting function * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseCurveFitterApproximation(int segments, AbstractCurveFitter curveFitter) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; this.curveFitter = curveFitter; } @Override public double[][] transform(double[] values) { int len = values.length; if (len < segments) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.ArrayList; import java.util.List; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements Piecewise Approximation using a curve fitting function (ex: linear = PLA, quadratic = PQA etc.). * An optimised implementation for the mean function is the class {@code PiecewiseAggregateApproximation}. * * @since 0.10 */ public class PiecewiseCurveFitterApproximation implements GenericTransformer<double[], double[][]> { private static final long serialVersionUID = -410430777798956046L; private final int segments; private final AbstractCurveFitter curveFitter; /** * Creates a new instance of this class. * * @param segments the number of segments * @param curveFitter the curve fitting function * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseCurveFitterApproximation(int segments, AbstractCurveFitter curveFitter) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; this.curveFitter = curveFitter; } @Override public double[][] transform(double[] values) { int len = values.length; if (len < segments) {
throw new ArrayLengthIsTooSmallException(len, segments, true);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.ArrayList; import java.util.List;
List<WeightedObservedPoint> segment = new ArrayList<>(segmentSize); for (int i = 0; i < segmentSize; i++) { segment.add(null); } int n = 0; for (int i = 0; i < len; i++) { int index = i % segmentSize; segment.set(index, new WeightedObservedPoint(1, index, values[i])); if (index + 1 == segmentSize) { reducedValues[n++] = curveFitter.fit(segment); if (n == segments) break; } } } else { double segmentSize = len * 1.0 / segments; int k = 0; int segmentSizeReal = (int) FastMath.ceil(segmentSize) + 1; int index = 0; List<WeightedObservedPoint> segment = new ArrayList<>(segmentSizeReal); for (int i = 0; i < segments - 1; i++) { double x = (i + 1) * segmentSize - 1; for (; k < x; k++) { segment.add(new WeightedObservedPoint(1, index, values[k])); index++; } double delta = x - (int) x;
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseCurveFitterApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.fitting.AbstractCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoint; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.ArrayList; import java.util.List; List<WeightedObservedPoint> segment = new ArrayList<>(segmentSize); for (int i = 0; i < segmentSize; i++) { segment.add(null); } int n = 0; for (int i = 0; i < len; i++) { int index = i % segmentSize; segment.set(index, new WeightedObservedPoint(1, index, values[i])); if (index + 1 == segmentSize) { reducedValues[n++] = curveFitter.fit(segment); if (n == segments) break; } } } else { double segmentSize = len * 1.0 / segments; int k = 0; int segmentSizeReal = (int) FastMath.ceil(segmentSize) + 1; int index = 0; List<WeightedObservedPoint> segment = new ArrayList<>(segmentSizeReal); for (int i = 0; i < segments - 1; i++) { double x = (i + 1) * segmentSize - 1; for (; k < x; k++) { segment.add(new WeightedObservedPoint(1, index, values[k])); index++; } double delta = x - (int) x;
if (!Precision.equals(delta, 0, TimeSeriesPrecision.EPSILON)) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/AbstractMatrixProfileTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // }
import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import java.io.Serializable; import java.util.Random; import java.util.concurrent.ThreadLocalRandom;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Useful methods used by full and self join matrix profile algorithms. * * @since 0.17 */ public abstract class AbstractMatrixProfileTransformer implements Serializable { private static final long serialVersionUID = -4758909899130005950L; protected final int window; protected final double exclusionZonePercentage; protected final boolean useNormalization; /** * Creates a new instance of this class with normalization enabled and an exclusion zone of 25%. * * @param window the length of the window * @throws NumberIsTooSmallException if window is lower than 4 */ public AbstractMatrixProfileTransformer(int window) { this(window, 0.25, true); } /** * @param window the length of the window * @param exclusionZonePercentage percentage of window that should be excluded at distance profile computing * @param useNormalization flag to use Z-Normalization * @throws NumberIsTooSmallException if window is lower than 1 */ public AbstractMatrixProfileTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { this.useNormalization = useNormalization; if (window < 1) { throw new NumberIsTooSmallException(window, 1, true); } this.window = window; this.exclusionZonePercentage = exclusionZonePercentage; } /** * This method will update bStatistics with last sliding window statistics */
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/AbstractMatrixProfileTransformer.java import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import java.io.Serializable; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Useful methods used by full and self join matrix profile algorithms. * * @since 0.17 */ public abstract class AbstractMatrixProfileTransformer implements Serializable { private static final long serialVersionUID = -4758909899130005950L; protected final int window; protected final double exclusionZonePercentage; protected final boolean useNormalization; /** * Creates a new instance of this class with normalization enabled and an exclusion zone of 25%. * * @param window the length of the window * @throws NumberIsTooSmallException if window is lower than 4 */ public AbstractMatrixProfileTransformer(int window) { this(window, 0.25, true); } /** * @param window the length of the window * @param exclusionZonePercentage percentage of window that should be excluded at distance profile computing * @param useNormalization flag to use Z-Normalization * @throws NumberIsTooSmallException if window is lower than 1 */ public AbstractMatrixProfileTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { this.useNormalization = useNormalization; if (window < 1) { throw new NumberIsTooSmallException(window, 1, true); } this.window = window; this.exclusionZonePercentage = exclusionZonePercentage; } /** * This method will update bStatistics with last sliding window statistics */
protected void computeFirstNormalizedDistanceProfile(double[] a, BothWaySummaryStatistics aStatistics, double[] b, BothWaySummaryStatistics bStatistics, int skip, int nb, double[] productSums, double[] distanceProfile) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // }
import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.util.LocalizableMessages;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Longest Common Subsequence. * <p> * Reference: * Vlachos Michail, George Kollios and Dimitrios Gunopulos (2002) * <i>Discovering similar multidimensional trajectories</i> * </p> * * @since 0.7 */ public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 4542559569313251930L; private final double epsilon; private final double radiusPercentage; /** * Creates a new instance of this class with * * @param epsilon the maximum absolute difference between two values that are considered equal * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] */ public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { this.epsilon = epsilon; if (radiusPercentage < 0 || radiusPercentage > 1) {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/LongestCommonSubsequenceDistance.java import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.exception.util.LocalizableMessages; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Longest Common Subsequence. * <p> * Reference: * Vlachos Michail, George Kollios and Dimitrios Gunopulos (2002) * <i>Discovering similar multidimensional trajectories</i> * </p> * * @since 0.7 */ public class LongestCommonSubsequenceDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = 4542559569313251930L; private final double epsilon; private final double radiusPercentage; /** * Creates a new instance of this class with * * @param epsilon the maximum absolute difference between two values that are considered equal * @param radiusPercentage Sakoe-Chiba Band width used to constraint the searching window * @throws OutOfRangeException if radiusPercentage is outside the interval [0, 1] */ public LongestCommonSubsequenceDistance(double epsilon, double radiusPercentage) { this.epsilon = epsilon; if (radiusPercentage < 0 || radiusPercentage > 1) {
throw new OutOfRangeException(LocalizableMessages.OUT_OF_RANGE_BOTH_INCLUSIVE, radiusPercentage, 0, 1);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/normalization/MinMaxNormalizerTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.normalization; public class MinMaxNormalizerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooLargeException.class); thrown.expectMessage("4 is larger than the maximum (3)"); new MinMaxNormalizer(4, 3); } @Test public void testNormalizeDefaultConstructor() throws Exception { MinMaxNormalizer normalizer = new MinMaxNormalizer(); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; double[] expected = {0.0, 0.25, 0.5, 0.75, 1.0}; double[] out = normalizer.normalize(v);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/normalization/MinMaxNormalizerTest.java import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.normalization; public class MinMaxNormalizerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooLargeException.class); thrown.expectMessage("4 is larger than the maximum (3)"); new MinMaxNormalizer(4, 3); } @Test public void testNormalizeDefaultConstructor() throws Exception { MinMaxNormalizer normalizer = new MinMaxNormalizer(); double[] v = {1.0, 2.0, 3.0, 4.0, 5.0}; double[] expected = {0.0, 0.25, 0.5, 0.75, 1.0}; double[] out = normalizer.normalize(v);
Assert.assertArrayEquals(expected, out, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Linear Aggregate Approximation (PLAA) algorithm. * <p> * Reference: * Hung N. Q. V., Anh D. T. (2008) * <i>An Improvement of PAA for Dimensionality Reduction in Large Time Series Databases</i> * </p> * * @since 0.6 */ public class PiecewiseLinearAggregateApproximation implements GenericTransformer<double[], MeanSlopePair[]> { private static final long serialVersionUID = -4073250977010141095L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseLinearAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } /** * Transform a given sequence of values using the algorithm PLAA. * * @param values the sequence of values * @return the result of the transformation */ public MeanSlopePair[] transform(double[] values) { int len = values.length; if (len < segments) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // } // Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Linear Aggregate Approximation (PLAA) algorithm. * <p> * Reference: * Hung N. Q. V., Anh D. T. (2008) * <i>An Improvement of PAA for Dimensionality Reduction in Large Time Series Databases</i> * </p> * * @since 0.6 */ public class PiecewiseLinearAggregateApproximation implements GenericTransformer<double[], MeanSlopePair[]> { private static final long serialVersionUID = -4073250977010141095L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseLinearAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } /** * Transform a given sequence of values using the algorithm PLAA. * * @param values the sequence of values * @return the result of the transformation */ public MeanSlopePair[] transform(double[] values) { int len = values.length; if (len < segments) {
throw new ArrayLengthIsTooSmallException(len, segments, true);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximation.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Linear Aggregate Approximation (PLAA) algorithm. * <p> * Reference: * Hung N. Q. V., Anh D. T. (2008) * <i>An Improvement of PAA for Dimensionality Reduction in Large Time Series Databases</i> * </p> * * @since 0.6 */ public class PiecewiseLinearAggregateApproximation implements GenericTransformer<double[], MeanSlopePair[]> { private static final long serialVersionUID = -4073250977010141095L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseLinearAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } /** * Transform a given sequence of values using the algorithm PLAA. * * @param values the sequence of values * @return the result of the transformation */ public MeanSlopePair[] transform(double[] values) { int len = values.length; if (len < segments) { throw new ArrayLengthIsTooSmallException(len, segments, true); } int modulo = len % segments; if (modulo != 0) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsNotDivisibleException.java // public class ArrayLengthIsNotDivisibleException extends NumberIsNotDivisibleException { // private static final long serialVersionUID = 1652407890465175618L; // // /** // * Construct the exception. // * // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Number wrong, Integer factor) { // super(wrong, factor); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is not divisible with the factor. // * @param factor The factor. // */ // public ArrayLengthIsNotDivisibleException(Localizable specific, Number wrong, Integer factor) { // super(specific, wrong, factor); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanSlopePair.java // @Data // public class MeanSlopePair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The slope of the segment. // */ // private final double slope; // } // Path: src/main/java/ro/hasna/ts/math/representation/PiecewiseLinearAggregateApproximation.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance; import ro.hasna.ts.math.exception.ArrayLengthIsNotDivisibleException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanSlopePair; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; /** * Implements the Piecewise Linear Aggregate Approximation (PLAA) algorithm. * <p> * Reference: * Hung N. Q. V., Anh D. T. (2008) * <i>An Improvement of PAA for Dimensionality Reduction in Large Time Series Databases</i> * </p> * * @since 0.6 */ public class PiecewiseLinearAggregateApproximation implements GenericTransformer<double[], MeanSlopePair[]> { private static final long serialVersionUID = -4073250977010141095L; private final int segments; /** * Creates a new instance of this class. * * @param segments the number of segments * @throws NumberIsTooSmallException if segments lower than 1 */ public PiecewiseLinearAggregateApproximation(int segments) { if (segments < 1) { throw new NumberIsTooSmallException(segments, 1, true); } this.segments = segments; } /** * Transform a given sequence of values using the algorithm PLAA. * * @param values the sequence of values * @return the result of the transformation */ public MeanSlopePair[] transform(double[] values) { int len = values.length; if (len < segments) { throw new ArrayLengthIsTooSmallException(len, segments, true); } int modulo = len % segments; if (modulo != 0) {
throw new ArrayLengthIsNotDivisibleException(len, segments);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/distribution/AdaptiveDistributionDividerTest.java
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class AdaptiveDistributionDividerTest { private AdaptiveDistributionDivider divider; @Before public void setUp() throws Exception { double[][] trainingSet = { {60.7, 96.05, 130.45, 151.3, 160.45, 162.55, 160.3, 138.8, 111.85, 79.6}, {59.5, 93.85, 128.9, 150.9, 160.55, 162.6, 160.45, 140.1, 112.6, 81.25}, {63.7, 99.4, 131.55, 150.9, 160.85, 163.8, 159.55, 135.2, 109.4, 78.65}, {62.6, 96.7, 129.85, 150.35, 161.05, 163.75, 160.5, 137.15, 110.95, 80.6}, {59.35, 94, 128.1, 150, 160.3, 163.7, 160.55, 139.15, 111, 83.05}, {58.35, 92.1, 127.3, 149.4, 160, 162.8, 160.95, 139.9, 112.6, 83.5} };
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/distribution/AdaptiveDistributionDividerTest.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class AdaptiveDistributionDividerTest { private AdaptiveDistributionDivider divider; @Before public void setUp() throws Exception { double[][] trainingSet = { {60.7, 96.05, 130.45, 151.3, 160.45, 162.55, 160.3, 138.8, 111.85, 79.6}, {59.5, 93.85, 128.9, 150.9, 160.55, 162.6, 160.45, 140.1, 112.6, 81.25}, {63.7, 99.4, 131.55, 150.9, 160.85, 163.8, 159.55, 135.2, 109.4, 78.65}, {62.6, 96.7, 129.85, 150.35, 161.05, 163.75, 160.5, 137.15, 110.95, 80.6}, {59.35, 94, 128.1, 150, 160.3, 163.7, 160.55, 139.15, 111, 83.05}, {58.35, 92.1, 127.3, 149.4, 160, 162.8, 160.95, 139.9, 112.6, 83.5} };
ZNormalizer normalizer = new ZNormalizer();
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/distribution/AdaptiveDistributionDividerTest.java
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class AdaptiveDistributionDividerTest { private AdaptiveDistributionDivider divider; @Before public void setUp() throws Exception { double[][] trainingSet = { {60.7, 96.05, 130.45, 151.3, 160.45, 162.55, 160.3, 138.8, 111.85, 79.6}, {59.5, 93.85, 128.9, 150.9, 160.55, 162.6, 160.45, 140.1, 112.6, 81.25}, {63.7, 99.4, 131.55, 150.9, 160.85, 163.8, 159.55, 135.2, 109.4, 78.65}, {62.6, 96.7, 129.85, 150.35, 161.05, 163.75, 160.5, 137.15, 110.95, 80.6}, {59.35, 94, 128.1, 150, 160.3, 163.7, 160.55, 139.15, 111, 83.05}, {58.35, 92.1, 127.3, 149.4, 160, 162.8, 160.95, 139.9, 112.6, 83.5} }; ZNormalizer normalizer = new ZNormalizer(); for (int i = 0; i < trainingSet.length; i++) { trainingSet[i] = normalizer.normalize(trainingSet[i]); }
// Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/distribution/AdaptiveDistributionDividerTest.java import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class AdaptiveDistributionDividerTest { private AdaptiveDistributionDivider divider; @Before public void setUp() throws Exception { double[][] trainingSet = { {60.7, 96.05, 130.45, 151.3, 160.45, 162.55, 160.3, 138.8, 111.85, 79.6}, {59.5, 93.85, 128.9, 150.9, 160.55, 162.6, 160.45, 140.1, 112.6, 81.25}, {63.7, 99.4, 131.55, 150.9, 160.85, 163.8, 159.55, 135.2, 109.4, 78.65}, {62.6, 96.7, 129.85, 150.35, 161.05, 163.75, 160.5, 137.15, 110.95, 80.6}, {59.35, 94, 128.1, 150, 160.3, 163.7, 160.55, 139.15, 111, 83.05}, {58.35, 92.1, 127.3, 149.4, 160, 162.8, 160.95, 139.9, 112.6, 83.5} }; ZNormalizer normalizer = new ZNormalizer(); for (int i = 0; i < trainingSet.length; i++) { trainingSet[i] = normalizer.normalize(trainingSet[i]); }
divider = new AdaptiveDistributionDivider(trainingSet, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class SelfJoinAbstractMatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new SelfJoinAbstractMatrixProfileTransformer(3) { private static final long serialVersionUID = 7691413957352355633L; @Override
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformerTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class SelfJoinAbstractMatrixProfileTransformerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void constructor_withSmallWindow() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (4)"); new SelfJoinAbstractMatrixProfileTransformer(3) { private static final long serialVersionUID = 7691413957352355633L; @Override
protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformer.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/CancellationException.java // public class CancellationException extends MathIllegalStateException { // private static final long serialVersionUID = 8488577710717564366L; // // public CancellationException() { // super(LocalizableMessages.OPERATION_WAS_CANCELLED); // } // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.exception.CancellationException; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Useful methods for self-join matrix profile algorithms. * * @since 0.17 */ public abstract class SelfJoinAbstractMatrixProfileTransformer extends AbstractMatrixProfileTransformer implements GenericTransformer<double[], MatrixProfile> { private static final long serialVersionUID = 4273395812927663256L; /** * Creates a new instance of this class with normalization enabled and an exclusion zone of 25%. * * @param window the length of the window * @throws NumberIsTooSmallException if window is lower than 4 */ public SelfJoinAbstractMatrixProfileTransformer(int window) { this(window, 0.25, true); } /** * @param window the length of the window * @param exclusionZonePercentage percentage of window that should be excluded at distance profile computing * @param useNormalization flag to use Z-Normalization * @throws NumberIsTooSmallException if window or window * exclusionZonePercentage is lower than 1 */ public SelfJoinAbstractMatrixProfileTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); int skip = (int) (window * exclusionZonePercentage); if (skip < 1) { int minWindow = (int) Math.ceil(1 / exclusionZonePercentage); throw new NumberIsTooSmallException(window, minWindow, true); } } @Override public MatrixProfile transform(double[] input) { int len = input.length; int skip = (int) (window * exclusionZonePercentage); if (len < window + skip) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/CancellationException.java // public class CancellationException extends MathIllegalStateException { // private static final long serialVersionUID = 8488577710717564366L; // // public CancellationException() { // super(LocalizableMessages.OPERATION_WAS_CANCELLED); // } // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformer.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.exception.CancellationException; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Useful methods for self-join matrix profile algorithms. * * @since 0.17 */ public abstract class SelfJoinAbstractMatrixProfileTransformer extends AbstractMatrixProfileTransformer implements GenericTransformer<double[], MatrixProfile> { private static final long serialVersionUID = 4273395812927663256L; /** * Creates a new instance of this class with normalization enabled and an exclusion zone of 25%. * * @param window the length of the window * @throws NumberIsTooSmallException if window is lower than 4 */ public SelfJoinAbstractMatrixProfileTransformer(int window) { this(window, 0.25, true); } /** * @param window the length of the window * @param exclusionZonePercentage percentage of window that should be excluded at distance profile computing * @param useNormalization flag to use Z-Normalization * @throws NumberIsTooSmallException if window or window * exclusionZonePercentage is lower than 1 */ public SelfJoinAbstractMatrixProfileTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); int skip = (int) (window * exclusionZonePercentage); if (skip < 1) { int minWindow = (int) Math.ceil(1 / exclusionZonePercentage); throw new NumberIsTooSmallException(window, minWindow, true); } } @Override public MatrixProfile transform(double[] input) { int len = input.length; int skip = (int) (window * exclusionZonePercentage); if (len < window + skip) {
throw new ArrayLengthIsTooSmallException(len, window + skip, true);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformer.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/CancellationException.java // public class CancellationException extends MathIllegalStateException { // private static final long serialVersionUID = 8488577710717564366L; // // public CancellationException() { // super(LocalizableMessages.OPERATION_WAS_CANCELLED); // } // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.exception.CancellationException; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
for (int i = 0; i < profile.length; i++) { profile[i] = FastMath.sqrt(profile[i]); } } protected void updateMatrixProfileFromDistanceProfile(double[] distanceProfile, int i, int skip, int n, MatrixProfile mp, Predicate<MatrixProfile> callback) { for (int j = i + skip; j < n; j++) { // update horizontal line from upper triangle if (mp.getProfile()[j] > distanceProfile[j]) { mp.getProfile()[j] = distanceProfile[j]; mp.getIndexProfile()[j] = i; } // update vertical line i from matrix profile if (mp.getProfile()[i] > distanceProfile[j]) { mp.getProfile()[i] = distanceProfile[j]; mp.getIndexProfile()[i] = j; } } executeCallback(callback, mp); } protected void executeCallback(Predicate<MatrixProfile> callback, MatrixProfile mp) { if (callback == null) { return; } MatrixProfile clone = mp.clone(); updateMatrixProfileWithSqrt(clone); if (!callback.test(clone)) {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/exception/CancellationException.java // public class CancellationException extends MathIllegalStateException { // private static final long serialVersionUID = 8488577710717564366L; // // public CancellationException() { // super(LocalizableMessages.OPERATION_WAS_CANCELLED); // } // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/SelfJoinAbstractMatrixProfileTransformer.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.util.FastMath; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.exception.CancellationException; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; for (int i = 0; i < profile.length; i++) { profile[i] = FastMath.sqrt(profile[i]); } } protected void updateMatrixProfileFromDistanceProfile(double[] distanceProfile, int i, int skip, int n, MatrixProfile mp, Predicate<MatrixProfile> callback) { for (int j = i + skip; j < n; j++) { // update horizontal line from upper triangle if (mp.getProfile()[j] > distanceProfile[j]) { mp.getProfile()[j] = distanceProfile[j]; mp.getIndexProfile()[j] = i; } // update vertical line i from matrix profile if (mp.getProfile()[i] > distanceProfile[j]) { mp.getProfile()[i] = distanceProfile[j]; mp.getIndexProfile()[i] = j; } } executeCallback(callback, mp); } protected void executeCallback(Predicate<MatrixProfile> callback, MatrixProfile mp) { if (callback == null) { return; } MatrixProfile clone = mp.clone(); updateMatrixProfileWithSqrt(clone); if (!callback.test(clone)) {
throw new CancellationException();
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/DiscreteChebyshevTransformTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision;
@Test public void testTransform() throws Exception { double[] v = {1, 2, 3}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer).transform(new double[]{1, 2, 3, 2}, TransformType.FORWARD); } @Test public void testTransform2() throws Exception { double[] v = {1, 2, 3, 4}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer).transform(new double[]{1, 2, 3, 4, 3, 2, 0, 0}, TransformType.FORWARD); } @Test public void testTransformSmallVector() throws Exception { double[] v = {1, 2}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer, Mockito.never()).transform(Mockito.<double[]>any(), Mockito.any()); } @Test public void testTransformConcrete() throws Exception { double[] v = {98, 100}; // 99 * x^2 - x double[] expected = {99, -1}; double[] result = new DiscreteChebyshevTransform().transform(v);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/DiscreteChebyshevTransformTest.java import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import ro.hasna.ts.math.util.TimeSeriesPrecision; @Test public void testTransform() throws Exception { double[] v = {1, 2, 3}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer).transform(new double[]{1, 2, 3, 2}, TransformType.FORWARD); } @Test public void testTransform2() throws Exception { double[] v = {1, 2, 3, 4}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer).transform(new double[]{1, 2, 3, 4, 3, 2, 0, 0}, TransformType.FORWARD); } @Test public void testTransformSmallVector() throws Exception { double[] v = {1, 2}; discreteChebyshevTransform.transform(v); Mockito.verify(fastFourierTransformer, Mockito.never()).transform(Mockito.<double[]>any(), Mockito.any()); } @Test public void testTransformConcrete() throws Exception { double[] v = {98, 100}; // 99 * x^2 - x double[] expected = {99, -1}; double[] result = new DiscreteChebyshevTransform().transform(v);
Assert.assertArrayEquals(expected, result, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/exception/CancellationException.java
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // }
import org.apache.commons.math3.exception.MathIllegalStateException; import ro.hasna.ts.math.exception.util.LocalizableMessages;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; /** * Exception to be thrown when an async task is canceled. * * @since 0.17 */ public class CancellationException extends MathIllegalStateException { private static final long serialVersionUID = 8488577710717564366L; public CancellationException() {
// Path: src/main/java/ro/hasna/ts/math/exception/util/LocalizableMessages.java // public class LocalizableMessages { // public static final Localizable NUMBER_NOT_DIVISIBLE_WITH = new DummyLocalizable("{0} is not divisible with {1}"); // public static final Localizable OUT_OF_RANGE_BOTH_EXCLUSIVE = new DummyLocalizable("{0} out of ({1}, {2}) range"); // public static final Localizable OUT_OF_RANGE_BOTH_INCLUSIVE = new DummyLocalizable("{0} out of [{1}, {2}] range"); // public static final Localizable OPERATION_WAS_CANCELLED = new DummyLocalizable("The operation was cancelled."); // // private LocalizableMessages() { // } // } // Path: src/main/java/ro/hasna/ts/math/exception/CancellationException.java import org.apache.commons.math3.exception.MathIllegalStateException; import ro.hasna.ts.math.exception.util.LocalizableMessages; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.exception; /** * Exception to be thrown when an async task is canceled. * * @since 0.17 */ public class CancellationException extends MathIllegalStateException { private static final long serialVersionUID = 8488577710717564366L; public CancellationException() {
super(LocalizableMessages.OPERATION_WAS_CANCELLED);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/distribution/NormalDistributionDividerTest.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class NormalDistributionDividerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private NormalDistributionDivider divider; @Before public void setUp() throws Exception { divider = new NormalDistributionDivider(); } @After public void tearDown() throws Exception { divider = null; } @Test public void testGetBreakpointsWithException() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("1 is smaller than the minimum (2)"); divider.getBreakpoints(1); } @Test public void testGetBreakpoints1() throws Exception { double[] expected = {-0.4307272992954576, 0.4307272992954576}; double[] v = divider.getBreakpoints(3);
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/distribution/NormalDistributionDividerTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.*; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.distribution; public class NormalDistributionDividerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private NormalDistributionDivider divider; @Before public void setUp() throws Exception { divider = new NormalDistributionDivider(); } @After public void tearDown() throws Exception { divider = null; } @Test public void testGetBreakpointsWithException() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("1 is smaller than the minimum (2)"); divider.getBreakpoints(1); } @Test public void testGetBreakpoints1() throws Exception { double[] expected = {-0.4307272992954576, 0.4307272992954576}; double[] v = divider.getBreakpoints(3);
Assert.assertArrayEquals(expected, v, TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/ml/distance/RealSequenceEditDistance.java
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Edit Distance on Real Sequence. * <p> * Reference: * Wagner Robert A. and Michael J. Fischer (1974) * <i>The string-to-string correction problem</i> * Chen Lei and Raymond Ng (2004) * <i>On the marriage of lp-norms and edit distance</i> * Chen Lei (2005) * <i>Similarity search over time series and trajectory data</i> * </p> * * @since 0.10 */ public class RealSequenceEditDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = -373272813771443967L; private final double epsilon; private final double radiusPercentage; public RealSequenceEditDistance() {
// Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/main/java/ro/hasna/ts/math/ml/distance/RealSequenceEditDistance.java import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; /** * Calculates the distance between two vectors using Edit Distance on Real Sequence. * <p> * Reference: * Wagner Robert A. and Michael J. Fischer (1974) * <i>The string-to-string correction problem</i> * Chen Lei and Raymond Ng (2004) * <i>On the marriage of lp-norms and edit distance</i> * Chen Lei (2005) * <i>Similarity search over time series and trajectory data</i> * </p> * * @since 0.10 */ public class RealSequenceEditDistance implements GenericDistanceMeasure<double[]> { private static final long serialVersionUID = -373272813771443967L; private final double epsilon; private final double radiusPercentage; public RealSequenceEditDistance() {
this(TimeSeriesPrecision.EPSILON, 1.0);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception {
thrown.expect(ArrayLengthIsTooSmallException.class);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (8)"); AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(4); double[] v = {1, 2, 3}; apca.transform(v); } @Test public void testTransform() throws Exception { AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(3); double[] v = {1, 1, 4, 5, 1, 0, 1, 2, 1};
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (8)"); AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(4); double[] v = {1, 2, 3}; apca.transform(v); } @Test public void testTransform() throws Exception { AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(3); double[] v = {1, 1, 4, 5, 1, 0, 1, 2, 1};
MeanLastPair[] result = apca.transform(v);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (8)"); AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(4); double[] v = {1, 2, 3}; apca.transform(v); } @Test public void testTransform() throws Exception { AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(3); double[] v = {1, 1, 4, 5, 1, 0, 1, 2, 1}; MeanLastPair[] result = apca.transform(v);
// Path: src/main/java/ro/hasna/ts/math/exception/ArrayLengthIsTooSmallException.java // public class ArrayLengthIsTooSmallException extends NumberIsTooSmallException { // private static final long serialVersionUID = -2633584088507009304L; // // /** // * Construct the exception. // * // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Number wrong, Number min, boolean boundIsAllowed) { // super(wrong, min, boundIsAllowed); // } // // /** // * Construct the exception with a specific context. // * // * @param specific Specific context pattern. // * @param wrong Value that is smaller than the minimum. // * @param min Minimum. // * @param boundIsAllowed Whether {@code min} is included in the allowed range. // */ // public ArrayLengthIsTooSmallException(Localizable specific, Number wrong, Number min, boolean boundIsAllowed) { // super(specific, wrong, min, boundIsAllowed); // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MeanLastPair.java // @Data // public class MeanLastPair { // /** // * The mean value for the segment. // */ // private final double mean; // /** // * The position from the last element of the segment. // */ // private final int last; // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/AdaptivePiecewiseConstantApproximationTest.java import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.exception.ArrayLengthIsTooSmallException; import ro.hasna.ts.math.type.MeanLastPair; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class AdaptivePiecewiseConstantApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructor() throws Exception { thrown.expect(NumberIsTooSmallException.class); thrown.expectMessage("0 is smaller than the minimum (1)"); new AdaptivePiecewiseConstantApproximation(0); } @Test public void testTransformMoreSegmentsThanValues() throws Exception { thrown.expect(ArrayLengthIsTooSmallException.class); thrown.expectMessage("3 is smaller than the minimum (8)"); AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(4); double[] v = {1, 2, 3}; apca.transform(v); } @Test public void testTransform() throws Exception { AdaptivePiecewiseConstantApproximation apca = new AdaptivePiecewiseConstantApproximation(3); double[] v = {1, 1, 4, 5, 1, 0, 1, 2, 1}; MeanLastPair[] result = apca.transform(v);
Assert.assertEquals(1, result[0].getMean(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class IndexableSymbolicAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructorException() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("5 != 4"); new IndexableSymbolicAggregateApproximation(4, new int[5]); } @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; }
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation; public class IndexableSymbolicAggregateApproximationTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testConstructorException() throws Exception { thrown.expect(DimensionMismatchException.class); thrown.expectMessage("5 != 4"); new IndexableSymbolicAggregateApproximation(4, new int[5]); } @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; }
SaxPair[] expected = new SaxPair[9];
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random;
new IndexableSymbolicAggregateApproximation(4, new int[5]); } @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; } SaxPair[] expected = new SaxPair[9]; expected[0] = new SaxPair(0, 3); expected[1] = new SaxPair(0, 3); expected[2] = new SaxPair(1, 3); expected[3] = new SaxPair(2, 3); expected[4] = new SaxPair(2, 3); expected[5] = new SaxPair(2, 3); expected[6] = new SaxPair(1, 3); expected[7] = new SaxPair(0, 3); expected[8] = new SaxPair(0, 3); IndexableSymbolicAggregateApproximation isax = new IndexableSymbolicAggregateApproximation( new PiecewiseAggregateApproximation(9),
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random; new IndexableSymbolicAggregateApproximation(4, new int[5]); } @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; } SaxPair[] expected = new SaxPair[9]; expected[0] = new SaxPair(0, 3); expected[1] = new SaxPair(0, 3); expected[2] = new SaxPair(1, 3); expected[3] = new SaxPair(2, 3); expected[4] = new SaxPair(2, 3); expected[5] = new SaxPair(2, 3); expected[6] = new SaxPair(1, 3); expected[7] = new SaxPair(0, 3); expected[8] = new SaxPair(0, 3); IndexableSymbolicAggregateApproximation isax = new IndexableSymbolicAggregateApproximation( new PiecewiseAggregateApproximation(9),
new ZNormalizer(),
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // }
import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random;
} @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; } SaxPair[] expected = new SaxPair[9]; expected[0] = new SaxPair(0, 3); expected[1] = new SaxPair(0, 3); expected[2] = new SaxPair(1, 3); expected[3] = new SaxPair(2, 3); expected[4] = new SaxPair(2, 3); expected[5] = new SaxPair(2, 3); expected[6] = new SaxPair(1, 3); expected[7] = new SaxPair(0, 3); expected[8] = new SaxPair(0, 3); IndexableSymbolicAggregateApproximation isax = new IndexableSymbolicAggregateApproximation( new PiecewiseAggregateApproximation(9), new ZNormalizer(), alphabetSizes,
// Path: src/main/java/ro/hasna/ts/math/distribution/NormalDistributionDivider.java // public class NormalDistributionDivider implements DistributionDivider { // private static final long serialVersionUID = -909800668897655203L; // // @Override // public double[] getBreakpoints(int areas) { // if (areas < 2) { // throw new NumberIsTooSmallException(areas, 2, true); // } // // NormalDistribution normalDistribution = new NormalDistribution(); // int len = areas - 1; // double[] result = new double[len]; // double searchArea = 1.0 / areas; // for (int i = 0; i < len; i++) { // result[i] = normalDistribution.inverseCumulativeProbability(searchArea * (i + 1)); // } // // return result; // } // } // // Path: src/main/java/ro/hasna/ts/math/normalization/ZNormalizer.java // public class ZNormalizer implements Normalizer { // private static final long serialVersionUID = 6446811014325682141L; // private final Mean mean; // private final StandardDeviation standardDeviation; // // public ZNormalizer() { // this(new Mean(), new StandardDeviation(false)); // } // // /** // * Creates a new instance of this class with the given mean and standard deviation algorithms. // * // * @param mean the mean // * @param standardDeviation the standard deviation // */ // public ZNormalizer(final Mean mean, final StandardDeviation standardDeviation) { // this.mean = mean; // this.standardDeviation = standardDeviation; // } // // /** // * {@inheritDoc} // */ // @Override // public double[] normalize(double[] values) { // double m = mean.evaluate(values); // double sd = standardDeviation.evaluate(values, m); // // int length = values.length; // double[] normalizedValues = new double[length]; // for (int i = 0; i < length; i++) { // normalizedValues[i] = (values[i] - m) / sd; // } // return normalizedValues; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/SaxPair.java // @Data // public class SaxPair { // /** // * The symbol value for the segment. // */ // private final int symbol; // /** // * The size of the alphabet used by the symbol. // */ // private final int alphabetSize; // } // Path: src/test/java/ro/hasna/ts/math/representation/IndexableSymbolicAggregateApproximationTest.java import org.apache.commons.math3.exception.DimensionMismatchException; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ro.hasna.ts.math.distribution.NormalDistributionDivider; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.type.SaxPair; import java.util.Random; } @Test public void testTransformToSaxPairArray1() throws Exception { double[] list = new double[64]; for (int i = 0; i < 32; i++) { list[i] = i; } for (int i = 32; i < 64; i++) { list[i] = 64 - i; } int[] alphabetSizes = new int[9]; for (int i = 0; i < 9; i++) { alphabetSizes[i] = 3; } SaxPair[] expected = new SaxPair[9]; expected[0] = new SaxPair(0, 3); expected[1] = new SaxPair(0, 3); expected[2] = new SaxPair(1, 3); expected[3] = new SaxPair(2, 3); expected[4] = new SaxPair(2, 3); expected[5] = new SaxPair(2, 3); expected[6] = new SaxPair(1, 3); expected[7] = new SaxPair(0, 3); expected[8] = new SaxPair(0, 3); IndexableSymbolicAggregateApproximation isax = new IndexableSymbolicAggregateApproximation( new PiecewiseAggregateApproximation(9), new ZNormalizer(), alphabetSizes,
new NormalDistributionDivider());
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/StompTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STOMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Zimmerman Z., Senobari N. S., Yeh C. C. M., Funning G., Mueen A., Keogh E. (2016) * <i>Exploiting a Novel Algorithm and GPUs to Break the One Hundred Million Barrier for Time Series Motifs and Joins</i> * </p> * * @since 0.17 */ public class StompTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 2910211807207716085L; public StompTransformer(int window) { super(window); } public StompTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/StompTransformer.java import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STOMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Zimmerman Z., Senobari N. S., Yeh C. C. M., Funning G., Mueen A., Keogh E. (2016) * <i>Exploiting a Novel Algorithm and GPUs to Break the One Hundred Million Barrier for Time Series Motifs and Joins</i> * </p> * * @since 0.17 */ public class StompTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 2910211807207716085L; public StompTransformer(int window) { super(window); } public StompTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/StompTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STOMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Zimmerman Z., Senobari N. S., Yeh C. C. M., Funning G., Mueen A., Keogh E. (2016) * <i>Exploiting a Novel Algorithm and GPUs to Break the One Hundred Million Barrier for Time Series Motifs and Joins</i> * </p> * * @since 0.17 */ public class StompTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 2910211807207716085L; public StompTransformer(int window) { super(window); } public StompTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) { int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; double[] productSums = new double[n];
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/StompTransformer.java import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the STOMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Zimmerman Z., Senobari N. S., Yeh C. C. M., Funning G., Mueen A., Keogh E. (2016) * <i>Exploiting a Novel Algorithm and GPUs to Break the One Hundred Million Barrier for Time Series Motifs and Joins</i> * </p> * * @since 0.17 */ public class StompTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = 2910211807207716085L; public StompTransformer(int window) { super(window); } public StompTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) { int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; double[] productSums = new double[n];
BothWaySummaryStatistics first = new BothWaySummaryStatistics();
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/ScrimpTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the SCRIMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Yeh C. C. M., Zimmerman Z., Kamgar K., Keogh E. (2018, November) * <i>Matrix profile XI: SCRIMP++: time series motif discovery at interactive speeds</i> * </p> * * @since 0.17 */ public class ScrimpTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = -7360923839319598742L; public ScrimpTransformer(int window) { super(window); } public ScrimpTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/ScrimpTransformer.java import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the SCRIMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Yeh C. C. M., Zimmerman Z., Kamgar K., Keogh E. (2018, November) * <i>Matrix profile XI: SCRIMP++: time series motif discovery at interactive speeds</i> * </p> * * @since 0.17 */ public class ScrimpTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = -7360923839319598742L; public ScrimpTransformer(int window) { super(window); } public ScrimpTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override
protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) {
octavian-h/time-series-math
src/main/java/ro/hasna/ts/math/representation/mp/ScrimpTransformer.java
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // }
import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the SCRIMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Yeh C. C. M., Zimmerman Z., Kamgar K., Keogh E. (2018, November) * <i>Matrix profile XI: SCRIMP++: time series motif discovery at interactive speeds</i> * </p> * * @since 0.17 */ public class ScrimpTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = -7360923839319598742L; public ScrimpTransformer(int window) { super(window); } public ScrimpTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) { int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; double[] productSums = new double[n];
// Path: src/main/java/ro/hasna/ts/math/stat/BothWaySummaryStatistics.java // public class BothWaySummaryStatistics implements StatisticalSummary, Serializable, Cloneable { // private static final long serialVersionUID = -8419769227216721345L; // private long n; // private double sum; // private double sumSquares; // private Max max; // private Min min; // private boolean removeMade; // // public BothWaySummaryStatistics() { // n = 0; // sum = 0; // sumSquares = 0; // max = new Max(); // min = new Min(); // removeMade = false; // } // // public void addValue(double d) { // sum += d; // sumSquares += d * d; // n++; // if (!removeMade) { // max.increment(d); // min.increment(d); // } // } // // public void removeValue(double d) { // if (n == 0) { // throw new InsufficientDataException(); // } // // sum -= d; // sumSquares -= d * d; // n--; // removeMade = true; // max.clear(); // min.clear(); // } // // @Override // public double getMean() { // if (n == 0) return 0; // return sum / n; // } // // @Override // public double getVariance() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // double mean = getMean(); // return sumSquares / n - mean * mean; // } // // @Override // public double getStandardDeviation() { // if (n == 0) return Double.NaN; // if (n == 1) return 0; // return FastMath.sqrt(getVariance()); // } // // /** // * @return max value or Double.NaN if removeValue was called // */ // @Override // public double getMax() { // return max.getResult(); // } // // /** // * @return min value or Double.NaN if removeValue was called // */ // @Override // public double getMin() { // return min.getResult(); // } // // @Override // public long getN() { // return n; // } // // @Override // public double getSum() { // return sum; // } // // @Override // public BothWaySummaryStatistics clone() { // BothWaySummaryStatistics copy = new BothWaySummaryStatistics(); // copy.n = n; // copy.sum = sum; // copy.sumSquares = sumSquares; // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // Path: src/main/java/ro/hasna/ts/math/representation/mp/ScrimpTransformer.java import ro.hasna.ts.math.stat.BothWaySummaryStatistics; import ro.hasna.ts.math.type.MatrixProfile; import java.util.function.Predicate; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; /** * Implements the SCRIMP algorithm to compute the self join matrix profile. * <p> * Reference: * Zhu Y., Yeh C. C. M., Zimmerman Z., Kamgar K., Keogh E. (2018, November) * <i>Matrix profile XI: SCRIMP++: time series motif discovery at interactive speeds</i> * </p> * * @since 0.17 */ public class ScrimpTransformer extends SelfJoinAbstractMatrixProfileTransformer { private static final long serialVersionUID = -7360923839319598742L; public ScrimpTransformer(int window) { super(window); } public ScrimpTransformer(int window, double exclusionZonePercentage, boolean useNormalization) { super(window, exclusionZonePercentage, useNormalization); } @Override protected MatrixProfile computeNormalizedMatrixProfile(double[] input, int skip, Predicate<MatrixProfile> callback) { int n = input.length - window + 1; MatrixProfile mp = new MatrixProfile(n); double[] distanceProfile = new double[n]; double[] productSums = new double[n];
BothWaySummaryStatistics first = new BothWaySummaryStatistics();
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/ScrimpTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class ScrimpTransformerTest { @Test public void transform_withoutNormalization() { ScrimpTransformer transformer = new ScrimpTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/ScrimpTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class ScrimpTransformerTest { @Test public void transform_withoutNormalization() { ScrimpTransformer transformer = new ScrimpTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19};
MatrixProfile transform = transformer.transform(v);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/representation/mp/ScrimpTransformerTest.java
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class ScrimpTransformerTest { @Test public void transform_withoutNormalization() { ScrimpTransformer transformer = new ScrimpTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
// Path: src/main/java/ro/hasna/ts/math/type/MatrixProfile.java // @Data // public class MatrixProfile implements Cloneable { // private final double[] profile; // private final int[] indexProfile; // // public MatrixProfile(double[] profile, int[] indexProfile) { // if (profile.length != indexProfile.length) { // throw new DimensionMismatchException(profile.length, indexProfile.length); // } // // this.profile = profile; // this.indexProfile = indexProfile; // } // // public MatrixProfile(int size) { // profile = new double[size]; // indexProfile = new int[size]; // for (int j = 0; j < size; j++) { // profile[j] = Double.POSITIVE_INFINITY; // indexProfile[j] = -1; // } // } // // @Override // public MatrixProfile clone() { // int size = profile.length; // MatrixProfile copy = new MatrixProfile(size); // for (int i = 0; i < size; i++) { // copy.profile[i] = profile[i]; // copy.indexProfile[i] = indexProfile[i]; // } // return copy; // } // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/representation/mp/ScrimpTransformerTest.java import org.junit.Assert; import org.junit.Test; import ro.hasna.ts.math.type.MatrixProfile; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.representation.mp; public class ScrimpTransformerTest { @Test public void transform_withoutNormalization() { ScrimpTransformer transformer = new ScrimpTransformer(4, 0.25, false); double[] v = {1, 2, 3, 4, 120, 71, 2, 2, 3, 5, 19}; MatrixProfile transform = transformer.transform(v); double[] expectedMp = {1.4142135623730951, 101.00495037373169, 125.93252161375949, 135.41787178950938, 84.63450832845902, 69.03622237637282, 1.4142135623730951, 14.177446878757825}; int[] expectedIp = {6, 7, 1, 7, 5, 6, 0, 6};
Assert.assertArrayEquals(expectedMp, transform.getProfile(), TimeSeriesPrecision.EPSILON);
octavian-h/time-series-math
src/test/java/ro/hasna/ts/math/ml/distance/util/DistanceTester.java
// Path: src/main/java/ro/hasna/ts/math/ml/distance/GenericDistanceMeasure.java // public interface GenericDistanceMeasure<T> extends Serializable { // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @return the distance between the two vectors // */ // double compute(T a, T b); // // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @param cutOffValue if the distance being calculated is above this value // * stop computing the remaining distance // * @return the distance between the two vectors // */ // double compute(T a, T b, double cutOffValue); // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // }
import org.apache.commons.math3.ml.distance.DistanceMeasure; import org.junit.Assert; import ro.hasna.ts.math.ml.distance.GenericDistanceMeasure; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.util.TimeSeriesPrecision;
/* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance.util; public class DistanceTester { private GenericDistanceMeasure<double[]> distance; private int vectorLength = 128; private double offset; private double cutOffValue; private double expectedResult; /** * Private constructor. */ public DistanceTester() { }
// Path: src/main/java/ro/hasna/ts/math/ml/distance/GenericDistanceMeasure.java // public interface GenericDistanceMeasure<T> extends Serializable { // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @return the distance between the two vectors // */ // double compute(T a, T b); // // /** // * Compute the distance between two n-dimensional vectors. // * <p> // * The two vectors are required to have the same dimension. // * // * @param a the first vector // * @param b the second vector // * @param cutOffValue if the distance being calculated is above this value // * stop computing the remaining distance // * @return the distance between the two vectors // */ // double compute(T a, T b, double cutOffValue); // } // // Path: src/main/java/ro/hasna/ts/math/representation/GenericTransformer.java // public interface GenericTransformer<I, O> extends Serializable { // /** // * Transform the input vector from type I into type O. // * // * @param input the input vector // * @return the output vector // */ // O transform(I input); // } // // Path: src/main/java/ro/hasna/ts/math/util/TimeSeriesPrecision.java // public class TimeSeriesPrecision { // public static final double EPSILON = FastMath.pow(2, -30); // // /** // * Private constructor. // */ // private TimeSeriesPrecision() { // } // } // Path: src/test/java/ro/hasna/ts/math/ml/distance/util/DistanceTester.java import org.apache.commons.math3.ml.distance.DistanceMeasure; import org.junit.Assert; import ro.hasna.ts.math.ml.distance.GenericDistanceMeasure; import ro.hasna.ts.math.representation.GenericTransformer; import ro.hasna.ts.math.util.TimeSeriesPrecision; /* * Copyright 2015 Octavian Hasna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance.util; public class DistanceTester { private GenericDistanceMeasure<double[]> distance; private int vectorLength = 128; private double offset; private double cutOffValue; private double expectedResult; /** * Private constructor. */ public DistanceTester() { }
public <T> DistanceTester withGenericDistanceMeasure(final GenericDistanceMeasure<T[]> distance, final GenericTransformer<double[], T[]> transformer) {