index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/IDatabaseConfig.java
|
package ai.libs.jaicore.db;
import org.aeonbits.owner.Reloadable;
import ai.libs.jaicore.basic.IOwnerBasedConfig;
/**
* Configuration interface to defined the access properties for a database connection
*
* @author fmohr
*
*/
public interface IDatabaseConfig extends IOwnerBasedConfig, Reloadable {
/* The table is the one where the experiments will be maintained */
public static final String DB_DRIVER = "db.driver";
public static final String DB_HOST = "db.host";
public static final String DB_USER = "db.username";
public static final String DB_PASS = "db.password";
public static final String DB_NAME = "db.database";
public static final String DB_TABLE = "db.table";
public static final String DB_SSL = "db.ssl";
@Key(DB_DRIVER)
public String getDBDriver();
@Key(DB_HOST)
public String getDBHost();
@Key(DB_USER)
public String getDBUsername();
@Key(DB_PASS)
public String getDBPassword();
@Key(DB_NAME)
public String getDBDatabaseName();
@Key(DB_TABLE)
public String getDBTableName();
@Key(DB_SSL)
@DefaultValue("true")
public Boolean getDBSSL();
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/package-info.java
|
package ai.libs.jaicore.db;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/ASqlBasedAdapter.java
|
package ai.libs.jaicore.db.sql;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import ai.libs.jaicore.db.IDatabaseAdapter;
public abstract class ASqlBasedAdapter implements IDatabaseAdapter {
/**
*
*/
private static final long serialVersionUID = 153647641292144496L;
protected static final String KEY_EQUALS_VALUE_TO_BE_SET = " = (?)";
protected static final String STR_SPACE_AND = " AND ";
protected static final String STR_SPACE_WHERE = " WHERE ";
protected ASqlBasedAdapter() {
}
@Override
public int delete(final String table, final Map<String, ? extends Object> conditions) throws SQLException {
StringBuilder conditionSB = new StringBuilder();
for (Entry<String, ? extends Object> entry : conditions.entrySet()) {
if (conditionSB.length() > 0) {
conditionSB.append(STR_SPACE_AND);
}
if (entry.getValue() != null) {
conditionSB.append(entry.getKey() + KEY_EQUALS_VALUE_TO_BE_SET);
} else {
conditionSB.append(entry.getKey());
conditionSB.append(" IS NULL");
}
}
return this.update("DELETE FROM `" + table + "`" + STR_SPACE_WHERE + " " + conditionSB);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/DatabaseAdapterFactory.java
|
package ai.libs.jaicore.db.sql;
import java.util.Objects;
import ai.libs.jaicore.db.IDatabaseAdapter;
import ai.libs.jaicore.db.IDatabaseConfig;
public class DatabaseAdapterFactory {
private DatabaseAdapterFactory() {
/* avoid instantiation */
}
public static IDatabaseAdapter get(final IDatabaseConfig config) {
Objects.requireNonNull(config);
return new SQLAdapter(config);
}
public static IDatabaseAdapter get(final IRestDatabaseConfig config) {
Objects.requireNonNull(config);
return new RestSqlAdapter(config);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/IRestDatabaseConfig.java
|
package ai.libs.jaicore.db.sql;
import org.aeonbits.owner.Reloadable;
import ai.libs.jaicore.basic.IOwnerBasedConfig;
public interface IRestDatabaseConfig extends IOwnerBasedConfig, Reloadable {
public static final String K_REST_DB_HOST = "sql.rest.host";
public static final String K_REST_DB_URL_INSERT = "sql.rest.host.insert";
public static final String K_REST_DB_URL_UPDATE = "sql.rest.host.update";
public static final String K_REST_DB_URL_SELECT = "sql.rest.host.select";
public static final String K_REST_DB_URL_QUERY = "sql.rest.host.query";
public static final String K_REST_DB_TOKEN = "sql.rest.token";
public static final String K_REST_DB_TABLE = "sql.rest.table";
@Key(K_REST_DB_HOST)
public String getHost();
@Key(K_REST_DB_TOKEN)
public String getToken();
@Key(K_REST_DB_URL_INSERT)
@DefaultValue("/insert")
public String getInsertSuffix();
@Key(K_REST_DB_URL_UPDATE)
@DefaultValue("/update")
public String getUpdateSuffix();
@Key(K_REST_DB_URL_SELECT)
@DefaultValue("/query")
public String getSelectSuffix();
@Key(K_REST_DB_URL_QUERY)
@DefaultValue("/query")
public String getQuerySuffix();
@Key(K_REST_DB_TABLE)
public String getTable();
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/ISQLQueryBuilder.java
|
package ai.libs.jaicore.db.sql;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
public interface ISQLQueryBuilder {
public Pair<String, List<Object>> buildInsertStatement(final String table, final Map<String, ? extends Object> values);
public String parseSQLCommand(final String sql, final List<?> values);
public String buildInsertSQLCommand(final String table, final Map<String, ? extends Object> values);
public String buildMultiInsertSQLCommand(final String table, final List<String> keys, final List<List<?>> datarows);
public String buildSelectSQLCommand(String table, final Map<String, String> conditions);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/MySQLQueryBuilder.java
|
package ai.libs.jaicore.db.sql;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.Pair;
public class MySQLQueryBuilder implements ISQLQueryBuilder {
private static final String KEY_EQUALS_VALUE_TO_BE_SET = " = (?)";
private static final String STR_SPACE_AND = " AND ";
private static final String STR_SPACE_WHERE = " WHERE ";
@Override
public Pair<String, List<Object>> buildInsertStatement(final String table, final Map<String, ? extends Object> map) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
List<Object> values = new ArrayList<>();
for (Entry<String, ? extends Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
continue;
}
if (sb1.length() != 0) {
sb1.append(", ");
sb2.append(", ");
}
sb1.append(entry.getKey());
sb2.append("?");
values.add(entry.getValue());
}
String statement = "INSERT INTO " + table + " (" + sb1.toString() + ") VALUES (" + sb2.toString() + ")";
return new Pair<>(statement, values);
}
@Override
public String buildInsertSQLCommand(final String table, final Map<String, ? extends Object> map) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (Entry<String, ? extends Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
continue;
}
if (sb1.length() != 0) {
sb1.append(", ");
sb2.append(", ");
}
sb1.append(entry.getKey());
sb2.append("\"" + entry.getValue().toString().replace("\\", "\\\\").replace("\"", "\\\"") + "\"");
}
return "INSERT INTO " + table + " (" + sb1.toString() + ") VALUES (" + sb2.toString() + ")";
}
@Override
public String buildMultiInsertSQLCommand(final String table, final List<String> keys, final List<List<?>> datarows) {
StringBuilder sbMain = new StringBuilder();
StringBuilder sbKeys = new StringBuilder();
StringBuilder sbValues = new StringBuilder();
/* create command phrase */
sbMain.append("INSERT INTO `");
sbMain.append(table);
sbMain.append("` (");
/* create key phrase */
for (String key : keys) {
if (sbKeys.length() != 0) {
sbKeys.append(", ");
}
sbKeys.append(key);
}
sbMain.append(sbKeys);
sbMain.append(") VALUES\n");
/* create value phrases */
for (List<?> datarow : datarows) {
if (datarow.contains(null)) { // the rule that fires here is wrong! The list CAN contain a null element
throw new IllegalArgumentException("Row " + datarow + " contains null element!");
}
if (sbValues.length() > 0) {
sbValues.append(",\n ");
}
sbValues.append("(");
sbValues.append(datarow.stream().map(s -> "\"" + s.toString().replace("\\", "\\\\").replace("\"", "\\\"") + "\"").collect(Collectors.joining(", ")));
sbValues.append(")");
}
sbMain.append(sbValues);
return sbMain.toString();
}
@Override
public String parseSQLCommand(final String sql, final List<?> values) {
Pattern p = Pattern.compile("\\?");
Matcher m = p.matcher(sql);
String modifiedSql = sql;
int index = 0;
while (m.find()) {
modifiedSql = modifiedSql.replaceFirst("\\?", values.get(index).toString());
index++;
}
return modifiedSql;
}
@Override
public String buildSelectSQLCommand(final String table, final Map<String, String> conditions) {
StringBuilder conditionSB = new StringBuilder();
List<String> values = new ArrayList<>();
for (Entry<String, String> entry : conditions.entrySet()) {
if (conditionSB.length() > 0) {
conditionSB.append(STR_SPACE_AND);
} else {
conditionSB.append(STR_SPACE_WHERE);
}
conditionSB.append(entry.getKey() + KEY_EQUALS_VALUE_TO_BE_SET);
values.add(entry.getValue());
}
return this.parseSQLCommand("SELECT * FROM `" + table + "`" + conditionSB.toString(), values);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/RestSqlAdapter.java
|
package ai.libs.jaicore.db.sql;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ai.libs.jaicore.basic.kvstore.KVStoreUtil;
/**
* This is a simple util class for easy database access and query execution in sql. You need to make sure that the respective JDBC connector is in the class path. By default, the adapter uses the mysql driver, but any jdbc driver can be
* used.
*
* @author fmohr, mwever
*
*/
@SuppressWarnings("serial")
class RestSqlAdapter extends ASqlBasedAdapter {
private final transient ISQLQueryBuilder queryBuilder = new MySQLQueryBuilder();
private transient Logger logger = LoggerFactory.getLogger(RestSqlAdapter.class);
private final String host;
private final String token;
private final String querySuffix;
private final String selectSuffix;
private final String insertSuffix;
private final String updateSuffix;
public RestSqlAdapter(final IRestDatabaseConfig config) {
this.host = config.getHost();
this.token = config.getToken();
this.querySuffix = config.getQuerySuffix();
this.selectSuffix = config.getSelectSuffix();
this.updateSuffix = config.getUpdateSuffix();
this.insertSuffix = config.getInsertSuffix();
Objects.requireNonNull(this.host);
Objects.requireNonNull(this.insertSuffix);
Objects.requireNonNull(this.updateSuffix);
Objects.requireNonNull(this.selectSuffix);
Objects.requireNonNull(this.querySuffix);
}
public List<IKVStore> select(final String query) throws SQLException {
this.logger.info("Sending query {}", query);
JsonNode res = this.executeRESTCall(this.host + this.selectSuffix, query);
this.logger.info("Received result as JSON node: {}.", res);
return KVStoreUtil.readFromJson(res);
}
@Override
public int[] insert(final String table, final Map<String, ? extends Object> values) throws SQLException {
return this.insert(this.queryBuilder.buildInsertSQLCommand(table, values));
}
@Override
public int[] insertMultiple(final String tablename, final List<String> keys, final List<List<?>> values) throws SQLException {
return this.insert(this.queryBuilder.buildMultiInsertSQLCommand(tablename, keys, values));
}
@Override
public int[] insert(final String query) throws SQLException {
JsonNode res = this.executeRESTCall(this.host + this.insertSuffix, query);
if (res instanceof ArrayNode) {
ArrayNode array = (ArrayNode) res;
return IntStream.range(0, array.size()).map(i -> array.get(i).asInt()).toArray();
} else {
if ((res.get("status").asInt() == 500) && (res.get("message").textValue().matches("(.*)Duplicate entry(.*) for key(.*)"))) {
throw new SQLException(res.get("message").textValue());
}
throw new IllegalStateException("Cannot parse result for insert query. Result is:\n" + res);
}
}
@Override
public int update(final String query) throws SQLException {
JsonNode res = this.executeRESTCall(this.host + this.updateSuffix, query);
return res.asInt();
}
@Override
public List<IKVStore> query(final String query) throws SQLException {
JsonNode res = this.executeRESTCall(this.host + this.querySuffix, query);
return KVStoreUtil.readFromJson(res);
}
public JsonNode executeRESTCall(final String URL, final String query) throws SQLException {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
root.set("token", root.textNode(this.token));
root.set("query", root.textNode(query));
this.logger.info("Sending query {}", query);
String jsonPayload = mapper.writeValueAsString(root);
StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(requestEntity);
this.logger.info("Waiting for response.");
CloseableHttpResponse response = client.execute(post);
this.logger.info("Received response. Now processing the result.");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode / 100 == 4 || statusCode / 100 == 5) {
// status code is 4xx or 5xx
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
this.logger.error("SQLasRESTServer returned status code: {}." + " \nThe sql query was: {}." + " \nThe response body is: {}", statusCode, query, responseBody);
throw new SQLException("SQL Server error: " + responseBody);
}
assert (statusCode == HttpStatus.SC_OK);
HttpEntity entity = response.getEntity();
return mapper.readTree(entity.getContent());
} catch (UnsupportedOperationException | IOException e) {
throw new SQLException(e);
}
}
@Override
public int update(final String tablename, final Map<String, ? extends Object> valuesToWrite, final Map<String, ? extends Object> where) throws SQLException {
StringBuilder queryStringBuilder = new StringBuilder();
queryStringBuilder.append("UPDATE " + tablename + " SET ");
queryStringBuilder.append(valuesToWrite.entrySet().stream().map(e -> e.getKey() + "='" + e.getValue() + "'").collect(Collectors.joining(",")));
if (!where.isEmpty()) {
queryStringBuilder.append(STR_SPACE_WHERE);
queryStringBuilder.append(where.entrySet().stream().map(e -> RestSqlAdapter.whereClauseElement(e.getKey(), e.getValue() != null ? e.getValue().toString() : null)).collect(Collectors.joining(STR_SPACE_AND)));
}
return this.update(queryStringBuilder.toString());
}
public static String whereClauseElement(final String key, final String value) {
StringBuilder sb = new StringBuilder();
sb.append(key);
if (value == null || value.equals("null")) {
sb.append(" IS NULL");
} else {
sb.append("='");
sb.append(value);
sb.append("'");
}
return sb.toString();
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
}
@Override
public void checkConnection() throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public void createTable(final String tablename, final String nameOfPrimaryField, final Collection<String> fieldnames, final Map<String, String> types, final Collection<String> keys) throws SQLException {
StringBuilder sqlMainTable = new StringBuilder();
StringBuilder keyFieldsSB = new StringBuilder();
sqlMainTable.append("CREATE TABLE IF NOT EXISTS `" + tablename + "` (");
if (!types.containsKey(nameOfPrimaryField)) {
throw new IllegalArgumentException("Type for primary field " + nameOfPrimaryField + " not specified.");
}
sqlMainTable.append("`" + nameOfPrimaryField + "` " + types.get(nameOfPrimaryField) + " NOT NULL AUTO_INCREMENT,");
for (String key : fieldnames) {
sqlMainTable.append("`" + key + "` " + types.get(key) + " NULL,");
keyFieldsSB.append("`" + key + "`,");
}
sqlMainTable.append("PRIMARY KEY (`" + nameOfPrimaryField + "`)");
sqlMainTable.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
this.update(sqlMainTable.toString());
}
@Override
public List<IKVStore> getRowsOfTable(final String table, final Map<String, String> conditions) throws SQLException {
return this.query(this.queryBuilder.buildSelectSQLCommand(table, conditions));
}
@Override
public List<IKVStore> getResultsOfQuery(final String query, final List<String> values) throws SQLException {
if (values.isEmpty()) {
return this.select(query);
} else {
throw new UnsupportedOperationException("Cannot cope with prepared statements and values to set.");
}
}
@Override
public int[] insert(final String sql, final List<? extends Object> values) throws SQLException {
return this.insert(this.queryBuilder.parseSQLCommand(sql, values));
}
@Override
public int[] insertMultiple(final String table, final List<String> keys, final List<List<? extends Object>> datarows, final int chunkSize) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public int update(final String sql, final List<? extends Object> values) throws SQLException {
return this.update(this.queryBuilder.parseSQLCommand(sql, values));
}
@Override
public void executeQueriesAtomically(final List<PreparedStatement> queries) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public void close() {
/* nothing to do */
}
@Override
public boolean doesTableExist(final String tablename) throws SQLException, IOException {
return this.getResultsOfQuery("SHOW TABLES").stream().anyMatch(r -> r.values().iterator().next().equals(tablename));
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/ResultSetSerializerException.java
|
package ai.libs.jaicore.db.sql;
import com.fasterxml.jackson.core.JsonProcessingException;
public class ResultSetSerializerException extends JsonProcessingException {
/**
* Automatically generated UID for serialization.
*/
private static final long serialVersionUID = -5056231809515489843L;
public ResultSetSerializerException(final String msg) {
super(msg);
}
public ResultSetSerializerException(final String msg, final Throwable cause) {
super(msg, cause);
}
public ResultSetSerializerException(final Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/ResultSetToJsonSerializer.java
|
package ai.libs.jaicore.db.sql;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ResultSetToJsonSerializer extends JsonSerializer<ResultSet> {
@Override
public Class<ResultSet> handledType() {
return ResultSet.class;
}
@Override
public void serialize(final ResultSet values, final JsonGenerator gen, final SerializerProvider serializer) throws IOException {
try {
ResultSetMetaData rsmd = values.getMetaData();
int numColumns = rsmd.getColumnCount();
String[] columnNames = new String[numColumns];
int[] columnTypes = new int[numColumns];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
columnTypes[i] = rsmd.getColumnType(i + 1);
}
gen.writeStartArray();
while (values.next()) {
boolean b;
long l;
double d;
gen.writeStartObject();
for (int i = 0; i < columnNames.length; i++) {
gen.writeFieldName(columnNames[i]);
switch (columnTypes[i]) {
case Types.INTEGER:
l = values.getInt(i + 1);
if (values.wasNull()) {
gen.writeNull();
} else {
gen.writeNumber(l);
}
break;
case Types.BIGINT:
l = values.getLong(i + 1);
if (values.wasNull()) {
gen.writeNull();
} else {
gen.writeNumber(l);
}
break;
case Types.DECIMAL:
case Types.NUMERIC:
gen.writeNumber(values.getBigDecimal(i + 1));
break;
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
d = values.getDouble(i + 1);
if (values.wasNull()) {
gen.writeNull();
} else {
gen.writeNumber(d);
}
break;
case Types.NVARCHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
gen.writeString(values.getString(i + 1));
break;
case Types.BOOLEAN:
case Types.BIT:
b = values.getBoolean(i + 1);
if (values.wasNull()) {
gen.writeNull();
} else {
gen.writeBoolean(b);
}
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
gen.writeBinary(values.getBytes(i + 1));
break;
case Types.TINYINT:
case Types.SMALLINT:
l = values.getShort(i + 1);
if (values.wasNull()) {
gen.writeNull();
} else {
gen.writeNumber(l);
}
break;
case Types.DATE:
serializer.defaultSerializeDateValue(values.getDate(i + 1), gen);
break;
case Types.TIMESTAMP:
serializer.defaultSerializeDateValue(values.getTime(i + 1), gen);
break;
case Types.BLOB:
Blob blob = values.getBlob(i);
serializer.defaultSerializeValue(blob.getBinaryStream(), gen);
blob.free();
break;
case Types.CLOB:
Clob clob = values.getClob(i);
serializer.defaultSerializeValue(clob.getCharacterStream(), gen);
clob.free();
break;
case Types.ARRAY:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type ARRAY");
case Types.STRUCT:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type STRUCT");
case Types.DISTINCT:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type DISTINCT");
case Types.REF:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type REF");
case Types.JAVA_OBJECT:
default:
serializer.defaultSerializeValue(values.getObject(i + 1), gen);
break;
}
}
gen.writeEndObject();
}
gen.writeEndArray();
} catch (SQLException e) {
throw new ResultSetSerializerException(e);
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/ResultSetToKVStoreSerializer.java
|
package ai.libs.jaicore.db.sql;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.api4.java.datastructure.kvstore.IKVStore;
import ai.libs.jaicore.basic.kvstore.KVStore;
import ai.libs.jaicore.basic.kvstore.KVStoreCollection;
import ai.libs.jaicore.logging.LoggerUtil;
public class ResultSetToKVStoreSerializer {
public List<IKVStore> serialize(final ResultSet values) {
KVStoreCollection collection = new KVStoreCollection();
Iterator<IKVStore> it = this.getSerializationIterator(values);
while (it.hasNext()) {
collection.add(it.next());
}
return collection;
}
public Iterator<IKVStore> getSerializationIterator(final ResultSet values) {
return new Iterator<IKVStore>() {
private boolean init = false;
private boolean hasNext = false;
private String[] columnNames;
private int[] columnTypes;
private void init() throws SQLException {
if (!this.init) {
this.init = true;
ResultSetMetaData rsmd = values.getMetaData();
int numColumns = rsmd.getColumnCount();
this.hasNext = values.next();
this.columnNames = new String[numColumns];
this.columnTypes = new int[numColumns];
for (int i = 0; i < this.columnNames.length; i++) {
this.columnNames[i] = rsmd.getColumnLabel(i + 1);
this.columnTypes[i] = rsmd.getColumnType(i + 1);
}
}
}
@Override
public boolean hasNext() {
try {
this.init();
return this.hasNext;
} catch (SQLException e) {
throw new NoSuchElementException(LoggerUtil.getExceptionInfo(e));
}
}
@Override
public IKVStore next() {
try {
this.init();
IKVStore val = ResultSetToKVStoreSerializer.this.serializeRow(values, this.columnNames, this.columnTypes);
this.hasNext = values.next();
if (!this.hasNext) {
values.getStatement().close();
}
return val;
} catch (ResultSetSerializerException | SQLException e) {
throw new NoSuchElementException(LoggerUtil.getExceptionInfo(e));
}
}
};
}
public IKVStore serializeRow(final ResultSet values, final String[] columnNames, final int[] columnTypes) throws SQLException, ResultSetSerializerException {
KVStore store = new KVStore();
for (int i = 0; i < columnNames.length; i++) {
String fieldName = columnNames[i];
switch (columnTypes[i]) {
case Types.INTEGER:
store.put(fieldName, values.getInt(i + 1));
break;
case Types.BIGINT:
store.put(fieldName, values.getLong(i + 1));
break;
case Types.DECIMAL:
case Types.NUMERIC:
store.put(fieldName, values.getBigDecimal(i + 1));
break;
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
store.put(fieldName, values.getDouble(i + 1));
break;
case Types.NVARCHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
store.put(fieldName, values.getString(i + 1));
break;
case Types.BOOLEAN:
case Types.BIT:
store.put(fieldName, values.getBoolean(i + 1));
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
store.put(fieldName, values.getByte(i + 1));
break;
case Types.TINYINT:
case Types.SMALLINT:
store.put(fieldName, values.getShort(i + 1));
break;
case Types.DATE:
store.put(fieldName, values.getDate(i + 1));
break;
case Types.TIMESTAMP:
store.put(fieldName, values.getTime(i + 1));
break;
case Types.BLOB:
store.put(fieldName, values.getBlob(i));
break;
case Types.CLOB:
store.put(fieldName, values.getClob(i));
break;
case Types.ARRAY:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type ARRAY");
case Types.STRUCT:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type STRUCT");
case Types.DISTINCT:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type DISTINCT");
case Types.REF:
throw new ResultSetSerializerException("ResultSetSerializer not yet implemented for SQL type REF");
case Types.JAVA_OBJECT:
default:
store.put(fieldName, values.getObject(i + 1));
break;
}
if (values.wasNull()) {
store.put(fieldName, null);
}
}
return store;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/sql/SQLAdapter.java
|
package ai.libs.jaicore.db.sql;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.db.IDatabaseConfig;
/**
* This is a simple util class for easy database access and query execution in sql. You need to make sure that the respective JDBC connector is in the class path. By default, the adapter uses the mysql driver, but any jdbc driver can be
* used.
*
* @author fmohr, mwever
*
*/
@SuppressWarnings("serial")
class SQLAdapter extends ASqlBasedAdapter {
private transient Logger logger = LoggerFactory.getLogger(SQLAdapter.class);
private static final String DB_DRIVER = "mysql";
/* Credentials and properties for the connection establishment. */
private final String driver;
private final String host;
private final String user;
private final String password;
private final String database;
private final boolean ssl;
private final Properties connectionProperties;
private final transient ISQLQueryBuilder queryBuilder = new MySQLQueryBuilder();
/* Connection object */
private transient Connection connect;
private long timestampOfLastAction = Long.MIN_VALUE;
/**
* Standard c'tor.
*
* @param config The database configuration including a definition of host, user, password, database and whether to connect to the server via SSL.
*/
public SQLAdapter(final IDatabaseConfig config) {
this(DB_DRIVER, config.getDBHost(), config.getDBUsername(), config.getDBPassword(), config.getDBDatabaseName(), new Properties(), config.getDBSSL());
}
/**
* Constructor for an SQLAdapter.
*
* @param host The host of the (remote) database server.
* @param user The username for logging into the database server.
* @param password The password corresponding to the username.
* @param database The name of the database to connect to.
* @param ssl Flag whether the connection must be ssl encrypted or not.
*/
public SQLAdapter(final String host, final String user, final String password, final String database, final boolean ssl) {
this(DB_DRIVER, host, user, password, database, new Properties(), ssl);
}
/**
* Constructor for an SQLAdapter. The connection is by default SSL encrypted.
*
* @param host The host of the (remote) database server.
* @param user The username for logging into the database server.
* @param password The password corresponding to the username.
* @param database The name of the database to connect to.
*/
public SQLAdapter(final String host, final String user, final String password, final String database) {
this(DB_DRIVER, host, user, password, database, new Properties());
}
/**
* Constructor for an SQLAdapter. The connection is by default SSL encrypted.
*
* @param host The host of the (remote) database server.
* @param user The username for logging into the database server.
* @param password The password corresponding to the username.
* @param database The name of the database to connect to.
* @param connectionProperties In these properties additional properties for the SQL connection may be defined.
*/
public SQLAdapter(final String driver, final String host, final String user, final String password, final String database, final Properties connectionProperties) {
this(driver, host, user, password, database, connectionProperties, true);
}
/**
* Constructor for an SQLAdapter.
*
* @param host The host of the (remote) database server.
* @param user The username for logging into the database server.
* @param password The password corresponding to the username.
* @param database The name of the database to connect to.
* @param connectionProperties In these properties additional properties for the SQL connection may be defined.
* @param ssl Flag whether the connection must be ssl encrypted or not.
*/
public SQLAdapter(final String driver, final String host, final String user, final String password, final String database, final Properties connectionProperties, final boolean ssl) {
super();
this.ssl = ssl;
this.driver = driver;
this.host = host;
this.user = user;
this.password = password;
this.database = database;
this.connectionProperties = connectionProperties;
try {
Runtime.getRuntime().addShutdownHook(new ShutdownThread(SQLAdapter.this));
} catch (Exception e) {
this.logger.warn("Failed to add shutdown hook for SQLAdapter");
}
}
/**
* Thread shutting down the SQLAdapter in the event of a shutdown of the JVM.
*
* @author mwever
*/
private class ShutdownThread extends Thread {
private SQLAdapter adapter;
/**
* C'tor that is provided with an SQLAdapter to be shut down.
*
* @param adapter The SQLAdapter to be shut down.
*/
public ShutdownThread(final SQLAdapter adapter) {
this.adapter = adapter;
}
@Override
public void run() {
this.adapter.close();
}
}
private void connect() throws SQLException {
int tries = 0;
this.logger.info("Connecting to database.");
do {
try {
Properties connectionProps = new Properties(this.connectionProperties);
connectionProps.put("user", this.user);
connectionProps.put("password", this.password != null ? this.password : "");
String connectionString = "jdbc:" + this.driver + "://" + this.host + "/" + this.database + ((this.ssl) ? "?verifyServerCertificate=false&requireSSL=true&useSSL=true" : "?useSSL=false");
this.logger.info("Connecting to {}", connectionString);
this.connect = DriverManager.getConnection(connectionString, connectionProps);
this.logger.info("Connection established.");
return;
} catch (SQLException e) {
tries++;
this.logger.error("Connection to server {} failed with JDBC driver {} (attempt {} of 3), waiting 3 seconds before trying again.", this.host, this.driver, tries, e);
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
this.logger.error(
"SQLAdapter got interrupted while trying to establish a connection to the database. NOTE: This will trigger an immediate shutdown as no sql connection could be established. Reason for the interrupt was:", e1);
break;
}
}
} while (tries < 3);
this.logger.error("Quitting execution as no database connection could be established");
}
/**
* Returns a prepared statement for the given query so that any placeholder may be filled into the prepared statement.
* @param query The query for which a prepared statement shall be returned.
* @return The prepared statement for the given query.
* @throws SQLException Thrown, if there was an issue with the connection to the database.
*/
public PreparedStatement getPreparedStatement(final String query) throws SQLException {
this.checkConnection();
return this.connect.prepareStatement(query);
}
/**
* Checks whether the connection to the database is still alive and re-establishs the connection if it is not.
* @throws SQLException Thrown, if there was an issue with reconnecting to the database server.
*/
@Override
public synchronized void checkConnection() throws SQLException {
int renewAfterSeconds = 5 * 60;
if (this.timestampOfLastAction + renewAfterSeconds * 1000 < System.currentTimeMillis()) {
this.close();
this.connect();
}
this.timestampOfLastAction = System.currentTimeMillis();
Objects.requireNonNull(this.connect, "Connection object is null!");
}
/**
* Retrieves all rows of a table.
* @param table The table for which all entries shall be returned.
* @return A list of {@link IKVStore}s containing the data of the table.
* @throws SQLException Thrown, if there was an issue with the connection to the database.
*/
@Override
public List<IKVStore> getRowsOfTable(final String table) throws SQLException {
this.logger.info("Fetching complete table {}", table);
return this.getRowsOfTable(table, new HashMap<>());
}
/**
* Retrieves all rows of a table which satisfy certain conditions (WHERE clause).
* @param table The table for which all entries shall be returned.
* @param conditions The conditions a result entry must satisfy.
* @return A list of {@link IKVStore}s containing the data of the table.
* @throws SQLException Thrown, if there was an issue with the connection to the database.
*/
@Override
public List<IKVStore> getRowsOfTable(final String table, final Map<String, String> conditions) throws SQLException {
return this.getResultsOfQuery(this.queryBuilder.buildSelectSQLCommand(table, conditions));
}
public Iterator<IKVStore> getRowIteratorOfTable(final String table) throws SQLException {
return this.getRowIteratorOfTable(table, new HashMap<>());
}
public Iterator<IKVStore> getRowIteratorOfTable(final String table, final Map<String, String> conditions) throws SQLException {
StringBuilder conditionSB = new StringBuilder();
List<String> values = new ArrayList<>();
for (Entry<String, String> entry : conditions.entrySet()) {
if (conditionSB.length() > 0) {
conditionSB.append(STR_SPACE_AND);
} else {
conditionSB.append(STR_SPACE_WHERE);
}
conditionSB.append(entry.getKey() + KEY_EQUALS_VALUE_TO_BE_SET);
values.add(entry.getValue());
}
return this.getResultIteratorOfQuery("SELECT * FROM `" + table + "`" + conditionSB.toString(), values);
}
/**
* Retrieves the select result for the given query.
* @param query The SQL query which is to be executed.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException Thrown, if there was an issue with the connection to the database.
*/
@Override
public List<IKVStore> getResultsOfQuery(final String query) throws SQLException {
return this.getResultsOfQuery(query, new ArrayList<>());
}
/**
* Retrieves the select result for the given query that can have placeholders.
* @param query The SQL query which is to be executed (with placeholders).
* @param values An array of placeholder values that need to be filled in.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException Thrown, if there was an issue with the connection to the database.
*/
@Override
public List<IKVStore> getResultsOfQuery(final String query, final String[] values) throws SQLException {
return this.getResultsOfQuery(query, Arrays.asList(values));
}
/**
* Retrieves the select result for the given query that can have placeholders.
* @param query The SQL query which is to be executed (with placeholders).
* @param values A list of placeholder values that need to be filled in.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException Thrown, if there was an issue with the query format or the connection to the database.
*/
@Override
public List<IKVStore> getResultsOfQuery(final String query, final List<String> values) throws SQLException {
this.checkConnection();
this.logger.info("Conducting query {} with values {}", query, values);
try (PreparedStatement statement = this.connect.prepareStatement(query)) {
for (int i = 1; i <= values.size(); i++) {
statement.setString(i, values.get(i - 1));
}
return new ResultSetToKVStoreSerializer().serialize(statement.executeQuery());
}
}
public Iterator<IKVStore> getResultIteratorOfQuery(final String query, final List<String> values) throws SQLException {
this.checkConnection();
boolean autoCommit = this.connect.getAutoCommit();
this.connect.setAutoCommit(false); // deactivate autocommit for this request
this.logger.info("Conducting query {} with values {}", query, values);
PreparedStatement statement = this.connect.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statement.setFetchSize(100); // this avoids that the whole result table is read
for (int i = 1; i <= values.size(); i++) {
statement.setString(i, values.get(i - 1));
}
Iterator<IKVStore> iterator = new ResultSetToKVStoreSerializer().getSerializationIterator(statement.executeQuery());
this.connect.setAutoCommit(autoCommit);
return iterator;
}
/**
* Executes an insert query and returns the row ids of the created entries.
* @param sql The insert statement which shall be executed that may have placeholders.
* @param values The values for the placeholders.
* @return An array of the row ids of the inserted entries.
* @throws SQLException Thrown, if there was an issue with the query format or the connection to the database.
*/
@Override
public int[] insert(final String sql, final String[] values) throws SQLException {
return this.insert(sql, Arrays.asList(values));
}
/**
* Executes an insert query and returns the row ids of the created entries.
* @param sql The insert statement which shall be executed that may have placeholders.
* @param values A list of values for the placeholders.
* @return An array of the row ids of the inserted entries.
* @throws SQLException Thrown, if there was an issue with the query format or the connection to the database.
*/
@Override
public int[] insert(final String sql, final List<? extends Object> values) throws SQLException {
this.checkConnection();
try (PreparedStatement stmt = this.connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
for (int i = 1; i <= values.size(); i++) {
this.setValue(stmt, i, values.get(i - 1));
}
stmt.executeUpdate();
List<Integer> generatedKeys = new LinkedList<>();
try (ResultSet rs = stmt.getGeneratedKeys()) {
while (rs.next()) {
generatedKeys.add(rs.getInt(1));
}
}
return generatedKeys.stream().mapToInt(x -> x).toArray();
}
}
/**
* Creates and executes an insert query for the given table and the values as specified in the map.
* @param table The table where to insert the data.
* @param map The map of key:value pairs to be inserted into the table.
* @return An array of the row ids of the inserted entries.
* @throws SQLException Thrown, if there was an issue with the query format or the connection to the database.
*/
@Override
public int[] insert(final String table, final Map<String, ? extends Object> map) throws SQLException {
Pair<String, List<Object>> insertStatement = this.queryBuilder.buildInsertStatement(table, map);
return this.insert(insertStatement.getX(), insertStatement.getY());
}
/**
* Creates a multi-insert statement and executes it. The returned array contains the row id's of the inserted rows. (By default it creates chunks of size 10.000 rows per query to be inserted.)
* @param table The table to which the rows are to be added.
* @param keys The list of column keys for which values are set.
* @param datarows The list of value lists to be filled into the table.
* @return An array of row id's of the inserted rows.
* @throws SQLException Thrown, if the sql statement was malformed, could not be executed, or the connection to the database failed.
*/
@Override
public int[] insertMultiple(final String table, final List<String> keys, final List<List<? extends Object>> datarows) throws SQLException {
return this.insertMultiple(table, keys, datarows, 10000);
}
/**
* Creates a multi-insert statement and executes it. The returned array contains the row id's of the inserted rows.
* @param table The table to which the rows are to be added.
* @param keys The list of column keys for which values are set.
* @param datarows The list of value lists to be filled into the table.
* @param chunkSize The number of rows which are added within one single database transaction. (10,000 seems to be a good value for this)
* @return An array of row id's of the inserted rows.
* @throws SQLException Thrown, if the sql statement was malformed, could not be executed, or the connection to the database failed.
*/
@Override
public int[] insertMultiple(final String table, final List<String> keys, final List<List<? extends Object>> datarows, final int chunkSize) throws SQLException {
int n = datarows.size();
this.checkConnection();
List<Integer> ids = new ArrayList<>(n);
for (int i = 0; i < Math.ceil(n * 1.0 / chunkSize); i++) {
int startIndex = i * chunkSize;
int endIndex = Math.min((i + 1) * chunkSize, n);
String sql = this.queryBuilder.buildMultiInsertSQLCommand(table, keys, datarows.subList(startIndex, endIndex));
try (PreparedStatement stmt = this.connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
this.logger.debug("Created SQL for {} entries", endIndex - startIndex);
stmt.executeUpdate();
this.logger.debug("Finished batch execution.");
try (ResultSet rs = stmt.getGeneratedKeys()) {
while (rs.next()) {
ids.add(rs.getInt(1));
}
}
}
}
return ids.stream().mapToInt(x -> x).toArray();
}
/**
* Execute the given sql statement as an update.
* @param sql The sql statement to be executed.
* @return The number of rows affected by the update statement.
* @throws SQLException Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
@Override
public int update(final String sql) throws SQLException {
return this.update(sql, new ArrayList<>());
}
/**
* Execute the given sql statement with placeholders as an update filling the placeholders with the given values beforehand.
* @param sql The sql statement with placeholders to be executed.
* @param sql Array of values for the respective placeholders.
* @return The number of rows affected by the update statement.
* @throws SQLException Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
@Override
public int update(final String sql, final String[] values) throws SQLException {
return this.update(sql, Arrays.asList(values));
}
/**
* Execute the given sql statement with placeholders as an update filling the placeholders with the given values beforehand.
* @param sql The sql statement with placeholders to be executed.
* @param values List of values for the respective placeholders.
* @return The number of rows affected by the update statement.
* @throws SQLException Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
@Override
public int update(final String sql, final List<? extends Object> values) throws SQLException {
this.checkConnection();
this.logger.debug("Executing update query: {} with values {}", sql, values);
try (PreparedStatement stmt = this.connect.prepareStatement(sql)) {
for (int i = 1; i <= values.size(); i++) {
stmt.setString(i, values.get(i - 1).toString());
}
return stmt.executeUpdate();
}
}
/**
* Create and execute an update statement for some table updating the values as described in <code>updateValues</code> and only affect those entries satisfying the <code>conditions</code>.
* @param table The table which is to be updated.
* @param updateValues The description how entries are to be updated.
* @param conditions The description of the where-clause, conditioning the entries which are to be updated.
* @return The number of rows affected by the update statement.
* @throws SQLException Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
@Override
public int update(final String table, final Map<String, ? extends Object> updateValues, final Map<String, ? extends Object> conditions) throws SQLException {
this.checkConnection();
// build the update mapping.
StringBuilder updateSB = new StringBuilder();
List<Object> values = new ArrayList<>();
for (Entry<String, ? extends Object> entry : updateValues.entrySet()) {
if (updateSB.length() > 0) {
updateSB.append(", ");
}
updateSB.append(entry.getKey() + KEY_EQUALS_VALUE_TO_BE_SET);
values.add(entry.getValue());
}
// build the condition restricting the elements which are affected by the update.
StringBuilder conditionSB = new StringBuilder();
for (Entry<String, ? extends Object> entry : conditions.entrySet()) {
if (conditionSB.length() > 0) {
conditionSB.append(STR_SPACE_AND);
}
if (entry.getValue() != null) {
conditionSB.append(entry.getKey() + KEY_EQUALS_VALUE_TO_BE_SET);
values.add(entry.getValue());
} else {
conditionSB.append(entry.getKey());
conditionSB.append(" IS NULL");
}
}
// Build query for the update command.
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("UPDATE ");
sqlBuilder.append(table);
sqlBuilder.append(" SET ");
sqlBuilder.append(updateSB.toString());
sqlBuilder.append(STR_SPACE_WHERE);
sqlBuilder.append(conditionSB.toString());
try (PreparedStatement stmt = this.connect.prepareStatement(sqlBuilder.toString())) {
for (int i = 1; i <= values.size(); i++) {
this.setValue(stmt, i, values.get(i - 1));
}
return stmt.executeUpdate();
}
}
/**
* Executes the given statements atomically. Only works if no other statements are sent through this adapter in parallel! Only use for single-threaded applications, otherwise side effects may happen as this changes the auto commit
* settings of the connection temporarily.
*
* @param queries
* The queries to execute atomically
* @throws SQLException
* If the status of the connection cannot be changed. If something goes wrong while executing the given statements, they are rolled back before they are committed.
*/
@Override
public void executeQueriesAtomically(final List<PreparedStatement> queries) throws SQLException {
this.checkConnection();
this.connect.setAutoCommit(false);
try {
for (PreparedStatement query : queries) {
query.execute();
}
this.connect.commit();
} catch (SQLException e) {
this.logger.error("Transaction is being rolled back.", e);
try {
this.connect.rollback();
} catch (SQLException e1) {
this.logger.error("Could not rollback the connection", e1);
}
} finally {
for (PreparedStatement query : queries) {
if (query != null) {
query.close();
}
}
this.connect.setAutoCommit(true);
}
}
@Override
public List<IKVStore> query(final String sqlStatement) throws SQLException, IOException {
this.checkConnection();
try (Statement stmt = this.connect.createStatement()) {
try (ResultSet ps = stmt.executeQuery(sqlStatement)) {
return new ResultSetToKVStoreSerializer().serialize(ps);
}
}
}
private void setValue(final PreparedStatement stmt, final int index, final Object val) throws SQLException {
if (val instanceof Integer) {
stmt.setInt(index, (Integer) val);
} else if (val instanceof Long) {
stmt.setLong(index, (Long) val);
} else if (val instanceof Number) {
stmt.setDouble(index, (Double) val);
} else if (val instanceof String) {
stmt.setString(index, (String) val);
} else {
stmt.setObject(index, val);
}
}
/**
* Close the connection. No more queries can be sent after having the access object closed
*/
@Override
public void close() {
try {
if (this.connect != null) {
this.connect.close();
}
} catch (Exception e) {
this.logger.error("An exception occurred while closing the database connection.", e);
}
}
/**
* Getter for the sql database driver.
* @return The name of the database driver.
*/
public String getDriver() {
return this.driver;
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
}
@Override
public void createTable(final String tablename, final String nameOfPrimaryField, final Collection<String> fieldnames, final Map<String, String> types, final Collection<String> keys) throws SQLException {
this.checkConnection();
Objects.requireNonNull(this.connect);
StringBuilder sqlMainTable = new StringBuilder();
StringBuilder keyFieldsSB = new StringBuilder();
sqlMainTable.append("CREATE TABLE IF NOT EXISTS `" + tablename + "` (");
if (!types.containsKey(nameOfPrimaryField)) {
throw new IllegalArgumentException("No type definition given for primary field!");
}
sqlMainTable.append("`" + nameOfPrimaryField + "` " + types.get(nameOfPrimaryField) + " NOT NULL AUTO_INCREMENT,");
for (String key : fieldnames) {
if (!types.containsKey(key)) {
throw new IllegalArgumentException("No type information given for field " + key);
}
sqlMainTable.append("`" + key + "` " + types.get(key) + (types.get(key).contains("NULL") ? "" : " NOT NULL") + ",");
keyFieldsSB.append("`" + key + "`,");
}
sqlMainTable.append("PRIMARY KEY (`" + nameOfPrimaryField + "`)");
sqlMainTable.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
/* prepare statement */
try (Statement stmt = this.connect.createStatement()) {
this.logger.info("Executing query: {}", sqlMainTable);
stmt.execute(sqlMainTable.toString());
}
}
@Override
public boolean doesTableExist(final String tablename) throws IOException, SQLException {
return this.getResultsOfQuery("SHOW TABLES").stream().anyMatch(r -> r.values().iterator().next().equals(tablename));
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/graph/Graph.java
|
package ai.libs.jaicore.graph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.SetUtil;
public class Graph<T> {
private T root;
private final Map<T, Set<T>> successors = new HashMap<>();
private final Map<T, Set<T>> predecessors = new HashMap<>();
private boolean useBackPointers = true;
private boolean useForwardPointers = true;
public Graph() {
}
public Graph(final T node) {
this();
this.addItem(node);
}
public Graph(final Collection<T> nodes) {
this();
for (T node : nodes) {
this.addItem(node);
}
}
public Graph(final Graph<T> toClone) {
this();
for (T i : toClone.getItems()) {
for (T i2 : toClone.getSuccessors(i)) {
this.addEdge(i, i2);
}
}
}
public void addItem(final T item) {
if (this.getItems().contains(item)) {
throw new IllegalArgumentException("Cannot add node " + item + " to graph since such a node exists already. Current nodes: " + this.getItems().stream().map(e -> "\n\t" + e).collect(Collectors.joining()));
}
if (this.useForwardPointers) {
this.successors.put(item, new HashSet<>());
}
if (this.useBackPointers) {
this.predecessors.put(item, new HashSet<>());
}
if (this.root == null) {
this.root = item;
}
if (!this.hasItem(item)) {
throw new IllegalStateException("Just added node " + item + " does not respond positively on a call to hasItem");
}
}
public void addPath(final List<T> path) {
T parent = null;
for (T node : path) {
if (!this.hasItem(node)) {
this.addItem(node);
}
if (parent != null && !this.getPredecessors(node).contains(parent)) {
this.addEdge(parent, node);
}
parent = node;
}
}
public Set<T> getItems() {
return Collections.unmodifiableSet(this.successors.keySet());
}
public boolean hasItem(final T item) {
if (this.useForwardPointers) {
return this.successors.containsKey(item);
}
if (this.useBackPointers) {
return this.predecessors.containsKey(item);
}
throw new IllegalStateException("Graph must use forward pointers and/or backward pointers.");
}
public boolean hasEdge(final T from, final T to) {
return this.successors.containsKey(from) && this.successors.get(from).contains(to);
}
public boolean hasPath(final List<T> nodes) {
T last = null;
for (T current : nodes) {
if (last != null && !this.hasEdge(last, current)) {
return false;
}
last = current;
}
return true;
}
public void removeItem(final T item) {
if (this.useForwardPointers) {
this.successors.remove(item); // remove successors of this node
this.successors.forEach((k, v) -> v.remove(item)); // erase the node from successor lists
}
if (this.useBackPointers) {
this.predecessors.remove(item); // remove predecessors of this node
this.predecessors.forEach((k, v) -> v.remove(item)); // erase the node from predecessor lists
}
}
public void addEdge(final T from, final T to) {
if (!this.hasItem(from)) {
this.addItem(from);
}
if (!this.hasItem(to)) {
this.addItem(to);
}
if (this.useForwardPointers) {
this.successors.get(from).add(to);
}
if (this.useBackPointers) {
this.predecessors.computeIfAbsent(to, n -> new HashSet<>()).add(from);
}
/* update root if necessary */
if (to == this.root) {
this.root = null;
if (this.predecessors.get(from).isEmpty()) {
this.root = from;
}
}
}
public void removeEdge(final T from, final T to) {
this.checkNodeExistence(from);
this.checkNodeExistence(to);
this.successors.get(from).remove(to);
this.predecessors.get(to).remove(from);
/* update root if necessary */
if (from == this.root) {
this.root = null;
if (this.getPredecessors(to).isEmpty()) {
this.root = to;
}
}
}
public Set<T> getSuccessors(final T item) {
if (!this.useForwardPointers) {
throw new UnsupportedOperationException();
}
if (!this.successors.containsKey(item)) {
throw new IllegalStateException("No predecessor map defined for node " + item);
}
return Collections.unmodifiableSet(this.successors.get(item));
}
public Set<T> getPredecessors(final T item) {
if (!this.useBackPointers) {
throw new UnsupportedOperationException();
}
if (!this.predecessors.containsKey(item)) {
throw new IllegalStateException("No predecessor map defined for node " + item);
}
return Collections.unmodifiableSet(this.predecessors.get(item));
}
public Set<T> getSiblings(final T item) {
Set<T> siblings = new HashSet<>();
for (T parent : this.getPredecessors(item)) {
for (T child : this.getSuccessors(parent)) {
if (!child.equals(item)) {
siblings.add(child);
}
}
}
return siblings;
}
public Set<T> getDescendants(final T item) {
List<T> open = new ArrayList<>();
open.add(item);
Set<T> descendants = new HashSet<>();
while (!open.isEmpty()) {
T next = open.remove(0);
descendants.add(next);
this.getSuccessors(next).forEach(open::add);
}
descendants.remove(item);
return descendants;
}
public Set<T> getConnected(final T item) {
Set<T> connected = new HashSet<>();
connected.addAll(this.getSuccessors(item));
connected.addAll(this.getPredecessors(item));
return connected;
}
private void checkNodeExistence(final T item) {
if (!this.hasItem(item)) {
throw new IllegalArgumentException("Cannot perform operation on node " + item + ", which does not exist!");
}
}
public final Collection<T> getSources() {
Collection<T> sources;
if (this.useBackPointers) {
sources = new ArrayList<>();
for (Entry<T, Set<T>> parentRelations : this.predecessors.entrySet()) {
if (parentRelations.getValue().isEmpty()) {
sources.add(parentRelations.getKey());
}
}
}
else if (this.useForwardPointers) {
sources = new HashSet<>(this.successors.keySet());
for (Entry<T, Set<T>> childRelations : this.successors.entrySet()) {
sources.removeAll(childRelations.getValue());
}
}
else {
throw new UnsupportedOperationException("Neither forward edges nor backward edges are contained.");
}
return sources;
}
public final T getRoot() {
return this.root;
}
public final Collection<T> getSinks() {
Collection<T> sinks;
if (this.useForwardPointers) {
sinks = new ArrayList<>();
for (Entry<T, Set<T>> childRelations : this.successors.entrySet()) {
if (childRelations.getValue().isEmpty()) {
sinks.add(childRelations.getKey());
}
}
}
else if (this.useBackPointers){
sinks = new HashSet<>(this.predecessors.keySet());
for (Entry<T, Set<T>> parentRelations : this.predecessors.entrySet()) {
sinks.removeAll(parentRelations.getValue());
}
}
else {
throw new UnsupportedOperationException("Neither forward edges nor backward edges are contained.");
}
return sinks;
}
public final void addGraph(final Graph<T> g) {
for (T t : SetUtil.difference(g.getItems(), this.getItems())) {
this.addItem(t);
}
for (T t1 : g.getItems()) {
for (T t2 : g.getSuccessors(t1)) {
this.addEdge(t1, t2);
}
}
}
public boolean isEmpty() {
return this.useForwardPointers ? this.successors.isEmpty() : this.predecessors.isEmpty();
}
/**
* Creates a new line for each path in the graph where the prefix common to the previous line is omitted.
* The order is obtained by BFS.
**/
public String getLineBasedStringRepresentation() {
return this.getLineBasedStringRepresentation(1);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.predecessors.hashCode();
result = prime * result + this.successors.hashCode();
result = prime * result + (this.useBackPointers ? 1231 : 1237);
result = prime * result + (this.useForwardPointers ? 1231 : 1237);
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Graph<?> other = (Graph<?>) obj;
if (!this.predecessors.equals(other.predecessors)) {
return false;
}
if (!this.successors.equals(other.successors)) {
return false;
}
if (this.useBackPointers != other.useBackPointers) {
return false;
}
return this.useForwardPointers == other.useForwardPointers;
}
public String getLineBasedStringRepresentation(final int offset) {
StringBuilder sb = new StringBuilder();
for (T source : this.getSources()) {
sb.append(this.getLineBasedStringRepresentation(source, offset, new ArrayList<>()));
}
return sb.toString();
}
private String getLineBasedStringRepresentation(final T node, final int outerOffset, final List<Boolean> childrenOffset) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < outerOffset; i++) {
sb.append("\t");
}
for (boolean lastChild : childrenOffset) {
sb.append(lastChild ? " " : "|");
sb.append(" ");
}
if (!childrenOffset.isEmpty()) {
sb.append("+----- ");
}
sb.append(node.toString());
Collection<T> successorsOfThisNode = this.getSuccessors(node);
int n = successorsOfThisNode.size();
int i = 1;
for (T successor : successorsOfThisNode) {
sb.append("\n");
List<Boolean> childrenOffsetCopy = new ArrayList<>(childrenOffset);
childrenOffsetCopy.add(i++ == n);
sb.append(this.getLineBasedStringRepresentation(successor, outerOffset, childrenOffsetCopy));
}
return sb.toString();
}
public boolean isGraphSane() {
/* check that all nodes are contained */
boolean allNodesContained = this.getItems().stream().allMatch(this::hasItem);
if (!allNodesContained) {
assert allNodesContained : "Not every node n in the node map have positive responses for a call of hasItem(n)";
return false;
}
/* check that all successors are contained */
boolean allSuccessorsContained = this.getItems().stream().allMatch(n -> this.getSuccessors(n).stream().allMatch(this::hasItem));
if (!allSuccessorsContained) {
assert allSuccessorsContained : "There is a node in the graph such that not every successor n of it has a positive response for a call of hasItem(n)";
return false;
}
/* check that all predecessors are contained */
return true;
}
public boolean isUseBackPointers() {
return this.useBackPointers;
}
public void setUseBackPointers(final boolean useBackPointers) {
this.useBackPointers = useBackPointers;
if (!useBackPointers) {
this.predecessors.clear();
}
}
public boolean isUseForwardPointers() {
return this.useForwardPointers;
}
public void setUseForwardPointers(final boolean useForwardPointers) {
this.useForwardPointers = useForwardPointers;
if (!useForwardPointers) {
this.successors.clear();
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/graph/LabeledGraph.java
|
package ai.libs.jaicore.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
public class LabeledGraph<T, L> extends Graph<T> {
private static class Edge<T> {
private T from;
private T to;
public Edge(final T from, final T to) {
super();
this.from = from;
this.to = to;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.from == null) ? 0 : this.from.hashCode());
result = prime * result + ((this.to == null) ? 0 : this.to.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Edge<?> other = (Edge<?>) obj;
if (this.from == null) {
if (other.from != null) {
return false;
}
} else if (!this.from.equals(other.from)) {
return false;
}
if (this.to == null) {
if (other.to != null) {
return false;
}
} else if (!this.to.equals(other.to)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Edge [from=" + this.from + ", to=" + this.to + "]";
}
}
private final Map<Edge<T>, L> labels = new HashMap<>();
public LabeledGraph() {
super();
}
public LabeledGraph(final LabeledGraph<T, L> graph) {
super();
for (T i : graph.getItems()) {
this.addItem(i);
}
for (T i : this.getItems()) {
for (T i2 : graph.getSuccessors(i)) {
this.addEdge(i, i2, graph.getEdgeLabel(i, i2));
}
}
}
@Override
public void addEdge(final T from, final T to) {
this.addEdge(from, to, null);
}
public void addEdge(final T from, final T to, final L label) {
super.addEdge(from, to);
this.labels.put(new Edge<>(from, to), label);
}
public final void addGraph(final LabeledGraph<T, L> g) {
for (T t : SetUtil.difference(g.getItems(), this.getItems())) {
this.addItem(t);
}
for (T t1 : g.getItems()) {
for (T t2 : g.getSuccessors(t1)) {
this.addEdge(t1, t2, g.getEdgeLabel(t1, t2));
}
}
}
public void addPath(final ILabeledPath<T, L> path) {
List<T> nodes = path.getNodes();
List<L> pathLabels = path.getArcs();
int n = nodes.size();
T last = null;
for (int i = 0; i < n; i++) {
T current = nodes.get(i);
this.addItem(current);
if (last != null) {
L label = pathLabels.get(i - 1);
this.addEdge(last, current, label);
}
last = current;
}
}
public L getEdgeLabel(final Pair<T, T> edge) {
return this.getEdgeLabel(edge.getX(), edge.getY());
}
public L getEdgeLabel(final T from, final T to) {
Edge<T> e = new Edge<>(from, to);
if (!this.labels.containsKey(e)) {
List<T> targets = new ArrayList<>();
for (Edge<T> e2 : this.labels.keySet()) {
if (e2.from.equals(from)) {
targets.add(e2.to);
if (e2.to.equals(to)) {
if (!this.labels.containsKey(e2)) {
throw new IllegalStateException("The edge " + e2 + " with hashCode " + e2.hashCode() + " is contained in the labeling but cannot be accessed anymore using new edge object with hash value " + e.hashCode() + "!");
}
assert false : "This line should never be reached!";
}
}
}
throw new IllegalArgumentException("No label for the edge from " + from + " (" + from.hashCode() + ") to " + to + " (" + to.hashCode() + ") is available! List of targets of " + from + ": " + targets);
}
return this.labels.get(e);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + this.labels.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
LabeledGraph other = (LabeledGraph) obj;
return this.labels.equals(other.labels);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/graph/NodeNotFoundException.java
|
package ai.libs.jaicore.graph;
public class NodeNotFoundException extends Exception {
/**
* Generated Serial UID for extending Java API class Exception
*/
private static final long serialVersionUID = -8334959000362299402L;
private final transient Object item;
public NodeNotFoundException(final Object item) {
super();
this.item = item;
}
public Object getItem() {
return this.item;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/graph/ReadOnlyPathAccessor.java
|
package ai.libs.jaicore.graph;
import java.util.Collections;
import java.util.List;
import org.api4.java.datastructure.graph.ILabeledPath;
public class ReadOnlyPathAccessor<N, A> implements ILabeledPath<N, A> {
private final ILabeledPath<N, A> path;
public ReadOnlyPathAccessor(final ILabeledPath<N, A> path) {
super();
this.path = path;
}
@Override
public ILabeledPath<N, A> getUnmodifiableAccessor() {
return this;
}
@Override
public N getRoot() {
return this.path.getRoot();
}
@Override
public N getHead() {
return this.path.getHead();
}
@Override
public N getParentOfHead() {
return this.path.getParentOfHead();
}
@Override
public void extend(final N newHead, final A arcToNewHead) {
throw new UnsupportedOperationException("This is a read-only path.");
}
@Override
public void cutHead() {
throw new UnsupportedOperationException("This is a read-only path.");
}
@Override
public ILabeledPath<N, A> getPathToParentOfHead() {
return this.path.getPathToParentOfHead();
}
@Override
public ILabeledPath<N, A> getPathFromChildOfRoot() {
return this.path.getPathFromChildOfRoot();
}
@Override
public List<N> getNodes() {
return Collections.unmodifiableList(this.path.getNodes());
}
@Override
public boolean isPoint() {
return this.path.isPoint();
}
@Override
public int getNumberOfNodes() {
return this.path.getNumberOfNodes();
}
@Override
public List<A> getArcs() {
return Collections.unmodifiableList(this.path.getArcs());
}
@Override
public A getInArc(final N node) {
return this.path.getInArc(node);
}
@Override
public A getOutArc(final N node) {
return this.path.getOutArc(node);
}
@Override
public boolean containsNode(final N node) {
return this.path.containsNode(node);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/graph/TreeNode.java
|
package ai.libs.jaicore.graph;
import java.util.ArrayList;
import java.util.List;
public class TreeNode<T> {
private final T value;
private final TreeNode<T> parent;
private final List<TreeNode<T>> children = new ArrayList<>();
public TreeNode(final T rootData) {
this(rootData,null);
}
public TreeNode(final T value, final TreeNode<T> parent) {
this.value = value;
this.parent = parent;
}
public TreeNode<T> addChild(final T child) {
TreeNode<T> childNode = new TreeNode<>(child, this);
this.children.add(childNode);
return childNode;
}
public void removeChild(final T child) {
this.children.removeIf(c -> c.value.equals(child));
}
public T getValue() {
return this.value;
}
public TreeNode<T> getParent() {
return this.parent;
}
public List<TreeNode<T>> getChildren() {
return this.children;
}
public TreeNode<T> getRootNode() {
return this.parent == null ? this : this.parent.getRootNode();
}
public List<T> getValuesOnPathFromRoot() {
if (this.parent == null) {
List<T> path = new ArrayList<>();
path.add(this.value);
return path;
}
List<T> valuesOnPathFromRootToParent = this.parent.getValuesOnPathFromRoot();
valuesOnPathFromRootToParent.add(this.value);
return valuesOnPathFromRootToParent;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/interrupt/Interrupt.java
|
package ai.libs.jaicore.interrupt;
public class Interrupt {
private final Thread interruptingThread;
private final Thread interruptedThread;
private final long timestampOfInterruption;
private final Object reasonForInterruption;
public Interrupt(final Thread interruptingThread, final Thread interruptedThread, final long timestampOfInterruption, final Object reasonForInterruption) {
super();
this.interruptingThread = interruptingThread;
this.interruptedThread = interruptedThread;
this.timestampOfInterruption = timestampOfInterruption;
this.reasonForInterruption = reasonForInterruption;
}
public Thread getInterruptingThread() {
return this.interruptingThread;
}
public Thread getInterruptedThread() {
return this.interruptedThread;
}
public long getTimestampOfInterruption() {
return this.timestampOfInterruption;
}
public Object getReasonForInterruption() {
return this.reasonForInterruption;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/interrupt/Interrupter.java
|
package ai.libs.jaicore.interrupt;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is used to conduct managed interrupts, which is essential for organized interrupts.
*
* In AILibs, it is generally forbidden to directly interrupt any thread.
* Instead, the Interrupter should be used, because this enables the interrupted thread to decide how to proceed.
*
* Using the Interrupter has several advantages in debugging:
*
* 1. the Interrupter tells which thread caused the interrupt
* 2. the Interrupter tells the time when the thread was interrupted
* 3. the Interrupter provides a reason for the interrupt
*
* @author fmohr
*
*/
public class Interrupter {
/**
* The interrupter is a singleton and must not be created manually.
*/
private Interrupter() {
super();
}
private static final Logger logger = LoggerFactory.getLogger(Interrupter.class);
private static final Interrupter instance = new Interrupter();
public static Interrupter get() {
return instance;
}
private final Map<Thread, Set<Object>> blackListedInterruptReasons = new HashMap<>(); // interrupts to avoid when they arrive
private final List<Interrupt> openInterrupts = new LinkedList<>();
public synchronized void interruptThread(final Thread t, final Object reason) {
if (this.blackListedInterruptReasons.containsKey(t) && this.blackListedInterruptReasons.get(t).contains(reason)) {
this.blackListedInterruptReasons.get(t).remove(reason);
logger.info("Thread {} is not interrupted, because it has been marked to be avoided for reason {}. Removing the entry from the black list.", t, reason);
return;
}
this.openInterrupts.add(new Interrupt(Thread.currentThread(), t, System.currentTimeMillis(), reason));
logger.info("Interrupting {} on behalf of {} with reason {}", t, Thread.currentThread(), reason);
t.interrupt();
logger.info("Interrupt accomplished. Interrupt flag of {}: {}", t, t.isInterrupted());
}
public boolean hasCurrentThreadBeenInterruptedWithReason(final Object reason) {
return this.hasThreadBeenInterruptedWithReason(Thread.currentThread(), reason);
}
public Optional<Interrupt> getInterruptOfCurrentThreadWithReason(final Object reason) {
return this.getInterruptOfThreadWithReason(Thread.currentThread(), reason);
}
public Optional<Interrupt> getInterruptOfThreadWithReason(final Thread thread, final Object reason) {
return this.openInterrupts.stream().filter(i -> i.getInterruptedThread() == thread && i.getReasonForInterruption().equals(reason)).findFirst();
}
public void avoidInterrupt(final Thread t, final Object reason) {
this.blackListedInterruptReasons.computeIfAbsent(t, x -> new HashSet<>()).add(reason);
}
public boolean hasThreadBeenInterruptedWithReason(final Thread thread, final Object reason) {
boolean matches = this.openInterrupts.stream().anyMatch(i -> i.getInterruptedThread() == thread && i.getReasonForInterruption().equals(reason));
if (logger.isDebugEnabled()) {
if (matches) {
logger.debug("Reasons for why thread {} has currently been interrupted: {}. Checked reason {} matched? {}", thread,
this.openInterrupts.stream().filter(t -> t.getInterruptedThread() == thread).map(Interrupt::getReasonForInterruption).collect(Collectors.toList()), reason, matches);
} else {
logger.debug("Thread {} is currently not interrupted. In particular, it is not interrupted with reason {}", thread, reason);
}
}
return matches;
}
public Collection<Interrupt> getAllUnresolvedInterrupts() {
return this.openInterrupts;
}
public Collection<Interrupt> getAllUnresolvedInterruptsOfThread(final Thread thread) {
return this.openInterrupts.stream().filter(i -> i.getInterruptedThread() == thread).collect(Collectors.toList());
}
public Optional<Interrupt> getLatestUnresolvedInterruptOfThread(final Thread thread) {
return this.getAllUnresolvedInterruptsOfThread(thread).stream().sorted((i1, i2) -> Long.compare(i1.getTimestampOfInterruption(), i2.getTimestampOfInterruption())).findFirst();
}
public Optional<Interrupt> getLatestUnresolvedInterruptOfCurrentThread() {
return this.getLatestUnresolvedInterruptOfThread(Thread.currentThread());
}
public boolean hasCurrentThreadOpenInterrupts() {
Thread currentThread = Thread.currentThread();
return this.openInterrupts.stream().anyMatch(i -> i.getInterruptedThread() == currentThread);
}
public synchronized void markInterruptOnCurrentThreadAsResolved(final Object reason) throws InterruptedException {
Thread ct = Thread.currentThread();
this.markInterruptAsResolved(ct, reason);
if (this.hasCurrentThreadOpenInterrupts()) {
Thread.interrupted(); // clear flag prior to throwing the InterruptedException
logger.info("Throwing a new InterruptedException after having resolved the current interrupt, because the thread still has open interrupts! The reasons for these are: {}",
this.getAllUnresolvedInterruptsOfThread(ct).stream().map(Interrupt::getReasonForInterruption).collect(Collectors.toList()));
throw new InterruptedException();
}
}
public synchronized void markInterruptAsResolved(final Thread t, final Object reason) {
if (!this.hasThreadBeenInterruptedWithReason(t, reason)) {
throw new IllegalArgumentException("The thread " + t + " has not been interrupted with reason " + reason + ". Reasons for which it has been interrupted: "
+ Interrupter.get().getAllUnresolvedInterruptsOfThread(Thread.currentThread()).stream().map(Interrupt::getReasonForInterruption).collect(Collectors.toList()));
}
logger.debug("Removing interrupt with reason {} from list of open interrupts for thread {}", reason, t);
this.openInterrupts.removeIf(i -> i.getInterruptedThread() == t && i.getReasonForInterruption().equals(reason));
if (this.getAllUnresolvedInterruptsOfThread(t).contains(reason)) {
throw new IllegalStateException("The interrupt should have been resolved, but it has not!");
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/interrupt/InterruptionTimerTask.java
|
package ai.libs.jaicore.interrupt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.concurrent.ANamedTimerTask;
public class InterruptionTimerTask extends ANamedTimerTask {
private static final Logger logger = LoggerFactory.getLogger(InterruptionTimerTask.class);
private final Thread threadToBeInterrupted;
private final Object reason;
private final Runnable hookToExecutePriorToInterruption;
private boolean triggered = false;
private boolean finished = false;
public InterruptionTimerTask(final String descriptor, final Thread threadToBeInterrupted, final Object reason, final Runnable hookToExecutePriorToInterruption) {
super(descriptor);
this.threadToBeInterrupted = threadToBeInterrupted;
this.hookToExecutePriorToInterruption = hookToExecutePriorToInterruption;
this.reason = reason;
}
public InterruptionTimerTask(final String descriptor, final Thread threadToBeInterrupted, final Runnable hookToExecutePriorToInterruption) {
super(descriptor);
this.threadToBeInterrupted = threadToBeInterrupted;
this.hookToExecutePriorToInterruption = hookToExecutePriorToInterruption;
this.reason = this;
}
public InterruptionTimerTask(final String descriptor, final Thread threadToBeInterrupted) {
this(descriptor, threadToBeInterrupted, null);
}
public InterruptionTimerTask(final String descriptor, final Runnable hookToExecutePriorToInterruption) {
this(descriptor, Thread.currentThread(), hookToExecutePriorToInterruption);
}
public InterruptionTimerTask(final String descriptor) {
this(descriptor, Thread.currentThread(), null);
}
public Thread getThreadToBeInterrupted() {
return this.threadToBeInterrupted;
}
public Runnable getHookToExecutePriorToInterruption() {
return this.hookToExecutePriorToInterruption;
}
@Override
public void exec() {
long delay = System.currentTimeMillis() - this.scheduledExecutionTime();
this.triggered = true;
logger.info("Executing interruption task {} with descriptor \"{}\". Interrupting thread {}. This interrupt has been triggered with a delay of {}ms", this.hashCode(), this.getDescriptor(), this.threadToBeInterrupted, delay);
if (delay > 50) {
logger.warn("Interrupt is executed with a delay of {}ms", delay);
}
if (this.hookToExecutePriorToInterruption != null) {
logger.debug("Running pre-interruption hook");
this.hookToExecutePriorToInterruption.run();
} else {
logger.debug("No pre-interruption hook has been defined.");
}
logger.debug("Interrupting the thread.");
Interrupter.get().interruptThread(this.threadToBeInterrupted, this.reason);
this.finished = true;
}
public boolean isTriggered() {
return this.triggered;
}
public Object getReason() {
return this.reason;
}
@Override
public boolean isFinished() {
return this.finished;
}
@Override
public String toString() {
return "InterruptionTimerTask [threadToBeInterrupted=" + this.threadToBeInterrupted + ", name=" + this.getDescriptor() + ", triggered=" + this.triggered + ", finished=" + this.finished + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/interrupt/UndeclaredInterruptedException.java
|
package ai.libs.jaicore.interrupt;
public class UndeclaredInterruptedException extends RuntimeException {
private static final long serialVersionUID = 1387159071444885644L;
public UndeclaredInterruptedException(final String msg) {
super(msg);
}
public UndeclaredInterruptedException(final String msg, final InterruptedException e) {
super(msg, e);
}
public UndeclaredInterruptedException(final InterruptedException e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/logging/LoggerUtil.java
|
package ai.libs.jaicore.logging;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ai.libs.jaicore.basic.sets.Pair;
public class LoggerUtil {
public static final String LOGGER_NAME_EXAMPLE = "example"; // name for loggers of an object describing an example usage
public static final String LOGGER_NAME_TESTER = "tester"; // name for loggers that conduct tests
public static final String LOGGER_NAME_TESTEDALGORITHM = "testedalgorithm"; // name for loggers of algorithms that ARE tested within a test
public static final String LOGGER_NAME_EVALUATOR = "evaluator"; // name for loggers that conduct scientific experiments
public static final String LOGGER_NAME_EVALUATEDALGORITHM = "evaluatedalgorithm"; // name for loggers of algorithms that ARE evaluated in an experiment
private static final String INDENTED_LINEBREAK = "\n\t\t";
private LoggerUtil() {
/* avoid instantiation */
}
public static String getExceptionInfo(final Throwable e) {
return getExceptionInfo(e, new ArrayList<>());
}
public static String getExceptionInfo(final Throwable e, final List<Pair<String, Object>> additionalInformationObjects) {
StringBuilder sb = new StringBuilder();
sb.append("\n\tError class: ");
sb.append(e.getClass().getName());
sb.append("\n\tError message: ");
if (e.getMessage() != null) {
sb.append(e.getMessage().replace("\n", INDENTED_LINEBREAK));
} else {
sb.append("NaN");
}
sb.append("\n\tError trace:");
Arrays.asList(e.getStackTrace()).forEach(ste -> sb.append(INDENTED_LINEBREAK + ste.toString()));
Throwable current = e;
while (current.getCause() != null) {
current = current.getCause();
sb.append("\n\tCaused by " + current.getClass().getName() + " with message " + current.getMessage() + ". Stack trace of the cause:");
Arrays.asList(current.getStackTrace()).forEach(ste -> sb.append(INDENTED_LINEBREAK + ste.toString()));
}
/* if additional objects are given, add their content */
if (additionalInformationObjects != null) {
for (Pair<String, Object> additionalObject : additionalInformationObjects) {
sb.append("\n\t" + additionalObject.getX() + INDENTED_LINEBREAK);
sb.append(additionalObject.getY().toString().replace("\n", INDENTED_LINEBREAK));
}
}
return sb.toString();
}
public static String logException(final Throwable e) {
return getExceptionInfo(e, new ArrayList<>());
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/logging/ToJSONStringUtil.java
|
package ai.libs.jaicore.logging;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
/**
* This class provides a util for serializing specific contents of an object in the form of a JSON string. Furthermore, it recursively extracts json trees from object variables and mounts them into the current tree.
*
* @author wever
*/
public class ToJSONStringUtil {
/* Prevent this class to be instantiated. */
private ToJSONStringUtil() {
// intentionally left blank.
}
/**
* Util for transforming an object into a JSON string representation. It requires to pass a map of object variables of the object to serialize in form of a map.
*
* @param fields The map of object variables to be serialized as a json string.
* @return A string representing the object contents in JSON format.
*/
public static String toJSONString(final Map<String, Object> fields) {
ObjectMapper om = new ObjectMapper();
ObjectNode root = om.createObjectNode();
for (Entry<String, Object> field : fields.entrySet()) {
root.set(field.getKey(), parseObjectToJsonNode(field.getValue(), om));
}
try {
return om.writeValueAsString(root);
} catch (JsonProcessingException e) {
return "JSON representation of toString could not be generated.";
}
}
/**
* This method should be used with caution, as it introduces an additional layer for naming the object to serialize in json format with <code>rootName</code>.
* Thus, it introduces another layer in the object hierarchy.
*
* @param rootName The name of the object.
* @param fields The map of object variables to be serialized as a json string.
* @return A string representing the object contents in JSON format.
*/
public static String toJSONString(final String rootName, final Map<String, Object> fields) {
ObjectMapper om = new ObjectMapper();
ObjectNode root = om.createObjectNode();
ObjectNode innerObject = om.createObjectNode();
root.set(rootName, innerObject);
for (Entry<String, Object> field : fields.entrySet().stream().sorted((o1, o2) -> o1.getKey().compareTo(o2.getKey())).collect(Collectors.toList())) {
innerObject.set(field.getKey(), parseObjectToJsonNode(field.getValue(), om));
}
try {
return om.writeValueAsString(root);
} catch (JsonProcessingException e) {
return rootName + " JSON representation of toString could not be generated.";
}
}
/**
* Parses an object to JSON depending on the objects capabilities to express itself in JSON format or not.
*
* @param fieldValue The object to be parsed.
* @param om The object mapper that is to be used for parsing.
* @return A JsonNode representing the parsed object.
*/
@SuppressWarnings("unchecked")
public static JsonNode parseObjectToJsonNode(final Object fieldValue, final ObjectMapper om) {
if (fieldValue == null) {
return new TextNode(fieldValue + "");
}
if (fieldValue instanceof JsonNode) {
return (JsonNode) fieldValue;
}
if (fieldValue instanceof Collection<?>) {
ArrayNode valueArray = om.createArrayNode();
for (Object value : (Collection<?>) fieldValue) {
valueArray.add(parseObjectToJsonNode(value, om));
}
return valueArray;
} else if (fieldValue.getClass().isArray()) {
ArrayNode valueArray = om.createArrayNode();
for (Object value : (Object[]) fieldValue) {
valueArray.add(parseObjectToJsonNode(value, om));
}
return valueArray;
} else if (fieldValue instanceof Map) {
ObjectNode valueMap = om.createObjectNode();
for (Entry<Object, Object> entry : ((Map<Object, Object>) fieldValue).entrySet()) {
valueMap.set(entry.getKey() + "", parseObjectToJsonNode(entry.getValue(), om));
}
return valueMap;
}
try {
return om.readTree(fieldValue + "");
} catch (Exception e) {
return new TextNode(fieldValue + "");
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/ISearchProblem.java
|
package ai.libs.jaicore.problems;
public interface ISearchProblem<P, S> {
public P getInstance();
public boolean isSolution(S candidate);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/cannibals/CannibalProblem.java
|
package ai.libs.jaicore.problems.cannibals;
/**
* Problem describing the missionary cannibal game.
* All persons must be moved to the right and the missionaries must not be a minority on either side at any time.
*
* @author fmohr
*
*/
public class CannibalProblem {
private final boolean boatOnLeft;
private final int missionariesOnLeft;
private final int cannibalsOnLeft;
private final int missionariesOnRight;
private final int cannibalsOnRight;
public CannibalProblem(final boolean boatOnLeft, final int missionariesOnLeft, final int cannibalsOnLeft, final int missionariesOnRight, final int cannibalsOnRight) {
super();
this.boatOnLeft = boatOnLeft;
this.missionariesOnLeft = missionariesOnLeft;
this.cannibalsOnLeft = cannibalsOnLeft;
this.missionariesOnRight = missionariesOnRight;
this.cannibalsOnRight = cannibalsOnRight;
if (missionariesOnLeft < 0) {
throw new IllegalArgumentException("Number of missionaries on left must be non-negative!");
}
if (missionariesOnRight < 0) {
throw new IllegalArgumentException("Number of missionaries on right must be non-negative!");
}
if (cannibalsOnLeft < 0) {
throw new IllegalArgumentException("Number of cannibales on left must be non-negative!");
}
if (cannibalsOnRight < 0) {
throw new IllegalArgumentException("Number of cannibales on right must be non-negative!");
}
}
public boolean isLost() {
return missionariesOnLeft > 0 && missionariesOnLeft < cannibalsOnLeft || missionariesOnRight > 0 && missionariesOnRight < cannibalsOnRight;
}
public boolean isWon() {
return missionariesOnLeft == 0 && cannibalsOnLeft == 0;
}
public int getMissionariesOnLeft() {
return missionariesOnLeft;
}
public int getCannibalsOnLeft() {
return cannibalsOnLeft;
}
public int getMissionariesOnRight() {
return missionariesOnRight;
}
public int getCannibalsOnRight() {
return cannibalsOnRight;
}
public boolean isBoatOnLeft() {
return boatOnLeft;
}
public int getTotalNumberOfPeople() {
return cannibalsOnLeft + cannibalsOnRight + missionariesOnLeft + missionariesOnRight;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (missionariesOnLeft > 0) {
sb.append(missionariesOnLeft + "M");
}
if (cannibalsOnLeft > 0) {
sb.append(cannibalsOnLeft + "C");
}
sb.append(" ");
if (missionariesOnRight > 0) {
sb.append(missionariesOnRight + "M");
}
if (cannibalsOnRight > 0) {
sb.append(cannibalsOnRight + "C");
}
return sb.toString();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/AEnhancedTTSPBinaryTelescopeNode.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.ArrayList;
import java.util.List;
import it.unimi.dsi.fastutil.shorts.ShortList;
public abstract class AEnhancedTTSPBinaryTelescopeNode {
protected final AEnhancedTTSPBinaryTelescopeNode parent;
protected AEnhancedTTSPBinaryTelescopeNode(final AEnhancedTTSPBinaryTelescopeNode parent) {
super();
this.parent = parent;
}
public abstract EnhancedTTSPState getState();
public abstract short getCurLocation();
public abstract ShortList getCurTour();
public static class EnhancedTTSPBinaryTelescopeDeterminedDestinationNode extends AEnhancedTTSPBinaryTelescopeNode {
private final EnhancedTTSPState state;
public EnhancedTTSPBinaryTelescopeDeterminedDestinationNode(final AEnhancedTTSPBinaryTelescopeNode parent, final EnhancedTTSPState state) {
super(parent);
this.state = state;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.state == null) ? 0 : this.state.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
EnhancedTTSPBinaryTelescopeDeterminedDestinationNode other = (EnhancedTTSPBinaryTelescopeDeterminedDestinationNode) obj;
if (this.state == null) {
if (other.state != null) {
return false;
}
} else if (!this.state.equals(other.state)) {
return false;
}
return true;
}
@Override
public short getCurLocation() {
return this.state.getCurLocation();
}
@Override
public ShortList getCurTour() {
return this.state.getCurTour();
}
@Override
public EnhancedTTSPState getState() {
return this.state;
}
@Override
public String toString() {
return "EnhancedTTSPBinaryTelescopeDeterminedDestinationNode [state=" + this.state + "]";
}
}
public static class EnhancedTTSPBinaryTelescopeDestinationDecisionNode extends AEnhancedTTSPBinaryTelescopeNode {
public EnhancedTTSPBinaryTelescopeDestinationDecisionNode(final AEnhancedTTSPBinaryTelescopeNode parent, final boolean bitChoice) {
super(parent);
this.bitChoice = bitChoice;
}
private final boolean bitChoice; // false if left child, true if right child
@Override
public ShortList getCurTour() {
return this.parent.getCurTour();
}
@Override
public short getCurLocation() {
return this.parent.getCurLocation();
}
public boolean isBitChoice() {
return this.bitChoice;
}
public List<Boolean> getField() {
if (this.parent instanceof EnhancedTTSPBinaryTelescopeDeterminedDestinationNode) {
List<Boolean> l = new ArrayList<>();
l.add(this.bitChoice);
return l;
}
List<Boolean> l = ((EnhancedTTSPBinaryTelescopeDestinationDecisionNode) this.parent).getField();
l.add(this.bitChoice);
return l;
}
@Override
public EnhancedTTSPState getState() {
return this.parent.getState();
}
@Override
public String toString() {
return "EnhancedTTSPBinaryTelescopeDestinationDecisionNode [bitChoice=" + this.bitChoice + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.bitChoice ? 1231 : 1237);
result += this.parent.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
EnhancedTTSPBinaryTelescopeDestinationDecisionNode other = (EnhancedTTSPBinaryTelescopeDestinationDecisionNode) obj;
if (this.bitChoice != other.bitChoice) {
return false;
}
if (this.parent == null) {
if (other.parent != null) {
return false;
}
} else if (!this.parent.equals(other.parent)) {
return false;
}
return true;
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSP.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.unimi.dsi.fastutil.shorts.Short2DoubleArrayMap;
import it.unimi.dsi.fastutil.shorts.Short2DoubleMap;
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
import it.unimi.dsi.fastutil.shorts.ShortList;
/**
* This class provides a search graph generator for an augmented version of the timed TSP (TTSP) problem. In TTSP, the original route graph has not only one cost per edge (u,v) but a list of costs where each position in the list represents an hour of departure from u. That is,
* depending on the time when leaving u, the cost to reach v may vary.
*
* The intended time measure is hours. That is, the length of the lists of all edges should be identical and reflect the number of hours considered. Typically, this is 24 or a multiple of that, e.g. 7 * 24.
*
* Time is considered cyclic. That is, if you consider 24 hours and the current time is 25.5, then it is automatically set to 1.5.
*
* The TTSP is enhanced by the consideration of blocking times for the streets, e.g. on Sundays (as in Germany) or during nights (as in Austria or Switzerland). Blocking times are stored in a separated list of Booleans.
*
* Also, the TTSP is enhanced in that driving pauses need to be considered. That is, the driver must only drive x hours in a row and then make a break of duration y. In addition, there must be an uninterrupted break of z hours every day.
*
* IT IS ASSUMED THAT BREAKS CAN ONLY BE MADE AT LOCATIONS AND NOT "ON THE ROAD"!
*
* @author fmohr
*
*/
public class EnhancedTTSP {
private final short startLocation;
private final int numberOfConsideredHours;
private final List<Location> locations;
private final Short2DoubleMap xCoords = new Short2DoubleArrayMap();
private final Short2DoubleMap yCoords = new Short2DoubleArrayMap();
private final List<Boolean> blockedHours;
private final double hourOfDeparture;
private final double durationOfShortBreak;
private final double durationOfLongBreak;
private final double maxConsecutiveDrivingTime;
private final double maxDrivingTimeBetweenLongBreaks;
private final ShortList possibleDestinations;
private final EnhancedTTSPSolutionEvaluator solutionEvaluator;
private Logger logger = LoggerFactory.getLogger(EnhancedTTSP.class);
public EnhancedTTSP(final List<Location> locations, final short startLocation, final List<Boolean> blockedHours, final double hourOfDeparture, final double maxConsecutiveDrivingTime,
final double durationOfShortBreak, final double durationOfLongBreak) {
super();
this.startLocation = startLocation;
this.numberOfConsideredHours = blockedHours.size();
this.locations = locations;
for (Location l : locations) {
this.xCoords.put(l.getId(), l.getX());
this.yCoords.put(l.getId(), l.getY());
}
this.blockedHours = blockedHours;
this.hourOfDeparture = hourOfDeparture;
this.durationOfShortBreak = durationOfShortBreak;
this.durationOfLongBreak = durationOfLongBreak;
this.maxConsecutiveDrivingTime = maxConsecutiveDrivingTime;
this.maxDrivingTimeBetweenLongBreaks = 24 - durationOfLongBreak;
this.possibleDestinations = new ShortArrayList(locations.stream().map(Location::getId).sorted().collect(Collectors.toList()));
this.solutionEvaluator = new EnhancedTTSPSolutionEvaluator(this);
}
public List<Location> getLocations() {
return this.locations;
}
public short getStartLocation() {
return this.startLocation;
}
public int getNumberOfConsideredHours() {
return this.numberOfConsideredHours;
}
public List<Boolean> getBlockedHours() {
return this.blockedHours;
}
public double getHourOfDeparture() {
return this.hourOfDeparture;
}
public double getDurationOfShortBreak() {
return this.durationOfShortBreak;
}
public double getDurationOfLongBreak() {
return this.durationOfLongBreak;
}
public double getMaxConsecutiveDrivingTime() {
return this.maxConsecutiveDrivingTime;
}
public double getMaxDrivingTimeBetweenLongBreaks() {
return this.maxDrivingTimeBetweenLongBreaks;
}
public ShortList getPossibleDestinations() {
return this.possibleDestinations;
}
public EnhancedTTSPState getInitalState() {
return new EnhancedTTSPState(null, this.startLocation, this.hourOfDeparture, 0, 0);
}
public EnhancedTTSPState computeSuccessorState(final EnhancedTTSPState n, final short destination) throws InterruptedException {
this.logger.info("Generating successor for node {} to go to destination {}", n, destination);
if (n.getCurLocation() == destination) {
throw new IllegalArgumentException("It is forbidden to ask for the successor to the current position as a destination!");
}
/*
* there is one successor for going to any of the not visited places that can be
* reached without making a break and that can reached without violating the
* blocking hour constraints
*/
short curLocation = n.getCurLocation();
double curTime = n.getTime();
double timeSinceLastShortBreak = n.getTimeTraveledSinceLastShortBreak();
double timeSinceLastLongBreak = n.getTimeTraveledSinceLastLongBreak();
double minTravelTime = Math.sqrt(Math.pow(this.xCoords.get(curLocation) - this.xCoords.get(destination), 2) + Math.pow(this.yCoords.get(curLocation)- this.yCoords.get(destination), 2)); // use Euclidean distance as min travel time
this.logger.info("Simulating the ride from {} to {}, which minimally takes {}. We are departing at {}", curLocation, destination , minTravelTime, curTime);
double timeToNextShortBreak = this.getTimeToNextShortBreak(Math.min(timeSinceLastShortBreak, timeSinceLastLongBreak));
double timeToNextLongBreak = this.getTimeToNextLongBreak(curTime, timeSinceLastLongBreak);
this.logger.info("Next short break will be in {}h", timeToNextShortBreak);
this.logger.info("Next long break will be in {}h", timeToNextLongBreak);
/* if we can do the tour without a break, do it */
boolean arrived = false;
double shareOfTheTripDone = 0.0;
double timeOfArrival = -1;
while (!arrived && !Thread.currentThread().isInterrupted()) {
double permittedTimeToTravel = Math.min(timeToNextShortBreak, timeToNextLongBreak);
double travelTimeWithoutBreak = this.getActualDrivingTimeWithoutBreak(minTravelTime, curTime, shareOfTheTripDone);
assert timeToNextShortBreak >= 0 : "Time to next short break cannot be negative!";
assert timeToNextLongBreak >= 0 : "Time to next long break cannot be negative!";
assert travelTimeWithoutBreak >= 0 : "Travel time cannot be negative!";
if (permittedTimeToTravel >= travelTimeWithoutBreak) {
curTime += travelTimeWithoutBreak;
arrived = true;
timeOfArrival = curTime;
timeSinceLastLongBreak += travelTimeWithoutBreak;
timeSinceLastShortBreak += travelTimeWithoutBreak;
this.logger.info("\tDriving the remaining distance to goal without a break. This takes {} (min time for this distance is {})", travelTimeWithoutBreak, minTravelTime * (1 - shareOfTheTripDone));
} else {
/* simulate driving to next break */
this.logger.info("\tCurrently achieved {}% of the trip.", shareOfTheTripDone);
this.logger.info("\tCannot reach the goal within the permitted {}, because the travel without a break would take {}", permittedTimeToTravel, travelTimeWithoutBreak);
shareOfTheTripDone = this.getShareOfTripWhenDrivingOverEdgeAtAGivenTimeForAGivenTimeWithoutDoingABreak(minTravelTime, curTime, shareOfTheTripDone, permittedTimeToTravel);
this.logger.info("\tDriving the permitted {}h. This allows us to finish {}% of the trip.", permittedTimeToTravel, (shareOfTheTripDone * 100));
if (permittedTimeToTravel == timeToNextLongBreak) {
this.logger.info("\tDo long break, because it is necessary");
}
if (permittedTimeToTravel + this.durationOfShortBreak + 2 > timeToNextLongBreak) {
this.logger.info("\tDo long break, because short break + 2 hours driving would require a long break anyway");
}
boolean doLongBreak = permittedTimeToTravel == timeToNextLongBreak || permittedTimeToTravel + this.durationOfShortBreak + 2 >= timeToNextLongBreak;
if (doLongBreak) {
curTime += permittedTimeToTravel + this.durationOfLongBreak;
this.logger.info("\tDoing a long break ({}h)", this.durationOfLongBreak);
timeSinceLastShortBreak = 0;
timeSinceLastLongBreak = 0;
timeToNextShortBreak = this.getTimeToNextShortBreak(0);
timeToNextLongBreak = this.getTimeToNextLongBreak(curTime, 0);
} else {
double timeElapsed = permittedTimeToTravel + this.durationOfShortBreak;
curTime += timeElapsed;
this.logger.info("\tDoing a short break ({}h)", this.durationOfShortBreak);
timeSinceLastShortBreak = 0;
timeSinceLastLongBreak += timeElapsed;
timeToNextShortBreak = this.getTimeToNextShortBreak(0);
timeToNextLongBreak = this.getTimeToNextLongBreak(curTime, timeSinceLastLongBreak);
}
}
}
if (Thread.interrupted()) {
throw new InterruptedException("Successor computation interrupted!");
}
double travelDuration = curTime - n.getTime();
this.logger.info("Finished travel simulation. Travel duration: {}", travelDuration);
ShortList tourToHere = new ShortArrayList(n.getCurTour());
tourToHere.add(destination);
return new EnhancedTTSPState(n, destination, timeOfArrival, timeSinceLastShortBreak, timeSinceLastLongBreak);
}
public ShortList getPossibleRemainingDestinationsInState(final EnhancedTTSPState n) {
short curLoc = n.getCurLocation();
ShortList possibleDestinationsToGoFromhere = new ShortArrayList();
ShortList seenPlaces = n.getCurTour();
int k = 0;
boolean openPlaces = seenPlaces.size() < this.getPossibleDestinations().size() - 1;
if (n.getCurTour().size() >= this.getPossibleDestinations().size()) {
throw new IllegalArgumentException("We have already visited everything!");
}
assert openPlaces || curLoc != 0 : "There are no open places (out of the " + this.getPossibleDestinations().size() + ", " + seenPlaces.size()
+ " of which have already been seen) but we are still in the initial position. This smells like a strange TSP.";
if (openPlaces) {
for (short l : this.getPossibleDestinations()) {
if (k++ == 0) {
continue;
}
if (l != curLoc && !seenPlaces.contains(l)) {
possibleDestinationsToGoFromhere.add(l);
}
}
} else {
possibleDestinationsToGoFromhere.add((short) 0);
}
return possibleDestinationsToGoFromhere;
}
private double getTimeToNextShortBreak(final double timeSinceLastBreak) {
return this.maxConsecutiveDrivingTime - timeSinceLastBreak;
}
private double getTimeToNextLongBreak(final double time, final double timeSinceLastLongBreak) {
return Math.min(this.getTimeToNextBlock(time), this.maxDrivingTimeBetweenLongBreaks - timeSinceLastLongBreak);
}
private double getTimeToNextBlock(final double time) {
double timeToNextBlock = Math.ceil(time) - time;
while (!(boolean)this.blockedHours.get((int) Math.round(time + timeToNextBlock) % this.numberOfConsideredHours)) {
timeToNextBlock++;
}
return timeToNextBlock;
}
public double getActualDrivingTimeWithoutBreak(final double minTravelTime, final double departure, final double shareOfTheTripDone) {
int t = (int) Math.round(departure);
double travelTime = minTravelTime * (1 - shareOfTheTripDone);
int departureTimeRelativeToSevenNineInterval = t > 9 ? t - 24 : t;
double startSevenNineSubInterval = Math.max(7, departureTimeRelativeToSevenNineInterval);
double endSevenNineSubInterval = Math.min(9, departureTimeRelativeToSevenNineInterval + travelTime);
double travelTimeInSevenToNineSlot = Math.max(0, endSevenNineSubInterval - startSevenNineSubInterval);
travelTime += travelTimeInSevenToNineSlot * 0.5;
int departureTimeRelativeToFourSixInterval = t > 18 ? t - 24 : t;
double startFourSixSubInterval = Math.max(16, departureTimeRelativeToFourSixInterval);
double endFourSixSubInterval = Math.min(18, departureTimeRelativeToFourSixInterval + travelTime);
double travelTimeInFourToSixSlot = Math.max(0, endFourSixSubInterval - startFourSixSubInterval);
travelTime += travelTimeInFourToSixSlot * 0.5;
return travelTime;
}
public double getShareOfTripWhenDrivingOverEdgeAtAGivenTimeForAGivenTimeWithoutDoingABreak(final double minTravelTime, final double departureOfCurrentPoint, final double shareOfTripDone, final double drivingTime) {
/* do a somewhat crude numeric approximation */
double minTravelTimeForRest = minTravelTime * (1 - shareOfTripDone);
this.logger.info("\t\tMin travel time for rest: {}", minTravelTimeForRest);
double doableMinTravelTimeForRest = minTravelTimeForRest;
double estimatedTravelingTimeForThatPortion = 0;
while ((estimatedTravelingTimeForThatPortion = this.getActualDrivingTimeWithoutBreak(doableMinTravelTimeForRest, departureOfCurrentPoint, shareOfTripDone)) > drivingTime) {
doableMinTravelTimeForRest -= 0.01;
}
this.logger.info("\t\tDoable min travel time for rest: {}. The estimated true travel time for that portion is {}", doableMinTravelTimeForRest, estimatedTravelingTimeForThatPortion);
double additionalShare = (doableMinTravelTimeForRest / minTravelTimeForRest) * (1 - shareOfTripDone);
this.logger.info("\t\tAdditional share: {}", additionalShare);
return shareOfTripDone + additionalShare;
}
public EnhancedTTSPSolutionEvaluator getSolutionEvaluator() {
return this.solutionEvaluator;
}
public double getMinTravelTimeBetweenLocations(final short a, final short b) {
return Math.sqrt(Math.pow(this.xCoords.get(a) - this.xCoords.get(b), 2) + Math.pow(this.yCoords.get(a)- this.yCoords.get(b), 2)); // use Euclidean distance as min travel time
}
public double getLongestMinTravelTimeBetweenTwoLocations() {
double max = 0;
for (short a = 0; a < this.locations.size(); a++) {
for (short b = 0; b < a; b ++) {
max = Math.max(max, this.getMinTravelTimeBetweenLocations(a, b));
}
}
return max;
}
public double getUpperBoundForAnyTour() {
double maxTime = this.getLongestMinTravelTimeBetweenTwoLocations();
double totalTimeBoundForTraveling = maxTime * this.locations.size();
int longBreaks = (int)Math.floor(totalTimeBoundForTraveling / this.maxDrivingTimeBetweenLongBreaks);
return totalTimeBoundForTraveling + longBreaks * this.durationOfLongBreak;
}
@Override
public String toString() {
return "EnhancedTTSP [startLocation=" + this.startLocation + ", numberOfConsideredHours=" + this.numberOfConsideredHours + ", blockedHours=" + this.blockedHours + ", hourOfDeparture="
+ this.hourOfDeparture + ", durationOfShortBreak=" + this.durationOfShortBreak + ", durationOfLongBreak=" + this.durationOfLongBreak + ", maxConsecutiveDrivingTime=" + this.maxConsecutiveDrivingTime + ", maxDrivingTimeBetweenLongBreaks="
+ this.maxDrivingTimeBetweenLongBreaks + ", possibleDestinations=" + this.possibleDestinations + ", solutionEvaluator=" + this.solutionEvaluator + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSPEnumeratingSolver.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.SetUtil;
public class EnhancedTTSPEnumeratingSolver {
public Collection<List<Short>> getSolutions(final EnhancedTTSP problem) {
Set<Short> places = problem.getLocations().stream().map(Location::getId).collect(Collectors.toSet());
places.remove((short)0);
return SetUtil.getPermutations(places);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSPGenerator.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class EnhancedTTSPGenerator {
private final ITSPLocationGenerator locationGenerator;
public EnhancedTTSPGenerator(final ITSPLocationGenerator locationGenerator) {
super();
this.locationGenerator = locationGenerator;
}
public EnhancedTTSP generate(final int n, final int maxDistance, final int seed) {
if (n > Short.MAX_VALUE) {
throw new IllegalArgumentException("Number of locations must not exceed " + Short.MAX_VALUE);
}
/* create TTSP problem */
List<Boolean> blockedHours = Arrays.asList(true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true);
List<Location> locations = this.locationGenerator.getLocations(n, 0, 0, maxDistance, 0.1);
Collections.shuffle(locations, new Random(seed));
return new EnhancedTTSP(locations, (short) 0, blockedHours, 8, 4.5, 1, 10);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSPSolutionEvaluator.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.HashSet;
import java.util.Set;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPSolutionEvaluator implements IObjectEvaluator<ShortList, Double> {
private final EnhancedTTSP problem;
public EnhancedTTSPSolutionEvaluator(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
@Override
public Double evaluate(final ShortList solutionTour) throws InterruptedException {
EnhancedTTSPState state = this.problem.getInitalState();
Set<Short> seenLocations = new HashSet<>();
for (short next : solutionTour) {
try {
if (seenLocations.contains(next)) {
throw new IllegalArgumentException("Given tour is not a valid (partial) solution. Location " + next + " is contained at least twice!");
}
seenLocations.add(next);
state = this.problem.computeSuccessorState(state, next);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Cannot evaluate tour " + solutionTour + " due to an error in successor computation of " + state + " with next step " + next + ". Message: " + e.getMessage());
}
}
return state.getTime() - this.problem.getHourOfDeparture();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSPState.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
import it.unimi.dsi.fastutil.shorts.ShortList;
import it.unimi.dsi.fastutil.shorts.ShortLists;
public class EnhancedTTSPState {
private final EnhancedTTSPState parent;
private final short curLocation;
private final double time;
private final double timeTraveledSinceLastShortBreak;
private final double timeTraveledSinceLastLongBreak;
public EnhancedTTSPState(final EnhancedTTSPState parent, final short curLocation, final double time, final double timeTraveledSinceLastShortBreak, final double timeTraveledSinceLastLongBreak) {
super();
this.parent = parent;
this.curLocation = curLocation;
if (time < 0) {
throw new IllegalArgumentException("Cannot create TTSP node with negative time");
}
if (timeTraveledSinceLastShortBreak < 0) {
throw new IllegalArgumentException("Cannot create TTSP node with negative time since last short break");
}
if (timeTraveledSinceLastLongBreak < 0) {
throw new IllegalArgumentException("Cannot create TTSP node with negative time since last long break");
}
this.time = time;
this.timeTraveledSinceLastShortBreak = timeTraveledSinceLastShortBreak;
this.timeTraveledSinceLastLongBreak = timeTraveledSinceLastLongBreak;
}
public short getCurLocation() {
return this.curLocation;
}
public double getTime() {
return this.time;
}
public double getTimeTraveledSinceLastShortBreak() {
return this.timeTraveledSinceLastShortBreak;
}
public double getTimeTraveledSinceLastLongBreak() {
return this.timeTraveledSinceLastLongBreak;
}
private ShortList getCurTourRec() {
if (this.parent == null) {
return new ShortArrayList(); // the starting location will NOT be part of the tour!
}
ShortList l = this.parent.getCurTourRec();
l.add(this.curLocation);
return l;
}
public ShortList getCurTour() {
return ShortLists.unmodifiable(this.getCurTourRec());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.curLocation;
result = prime * result + ((this.getCurTour() == null) ? 0 : this.getCurTour().hashCode());
long temp;
temp = Double.doubleToLongBits(this.time);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.timeTraveledSinceLastLongBreak);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.timeTraveledSinceLastShortBreak);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
EnhancedTTSPState other = (EnhancedTTSPState) obj;
if (this.curLocation != other.curLocation) {
return false;
}
if (this.getCurTour() == null) {
if (other.getCurTour() != null) {
return false;
}
} else if (!this.getCurTour().equals(other.getCurTour())) {
return false;
}
if (Double.doubleToLongBits(this.time) != Double.doubleToLongBits(other.time)) {
return false;
}
if (Double.doubleToLongBits(this.timeTraveledSinceLastLongBreak) != Double.doubleToLongBits(other.timeTraveledSinceLastLongBreak)) {
return false;
}
return Double.doubleToLongBits(this.timeTraveledSinceLastShortBreak) == Double.doubleToLongBits(other.timeTraveledSinceLastShortBreak);
}
@Override
public String toString() {
return "EnhancedTTSPNode [curLocation=" + this.curLocation + ", curTour=" + this.getCurTour() + ", time=" + this.time + ", timeTraveledSinceLastShortBreak=" + this.timeTraveledSinceLastShortBreak + ", timeTraveledSinceLastLongBreak="
+ this.timeTraveledSinceLastLongBreak + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/EnhancedTTSPUtil.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.Collection;
import java.util.stream.Collectors;
public class EnhancedTTSPUtil {
private EnhancedTTSPUtil() {
/* avoid instantiation */
}
public static Collection<Location> getLocationsInDistance(final Collection<Location> locations, final Location location, final double distance) {
return locations.stream().filter(l -> Math.sqrt(Math.pow(l.getX() - location.getX(), 2) + Math.pow(l.getY() - location.getY(), 2)) <= distance).collect(Collectors.toList());
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/ITSPLocationGenerator.java
|
package ai.libs.jaicore.problems.enhancedttsp;
import java.util.List;
public interface ITSPLocationGenerator {
public List<Location> getLocations(int n, double centerX, double centerY, double radius, double minDistance);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/Location.java
|
package ai.libs.jaicore.problems.enhancedttsp;
public class Location {
private final short id;
private final double x;
private final double y;
public Location(final short id, final double x, final double y) {
super();
this.id = id;
this.x = x;
this.y = y;
}
public short getId() {
return this.id;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.id;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Location other = (Location) obj;
return this.id == other.id;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/locationgenerator/CircleLocationGenerator.java
|
package ai.libs.jaicore.problems.enhancedttsp.locationgenerator;
import java.util.List;
import ai.libs.jaicore.problems.enhancedttsp.ITSPLocationGenerator;
import ai.libs.jaicore.problems.enhancedttsp.Location;
public class CircleLocationGenerator implements ITSPLocationGenerator {
@Override
public List<Location> getLocations(final int n, final double centerX, final double centerY, final double radius, final double minDistance) {
throw new UnsupportedOperationException("Not yet implemented.");
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/locationgenerator/ClusterBasedGenerator.java
|
package ai.libs.jaicore.problems.enhancedttsp.locationgenerator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import ai.libs.jaicore.problems.enhancedttsp.ITSPLocationGenerator;
import ai.libs.jaicore.problems.enhancedttsp.Location;
public class ClusterBasedGenerator implements ITSPLocationGenerator {
private ITSPLocationGenerator clusterLocationGenerator;
private ITSPLocationGenerator inClusterLocationGenerator;
private double density; // relative number of locations per cluster
private int clusterRadius;
private double minDistanceBetweenClusters;
private Random random;
public ClusterBasedGenerator(final ITSPLocationGenerator clusterLocationGenerator, final ITSPLocationGenerator inClusterLocationGenerator, final double density, final int clusterRadius, final double minDistanceBetweenClusters, final Random random) {
super();
this.clusterLocationGenerator = clusterLocationGenerator;
this.inClusterLocationGenerator = inClusterLocationGenerator;
this.density = density;
this.clusterRadius = clusterRadius;
this.minDistanceBetweenClusters = minDistanceBetweenClusters;
this.random = random;
}
@Override
public List<Location> getLocations(final int n, final double centerX, final double centerY, final double radius, final double minDistance) {
if (minDistance > 2 * this.clusterRadius) {
throw new IllegalArgumentException("");
}
int locationsPerCluster = (int)Math.ceil(this.density * n);
int numClusters = (int)Math.ceil(n * 1.0 / locationsPerCluster);
List<Location> clusterCentroids = this.clusterLocationGenerator.getLocations(numClusters, centerX, centerY, radius, 2 * this.clusterRadius + this.minDistanceBetweenClusters);
List<Location> locations = new ArrayList<>(n);
AtomicInteger ai = new AtomicInteger(0);
for (int i = 0; i < numClusters; i++) {
Location cl = clusterCentroids.get(i);
List<Location> localLocs = this.inClusterLocationGenerator.getLocations(locationsPerCluster, cl.getX(), cl.getY(), this.clusterRadius, minDistance);
localLocs.forEach(l -> locations.add(new Location((short)ai.getAndIncrement(), l.getX(), l.getY())));
}
Collections.shuffle(locations, this.random);
while (locations.size() > n) {
locations.remove(0);
}
return locations;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/enhancedttsp/locationgenerator/RandomLocationGenerator.java
|
package ai.libs.jaicore.problems.enhancedttsp.locationgenerator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPUtil;
import ai.libs.jaicore.problems.enhancedttsp.ITSPLocationGenerator;
import ai.libs.jaicore.problems.enhancedttsp.Location;
public class RandomLocationGenerator implements ITSPLocationGenerator {
private final Random random;
public RandomLocationGenerator(final Random random) {
super();
this.random = random;
}
@Override
public List<Location> getLocations(final int n, final double centerX, final double centerY, final double radius, final double minDistance) {
if (n > Short.MAX_VALUE) {
throw new IllegalArgumentException("Number of locations must not exceed " + Short.MAX_VALUE);
}
List<Location> locations = new LinkedList<>();
for (short i = 0; i < n; i++) {
Location nl;
do {
nl = new Location(i, centerX + (this.random.nextDouble() * radius * (this.random.nextBoolean() ? 1 : -1)), centerY + (this.random.nextDouble() * radius * (this.random.nextBoolean() ? 1 : -1)));
}
while (!EnhancedTTSPUtil.getLocationsInDistance(locations, nl, minDistance).isEmpty());
locations.add(nl);
}
return locations;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/gridworld/GridWorldNode.java
|
package ai.libs.jaicore.problems.gridworld;
public class GridWorldNode {
private final GridWorldProblem problem;
private final int posx;
private final int posy;
public GridWorldNode(final GridWorldProblem problem, final int x, final int y) {
if (x < 0 || x >= 16) {
throw new IllegalArgumentException("x has to be greater equals zero and less 16. Given x = " + x);
}
if (y < 0 || x >= 16) {
throw new IllegalArgumentException("y has to be greater equals zero and less 16. Given y = " + y);
}
this.problem = problem;
this.posx = x;
this.posy = y;
}
public GridWorldProblem getProblem() {
return this.problem;
}
public int getX() {
return this.posx;
}
public int getY() {
return this.posy;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/gridworld/GridWorldProblem.java
|
package ai.libs.jaicore.problems.gridworld;
import java.util.Arrays;
public class GridWorldProblem {
private final int[][] grid = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1},
{1, 1, 1, 1, 7, 7, 7, 7, 7, 7, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 7, 7, 8, 7, 7, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 7, 8, 8, 8, 7, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 8, 8, 9, 8, 8, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 7, 8, 8, 8, 7, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 7, 7, 8, 7, 7, 7, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 5, 4, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 6, 5, 4, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 5, 4, 4, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
private final int startX;
private final int startY;
private final int goalX;
private final int goaly;
public GridWorldProblem(final int startX, final int startY, final int goalX, final int goaly) {
super();
this.startX = startX;
this.startY = startY;
this.goalX = goalX;
this.goaly = goaly;
}
public int getStartX() {
return this.startX;
}
public int getStartY() {
return this.startY;
}
public int getGoalX() {
return this.goalX;
}
public int getGoaly() {
return this.goaly;
}
public int[][] getGrid() {
return this.grid;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.goalX;
result = prime * result + this.goaly;
result = prime * result + Arrays.deepHashCode(this.grid);
result = prime * result + this.startX;
result = prime * result + this.startY;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
GridWorldProblem other = (GridWorldProblem) obj;
if (this.goalX != other.goalX) {
return false;
}
if (this.goaly != other.goaly) {
return false;
}
if (!Arrays.deepEquals(this.grid, other.grid)) {
return false;
}
if (this.startX != other.startX) {
return false;
}
return this.startY == other.startY;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/knapsack/EnumeratingKnapsackSolver.java
|
package ai.libs.jaicore.problems.knapsack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import ai.libs.jaicore.basic.sets.SetUtil;
public class EnumeratingKnapsackSolver {
public Collection<Set<String>> getSolutions(final KnapsackProblem kp) throws InterruptedException {
Collection<Set<String>> solutions = new ArrayList<>();
Set<String> objectsAsSet = kp.getObjects();
for (Collection<String> selection : SetUtil.powerset(objectsAsSet)) {
double weight = 0;
for (String item : selection) {
weight += kp.getWeights().get(item);
}
if (weight > kp.getKnapsackCapacity()) {
continue;
}
double remainingWeight = kp.getKnapsackCapacity() - weight;
Collection<String> missingObjects = SetUtil.difference(objectsAsSet, selection);
boolean oneMoreFits = false;
for (String missingObject : missingObjects) {
if (kp.getWeights().get(missingObject) < remainingWeight) {
oneMoreFits = true;
break;
}
}
if (!oneMoreFits && !selection.isEmpty()) {
solutions.add(new HashSet<>(selection));
}
}
if (solutions.isEmpty()) {
solutions.addAll(new HashSet<>());
}
return solutions;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/knapsack/KnapsackConfiguration.java
|
package ai.libs.jaicore.problems.knapsack;
import java.util.Set;
public class KnapsackConfiguration {
private final Set<String> packedObjects;
private final Set<String> remainingObjects;
private final double usedCapacity;
public KnapsackConfiguration(final Set<String> packedObjects, final Set<String> remainingObjects, final double usedCapacity) {
super();
this.packedObjects = packedObjects;
this.remainingObjects = remainingObjects;
this.usedCapacity = usedCapacity;
}
public Set<String> getPackedObjects() {
return this.packedObjects;
}
public double getUsedCapacity() {
return this.usedCapacity;
}
public Set<String> getRemainingObjects() {
return this.remainingObjects;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.packedObjects == null) ? 0 : this.packedObjects.hashCode());
result = prime * result + ((this.remainingObjects == null) ? 0 : this.remainingObjects.hashCode());
long temp;
temp = Double.doubleToLongBits(this.usedCapacity);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
KnapsackConfiguration other = (KnapsackConfiguration) obj;
if (this.packedObjects == null) {
if (other.packedObjects != null) {
return false;
}
} else if (!this.packedObjects.equals(other.packedObjects)) {
return false;
}
if (this.remainingObjects == null) {
if (other.remainingObjects != null) {
return false;
}
} else if (!this.remainingObjects.equals(other.remainingObjects)) {
return false;
}
return Double.doubleToLongBits(this.usedCapacity) == Double.doubleToLongBits(other.usedCapacity);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.packedObjects);
sb.append("-<" + this.usedCapacity + ">");
return sb.toString();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/knapsack/KnapsackProblem.java
|
package ai.libs.jaicore.problems.knapsack;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
@SuppressWarnings("serial")
public class KnapsackProblem implements Serializable {
private final Set<String> objects;
private final Map<String, Double> values;
private final Map<String, Double> weights;
private final Map<Set<String>, Double> bonusPoints;
private final double knapsackCapacity;
public KnapsackProblem(final Set<String> objects, final Map<String, Double> values, final Map<String, Double> weights, final Map<Set<String>, Double> bonusPoints, final double knapsackCapacity) {
this.objects = objects;
this.values = values;
this.weights = weights;
this.bonusPoints = bonusPoints;
this.knapsackCapacity = knapsackCapacity;
}
public double getKnapsackCapacity() {
return this.knapsackCapacity;
}
public IObjectEvaluator<KnapsackConfiguration, Double> getSolutionEvaluator() {
return packedKnapsack -> {
if (packedKnapsack == null || packedKnapsack.getUsedCapacity() > KnapsackProblem.this.knapsackCapacity) {
return Double.MAX_VALUE;
} else {
double packedValue = 0.0d;
for (String object : packedKnapsack.getPackedObjects()) {
packedValue += KnapsackProblem.this.values.get(object);
}
for (Set<String> bonusCombination : KnapsackProblem.this.bonusPoints.keySet()) {
boolean allContained = true;
for (String object : bonusCombination) {
if (!packedKnapsack.getPackedObjects().contains(object)) {
allContained = false;
break;
}
}
if (allContained) {
packedValue += KnapsackProblem.this.bonusPoints.get(bonusCombination);
}
}
return packedValue * -1;
}
};
}
public Set<String> getObjects() {
return this.objects;
}
public Map<String, Double> getValues() {
return this.values;
}
public Map<String, Double> getWeights() {
return this.weights;
}
public Map<Set<String>, Double> getBonusPoints() {
return this.bonusPoints;
}
@Override
public String toString() {
return "KnapsackProblem [objects=" + this.objects + ", values=" + this.values + ", weights=" + this.weights + ", bonusPoints=" + this.bonusPoints + ", knapsackCapacity=" + this.knapsackCapacity + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/knapsack/KnapsackProblemGenerator.java
|
package ai.libs.jaicore.problems.knapsack;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class KnapsackProblemGenerator {
private KnapsackProblemGenerator() {
/* avoids instantiation */
}
public static KnapsackProblem getKnapsackProblem(final int numObjects) {
return getKnapsackProblem(numObjects, 0);
}
public static KnapsackProblem getKnapsackProblem(final int numObjects, final int seed) {
/* create knapsack problem */
Random r = new Random(seed);
Set<String> objects = new HashSet<>();
Map<String, Double> weights = new HashMap<>();
Map<String, Double> values = new HashMap<>();
Map<Set<String>, Double> bonusPoints;
for (int i = 0; i < numObjects; i++) {
objects.add(String.valueOf(i));
}
double minWeight = 100;
for (int i = 0; i < numObjects; i++) {
double weight = r.nextInt(100) * 1.0;
weights.put("" + i, weight);
if (weight < minWeight) {
minWeight = weight;
}
}
for (int i = 0; i < numObjects; i++) {
values.put("" + i, r.nextInt(100) * 1.0);
}
bonusPoints = new HashMap<>();
Set<String> bonusCombination = new HashSet<>();
bonusCombination.add("0");
bonusCombination.add("2");
bonusPoints.put(bonusCombination, 25.0d);
return new KnapsackProblem(objects, values, weights, bonusPoints, Math.max(numObjects * 20.0, minWeight));
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/npuzzle/NPuzzleProblem.java
|
package ai.libs.jaicore.problems.npuzzle;
public class NPuzzleProblem {
private final int[][] board;
private final int dim;
public NPuzzleProblem(final int[][] board) {
this.board = board;
this.dim = board.length;
}
public NPuzzleProblem(final int dim, final int seed) {
this(new NPuzzleState(dim, seed).board);
}
public int[][] getBoard() {
return this.board;
}
public int getDim() {
return this.dim;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/npuzzle/NPuzzleState.java
|
package ai.libs.jaicore.problems.npuzzle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* A node for the normal n-Puzzleproblem.
* Every node contains the current board configuration as an 2D-Array of integer.
* The empty space is indicated by an Integer with value 0.
*
* @author jkoepe
*/
public class NPuzzleState {
// board configuration and empty space
protected int[][] board;
protected int emptyX;
protected int emptyY;
/**
* Constructor for a NPuzzleNode which creates a NPuzzleNode with complete
* randomly distributed numbers.
*
* @param dim
* The dimension of the board.
*/
public NPuzzleState(final int dim) {
this(dim, 0);
}
/**
* Constructor for a NPuzzleNode which creates a NPuzzleNode.
* The board configuration starts with the targetconfiguration and shuffels the tiles afterwards.
*
* @param dim
* The dimension of the board.
* @param perm
* The number of moves which should be made before starting the search.
* This number is hardcoded to at least 1.
*/
public NPuzzleState(final int dim, final int seed) {
this.board = new int[dim][dim];
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < dim * dim; i++) {
numbers.add(i);
}
Collections.shuffle(numbers, new Random(seed));
int c = 0;
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
this.board[i][j] = numbers.get(c++);
}
}
}
/**
* Constructor for a NPuzzleNode in which the board is already given.
*
* @param board
* The board configuration for this node
* @param emptyX
* The empty space on the x-axis.
* @param emptyY
* The empty space on the y-axis.
*
* @param noMoves
* The number of already done moves.
*/
public NPuzzleState(final int[][] board, final int emptyX, final int emptyY) {
this.board = board;
this.emptyX = emptyX;
this.emptyY = emptyY;
}
public int[][] getBoard() {
return this.board;
}
public int getEmptyX() {
return this.emptyX;
}
public int getEmptyY() {
return this.emptyY;
}
/**
* Returns a graphical version of the board configuration.
* Works best if there is no number with two or more digits.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < this.board.length; j++) {
sb.append("----");
}
sb.append("\n");
for (int i = 0; i < this.board.length; i++) {
sb.append("| ");
for (int j = 0; j < this.board.length; j++) {
sb.append(this.board[i][j] + " | ");
}
sb.append("\n");
for (int j = 0; j < this.board.length; j++) {
sb.append("----");
}
sb.append("\n");
}
return sb.toString();
}
/**
* Returns the number of wrongly placed tiles
*
* @return
* The number of wrongly placed tiles.
*/
public int getNumberOfWrongTiles() {
int wrongTiles = 0;
int x = 1;
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board.length; j++) {
if (i == this.board.length - 1 && j == this.board.length - 1) {
x = 0;
}
if (x != this.board[i][j]) {
wrongTiles++;
}
x++;
}
}
return wrongTiles;
}
/**
* Returns the steps which are minimal need to reach a goal state
*
* @return
* The number of steps.
*/
public double getDistance() {
double d = 0.0;
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board.length; j++) {
int tile = this.board[i][j];
double x = (double) tile / this.board.length;
int y = tile % this.board.length - 1;
if (x % 1 == 0) {
x--;
}
x = Math.floor(x);
if (y < 0) {
y = this.board.length - 1;
}
if (tile == 0) {
continue;
}
double h1 = Math.abs(i - x);
double h2 = Math.abs(j - y);
double d1 = h1 + h2;
d += d1;
}
}
return d;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.deepHashCode(this.board);
result = prime * result + this.emptyX;
result = prime * result + this.emptyY;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
NPuzzleState other = (NPuzzleState) obj;
if (!Arrays.deepEquals(this.board, other.board)) {
return false;
}
if (this.emptyX != other.emptyX) {
return false;
}
return this.emptyY == other.emptyY;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/nqueens/EnumeratingNQueensSolver.java
|
package ai.libs.jaicore.problems.nqueens;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ai.libs.jaicore.basic.sets.SetUtil;
public class EnumeratingNQueensSolver {
public Collection<List<Integer>> getSolutions(final NQueensProblem problem) {
Collection<List<Integer>> solutions = new ArrayList<>();
Set<Integer> entries = new HashSet<>();
for (int i = 0; i < problem.getN(); i++) {
entries.add(i);
}
for (List<Integer> positioning : SetUtil.getPermutations(entries)) {
if (NQueenSolutionChecker.isSolution(positioning)) {
solutions.add(positioning);
}
}
return solutions;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/nqueens/NQueenSolutionChecker.java
|
package ai.libs.jaicore.problems.nqueens;
import java.util.List;
public class NQueenSolutionChecker {
private NQueenSolutionChecker() {
/* avoids instantiation */
}
public static boolean isSolution(final List<Integer> solution) {
int n = solution.size();
for (int i = 0; i < n; i++) {
int j = solution.get(i);
if (attack(solution, i, j)) {
return false;
}
}
return true;
}
/**
* Checks if a cell is attacked by the queens on the board
* @param i
* The row of the cell to be checked.
* @param j
* The collumn of the cell to be checked.
* @return
* <code>true</code> if the cell is attacked, <code>false</code> otherwise.
*/
public static boolean attack(final List<Integer> positions, final int i, final int j) {
int n = positions.size();
for(int x = 0; x < n; x++) {
int y = positions.get(x);
/* ignore the field that is queried as a source of attack */
if (x == i && y == j) {
continue;
}
/* if the queried field is in the same column as a positioned queen */
if(j == y) {
return true;
}
int z = Math.abs(i - positions.indexOf(y));
if(j == y+z || y-z == j) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/nqueens/NQueensProblem.java
|
package ai.libs.jaicore.problems.nqueens;
public class NQueensProblem {
private final int n;
public NQueensProblem(int n) {
super();
this.n = n;
}
public int getN() {
return n;
}
@Override
public String toString() {
return "NQueensProblem [n=" + n + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/samegame/SameGameCell.java
|
package ai.libs.jaicore.problems.samegame;
public class SameGameCell {
private final byte row;
private final byte col;
public SameGameCell(final byte row, final byte col) {
super();
this.row = row;
this.col = col;
}
public byte getCol() {
return this.col;
}
public byte getRow() {
return this.row;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.col;
result = prime * result + this.row;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
SameGameCell other = (SameGameCell) obj;
if (this.col != other.col) {
return false;
}
return this.row == other.row;
}
@Override
public String toString() {
return "SameGameCell [row=" + this.row + ", col=" + this.col + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/samegame/SameGameGenerator.java
|
package ai.libs.jaicore.problems.samegame;
import java.util.Random;
public class SameGameGenerator {
public SameGameState generate(final long seed) {
return this.generate(15, 15, 5, 1.0, new Random(seed));
}
public SameGameState generate(final int rows, final int cols, final int numColors, final double fillRate, final Random random) {
int maxPieces = (int)Math.round(rows * cols * fillRate);
int i = 0;
byte[][] board = new byte[rows][cols];
for (int row = rows - 1; row >= 0 && i < maxPieces; row --) {
for (int col = 0; col < cols && i < maxPieces; col ++, i++) {
board[row][col] = (byte)(random.nextInt(numColors) + 1);
}
}
return new SameGameState(board);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/samegame/SameGameState.java
|
package ai.libs.jaicore.problems.samegame;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import it.unimi.dsi.fastutil.ints.IntArraySet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.shorts.ShortRBTreeSet;
import it.unimi.dsi.fastutil.shorts.ShortSet;
public class SameGameState {
private final short score;
private final byte[][] board; // 0 for empty cells, positive ints for the colors
private final short numPieces;
public static byte[][] getBoardAsBytes(final String boardAsString) {
List<String> lines = Arrays.stream(boardAsString.split("\n")).filter(l -> !l.trim().isEmpty()).collect(Collectors.toList());
byte[][] board = new byte[lines.size()][lines.get(0).length()];
for (int i = 0; i < lines.size(); i++) {
String trimmedLine = lines.get(i).trim();
board[i] = new byte[trimmedLine.length()];
for (int j = 0; j < trimmedLine.length(); j++) {
board[i][j] = Byte.parseByte(trimmedLine.substring(j, j + 1));
}
}
return board;
}
public SameGameState(final String board) {
this(getBoardAsBytes(board));
}
public SameGameState(final byte[][] board) {
this.score = 0;
this.board = board;
short tmpNumPieces = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] != 0) {
tmpNumPieces++;
}
}
}
this.numPieces = tmpNumPieces;
}
private SameGameState(final short score, final byte[][] board, final short numPieces) {
super();
this.score = score;
this.board = board;
this.numPieces = numPieces;
}
public SameGameState getStateAfterMove(final Collection<SameGameCell> block) {
if (block.size() < 2) {
throw new IllegalArgumentException("Removed blocks must have size at least 2.");
}
/* create a copy of the board */
byte[][] boardCopy = new byte[this.board.length][this.board[0].length];
for (int i = 0; i < this.board.length; i++) {
for (int j = 0; j < this.board[i].length; j++) {
boardCopy[i] = Arrays.copyOf(this.board[i], this.board[i].length);
}
}
/* first remove all the blocks associated to the field */
Collection<SameGameCell> removedPieces = block;
if (removedPieces.size() < 2) {
throw new IllegalArgumentException();
}
int maximumAffectedRow = 0;
ShortSet colsToDrop = new ShortRBTreeSet();
for (SameGameCell piece : removedPieces) {
boardCopy[piece.getRow()][piece.getCol()] = 0;
colsToDrop.add(piece.getCol());
maximumAffectedRow = Math.max(maximumAffectedRow, piece.getCol());
}
/* now drop all the blocks in the affected columns */
for (int c : colsToDrop) {
int fallHeightInColumn = 0;
boolean touchedFirstEmpty = false;
for (int r = this.board.length - 1; r >= 0; r--) {
if (boardCopy[r][c] == 0) {
fallHeightInColumn++;
touchedFirstEmpty = true;
} else {
if (touchedFirstEmpty) {
boardCopy[r + fallHeightInColumn][c] = boardCopy[r][c];
boardCopy[r][c] = 0;
}
}
}
}
/* if a column has been cleared, move the others left */
int offset = 0;
for (int c = 0; c < boardCopy[0].length; c++) {
if (boardCopy[boardCopy.length - 1][c] == 0) {
offset++;
} else if (offset > 0) {
for (int r = 0; r < boardCopy.length; r++) {
boardCopy[r][c - offset] = boardCopy[r][c];
boardCopy[r][c] = 0;
}
}
}
short newScore = (short) (this.score + (int) Math.pow(removedPieces.size() - 2.0, 2));
short newNumPieces = (short) (this.numPieces - removedPieces.size());
if (!isMovePossible(boardCopy)) {
if (newNumPieces == 0) {
newScore += 1000;
} else {
newScore -= Math.pow(newNumPieces - 2.0, 2);
}
}
return new SameGameState(newScore, boardCopy, newNumPieces);
}
public SameGameState getStateAfterMove(final byte row, final byte col) {
return this.getStateAfterMove(this.getAllConnectedPiecesOfSameColor(row, col));
}
public List<SameGameCell> getAllConnectedPiecesOfSameColor(final byte row, final byte col) {
if (this.board[row][col] == 0) {
throw new IllegalArgumentException("There is no block in row " + row + " and col " + col);
}
List<SameGameCell> removed = new ArrayList<>();
removed.add(new SameGameCell(row, col));
this.getAllConnectedPiecesOfSameColor(row, col, removed);
return removed;
}
private boolean getAllConnectedPiecesOfSameColor(final byte row, final byte col, final List<SameGameCell> countedPieces) {
byte color = this.board[row][col];
boolean addedOne = false;
int colorLeft = col > 0 ? this.board[row][col - 1] : 0;
SameGameCell leftCell = new SameGameCell(row, (byte) (col - 1));
if (colorLeft == color && !countedPieces.contains(leftCell)) {
countedPieces.add(leftCell);
this.getAllConnectedPiecesOfSameColor(row, leftCell.getCol(), countedPieces);
addedOne = true;
}
int colorRight = col < this.board[row].length - 1 ? this.board[row][col + 1] : 0;
SameGameCell rightCell = new SameGameCell(row, (byte) (col + 1));
if (colorRight == color && !countedPieces.contains(rightCell)) {
countedPieces.add(rightCell);
this.getAllConnectedPiecesOfSameColor(row, rightCell.getCol(), countedPieces);
addedOne = true;
}
int colorUp = row > 0 ? this.board[row - 1][col] : 0;
SameGameCell upCell = new SameGameCell((byte) (row - 1), col);
if (colorUp == color && !countedPieces.contains(upCell)) {
countedPieces.add(upCell);
this.getAllConnectedPiecesOfSameColor(upCell.getRow(), col, countedPieces);
addedOne = true;
}
int colorDown = row < this.board.length - 1 ? this.board[row + 1][col] : 0;
SameGameCell downCell = new SameGameCell((byte) (row + 1), col);
if (colorDown == color && !countedPieces.contains(downCell)) {
countedPieces.add(downCell);
this.getAllConnectedPiecesOfSameColor(downCell.getRow(), col, countedPieces);
addedOne = true;
}
return addedOne;
}
public String getBoardAsString() {
StringBuilder sb = new StringBuilder();
for (int row = 0; row < this.board.length; row++) {
for (int col = 0; col < this.board[row].length; col++) {
sb.append(this.board[row][col]);
}
sb.append("\n");
}
return sb.toString();
}
public byte[][] getBoard() {
return this.board;
}
public int getNumRows() {
return this.board.length;
}
public int getNumCols() {
return this.board[0].length;
}
public Collection<Collection<SameGameCell>> getBlocksOfPieces() {
/* Collect one representative for each block */
List<Collection<SameGameCell>> identifiedBlocks = new ArrayList<>();
Map<SameGameCell, Integer> blocksOfCells = new HashMap<>();
SameGameCell[][] cellObjects = new SameGameCell[this.board.length][this.board[0].length];
byte lastRow = -1;
byte lastCol;
IntSet indicesToRemove = new IntArraySet();
for (byte row = 0; row < this.board.length; row++) {
lastCol = -1;
for (byte col = 0; col < this.board[row].length; col++) {
byte color = this.board[row][col];
if (color != 0) {
SameGameCell cell = new SameGameCell(row, col);
cellObjects[row][col] = cell;
/* if the cell has the same color as the cell above, put it into the same group */
if (row > 0 && this.board[lastRow][col] == color) {
int topBlockId = blocksOfCells.get(cellObjects[lastRow][col]);
blocksOfCells.put(cell, topBlockId);
identifiedBlocks.get(topBlockId).add(cell);
/* if the cell has ALSO the same value as the left neighbor, merge the groups (unless those groups already HAVE been merged) */
assert lastCol == col - 1;
if (col > 0 && this.board[row][lastCol] == color) {
int leftBlockId = blocksOfCells.get(cellObjects[row][lastCol]); // gets the id of the block of the piece on the left
if (identifiedBlocks.get(leftBlockId) != identifiedBlocks.get(topBlockId)) {
identifiedBlocks.get(topBlockId).addAll(identifiedBlocks.get(leftBlockId)); // adds all the elements of the left block to the top block
identifiedBlocks.set(leftBlockId, identifiedBlocks.get(topBlockId)); // sets the left block to be equal with the top block
indicesToRemove.add(leftBlockId);
}
}
}
/* else, if the cell has ONLY the same value as its left neighbor, joint them */
else if (col > 0 && this.board[row][lastCol] == color) {
int leftBlockId = blocksOfCells.get(cellObjects[row][lastCol]);
blocksOfCells.put(cell, leftBlockId);
identifiedBlocks.get(leftBlockId).add(cell);
}
/* otherwise, the cell cannot be merged with left or top and, hence, opens a new block */
else {
int blockId = identifiedBlocks.size();
Collection<SameGameCell> block = new ArrayList<>();
block.add(cell);
blocksOfCells.put(cell, blockId);
identifiedBlocks.add(block);
}
}
lastCol = col;
}
lastRow = row;
}
for (int r : indicesToRemove.stream().sorted((i1, i2) -> Integer.compare(i2, i1)).collect(Collectors.toList())) {
identifiedBlocks.remove(r);
}
return identifiedBlocks;
}
public short getScore() {
return this.score;
}
public int getNumPieces() {
return this.numPieces;
}
public static boolean isMovePossible(final byte[][] board) {
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (canCellBeSelected(board, row, col)) {
return true;
}
}
}
return false;
}
public boolean isMovePossible() {
return isMovePossible(this.board);
}
public boolean canCellBeSelected(final int row, final int col) {
return canCellBeSelected(this.board, row, col);
}
public static boolean canCellBeSelected(final byte[][] board, final int row, final int col) {
byte color = board[row][col];
if (color == 0) {
return false;
}
if (row > 0 && board[row - 1][col] == color) {
return true;
}
if (row < board.length - 1 && board[row + 1][col] == color) {
return true;
}
if (col < board[row].length - 1 && board[row][col + 1] == color) {
return true;
}
return (col > 0 && board[row][col - 1] == color);
}
public Map<Integer, Integer> getNumberOfPiecesPerColor() {
Map<Integer, Integer> map = new HashMap<>();
for (int row = 0; row < this.board.length; row++) {
for (int col = 0; col < this.board[row].length; col++) {
int color = this.board[row][col];
if (color == 0) {
continue;
}
map.put(color, map.computeIfAbsent(color, c -> 0) + 1);
}
}
return map;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.deepHashCode(this.board);
result = prime * result + this.score;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
SameGameState other = (SameGameState) obj;
if (!Arrays.deepEquals(this.board, other.board)) {
return false;
}
return this.score == other.score;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/samegame/SameGameStateChecker.java
|
package ai.libs.jaicore.problems.samegame;
import java.util.Collection;
import java.util.stream.Collectors;
public class SameGameStateChecker {
public boolean checkThatEveryPieceIsInExactlyOneBlock(final SameGameState s) {
Collection<Collection<SameGameCell>> blocks = s.getBlocksOfPieces();
byte[][] board = s.getBoard();
for (byte row = 0; row < board.length; row ++) {
for (byte col = 0; col < board[row].length; col ++) {
if (board[row][col] != 0) {
SameGameCell cell = new SameGameCell(row, col);
int matchingBlocks = blocks.stream().filter(b -> b.contains(cell)).collect(Collectors.toList()).size();
if (matchingBlocks != 1) {
return false;
}
}
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/ASchedulingComputer.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
public abstract class ASchedulingComputer implements IScheduleComputer {
@Override
public void fillTimes(final IJobSchedulingInput problemInput, final List<Pair<Operation, Machine>> assignments, final Map<Job, Integer> arrivalTimes, final Map<Operation, Integer> startTimes, final Map<Operation, Integer> endTimes,
final Map<Operation, Integer> setupStartTimes, final Map<Operation, Integer> setupEndTimes) {
startTimes.clear();
endTimes.clear();
setupStartTimes.clear();
setupEndTimes.clear();
/* compute stats for the operations */
Map<Job, Integer> jobReadyness = new HashMap<>();
Map<Machine, Integer> machineReadyness = new HashMap<>();
Map<Machine, Integer> machineStates = new HashMap<>();
for (Pair<Operation, Machine> p : assignments) {
/* get times when job can arrive at the machine and time when machine can start to consider the job */
Machine m = p.getY();
Operation o = p.getX();
int timeWhenMachineBecomesAvailableForOperation = this.getTimeWhenMachineBecomesAvailableForOperation(arrivalTimes, machineReadyness, m);
int timeWhenJobArrivesAtMachine = this.timeWhenOperationArrivesAtMachine(arrivalTimes, machineReadyness, jobReadyness, o, m); // maybe add travel time here
/* compute required setup time */
int actualMachineState = machineStates.computeIfAbsent(m, Machine::getInitialState);
int requiredMachineState = o.getStatus();
int setupTime = (actualMachineState == requiredMachineState) ? 0 : m.getWorkcenter().getSetupMatrix()[actualMachineState][requiredMachineState];
int timeWhenMachineIsReadyToProcessOperation = timeWhenMachineBecomesAvailableForOperation + setupTime;
/* compute and memorize operation stats */
int startTime = Math.max(timeWhenMachineIsReadyToProcessOperation, timeWhenJobArrivesAtMachine);
int endTime = startTime + o.getProcessTime();
setupStartTimes.put(o, timeWhenMachineBecomesAvailableForOperation);
setupEndTimes.put(o, timeWhenMachineIsReadyToProcessOperation);
startTimes.put(o, startTime);
endTimes.put(o, endTime);
/* update machine state and readyness and job readyness */
machineReadyness.put(m, endTime);
machineStates.put(m, o.getStatus());
jobReadyness.put(o.getJob(), endTime);
}
}
public abstract int getTimeWhenMachineBecomesAvailableForOperation(final Map<Job, Integer> arrivalTimes, Map<Machine, Integer> machineReadiness, Machine m);
public abstract int timeWhenOperationArrivesAtMachine(final Map<Job, Integer> arrivalTimes, Map<Machine, Integer> machineReadiness, Map<Job, Integer> jobReadyness, Operation o, Machine m);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/IJobSchedulingInput.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.Collection;
public interface IJobSchedulingInput {
public Collection<Job> getJobs();
public Job getJob(String jobId);
public Collection<Operation> getOperations();
public Operation getOperation(String opId);
public Collection<Workcenter> getWorkcenters();
public Workcenter getWorkcenter(String wcId);
public Collection<Machine> getMachines();
public Machine getMachine(String mId);
public JobShopMetric getMetric();
public double getScoreOfSchedule(final ISchedule s);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/IJobSchedulingProblem.java
|
package ai.libs.jaicore.problems.scheduling;
import ai.libs.jaicore.problems.ISearchProblem;
public interface IJobSchedulingProblem extends ISearchProblem<IJobSchedulingInput, ISchedule> {
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/ISchedule.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.List;
import ai.libs.jaicore.basic.sets.Pair;
public interface ISchedule {
public List<Pair<Operation, Machine>> getAssignments();
public List<Operation> getOperationsAssignedToMachine(final Machine m);
public Machine getMachineToWhichOperationHasBeenAssigned(final Operation o);
public List<Operation> getOrderOfOperationsForJob(final Job job);
public int getStartTimeOfOperation(final Operation o);
public int getEndTimeOfOperation(final Operation o);
public int getSetupStartTimeOfOperation(final Operation o);
public int getSetupEndTimeOfOperation(final Operation o);
public int getJobFinishTime(final Job job);
public int getJobFlowTime(final Job job);
public int getJobTardiness(final Job job);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/IScheduleComputer.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
public interface IScheduleComputer {
public void fillTimes(IJobSchedulingInput problemInput, List<Pair<Operation, Machine>> assignments, Map<Job, Integer> arrivalTimes, Map<Operation, Integer> startTimes, Map<Operation, Integer> endTimes, Map<Operation, Integer> setupStartTimes, Map<Operation, Integer> setupEndTimes);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/Job.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* <p>Title: AFS Java version 3.0</p>
*
* <p>Description: Algorithms for Scheduling version Java</p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: Pylo.Uniandes.edu.co</p>
*
* <p> Class Tjob </p>
* <p> The class Tjob provides all the attributes defined in Lekin for a job. Also provides a method to read a job from the _usr.job file.</p>
* The attributes (members) are: <br>
* <b> String jobId:</b> The job identifier. <br>
* <b> int jobNumber: </b>job number (as read). <br>
* <b> int releaseDate: </b>minimum availability date of a job. <br>
* <b> int dueDate: </b>Due date of a job. <br>
* <b> int weight: </b>Priority of a job. <br>
* <b> int totalWorkTime: </b> The sum of the processing times of a job <br>
* <b> int numberOfOperations: </b>Number of operations of a job. <br>
* <b> Operation route[]: </b>"Routing sheet". Array with the sequence of machines which a job visits (precedence constraints).<br>
* @author Gonzalo Mejia
* @author Felix Mohr
* @version 4.0
*/
/**
* @author gmejia
*
*/
public class Job {
private final String jobID; // name of the job
private final int releaseDate; // when the job arrives
private final int dueDate; // When the job should be finished
private final int weight; // job weight or priority
private final List<Operation> operations = new ArrayList<>();
Job(final String jobID, final int releaseDate, final int dueDate, final int weight) {
super();
this.jobID = jobID;
this.releaseDate = releaseDate;
this.dueDate = dueDate;
this.weight = weight;
}
public String getJobID() {
return this.jobID;
}
public int getReleaseDate() {
return this.releaseDate;
}
public int getDueDate() {
return this.dueDate;
}
public int getWeight() {
return this.weight;
}
/**
* Package visible add operation method. Can only be invoked by the builder to make sure that the problem is not altered later.
*
* @param op
*/
void addOperation(final Operation op) {
this.operations.add(op);
}
public List<Operation> getOperations() {
return Collections.unmodifiableList(this.operations);
}
} // class
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/JobSchedulingProblemBuilder.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class JobSchedulingProblemBuilder {
private final Map<String, Workcenter> workcenters = new HashMap<>();
private final Map<String, Job> jobs = new HashMap<>();
private final Map<String, Machine> machines = new HashMap<>();
private final Map<String, Operation> operations = new HashMap<>();
private JobShopMetric metric;
private int latestArrivalTime = -1;
public JobSchedulingProblemBuilder fork() {
JobSchedulingProblemBuilder copy = new JobSchedulingProblemBuilder();
copy.workcenters.putAll(this.workcenters);
copy.jobs.putAll(this.jobs);
copy.machines.putAll(this.machines);
copy.operations.putAll(this.operations);
copy.metric = this.metric;
return copy;
}
public JobSchedulingProblemBuilder withWorkcenter(final String workcenterID, final int[][] setupMatrix) {
if (this.workcenters.containsKey(workcenterID)) {
throw new IllegalArgumentException(String.format("Workcenter with id %s already exists", workcenterID));
}
this.workcenters.put(workcenterID, new Workcenter(workcenterID, setupMatrix));
return this;
}
public JobSchedulingProblemBuilder singleStaged() {
return this.withWorkcenter("W", null);
}
public JobSchedulingProblemBuilder singleOperationAndSingleMachine() {
this.singleStaged();
return this.withMachineForWorkcenter("M", "W", 0, 0);
}
public JobSchedulingProblemBuilder withParallelMachines(final int k) {
this.machines.clear();
for (Entry<String, Workcenter> wcEntry : this.workcenters.entrySet()) {
for (int i = 0; i < k; i++) {
String machineName = wcEntry.getKey() + "_M" + i;
this.withMachineForWorkcenter(machineName, wcEntry.getKey(), 0, 0);
}
}
return this;
}
public JobSchedulingProblemBuilder withJob(final String jobID, final int releaseDate, final int dueDate, final int weight) {
if (this.jobs.containsKey(jobID)) {
throw new IllegalArgumentException(String.format("A job with ID %s has already been defined.", jobID));
}
this.jobs.put(jobID, new Job(jobID, releaseDate, dueDate, weight));
return this;
}
public JobSchedulingProblemBuilder withSingleOpJob(final int processingTime, final int weight) {
int id = 1;
String jobId = "J" + id;
while (this.jobs.containsKey(jobId)) {
id++;
jobId = "J" + id;
}
this.withJob(jobId, 0, 0, weight);
id = 1;
String opId = "O" + id;
while (this.operations.containsKey(opId)) {
id++;
opId = "O" + id;
}
this.withOperationForJob(opId, jobId, processingTime, 0, "W");
return this;
}
public JobSchedulingProblemBuilder withOperationForJob(final String operationId, final String jobId, final int processTime, final int status, final String wcId) {
Workcenter wc = this.workcenters.get(wcId);
Job job = this.jobs.get(jobId);
if (wc == null) {
throw new IllegalArgumentException(String.format("No workcenter with id %s has been defined!", wcId));
}
if (job == null) {
throw new IllegalArgumentException(String.format("No job with id %s has been defined", jobId));
}
if (this.operations.containsKey(operationId)) {
throw new IllegalArgumentException(String.format("There is already an operation with name \"%s\" defined (in job %s)", operationId, this.operations.get(operationId).getJob().getJobID()));
}
this.operations.put(operationId, new Operation(operationId, processTime, status, job, wc)); // the constructor automatically adds the operation to the job
return this;
}
public JobSchedulingProblemBuilder withMachineForWorkcenter(final String machineId, final String wcId, final int availability, final int initialState) {
Workcenter wc = this.workcenters.get(wcId);
if (wc == null) {
throw new IllegalArgumentException(String.format("No workcenter with id %s has been defined!", wcId));
}
if (this.machines.containsKey(machineId)) {
throw new IllegalArgumentException(String.format("Machine with id %s has already been defined (for work center %s)", machineId, this.machines.get(machineId).getWorkcenter().getWorkcenterID()));
}
this.machines.put(machineId, new Machine(machineId, availability, initialState, wc)); // the constructor automatically adds the machine to the work center
return this;
}
public JobSchedulingProblemBuilder withMetric(final JobShopMetric metric) {
this.metric = metric;
return this;
}
public JobSchedulingProblemBuilder withLatestArrivalTime(final int latestArrivalTime) {
this.latestArrivalTime = latestArrivalTime;
return this;
}
public IJobSchedulingInput build() {
if (this.metric == null) {
throw new IllegalStateException("No metric for schedule evaluation has been defined.");
}
return new JobSchedulingProblemInput(new HashMap<>(this.jobs), new HashMap<>(this.workcenters), new HashMap<>(this.operations), new HashMap<>(this.machines), this.metric, this.latestArrivalTime);
}
public Map<String, Job> getJobs() {
return Collections.unmodifiableMap(this.jobs);
}
public Map<String, Workcenter> getWorkcenters() {
return Collections.unmodifiableMap(this.workcenters);
}
public Map<String, Operation> getOperations() {
return Collections.unmodifiableMap(this.operations);
}
public Map<String, Machine> getMachines() {
return Collections.unmodifiableMap(this.machines);
}
public Workcenter getWorkcenter(final String workcenterId) {
return this.workcenters.get(workcenterId);
}
public Machine getMachine(final String machineId) {
return this.machines.get(machineId);
}
public Operation getOperation(final String operationId) {
return this.operations.get(operationId);
}
public Job getJob(final String jobId) {
return this.jobs.get(jobId);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/JobSchedulingProblemInput.java
|
package ai.libs.jaicore.problems.scheduling;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
*
* @author Gonzalo Mejia
* @author Felix Mohr
*
* @version 4.0
*/
public class JobSchedulingProblemInput implements IJobSchedulingInput {
private final Map<String, Job> jobs;
private final Map<String, Workcenter> workcenters;
private final Map<String, Operation> operations;
private final Map<String, Machine> machines;
private final JobShopMetric metric;
private final int latestArrivalTime; // this is for problems in which the arrival time is a decision variable. Then we typically have an upper bound on the arrival time
public JobSchedulingProblemInput(final Collection<Job> jobs, final Collection<Workcenter> workcenters, final Collection<Operation> operations, final Collection<Machine> machines, final JobShopMetric metric,
final int latestArrivalTime) {
this.jobs = new HashMap<>();
jobs.forEach(j -> this.jobs.put(j.getJobID(), j));
this.workcenters = new HashMap<>();
workcenters.forEach(j -> this.workcenters.put(j.getWorkcenterID(), j));
this.operations = new HashMap<>();
operations.forEach(j -> this.operations.put(j.getName(), j));
this.machines = new HashMap<>();
machines.forEach(j -> this.machines.put(j.getMachineID(), j));
this.metric = metric;
this.latestArrivalTime = latestArrivalTime;
}
public JobSchedulingProblemInput(final Map<String, Job> jobs, final Map<String, Workcenter> workcenters, final Map<String, Operation> operations, final Map<String, Machine> machines, final JobShopMetric metric,
final int latestArrivalTime) {
super();
this.jobs = jobs;
this.workcenters = workcenters;
this.operations = operations;
this.machines = machines;
this.metric = metric;
this.latestArrivalTime = latestArrivalTime;
}
@Override
public Collection<Job> getJobs() {
return this.jobs.values();
}
@Override
public Collection<Workcenter> getWorkcenters() {
return this.workcenters.values();
}
@Override
public Collection<Operation> getOperations() {
return this.operations.values();
}
@Override
public Collection<Machine> getMachines() {
return this.machines.values();
}
@Override
public JobShopMetric getMetric() {
return this.metric;
}
public int getLatestArrivalTime() {
return this.latestArrivalTime;
}
@Override
public Workcenter getWorkcenter(final String workcenterId) {
return this.workcenters.get(workcenterId);
}
@Override
public Machine getMachine(final String machineId) {
return this.machines.get(machineId);
}
@Override
public Operation getOperation(final String operationId) {
return this.operations.get(operationId);
}
@Override
public Job getJob(final String jobId) {
return this.jobs.get(jobId);
}
@Override
public double getScoreOfSchedule(final ISchedule s) {
Objects.requireNonNull(s);
return this.metric.getScore(this, s);
}
public int getTotalProcessingTime() {
return this.operations.values().stream().map(Operation::getProcessTime).reduce((a, b) -> a + b).get();
}
public void printWorkcenters(final OutputStream out) throws IOException {
StringBuilder sb = new StringBuilder();
int n = this.workcenters.size();
sb.append("Number of work centers \t" + n);
sb.append("\n\n");
for (Workcenter w : this.workcenters.values().stream().sorted((w1, w2) -> w1.getWorkcenterID().compareTo(w2.getWorkcenterID())).collect(Collectors.toList())) {
sb.append(w.getWorkcenterID());
sb.append(" (" + w.getMachines().size() + " machines)");
sb.append("\n");
for (Machine m : w.getMachines()) {
sb.append("Machine: \t" + m.getMachineID());
sb.append("\tAvailability: " + m.getAvailableDate() + "\t Init state: ");
sb.append(m.getInitialState());
sb.append("\n");
}
sb.append("\n");
}
out.write(sb.toString().getBytes());
}
/**
* printJobs writes the job information to an output writer
*
* @param out
* BufferedWriter
* @throws IOException
*/
public void printJobs(final OutputStream out) throws IOException {
StringBuilder sb = new StringBuilder();
int n = this.jobs.size();
sb.append("Number of Jobs \t" + n);
sb.append("\n\n");
for (Job j : this.jobs.values().stream().sorted((j1, j2) -> j1.getJobID().compareTo(j2.getJobID())).collect(Collectors.toList())) {
sb.append(j.getJobID());
sb.append("\n");
sb.append("Release Date \t" + j.getReleaseDate());
sb.append("\n");
sb.append("Due Date \t" + j.getDueDate());
sb.append("\n");
sb.append("Weight \t \t" + j.getWeight());
sb.append("\n");
for (Operation op : j.getOperations()) {
sb.append("Operation: \t" + op.getName());
sb.append("\tWC: " + op.getWorkcenter().getWorkcenterID());
sb.append("\tProcess time: " + op.getProcessTime() + "\t Status: ");
sb.append(op.getStatus());
sb.append("\n");
}
sb.append("\n");
}
out.write(sb.toString().getBytes());
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/JobShopMetric.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.function.BiFunction;
public enum JobShopMetric {
TOTALFLOWTIME((p, s) -> (double)p.getJobs().stream().mapToInt(s::getJobFlowTime).reduce((r, c) -> r + c).getAsInt()),
TOTALTARDINESS((p, s) -> (double)p.getJobs().stream().mapToInt(s::getJobTardiness).reduce((r, c) -> r + c).getAsInt()),
TOTALFLOWTIME_WEIGHTED((p, s) -> (double)p.getJobs().stream().mapToInt(j -> j.getWeight() * s.getJobFlowTime(j)).reduce((r, c) -> r + c).getAsInt()),
TOTALTARDINESS_WEIGHTED((p, s) -> (double)p.getJobs().stream().mapToInt(j -> j.getWeight() * s.getJobTardiness(j)).reduce((r, c) -> r + c).getAsInt()),
MAKESPAN((p, s) -> (double) p.getOperations().stream().map(s::getEndTimeOfOperation).max(Double::compare).get()), // gets the latest point of time when any operation finishes
MAXTARDINESS((p, s) -> (double)p.getJobs().stream().mapToInt(s::getJobTardiness).max().getAsInt()),
NUM_TARDY_JOB((p, s) -> (double)p.getJobs().stream().filter(j -> s.getJobTardiness(j) > 0).count());
private final BiFunction<IJobSchedulingInput, ISchedule, Double> metricFunction;
private JobShopMetric(final BiFunction<IJobSchedulingInput, ISchedule, Double> metricFunction) {
this.metricFunction = metricFunction;
}
public double getScore(final JobSchedulingProblemInput problem, final ISchedule schedule) {
if (problem.getJobs().isEmpty()) {
throw new IllegalArgumentException("Cannot get score for a problem that has no jobs!");
}
return this.metricFunction.apply(problem, schedule);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/Machine.java
|
package ai.libs.jaicore.problems.scheduling;
/**
* @author Gonzalo Mejia
* @author Felix Mohr
* @version 4.0
*/
public class Machine {
private final String machineID; // unique identifier of the machine
private final int availableDate; // defines the date of when the machine becomes available
private final int initialState; // defines the initial status of the machine. Must be a capital letter (A, B, C, etc)<br>
private final Workcenter workcenter; // the work center the machine is located in
/**
* Package constructor.
*
* @param machineID
* @param availableDate
* @param initialState
* @param workcenter
*/
Machine(final String machineID, final int availableDate, final int initialState, final Workcenter workcenter) {
super();
this.machineID = machineID;
this.availableDate = availableDate;
this.initialState = initialState;
this.workcenter = workcenter;
workcenter.addMachine(this);
}
public String getMachineID() {
return this.machineID;
}
public int getAvailableDate() {
return this.availableDate;
}
public int getInitialState() {
return this.initialState;
}
public Workcenter getWorkcenter() {
return this.workcenter;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/Operation.java
|
package ai.libs.jaicore.problems.scheduling;
/**
**/
public class Operation {
private final String name;
private final int processTime; // processTime. The processing time of the operation valid integer:
private final int status; // the state in which the machine must be to conduct this operation
private final Job job; // the job this operation belongs to
private final Workcenter workcenter; // work center in which this operation needs to be realized
Operation(final String name, final int processTime, final int status, final Job job, final Workcenter workcenter) {
super();
this.name = name;
this.processTime = processTime;
this.status = status;
this.job = job;
this.workcenter = workcenter;
job.addOperation(this);
}
public String getName() {
return this.name;
}
public int getProcessTime() {
return this.processTime;
}
public int getStatus() {
return this.status;
}
public Workcenter getWorkcenter() {
return this.workcenter;
}
public Job getJob() {
return this.job;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.job == null) ? 0 : this.job.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + this.processTime;
result = prime * result + this.status;
result = prime * result + ((this.workcenter == null) ? 0 : this.workcenter.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Operation other = (Operation) obj;
if (this.job == null) {
if (other.job != null) {
return false;
}
} else if (!this.job.equals(other.job)) {
return false;
}
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
if (this.processTime != other.processTime) {
return false;
}
if (this.status != other.status) {
return false;
}
if (this.workcenter == null) {
if (other.workcenter != null) {
return false;
}
} else if (!this.workcenter.equals(other.workcenter)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/Schedule.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.Pair;
/**
* @author gmejia
* @author Felix Mohr
*
* @version 4.0
*
*/
public class Schedule implements ISchedule {
private final List<Pair<Operation, Machine>> assignments;
private final Map<Machine, List<Operation>> assignmentPerMachine = new HashMap<>();
private final Map<Job, Integer> arrivalTimes = new HashMap<>();
private final Map<Operation, Integer> startTimes = new HashMap<>();
private final Map<Operation, Integer> endTimes = new HashMap<>();
private final Map<Operation, Integer> setupStartTimes = new HashMap<>();
private final Map<Operation, Integer> setupEndTimes = new HashMap<>();
Schedule(final IJobSchedulingInput problemInput, final List<Pair<Operation, Machine>> assignments, final IScheduleComputer schedulingComputer) {
super();
this.assignments = assignments;
this.assignments.forEach(p -> this.assignmentPerMachine.computeIfAbsent(p.getY(), m -> new ArrayList<>()).add(p.getX()));
schedulingComputer.fillTimes(problemInput, assignments, this.arrivalTimes, this.startTimes, this.endTimes, this.setupStartTimes, this.setupEndTimes);
for (Operation o : problemInput.getOperations()) {
if (!this.arrivalTimes.containsKey(o.getJob())) {
throw new IllegalStateException("No arrival time defined for job " + o.getJob().getJobID());
}
}
}
@Override
public List<Pair<Operation, Machine>> getAssignments() {
return this.assignments;
}
@Override
public List<Operation> getOperationsAssignedToMachine(final Machine m) {
return this.assignmentPerMachine.get(m);
}
@Override
public List<Operation> getOrderOfOperationsForJob(final Job job) {
return this.assignments.stream().map(Pair::getX).filter(o -> o.getJob().equals(job)).collect(Collectors.toList());
}
@Override
public int getStartTimeOfOperation(final Operation o) {
return this.startTimes.get(o);
}
@Override
public int getEndTimeOfOperation(final Operation o) {
return this.endTimes.get(o);
}
@Override
public int getSetupStartTimeOfOperation(final Operation o) {
return this.setupStartTimes.get(o);
}
@Override
public int getSetupEndTimeOfOperation(final Operation o) {
return this.setupEndTimes.get(o);
}
@Override
public int getJobFinishTime(final Job job) {
return job.getOperations().stream().map(this::getEndTimeOfOperation).max(Double::compare).get();
}
/**
*
* @param job
* @return
*/
@Override
public int getJobFlowTime(final Job job) {
return this.getJobFinishTime(job) - this.arrivalTimes.get(job); // the arrival times can be part of the SCHEDULE (being decisions) rather than part of the job definition
}
@Override
public int getJobTardiness(final Job job) {
return Math.max(0, this.getJobFinishTime(job) - job.getDueDate());
}
public String getAsString() {
StringBuilder sb = new StringBuilder();
List<Workcenter> workcenters = this.assignmentPerMachine.keySet().stream().map(Machine::getWorkcenter).collect(Collectors.toSet()).stream().sorted((w1, w2) -> w1.getWorkcenterID().compareTo(w2.getWorkcenterID()))
.collect(Collectors.toList());
for (Workcenter wc : workcenters) {
sb.append("-------------------------------------------------------------------------------------------------\n");
sb.append(wc.getWorkcenterID());
sb.append("\n-------------------------------------------------------------------------------------------------\n");
for (Machine m : wc.getMachines()) {
sb.append("\t" + m.getMachineID() + " (init state " + m.getInitialState() + "): ");
List<Operation> ops = this.getOperationsAssignedToMachine(m);
if (ops != null) {
StringBuilder opSB = new StringBuilder();
for (Operation o : ops) {
if (opSB.length() != 0) {
opSB.append(" -> ");
}
int setupStartTime = this.setupStartTimes.get(o);
int setupEndTime = this.setupEndTimes.get(o);
if (setupStartTime != setupEndTime) {
opSB.append("modify state to " + o.getStatus() + " -> ");
}
opSB.append(o.getName() + " (of job " + o.getJob().getJobID() + " from " + this.startTimes.get(o) + " to " + this.endTimes.get(o) + ")");
}
sb.append(opSB);
}
sb.append("\n");
}
}
return sb.toString();
}
public String getGanttAsString() {
StringBuilder sb = new StringBuilder();
List<Workcenter> workcenters = this.assignmentPerMachine.keySet().stream().map(Machine::getWorkcenter).collect(Collectors.toSet()).stream().sorted((w1, w2) -> w1.getWorkcenterID().compareTo(w2.getWorkcenterID()))
.collect(Collectors.toList());
for (Workcenter wc : workcenters) {
sb.append("-------------------------------------------------------------------------------------------------\n");
sb.append(wc.getWorkcenterID());
sb.append("\n-------------------------------------------------------------------------------------------------\n");
for (Machine m : wc.getMachines()) {
sb.append("\t" + m.getMachineID() + " (init state " + m.getInitialState() + "): ");
List<Operation> ops = this.getOperationsAssignedToMachine(m);
int curTime = 0;
if (ops != null) {
StringBuilder opSB = new StringBuilder();
int lastStatus = m.getInitialState();
for (Operation o : ops) {
boolean needsSetup = false;
if (m.getWorkcenter().getSetupMatrix() != null) {
sb.append(lastStatus + " -> " + o.getStatus() + ": " + m.getWorkcenter().getSetupMatrix()[lastStatus][o.getStatus()]);
needsSetup = m.getWorkcenter().getSetupMatrix()[lastStatus][o.getStatus()] != 0;
}
lastStatus = o.getStatus();
int setupStartTime = this.setupStartTimes.get(o);
int setupEndTime = this.setupEndTimes.get(o);
int startTime = this.startTimes.get(o);
int endTime = this.endTimes.get(o);
sb.append(o.getName() + " (" + m.getMachineID() + "): " + setupStartTime + ", " + setupEndTime + ", " + startTime + ", " + endTime);
/* */
sb.append(needsSetup);
if (needsSetup) {
while (curTime < setupStartTime) {
sb.append(" ");
curTime++;
}
sb.append("|");
curTime++;
while (curTime < setupEndTime) {
sb.append("+");
curTime++;
}
while (curTime < startTime) {
sb.append("?");
curTime++;
}
} else {
while (curTime < startTime) {
sb.append(" ");
curTime++;
}
}
sb.append("|");
int spaceForLabeling = endTime - startTime;
int whiteSpace = Math.max(0, spaceForLabeling - o.getName().length());
int whiteSpaceLeft = whiteSpace / 2;
int startLabeling = startTime + whiteSpaceLeft;
while (curTime < startLabeling) {
sb.append(" ");
curTime++;
}
sb.append(o.getName());
curTime += o.getName().length();
while (curTime < endTime) {
sb.append(" ");
curTime++;
}
if (endTime - startTime > 1) {
sb.append("|");
}
}
sb.append(opSB);
}
sb.append("\n");
}
}
return sb.toString();
}
/**
* A schedule is active if no operation can be scheduled earlier without any other change. This method determines whether the schedule is active.
*
* @return
*/
public boolean isActive() {
for (Operation o : this.setupEndTimes.keySet()) {
if (this.canOperationBeScheduledEarlierWithoutAnyOtherEffect(o)) {
return false;
}
}
return true;
}
public boolean canOperationBeScheduledEarlierWithoutAnyOtherEffect(final Operation o) {
/* first condition: there is enough free time inbetween other operations of the JOB earlier */
Job j = o.getJob();
int requiredTime = o.getProcessTime();
List<Operation> otherOpsOfJobStartingEarlier = j.getOperations().stream().filter(op -> this.endTimes.containsKey(op) && this.endTimes.get(op) <= this.startTimes.get(o))
.sorted((o1, o2) -> Integer.compare(this.startTimes.get(o1), this.startTimes.get(o2))).collect(Collectors.toList());
/* if this is the first operation in the job, just look if we can allocate it earlier onto some of the machines in the WC */
if (otherOpsOfJobStartingEarlier.isEmpty()) {
int start = 0;
int end = this.endTimes.get(o);
for (Machine m : o.getWorkcenter().getMachines()) {
if (this.getEarliestTimeWhenMachineIsFreeForDurationInInterval(m, start, end, o) != -1) {
return true;
}
}
}
/* if there are other operation earlier, look whether we can get this operation squeezed somewhere in between */
else {
int endTimeOfLast = 0;
for (Operation otherOp : otherOpsOfJobStartingEarlier) {
int timeOfThis = this.endTimes.get(otherOp);
/* now check if we have enough time inbetween the operations of the job to put the operation here */
if (timeOfThis - endTimeOfLast > requiredTime) {
/* if this is the case, check whether the machine is free at any time in that slot */
int start = endTimeOfLast;
int end = timeOfThis;
for (Machine m : o.getWorkcenter().getMachines()) {
if (this.getEarliestTimeWhenMachineIsFreeForDurationInInterval(m, start, end, o) != -1) {
return true;
}
}
}
endTimeOfLast = this.endTimes.get(otherOp);
}
}
return false;
}
public int getEarliestTimeWhenMachineIsFreeForDurationInInterval(final Machine m, final int start, final int end, final Operation op) {
List<Operation> opsOnMachineDuringThatTime = this.getOperationsAssignedToMachine(m).stream()
.filter(o -> this.setupStartTimes.get(o) > start && this.setupStartTimes.get(o) < end || this.endTimes.get(o) > start && this.endTimes.get(o) < end).collect(Collectors.toList());
int currentOffset = Math.max(start, m.getAvailableDate());
for (Operation o : opsOnMachineDuringThatTime) {
int requiredSetupTimeIfInsertedHere = m.getWorkcenter().getSetupMatrix()[op.getStatus()][o.getStatus()];
if (this.startTimes.get(o) - requiredSetupTimeIfInsertedHere - currentOffset >= o.getProcessTime()) {
return currentOffset;
}
currentOffset = this.endTimes.get(o);
}
return -1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.assignments == null) ? 0 : this.assignments.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Schedule other = (Schedule) obj;
if (this.assignments == null) {
if (other.assignments != null) {
return false;
}
} else if (!this.assignments.equals(other.assignments)) {
return false;
}
return true;
}
@Override
public Machine getMachineToWhichOperationHasBeenAssigned(final Operation o) {
for (Pair<Operation, Machine> assignment : this.assignments) {
if (assignment.getX().equals(o)) {
return assignment.getY();
}
}
return null;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/ScheduleBuilder.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.problems.scheduling.computers.DefaultSchedulingComputer;
public class ScheduleBuilder {
private final IJobSchedulingInput problem;
private final Set<String> assignedOperations = new HashSet<>();
private final List<Pair<Operation, Machine>> assignments = new ArrayList<>();
private IScheduleComputer schedulingComputer = new DefaultSchedulingComputer();
public ScheduleBuilder(final JobSchedulingProblemBuilder builder) {
this(builder.fork().withMetric(JobShopMetric.TOTALFLOWTIME).build());
}
public ScheduleBuilder(final IJobSchedulingInput problem) {
super();
this.problem = problem;
}
public IJobSchedulingInput getProblem() {
return this.problem;
}
public List<Pair<Operation, Machine>> getOrder() {
return this.assignments;
}
public ScheduleBuilder assign(final Operation o, final Machine m) {
Objects.requireNonNull(o);
Objects.requireNonNull(m);
if (this.assignedOperations.contains(o.getName())) {
throw new IllegalArgumentException("Operation " + o.getName() + " has already been assigned.");
}
if (!o.getWorkcenter().getMachines().contains(m)) {
throw new IllegalArgumentException("Cannot assign operation " + o.getName() + " to machine " + m.getMachineID() + ", because that machine is in work center " + m.getWorkcenter().getWorkcenterID() + ", but the operation must be executed in work center " + o.getWorkcenter().getWorkcenterID());
}
this.assignments.add(new Pair<>(o, m));
this.assignedOperations.add(o.getName());
return this;
}
public ScheduleBuilder assign(final String o, final String m) {
return this.assign(this.problem.getOperation(o), this.problem.getMachine(m));
}
public ScheduleBuilder withSchedulingComputer(final IScheduleComputer schedulingComputer) {
this.schedulingComputer = schedulingComputer;
return this;
}
public Schedule build() {
Collection<Operation> unassignedOperations = SetUtil.difference(this.problem.getOperations(), this.assignments.stream().map(Pair::getX).collect(Collectors.toSet()));
if (!unassignedOperations.isEmpty()) {
throw new UnsupportedOperationException("Cannot create partial schedules at the moment. Unassigned operations: " + unassignedOperations);
}
return new Schedule(this.problem, this.assignments, this.schedulingComputer);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/Workcenter.java
|
package ai.libs.jaicore.problems.scheduling;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Gonzalo Mejia
* @author Felix Mohr
* @version 4.0
*/
public class Workcenter {
private final String workcenterID; // unique name
private final List<Machine> machines = new ArrayList<>(); // the machines in this work center
private final int[][] setupMatrix; // setupMatrix[i][j] defines for each tool the time to move any of its machines from state i into state j
Workcenter(final String workcenterID, final int[][] setupMatrix) {
super();
this.workcenterID = workcenterID;
if (setupMatrix != null) { // setup matrix is not mandatory (0-setup costs are assumed otherwise)
for (int i = 0; i < setupMatrix.length; i++) {
if (setupMatrix[i][i] != 0) {
throw new IllegalArgumentException("The diagonal entries of the setup matrix must always be 0.");
}
}
}
this.setupMatrix = setupMatrix;
}
public String getWorkcenterID() {
return this.workcenterID;
}
public List<Machine> getMachines() {
return Collections.unmodifiableList(this.machines);
}
void addMachine(final Machine m) {
this.machines.add(m);
}
public int[][] getSetupMatrix() {
return this.setupMatrix;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/computers/DefaultSchedulingComputer.java
|
package ai.libs.jaicore.problems.scheduling.computers;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.problems.scheduling.ASchedulingComputer;
import ai.libs.jaicore.problems.scheduling.IJobSchedulingInput;
import ai.libs.jaicore.problems.scheduling.Job;
import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput;
import ai.libs.jaicore.problems.scheduling.Machine;
import ai.libs.jaicore.problems.scheduling.Operation;
public class DefaultSchedulingComputer extends ASchedulingComputer {
@Override
public void fillTimes(final IJobSchedulingInput problemInput, final List<Pair<Operation, Machine>> assignments, final Map<Job, Integer> arrivalTimes, final Map<Operation, Integer> startTimes, final Map<Operation, Integer> endTimes, final Map<Operation, Integer> setupStartTimes,
final Map<Operation, Integer> setupEndTimes) {
if (!(problemInput instanceof JobSchedulingProblemInput)) {
throw new IllegalArgumentException();
}
JobSchedulingProblemInput cProblemInput = (JobSchedulingProblemInput)problemInput;
/* set all arrival times to the ones set in the job definitions */
problemInput.getJobs().forEach(j -> arrivalTimes.put(j, j.getReleaseDate()));
super.fillTimes(cProblemInput, assignments, arrivalTimes, startTimes, endTimes, setupStartTimes, setupEndTimes);
}
@Override
public int getTimeWhenMachineBecomesAvailableForOperation(final Map<Job, Integer> arrivalTimes, final Map<Machine, Integer> machineReadiness, final Machine m) {
return machineReadiness.computeIfAbsent(m, Machine::getAvailableDate);
}
@Override
public int timeWhenOperationArrivesAtMachine(final Map<Job, Integer> arrivalTimes, final Map<Machine, Integer> machineReadiness, final Map<Job, Integer> jobReadyness, final Operation o, final Machine m) {
return jobReadyness.computeIfAbsent(o.getJob(), Job::getReleaseDate); // maybe add travel time here
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/computers/VariableReleaseDatesSchedulingComputer.java
|
package ai.libs.jaicore.problems.scheduling.computers;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.problems.scheduling.ASchedulingComputer;
import ai.libs.jaicore.problems.scheduling.IJobSchedulingInput;
import ai.libs.jaicore.problems.scheduling.Job;
import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput;
import ai.libs.jaicore.problems.scheduling.Machine;
import ai.libs.jaicore.problems.scheduling.Operation;
/**
* The unique aspect of this computer is that Job release dates are ignored. Instead, release dates are automatically derived from the assignments and the latest arrival date: The release date is set to the minimum of the processing time
* and the latest allowed arrival time.
*
* @author Felix Mohr
*
*/
public class VariableReleaseDatesSchedulingComputer extends ASchedulingComputer {
private int latestArrivalTime;
@Override
public void fillTimes(final IJobSchedulingInput problemInput, final List<Pair<Operation, Machine>> assignments, final Map<Job, Integer> arrivalTimes, final Map<Operation, Integer> startTimes, final Map<Operation, Integer> endTimes, final Map<Operation, Integer> setupStartTimes,
final Map<Operation, Integer> setupEndTimes) {
if (!(problemInput instanceof JobSchedulingProblemInput)) {
throw new IllegalArgumentException();
}
JobSchedulingProblemInput cProblemInput = (JobSchedulingProblemInput)problemInput;
this.latestArrivalTime = cProblemInput.getLatestArrivalTime();
super.fillTimes(cProblemInput, assignments, arrivalTimes, startTimes, endTimes, setupStartTimes, setupEndTimes);
}
@Override
public int getTimeWhenMachineBecomesAvailableForOperation(final Map<Job, Integer> arrivalTimes, final Map<Machine, Integer> machineReadiness, final Machine m) {
return machineReadiness.computeIfAbsent(m, Machine::getAvailableDate);
}
@Override
public int timeWhenOperationArrivesAtMachine(final Map<Job, Integer> arrivalTimes, final Map<Machine, Integer> machineReadiness, final Map<Job, Integer> jobReadyness, final Operation o, final Machine m) {
Job job = o.getJob();
int timeWhenMachineBecomesAvailableForOperation = this.getTimeWhenMachineBecomesAvailableForOperation(arrivalTimes, machineReadiness, m);
int timeWhenJobArrivesAtMachine;
if (!arrivalTimes.containsKey(job)) { // this is the first operation of assigned for this job (then use it as the arrival time for the job)
timeWhenJobArrivesAtMachine = Math.min(timeWhenMachineBecomesAvailableForOperation, this.latestArrivalTime);
arrivalTimes.put(job, timeWhenJobArrivesAtMachine);
}
else {
timeWhenJobArrivesAtMachine = Math.max(timeWhenMachineBecomesAvailableForOperation, arrivalTimes.get(job));
}
return timeWhenJobArrivesAtMachine;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/openshop/OpenShopProblemGenerator.java
|
package ai.libs.jaicore.problems.scheduling.openshop;
import java.util.Random;
import java.util.function.IntBinaryOperator;
import org.apache.commons.math3.distribution.AbstractRealDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import ai.libs.jaicore.problems.scheduling.IJobSchedulingInput;
import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemBuilder;
import ai.libs.jaicore.problems.scheduling.JobShopMetric;
public class OpenShopProblemGenerator {
private int seed = 0;
private int numWorkcenters = 0;
private AbstractRealDistribution distributionOfMachinesPerWorkcenter = new NormalDistribution(3, 1);
private int numJobs = 0;
private AbstractRealDistribution distributionOfOperationsPerJob = new NormalDistribution(3, 1);
private IntBinaryOperator setupTimeGenerator = (i1, i2) -> Math.abs(i1 - i2);
private AbstractRealDistribution distributionOfToolsInWorkcenter = new NormalDistribution(3, 1);
private AbstractRealDistribution distributionOfMachineAvailability = new NormalDistribution(5, 3);
private AbstractRealDistribution distributionOfJobReleases= new UniformRealDistribution(0, 20);
private AbstractRealDistribution distributionOfJobDuration = new UniformRealDistribution(10, 20);
private AbstractRealDistribution distributionOfOperationProcessTime = new UniformRealDistribution(1, 20);
private JobShopMetric metric;
public IJobSchedulingInput generate() {
/* sanity check */
if (this.numWorkcenters <= 0) {
throw new UnsupportedOperationException("Positive number of work centers required.");
}
if (this.numJobs <= 0) {
throw new UnsupportedOperationException("Positive number of work centers required.");
}
if (this.metric == null) {
throw new UnsupportedOperationException("Metric must be set.");
}
JobSchedulingProblemBuilder builder = new JobSchedulingProblemBuilder();
/* seed all the distributions */
Random rand = new Random(this.seed);
this.distributionOfMachinesPerWorkcenter.reseedRandomGenerator(this.seed);
this.distributionOfOperationsPerJob.reseedRandomGenerator(this.seed);
this.distributionOfToolsInWorkcenter.reseedRandomGenerator(this.seed);
this.distributionOfMachineAvailability.reseedRandomGenerator(this.seed);
this.distributionOfJobReleases.reseedRandomGenerator(this.seed);
this.distributionOfJobDuration.reseedRandomGenerator(this.seed);
this.distributionOfOperationProcessTime.reseedRandomGenerator(this.seed);
/* create work centers */
int mId = 0;
for (int i = 0; i < this.numWorkcenters; i++) {
int numTools = this.sampleMinInteger(1, this.distributionOfToolsInWorkcenter);
int[][] setupMatrix = new int[numTools][numTools];
for (int j = 0; j < numTools; j++) {
for (int k = 0; k < numTools; k++) {
setupMatrix[j][k] = this.setupTimeGenerator.applyAsInt(j, k);
}
}
String wcName = "WC" + (i + 1);
builder.withWorkcenter(wcName, setupMatrix);
int numMachines = this.sampleMinInteger(1, this.distributionOfMachinesPerWorkcenter);
for (int j = 0; j < numMachines; j++) {
mId ++;
builder.withMachineForWorkcenter("M" + mId, wcName, this.sampleMinInteger(0, this.distributionOfMachineAvailability), rand.nextInt(numTools));
}
}
/* create jobs */
int opId = 0;
for (int j = 0; j < this.numJobs; j++) {
String jobId = "J" + (j+1);
int releaseDate = this.sampleMinInteger(0, this.distributionOfJobReleases);
int dueDate = releaseDate + this.sampleMinInteger(0, this.distributionOfJobDuration);
builder.withJob(jobId, releaseDate, dueDate, rand.nextInt(10));
int numOps = this.sampleMinInteger(1, this.distributionOfOperationsPerJob);
for (int k = 0; k < numOps; k++) {
opId ++;
String wcId = "WC" + (rand.nextInt(this.numWorkcenters) + 1);
int numTools = builder.getWorkcenter(wcId).getSetupMatrix().length;
builder.withOperationForJob("O" + opId, jobId, this.sampleMinInteger(1, this.distributionOfOperationProcessTime), rand.nextInt(numTools), wcId);
}
}
builder.withMetric(this.metric);
return builder.build();
}
private int sampleMinInteger(final int min, final AbstractRealDistribution dist) {
return Math.max(min, (int)Math.round(dist.sample()));
}
public int getNumWorkcenters() {
return this.numWorkcenters;
}
public void setNumWorkcenters(final int numWorkcenters) {
this.numWorkcenters = numWorkcenters;
}
public int getNumJobs() {
return this.numJobs;
}
public void setNumJobs(final int numJobs) {
this.numJobs = numJobs;
}
public JobShopMetric getMetric() {
return this.metric;
}
public void setMetric(final JobShopMetric metric) {
this.metric = metric;
}
public int getSeed() {
return this.seed;
}
public void setSeed(final int seed) {
this.seed = seed;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/problems/scheduling/openshop/OpenShopProblemReader.java
|
package ai.libs.jaicore.problems.scheduling.openshop;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import ai.libs.jaicore.basic.FileUtil;
import ai.libs.jaicore.problems.scheduling.IJobSchedulingInput;
import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemBuilder;
import ai.libs.jaicore.problems.scheduling.JobShopMetric;
/**
* @author Felix Mohr
*
*/
public class OpenShopProblemReader {
private OpenShopProblemReader() {
/* avoids instantiation */
}
public static IJobSchedulingInput getFromJobFileWithoutSetupTimesAndWithOneMachinePerWorkcenter(final File jobFile, final JobShopMetric metric) throws IOException {
/* get number of work centers */
List<String> jobFileLines = FileUtil.readFileAsList(jobFile);
final int numJobs = Integer.parseInt(jobFileLines.remove(0));
final int numWorkcenters = Integer.parseInt(jobFileLines.remove(0));
/* setup work centers with no setup times (assuming that the number of operations = number of jobs */
JobSchedulingProblemBuilder builder = new JobSchedulingProblemBuilder();
int[][] zeroSetupTimesArray = new int[numJobs + 1][numJobs + 1];
for (int i = 0; i <= numJobs; i++) {
for (int j = 0; j <= numJobs; j++) {
zeroSetupTimesArray[i][j] = 0;
}
}
for (int i = 0; i < numWorkcenters; i++) {
String wcId = "W" + (i + 1);
String machineId = "M" + (i + 1);
builder.withWorkcenter(wcId, zeroSetupTimesArray);
builder.withMachineForWorkcenter(machineId, wcId, 0, 0);
}
/* add jobs */
configureBuilderWithJobsFromJobFile(builder, jobFile);
/* setup metric and return */
builder.withMetric(metric);
return builder.build();
}
/**
* Reads the problem from a job file, a setup times file, and a file describing the number of parallel machines in each work center.
*
* The underlying assumption here is that all jobs have the same number of operations, one for each work center. Under this assumption, naturally each operation i of some job is assigned to the i-th work center by convention. In
* addition, we assume that each operation has a specific status required for the machines.
*
* @param jobFile
* @param setupTimesFile
* @param parallelMachinesFile
* @return
* @throws IOException
*/
public static IJobSchedulingInput mergeFromFiles(final File jobFile, final File setupTimesFile, final File parallelMachinesFile, final JobShopMetric metric) throws IOException {
/* existence check for files */
if (setupTimesFile == null || !setupTimesFile.exists()) {
throw new IllegalArgumentException("Cannot read setup times file \"" + setupTimesFile + "\"");
}
if (parallelMachinesFile == null || !parallelMachinesFile.exists()) {
throw new IllegalArgumentException("Cannot read parallel machines file \"" + parallelMachinesFile + "\"");
}
/* create builder */
JobSchedulingProblemBuilder builder = new JobSchedulingProblemBuilder();
/* read the setup times and create the work centers */
List<String> setupTimesFileLines = FileUtil.readFileAsList(setupTimesFile);
final int numOperations = Integer.parseInt(setupTimesFileLines.remove(0));
final int numWorkcenters = Integer.parseInt(setupTimesFileLines.remove(0));
setupTimesFileLines.remove(0); // remove line with initial setup cost
int[][] setupTimesForThisWorkcenter = null;
int[][][] setupTimesForWorkcenters = new int[numWorkcenters][numOperations + 1][numOperations + 1];
int wcId = 0;
int currentLineIndexWithinWorkcenter = 1; // skip first line, because this is a 0-entry for the initial setup
for (String line : setupTimesFileLines) {
if (line.isEmpty()) {
if (setupTimesForThisWorkcenter != null) {
setupTimesForWorkcenters[wcId++] = setupTimesForThisWorkcenter;
}
setupTimesForThisWorkcenter = new int[numOperations + 1][numOperations + 1];
currentLineIndexWithinWorkcenter = 1;
}
else {
String[] setupTimesForThisOperationAsString = line.replace("|", " ").trim().split(" ");
int[] setupTimeForThisOperation = new int[setupTimesForThisOperationAsString.length + 1];
for (int i = 1; i < setupTimeForThisOperation.length; i++) {
setupTimeForThisOperation[i] = Integer.parseInt(setupTimesForThisOperationAsString[i - 1]); // first element is just always 0
}
setupTimesForThisWorkcenter[currentLineIndexWithinWorkcenter] = setupTimeForThisOperation;
currentLineIndexWithinWorkcenter ++;
}
}
setupTimesForWorkcenters[wcId] = setupTimesForThisWorkcenter;
for (int i = 0; i < numWorkcenters; i++) {
builder.withWorkcenter("W" + (i + 1), setupTimesForWorkcenters[i]);
}
/* read in the number of machines for the work centers */
List<String> numMachineFileLines = FileUtil.readFileAsList(parallelMachinesFile);
String[] numMachineTimeParts = numMachineFileLines.get(0).replace("|", " ").trim().split(" ");
if (numMachineTimeParts.length != numWorkcenters) {
throw new IllegalArgumentException("The number of fields in the machine file must coincide with the number of work centers defined in the other files. Here, " + numMachineTimeParts.length
+ " numbers of machines have been defined: " + numMachineFileLines.get(0)+ ". The number of work centers however is " + numWorkcenters);
}
int machineIndex = 1;
for (int i = 0; i < numWorkcenters; i++) {
int numMachinesHere = Integer.parseInt(numMachineTimeParts[i]);
String wcName = "W" + (i + 1);
for (int j = 0; j < numMachinesHere; j++) {
builder.withMachineForWorkcenter("M" + (machineIndex++), wcName, 0, 0);
}
}
/* configure jobs */
configureBuilderWithJobsFromJobFile(builder, jobFile);
/* build the problem */
return builder.withMetric(metric).build();
}
private static void configureBuilderWithJobsFromJobFile(final JobSchedulingProblemBuilder builder, final File jobFile) throws IOException {
final int numWorkcentersDefinedInBuilder = builder.getWorkcenters().size();
if (jobFile == null || !jobFile.exists()) {
throw new IllegalArgumentException("Cannot read job file \"" + jobFile + "\"");
}
/* read job file
* 1st line is number of jobs
* 2nd line is number of work centers
* following lines define the matrix where [i][j] is the process time of the operation i, which is to be realized in work center j
**/
Queue<String> jobFileLines = new LinkedList<>(FileUtil.readFileAsList(jobFile));
final int numJobs = Integer.parseInt(jobFileLines.poll());
final int numWorkcentersHere = Integer.parseInt(jobFileLines.poll());
if (numWorkcentersDefinedInBuilder != numWorkcentersHere) {
throw new IllegalArgumentException("Number of work centers in setup file is " + numWorkcentersDefinedInBuilder + " but in job description is " + numWorkcentersHere);
}
int opIndex = 1;
for (int i = 0; i < numJobs; i++) {
String jobId = "J" + (i + 1);
String line = jobFileLines.poll();
String[] processTimeParts = line.replace("|", " ").trim().split(" ");
if (processTimeParts.length != (numWorkcentersDefinedInBuilder)) { // add one field for the first and last pipe respectively
throw new IllegalArgumentException("Ill-defined job specification \"" + line + "\" for " + numWorkcentersDefinedInBuilder + " work centers. Split length is " + processTimeParts.length + ": " + Arrays.toString(processTimeParts));
}
builder.withJob(jobId, 0, Integer.MAX_VALUE, 1);
for (int j = 0; j < numWorkcentersDefinedInBuilder; j++) {
builder.withOperationForJob("O" + opIndex, jobId, Integer.parseInt(processTimeParts[j]), j + 1, "W" + (j + 1)); // the status is j + 1, because status 0 is the inital state
opIndex++;
}
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/timing/TimeRecordingObjectEvaluator.java
|
package ai.libs.jaicore.timing;
import java.util.HashMap;
import java.util.Map;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.logging.ToJSONStringUtil;
public class TimeRecordingObjectEvaluator<T, V extends Comparable<V>> implements IObjectEvaluator<T, V>, ILoggingCustomizable{
private Logger logger = LoggerFactory.getLogger(TimeRecordingObjectEvaluator.class);
private final IObjectEvaluator<T, V> baseEvaluator;
private final Map<T, Integer> consumedTimes = new HashMap<>();
public TimeRecordingObjectEvaluator(final IObjectEvaluator<T, V> baseEvaluator) {
super();
this.baseEvaluator = baseEvaluator;
}
@Override
public V evaluate(final T object) throws InterruptedException, ObjectEvaluationFailedException {
long start = System.currentTimeMillis();
this.logger.info("Starting timed evaluation.");
V score = this.baseEvaluator.evaluate(object);
long end = System.currentTimeMillis();
int runtime = (int) (end - start);
this.logger.info("Finished evaluation in {}ms. Score is {}", runtime, score);
this.consumedTimes.put(object, runtime);
return score;
}
public boolean hasEvaluationForComponentInstance(final T inst) {
return this.consumedTimes.containsKey(inst);
}
public int getEvaluationTimeForComponentInstance(final T inst) {
return this.consumedTimes.get(inst);
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("baseEvaluator", this.baseEvaluator);
fields.put("consumedTimes", this.consumedTimes);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
if (this.baseEvaluator instanceof ILoggingCustomizable) {
this.logger.info("Setting logger of evaluator {} to {}.be", this.baseEvaluator.getClass().getName(), name);
((ILoggingCustomizable) this.baseEvaluator).setLoggerName(name + ".be");
}
else {
this.logger.info("Evaluator {} cannot be customized for logging, so not configuring its logger.", this.baseEvaluator.getClass().getName());
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/timing/TimedComputation.java
|
package ai.libs.jaicore.timing;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.concurrent.GlobalTimer;
import ai.libs.jaicore.interrupt.Interrupter;
import ai.libs.jaicore.interrupt.InterruptionTimerTask;
import ai.libs.jaicore.logging.LoggerUtil;
/**
* This class is the single-thread pendant to asynchronous computations realized with Futures
*
* @author fmohr
*
*/
public abstract class TimedComputation {
private static final Logger logger = LoggerFactory.getLogger(TimedComputation.class);
private TimedComputation() {
/* no explicit instantiation allowed */
}
public static <T> T compute(final Callable<T> callable, final Timeout timeout, final String reasonToLogOnTimeout) throws ExecutionException, AlgorithmTimeoutedException, InterruptedException {
/* schedule a timer that will interrupt the current thread and execute the task */
GlobalTimer timer = GlobalTimer.getInstance();
long start = System.currentTimeMillis();
InterruptionTimerTask task = new InterruptionTimerTask("Timeout for timed computation with thread " + Thread.currentThread() + " at timestamp " + start + ": " + reasonToLogOnTimeout);
logger.debug("Scheduling timer for interruption in {}ms with reason {}, i.e. timestamp {}.", timeout.milliseconds(), start + timeout.milliseconds(), reasonToLogOnTimeout);
timer.schedule(task, timeout.milliseconds());
Interrupter interrupter = Interrupter.get();
logger.debug("Acquired interrupter {}.", interrupter);
T output = null;
Exception caughtException = null;
try {
logger.debug("Starting supervised computation of {}.", callable);
output = callable.call();
} catch (Exception e) {
caughtException = e;
} finally {
task.cancel();
}
/* several circumstances define the state at this point:
* 1. the Callable has exited successfully or not
* 2. the thread is currently not interrupted or interrupted internally or externally
* 3. the time elapsed since calling the Callable is lower than the timeout or exceeds it
*
*/
int runtime = (int) (System.currentTimeMillis() - start);
int delay = runtime - (int) timeout.milliseconds();
boolean isInterrupted = Thread.currentThread().isInterrupted();
if (caughtException != null) {
logger.info("Timed computation has returned control after {}ms, i.e., with a delay of {}ms. Observed exception: {}. Thread interrupt flag is {}.", runtime, delay, caughtException.getClass().getName(), isInterrupted);
if ((caughtException instanceof InterruptedException) && isInterrupted && interrupter.getAllUnresolvedInterruptsOfThread(Thread.currentThread()).size() == 1) { // only the reason belonging to our task is on the stack
logger.warn("Timed computation has thrown an InterruptedException AND the thread is interrupted AND there are no other open interrupts on the thread! This should never happen! Here is the stack trace: \n\t{}",
LoggerUtil.getExceptionInfo(caughtException));
}
} else {
logger.info("Timed computation has returned control after {}ms, i.e., with a delay of {}ms. Observed regular output return value: {}. Thread interrupt flag is {}.", runtime, delay, output, isInterrupted);
}
/* now make sure that
* a) the timeoutTriggered flag is true iff the TimerTask for the timeout has been executed
* b) the interrupt-flag of the thread is true iff there has been another open (or untracked) interrupt
* */
boolean timeoutTriggered = false;
synchronized (interrupter) {
/* if the timeout has been triggered (with caution) */
logger.debug("Checking for an interruption and resolving potential interrupts.");
if (interrupter.hasCurrentThreadBeenInterruptedWithReason(task)) {
logger.info("Thread has been interrupted internally. Resolving the interrupt (this may throw an InterruptedException).");
timeoutTriggered = true;
Thread.interrupted(); // clear the interrupted field
Interrupter.get().markInterruptOnCurrentThreadAsResolved(task);
}
/* otherwise, if the thread has been interrupted directly and not as a consequence of a shutdown, forward the interrupt */
else if (task.isTriggered()) {
interrupter.avoidInterrupt(Thread.currentThread(), task);
logger.info("Interrupt is external, black-listed \"{}\" for interrupts on {} and re-throwing the exception.", task, Thread.currentThread());
}
assert !interrupter.hasCurrentThreadBeenInterruptedWithReason(task);
}
/* if there has been an exception, throw it if it is not the InterruptedException caused by the timeout (in this case, throw an AlgorithmTimeoutedException) */
if (caughtException != null) {
if (timeoutTriggered) {
logger.info("Throwing TimeoutException");
throw new AlgorithmTimeoutedException(delay);
} else if (caughtException instanceof InterruptedException) {
logger.debug("An InterruptedException was thrown during the timed execution: {}. Re-throwing it. Interrupt-flag is {}.", caughtException, Thread.currentThread().isInterrupted());
throw (InterruptedException) caughtException;
} else {
logger.debug("Now re-throwing {}, which was caught in timed computation. Interrupt-flag is {}.", caughtException, Thread.currentThread().isInterrupted());
throw new ExecutionException(caughtException);
}
}
/* if no exception has been thrown, return the received output. Maybe the thread is interrupted, but this is then not due to our timeout */
logger.debug("Finished timed computation of {} after {}ms where {}ms were allowed. Interrupt-flag is {}", callable, runtime, timeout, Thread.currentThread().isInterrupted());
return output;
}
public static void computeWithTimeout(final Timeout timeout, final Runnable runnable) throws InterruptedException {
Semaphore sync = new Semaphore(0);
Thread t = new Thread(() -> {
try {
runnable.run();
} catch (Exception e) {
logger.info("Caught exception in timed computation thread", e);
} finally {
sync.release();
}
});
t.start();
try {
if (timeout.milliseconds() > 0) {
logger.info("Wait for a timeout of {}ms.", timeout.milliseconds());
if (!sync.tryAcquire(timeout.milliseconds(), TimeUnit.MILLISECONDS)) {
t.interrupt();
}
} else {
logger.info("No timeout set, thus wait until the process is finished.");
sync.acquire();
}
} catch (InterruptedException e) {
logger.info("TimedComputation got interrupted or timeout has fired, thus interrupt nested thread.");
t.interrupt();
throw e;
}
}
public static void computeWithTimeoutInParallel(final int numCPUs, final Timeout timeout, final List<Runnable> taskList) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(numCPUs);
Semaphore sync = new Semaphore(0);
taskList.stream().forEach(x -> pool.submit(() -> {
try {
x.run();
} finally {
sync.release();
}
}));
pool.shutdown();
try
{
logger.info("Wait for a timeout of {}ms.", timeout.milliseconds());
if (timeout.milliseconds() > 0) {
if (!sync.tryAcquire(taskList.size(), timeout.milliseconds(), TimeUnit.MILLISECONDS)) {
logger.info("Timeout fired, shutdown pool right now.");
pool.shutdownNow();
}
} else {
sync.acquire(taskList.size());
}
} catch (InterruptedException e) {
logger.info("TimedComputation got interrupted or timeout has fired, thus interrupt nested thread.");
pool.shutdownNow();
throw e;
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/timing/TimedObjectEvaluator.java
|
package ai.libs.jaicore.timing;
import java.util.concurrent.ExecutionException;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException;
public abstract class TimedObjectEvaluator<T, V extends Comparable<V>> implements IObjectEvaluator<T, V> {
public abstract V evaluateSupervised(T item) throws InterruptedException, ObjectEvaluationFailedException;
public abstract Timeout getTimeout(T item);
public abstract String getMessage(T item);
@Override
public final V evaluate(final T object) throws InterruptedException, ObjectEvaluationFailedException {
try {
return TimedComputation.compute(() -> this.evaluateSupervised(object), this.getTimeout(object), this.getMessage(object));
} catch (InterruptedException e) { // re-throw interrupts
assert !Thread.currentThread().isInterrupted() : "The interrupt-flag should not be true when an InterruptedException is thrown! Stack trace of the InterruptedException is \n\t";
throw e;
} catch (AlgorithmTimeoutedException e) {
throw new ObjectEvaluationFailedException("Timed object evaluation failed", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof ObjectEvaluationFailedException) {
throw (ObjectEvaluationFailedException) e.getCause();
}
throw new ObjectEvaluationFailedException("Evaluation of composition failed as the component instantiation could not be built.", e.getCause());
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/metric/IDistanceMetric.java
|
package org.api4.java.common.metric;
import org.api4.java.common.math.IMetric;
/**
* Interface that describes a distance measure of two time series.
*
* @author fischor
*/
public interface IDistanceMetric extends IMetric<double[]> {
/**
* Calculates the distance between two time series.
*
* @param a First time series.
* @param b Second time series.
* @return Distance between the first and second time series.
*/
public double distance(double[] a, double[] b);
@Override
default double getDistance(final double[] a, final double[] b) {
return this.distance(a, b);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/metric/IScalarDistance.java
|
package org.api4.java.common.metric;
import org.api4.java.common.math.IMetric;
/**
* Functional interface for the distance of two scalars.
*
* @author fischor
*/
public interface IScalarDistance extends IMetric<Double> {
default double distance(final double a, final double b) {
return this.getDistance(a, b);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/metric/ITimeseriesDistanceMetric.java
|
package org.api4.java.common.metric;
import java.util.stream.IntStream;
/**
* Interface that describes a distance measure of two time series that takes the
* timestamps into account.
*
* @author fischor
*/
public interface ITimeseriesDistanceMetric extends IDistanceMetric {
/**
* Calculates the distance between two time series.
*
* @param a First time series.
* @param tA Timestamps for the first time series.
* @param b Second time series.
* @param tB Timestamps for the second times series.
* @return Distance between the first and second time series.
*/
public double distance(double[] a, double[] tA, double[] b, double[] tB);
@Override
public default double distance(final double[] a, final double[] b) {
return distance(a, IntStream.range(0, a.length).mapToDouble(x -> x).toArray(), b, IntStream.range(0, b.length).mapToDouble(x -> x).toArray());
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/metric/package-info.java
|
/**
* @author mwever
*
*/
package org.api4.java.common.metric;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/timeseries/ITimeSeriesComplexity.java
|
package org.api4.java.common.timeseries;
/**
* Interface that describes the complexity measure of a time series.
*
* @author fischor
*/
public interface ITimeSeriesComplexity {
public double complexity(double[] t);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common
|
java-sources/ai/libs/jaicore-basic/0.2.7/org/api4/java/common/timeseries/package-info.java
|
/**
*
*/
/**
* @author mwever
*
*/
package org.api4.java.common.timeseries;
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IComponent.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
import java.util.Collection;
public interface IComponent extends Serializable {
/**
* @return Name of the component
*/
public String getName();
/**
* @return Names of interfaces offered by this component
*/
public Collection<String> getProvidedInterfaces();
/**
* @return The required interfaces of this component
*/
public Collection<IRequiredInterfaceDefinition> getRequiredInterfaces();
/**
* @param id internal id of the required interface in the component
* @return The interface description for the respective required interface id
*/
public IRequiredInterfaceDefinition getRequiredInterfaceDescriptionById(String id);
public boolean hasRequiredInterfaceWithId(String id);
/**
* @return The parameters of this component
*/
public Collection<IParameter> getParameters();
/**
* @param name The name of the desired parameter
* @return The parameter object
*/
public IParameter getParameter(String name);
public Collection<IParameterDependency> getParameterDependencies();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IComponentInstance.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.IAnnotatable;
public interface IComponentInstance extends Serializable, IAnnotatable {
public IComponent getComponent();
/**
* @return The parameters and how their values were set.
*/
public Map<String, String> getParameterValues();
/**
* @return The set of parameters of which the values have been set explicitly.
*/
public Collection<IParameter> getParametersThatHaveBeenSetExplicitly();
/**
* @return The set of parameters of which the values have not been set explicitly.
*/
public Collection<IParameter> getParametersThatHaveNotBeenSetExplicitly();
/**
* @param param
* The parameter for which the value shall be returned.
* @return The value of the parameter.
*/
public String getParameterValue(final IParameter param);
/**
* @param paramName
* The name of the parameter for which the value is requested.
* @return The value of the parameter with the given name.
*/
public String getParameterValue(final String paramName);
/**
* @return This method returns a mapping of interface IDs to component instances.
*/
public Map<String, List<IComponentInstance>> getSatisfactionOfRequiredInterfaces();
public List<IComponentInstance> getSatisfactionOfRequiredInterface(String idOfRequiredInterface);
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IComponentInstanceConstraint.java
|
package ai.libs.jaicore.components.api;
public interface IComponentInstanceConstraint {
/**
* @return true if this rule MUST be satisfied and false if it MUST NOT be satisfied
*/
public boolean isPositive();
/**
* @return Component instance used to match an instance
*/
public IComponentInstance getPremisePattern();
/**
* @return Component instance the matched instance must or must not satisfy
*/
public IComponentInstance getConclusionPattern();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IComponentRepository.java
|
package ai.libs.jaicore.components.api;
import java.util.Collection;
public interface IComponentRepository extends Collection<IComponent> {
public IComponent getComponent(String name);
public Collection<IComponentInstanceConstraint> getConstraints();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IEvaluatedSoftwareConfigurationSolution.java
|
package ai.libs.jaicore.components.api;
import org.api4.java.common.attributedobjects.ScoredItem;
public interface IEvaluatedSoftwareConfigurationSolution<V extends Comparable<V>> extends ScoredItem<V> {
public IComponentInstance getComponentInstance();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/INumericParameterRefinementConfiguration.java
|
package ai.libs.jaicore.components.api;
public interface INumericParameterRefinementConfiguration {
public boolean isInitRefinementOnLogScale();
public double getFocusPoint();
public double getLogBasis();
public boolean isInitWithExtremalPoints();
public int getRefinementsPerStep();
public double getIntervalLength();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/INumericParameterRefinementConfigurationMap.java
|
package ai.libs.jaicore.components.api;
import java.util.Collection;
public interface INumericParameterRefinementConfigurationMap {
public Collection<String> getParameterNamesForWhichARefinementIsDefined(IComponent component);
public INumericParameterRefinementConfiguration getRefinement(IComponent component, IParameter parameter);
public INumericParameterRefinementConfiguration getRefinement(String componentName, String parameterName);
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IParameter.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
public interface IParameter extends Serializable {
public String getName();
public IParameterDomain getDefaultDomain();
public Object getDefaultValue();
public boolean isDefaultValue(final Object value);
public boolean isNumeric();
public boolean isCategorical();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IParameterDependency.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
import java.util.Collection;
import ai.libs.jaicore.basic.sets.Pair;
public interface IParameterDependency extends Serializable {
public Collection<Collection<Pair<IParameter, IParameterDomain>>> getPremise();
public Collection<Pair<IParameter, IParameterDomain>> getConclusion();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IParameterDomain.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import ai.libs.jaicore.components.model.BooleanParameterDomain;
import ai.libs.jaicore.components.model.CategoricalParameterDomain;
import ai.libs.jaicore.components.model.NumericParameterDomain;
public interface IParameterDomain extends Serializable {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = NumericParameterDomain.class, name = "numeric"), @Type(value = CategoricalParameterDomain.class, name = "categorical"), @Type(value = BooleanParameterDomain.class, name = "boolean") })
public boolean contains(Object item);
public boolean subsumes(IParameterDomain otherDomain);
public boolean isEquals(Object obj0, Object obj1);
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IRequiredInterfaceDefinition.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
public interface IRequiredInterfaceDefinition extends Serializable {
/**
* @return the name of the interface
*/
public String getName();
/**
* @return the id of this interface within the component that defines it (can be interpreted as the *role* name of this interface in the component)
*/
public String getId();
/**
* @return Tells whether the order of realizations of this interface is relevant or not.
*/
public boolean isOrdered();
/**
* @return Tells whether there is a limitation that each component must be contained at most once
*/
public boolean isUniqueComponents();
/**
* @return Tells whether the required interface is optional
*/
public boolean isOptional();
/**
* The minimum can be greater than 0 even if the interface is optional.
* In that case, the semantic is: Either the interface is not satisfied or it has at least this number of realizations.
*
* @return minimum number of required realizations if satisfied at all
*/
public int getMin();
/**
* @return maximum number of allowed realizations
*/
public int getMax();
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/api/IUnparametrizedComponentInstance.java
|
package ai.libs.jaicore.components.api;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface IUnparametrizedComponentInstance extends Serializable {
public IComponent getComponent();
/**
* @return This method returns a mapping of interface IDs to component instances.
*/
public Map<String, List<IUnparametrizedComponentInstance>> getSatisfactionOfRequiredInterfaces();
public List<IUnparametrizedComponentInstance> getSatisfactionOfRequiredInterface(String idOfRequiredInterface);
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/exceptions/ComponentInstantiationFailedException.java
|
package ai.libs.jaicore.components.exceptions;
@SuppressWarnings("serial")
public class ComponentInstantiationFailedException extends Exception {
public ComponentInstantiationFailedException(final String message) {
super(message);
}
public ComponentInstantiationFailedException(final Throwable cause, final String message) {
super(message, cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/exceptions/ComponentNotFoundException.java
|
package ai.libs.jaicore.components.exceptions;
public class ComponentNotFoundException extends Exception {
/**
* Generated by Eclipse
*/
private static final long serialVersionUID = -8112109551741268191L;
public ComponentNotFoundException() {
super();
}
public ComponentNotFoundException(String message) {
super(message);
}
public ComponentNotFoundException(Throwable cause) {
super(cause);
}
public ComponentNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/exceptions/UnresolvableRequiredInterfaceException.java
|
package ai.libs.jaicore.components.exceptions;
/**
* This exception can be thrown if components define required interfaces which cannot be resolved with the so far seen provided interfaces of components.
*
* @author wever
*/
public class UnresolvableRequiredInterfaceException extends RuntimeException {
/**
* Auto-generated version UID for serialization.
*/
private static final long serialVersionUID = -930881442829770230L;
public UnresolvableRequiredInterfaceException() {
super();
}
public UnresolvableRequiredInterfaceException(String msg) {
super(msg);
}
public UnresolvableRequiredInterfaceException(Throwable cause) {
super(cause);
}
public UnresolvableRequiredInterfaceException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/BooleanParameterDomain.java
|
package ai.libs.jaicore.components.model;
import com.fasterxml.jackson.annotation.JsonCreator;
public class BooleanParameterDomain extends CategoricalParameterDomain {
@JsonCreator
public BooleanParameterDomain() {
super(new String[] {"true", "false"});
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/CategoricalParameterDomain.java
|
package ai.libs.jaicore.components.model;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.libs.jaicore.components.api.IParameterDomain;
public class CategoricalParameterDomain implements IParameterDomain {
private final String[] values;
@SuppressWarnings("unused")
private CategoricalParameterDomain() {
// for serialization
this.values = null;
}
@JsonCreator
public CategoricalParameterDomain(@JsonProperty("values") final String[] values) {
super();
this.values = values;
}
@JsonCreator
public CategoricalParameterDomain(@JsonProperty("values") final Collection<String> values) {
this(values.toArray(new String[] {}));
}
public String[] getValues() {
return this.values;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.values).hashCode();
}
@Override
public boolean equals(final Object obj) {
return this == obj || (obj != null && obj.getClass() == this.getClass() && Arrays.equals(this.values, ((CategoricalParameterDomain)obj).values));
}
@Override
public boolean contains(final Object item) {
if (item == null) {
throw new IllegalArgumentException("Cannot request membership of NULL in a categorical parameter domain.");
}
String itemAsString = item.toString();
for (int i = 0; i < this.values.length; i++) {
if (this.values[i].equals(itemAsString)) {
return true;
}
}
return false;
}
@Override
public boolean subsumes(final IParameterDomain otherDomain) {
if (!(otherDomain instanceof CategoricalParameterDomain)) {
return false;
}
CategoricalParameterDomain otherCategoricalDomain = (CategoricalParameterDomain) otherDomain;
return Arrays.asList(this.values).containsAll(Arrays.asList(otherCategoricalDomain.getValues()));
}
@Override
public String toString() {
return "CategoricalParameterDomain [values=" + Arrays.toString(this.values) + "]";
}
@Override
public boolean isEquals(final Object obj0, final Object obj1) {
return (obj0 + "").equals(obj1 + "");
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/Component.java
|
package ai.libs.jaicore.components.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ai.libs.jaicore.basic.sets.PartialOrderedSet;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDependency;
import ai.libs.jaicore.components.api.IRequiredInterfaceDefinition;
import ai.libs.jaicore.logging.ToJSONStringUtil;
/**
* A <code>Component</code> is described by - a name - a collection of provided interfaces - a list of required interfaces - a set of parameters - a list of dependencies and can be used to describe any kind of components and model complex
* multi-component systems. More specifically, <code>Component</code>s are used to model the search space of HASCO. By recursively resolving required interfaces until there are no open choices left, HASCO may transform your component
* description automatically into an HTN planning problem to automatically optimize a component setup for a specific task.
*
* @author fmohr, wever
*/
@JsonPropertyOrder({ "name", "parameters", "dependencies", "providedInterfaces", "requiredInterfaces" })
public class Component implements IComponent, Serializable {
private static final long serialVersionUID = -5382777749445815025L;
/* Logger */
private static final Logger L = LoggerFactory.getLogger(Component.class);
/* Description of the component. */
private final String name;
private Collection<String> providedInterfaces = new ArrayList<>();
private final List<IRequiredInterfaceDefinition> requiredInterfaces = new ArrayList<>();
private PartialOrderedSet<IParameter> parameters = new PartialOrderedSet<>();
private Collection<IParameterDependency> dependencies = new ArrayList<>();
/**
* Constructor creating an empty <code>Component</code> with a specific name.
*
* @param name
* The name of the <code>Component</code>.
*/
public Component(final String name) {
super();
this.name = name;
this.getProvidedInterfaces().add(this.name);
}
/**
* Constructor for a component giving the provided and required interfaces, the collection of parameters and a list of dependencies.
*
* @param name
* The name of the <code>Component</code>.
* @param providedInterfaces
* The collection of provided interfaces.
* @param requiredInterfaces
* The list of required interfaces.
* @param parameters
* Parameters of the <code>Component</code>.
* @param dependencies
* A list of dependencies to constrain the values of parameters (may be empty).
*/
@JsonCreator
public Component(@JsonProperty("name") final String name, @JsonProperty("providedInterfaces") final Collection<String> providedInterfaces, @JsonProperty("requiredInterfaces") final List<Interface> requiredInterfaces,
@JsonProperty("parameters") final PartialOrderedSet<IParameter> parameters, @JsonProperty("dependencies") final Collection<IParameterDependency> dependencies) {
this(name);
this.providedInterfaces = providedInterfaces;
this.requiredInterfaces.addAll(requiredInterfaces);
this.parameters = parameters;
this.dependencies = new ArrayList<>(dependencies);
}
/**
* Constructor for a component giving the provided and required interfaces, the collection of parameters and a list of dependencies.
*
* @param name
* The name of the <code>Component</code>.
* @param providedInterfaces
* The collection of provided interfaces.
* @param requiredInterfaces
* The list of required interfaces.
* @param parameters
* Parameters of the <code>Component</code>.
* @param dependencies
* A list of dependencies to constrain the values of parameters (may be empty).
*/
public Component(final String name, final Collection<String> providedInterfaces, final List<IRequiredInterfaceDefinition> requiredInterfaces, final PartialOrderedSet<IParameter> parameters, final List<IParameterDependency> dependencies) {
this(name);
this.providedInterfaces = providedInterfaces;
this.requiredInterfaces.addAll(requiredInterfaces);
this.parameters = parameters;
this.dependencies = dependencies;
}
/**
* @return The name of the Component.
*/
@Override
public String getName() {
return this.name;
}
/**
* @return The list of required interfaces.
*/
@Override
public List<IRequiredInterfaceDefinition> getRequiredInterfaces() {
return this.requiredInterfaces;
}
/**
* @return The list of names of required interfaces.
*/
public List<String> getRequiredInterfaceNames() {
return this.requiredInterfaces.stream().map(IRequiredInterfaceDefinition::getName).collect(Collectors.toList());
}
/**
* @return The list of ids of required interfaces.
*/
public List<String> getRequiredInterfaceIds() {
return this.requiredInterfaces.stream().map(IRequiredInterfaceDefinition::getId).collect(Collectors.toList());
}
/**
* @return The collection of provided interfaces.
*/
@Override
public Collection<String> getProvidedInterfaces() {
return this.providedInterfaces;
}
/**
* @return The set of parameters of this Component.
*/
@Override
public PartialOrderedSet<IParameter> getParameters() {
return this.parameters;
}
/**
* Returns the parameter for a given name.
*
* @param paramName
* The name of the parameter to be returned.
* @return The parameter for the given name.
*/
public IParameter getParameterWithName(final String paramName) {
return this.getParameter(paramName);
}
/**
* @return The collection of dependencies on the parameters of this <code>Component</code>.
*/
@Override
public Collection<IParameterDependency> getParameterDependencies() {
return this.dependencies;
}
/**
* Adds another provided interface to the collection of provided interfaces.
*
* @param interfaceName
* The interface to be added to the provided interfaces.
*/
public boolean addProvidedInterface(final String interfaceName) {
if (!this.providedInterfaces.contains(interfaceName)) {
return this.providedInterfaces.add(interfaceName);
} else {
return false;
}
}
/**
* Adds a new required interface to the component
*
* @param ri The required interface definition
*/
public void addRequiredInterface(final IRequiredInterfaceDefinition ri) {
this.requiredInterfaces.add(ri);
}
/**
* Adds an additional required interface with an ID (local identifier) and an interface name (provided interface of another Component) to the required interfaces of this Component.
*
* @param interfaceID
* The local identifier to reference the specific required interface.
* @param interfaceName
* The provided interface of another component.
* @param uniqueComponents
* Whether or not this is a set interface (every component must be attached at most once)
* @param min
* Minimun times the interface is required?
* @param max
* Maximum times the interface is required?
*/
public void addRequiredInterface(final String interfaceID, final String interfaceName, final boolean optional, final boolean uniqueComponents, final boolean ordered, final Integer min, final Integer max) {
this.addRequiredInterface(new Interface(interfaceID, interfaceName, optional, uniqueComponents, ordered, min, max));
}
public void addRequiredInterface(final String interfaceID, final String interfaceName) {
this.addRequiredInterface(interfaceID, interfaceName, false, false, false, 1, 1);
}
/**
* Adds a parameter to the set of parameters iff the parameter or another parameter with the same name does not yet exist.
*
* @param param
* The parameter to be added.
*/
public void addParameter(final IParameter param) {
if (this.parameters.stream().anyMatch(p -> p.getName().equals(param.getName()))) {
throw new IllegalArgumentException("Component " + this.name + " already has a parameter with name " + param.getName());
}
this.parameters.add(param);
}
/**
* Adds a dependency constraint to the dependencies of this Component.
*
* @param dependency
* The dependency to be added.
*/
public void addDependency(final IParameterDependency dependency) {
/*
* check whether this dependency is coherent with the current partial order on
* the parameters
*/
Collection<IParameter> paramsInPremise = new HashSet<>();
dependency.getPremise().forEach(c -> c.forEach(i -> paramsInPremise.add(i.getX())));
Collection<IParameter> paramsInConclusion = new HashSet<>();
dependency.getConclusion().forEach(i -> paramsInConclusion.add(i.getX()));
for (IParameter before : paramsInPremise) {
for (IParameter after : paramsInConclusion) {
this.parameters.requireABeforeB(before, after);
}
}
/* add the dependency to the set of dependencies */
this.dependencies.add(dependency);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.dependencies == null) ? 0 : this.dependencies.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + ((this.parameters == null) ? 0 : this.parameters.hashCode());
result = prime * result + ((this.providedInterfaces == null) ? 0 : this.providedInterfaces.hashCode());
result = prime * result + this.requiredInterfaces.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Component other = (Component) obj;
if (this.dependencies == null) {
if (other.dependencies != null) {
return false;
}
} else if (!this.dependencies.equals(other.dependencies)) {
return false;
}
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
if (this.parameters == null) {
if (other.parameters != null) {
return false;
}
} else if (!this.parameters.equals(other.parameters)) {
return false;
}
if (this.providedInterfaces == null) {
if (other.providedInterfaces != null) {
return false;
}
} else if (!this.providedInterfaces.equals(other.providedInterfaces)) {
return false;
}
return this.requiredInterfaces.equals(other.requiredInterfaces);
}
@Override
public String toString() {
try {
return new ObjectMapper().writeValueAsString(this);
} catch (JsonProcessingException e) {
L.warn("Could not directly serialize Component to JSON: ", e);
}
Map<String, Object> fields = new HashMap<>();
fields.put("name", this.name);
fields.put("providedInterfaces", this.providedInterfaces);
fields.put("requiredInterfaces", this.requiredInterfaces);
fields.put("parameters", this.parameters);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
@Override
public IRequiredInterfaceDefinition getRequiredInterfaceDescriptionById(final String id) {
for (IRequiredInterfaceDefinition ri : this.requiredInterfaces) {
if (ri.getName().equals(id)) {
return ri;
}
}
throw new NoSuchElementException("There is no required interface with id " + id);
}
@Override
public IParameter getParameter(final String name) {
for (IParameter p : this.parameters) {
if (p.getName().equals(name)) {
return p;
}
}
throw new NoSuchElementException("There is no parameter with id " + name);
}
@Override
public boolean hasRequiredInterfaceWithId(final String id) {
return this.requiredInterfaces.stream().anyMatch(ri -> ri.getId().equals(id));
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/ComponentInstance.java
|
package ai.libs.jaicore.components.model;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.logging.ToJSONStringUtil;
/**
* For a given <code>Component</code>, a <code>Component Instance</code> defines all parameter values and the required interfaces (recursively) and thus provides a grounding of the respective
* <code>Component</code>.
*
* @author fmohr, mwever
*
*/
@JsonPropertyOrder(alphabetic = true)
public class ComponentInstance implements IComponentInstance, Serializable {
/* Auto-generated serial version UID. */
private static final long serialVersionUID = 714378153827839502L;
/* The component which serves as a kind of "type". */
private final IComponent component;
/* The grounding of the component including parameter values and recursively resolved required interfaces. */
private final Map<String, String> parameterValues;
private final Map<String, List<IComponentInstance>> satisfactionOfRequiredInterfaces;
private final Map<String, String> annotations = new HashMap<>();
@SuppressWarnings("unused")
private ComponentInstance() {
// for serialization purposes
this.component = null;
this.parameterValues = null;
this.satisfactionOfRequiredInterfaces = null;
}
public ComponentInstance(final ComponentInstance other) {
this.component = other.component;
this.parameterValues = new HashMap<>(other.parameterValues);
this.satisfactionOfRequiredInterfaces = new HashMap<>();
other.satisfactionOfRequiredInterfaces.entrySet().forEach(x -> this.satisfactionOfRequiredInterfaces.put(x.getKey(), new ArrayList<>()));
other.satisfactionOfRequiredInterfaces.entrySet().forEach(x -> x.getValue().forEach(ci -> this.satisfactionOfRequiredInterfaces.get(x.getKey()).add(new ComponentInstance((ComponentInstance) ci))));
other.annotations.entrySet().forEach(x -> this.annotations.put(x.getKey(), x.getValue()));
}
/**
* Constructor for creating a <code>ComponentInstance</code> for a particular <code>Component</code>.
*
* @param component
* The component that is grounded.
* @param parameterValues
* A map containing the parameter values of this grounding.
* @param satisfactionOfRequiredInterfaces
* The refinement of the required interfaces.
*/
public ComponentInstance(@JsonProperty("component") final IComponent component, @JsonProperty("parameterValues") final Map<String, String> parameterValues,
@JsonProperty("satisfactionOfRequiredInterfaces") final Map<String, List<IComponentInstance>> satisfactionOfRequiredInterfaces) {
super();
this.component = component;
this.parameterValues = parameterValues;
this.satisfactionOfRequiredInterfaces = satisfactionOfRequiredInterfaces;
}
/**
* @return The <code>Component</code> to this <code>ComponentInstance</code>.
*/
@Override
public IComponent getComponent() {
return this.component;
}
/**
* @return The parameters and how their values were set.
*/
@Override
public Map<String, String> getParameterValues() {
return this.parameterValues;
}
/**
* @return The set of parameters of which the values have been set explicitly.
*/
@Override
public Collection<IParameter> getParametersThatHaveBeenSetExplicitly() {
if (this.parameterValues == null) {
return new ArrayList<>();
}
return this.getComponent().getParameters().stream().filter(p -> this.parameterValues.containsKey(p.getName())).collect(Collectors.toList());
}
/**
* @return The set of parameters of which the values have not been set explicitly.
*/
@Override
public Collection<IParameter> getParametersThatHaveNotBeenSetExplicitly() {
return SetUtil.difference(this.component.getParameters(), this.getParametersThatHaveBeenSetExplicitly());
}
/**
* @param param
* The parameter for which the value shall be returned.
* @return The value of the parameter.
*/
@Override
public String getParameterValue(final IParameter param) {
return this.getParameterValue(param.getName());
}
/**
* @param paramName
* The name of the parameter for which the value is requested.
* @return The value of the parameter with the given name.
*/
@Override
public String getParameterValue(final String paramName) {
return this.parameterValues.get(paramName);
}
/**
* @return This method returns a mapping of interface IDs to component instances.
*/
@Override
public Map<String, List<IComponentInstance>> getSatisfactionOfRequiredInterfaces() {
return this.satisfactionOfRequiredInterfaces;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.component == null) ? 0 : this.component.hashCode());
result = prime * result + ((this.parameterValues == null) ? 0 : this.parameterValues.hashCode());
result = prime * result + ((this.satisfactionOfRequiredInterfaces == null) ? 0 : this.satisfactionOfRequiredInterfaces.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ComponentInstance other = (ComponentInstance) obj;
if (this.component == null) {
if (other.component != null) {
return false;
}
} else if (!this.component.equals(other.component)) {
return false;
}
if (this.parameterValues == null) {
if (other.parameterValues != null) {
return false;
}
} else if (!this.parameterValues.equals(other.parameterValues)) {
return false;
}
if (this.satisfactionOfRequiredInterfaces == null) {
if (other.satisfactionOfRequiredInterfaces != null) {
return false;
}
} else if (!this.satisfactionOfRequiredInterfaces.equals(other.satisfactionOfRequiredInterfaces)) {
return false;
}
return true;
}
public String toComponentNameString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getComponent().getName());
if (!this.satisfactionOfRequiredInterfaces.isEmpty()) {
sb.append(this.satisfactionOfRequiredInterfaces.entrySet().stream().map(x -> x.getValue().stream().map(ci -> ((ComponentInstance) ci).toComponentNameString()).collect(Collectors.joining())).collect(Collectors.toList())
.toString());
}
return sb.toString();
}
@JsonIgnore
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("component", this.component);
fields.put("parameterValues", this.parameterValues);
fields.put("satisfactionOfRequiredInterfaces", this.satisfactionOfRequiredInterfaces);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
/**
* Returns the description of a <code>ComponentInstance</code> as a pretty print with indentation.
*
* @return A string representing this object in JSON format.
* @throws IOException
* An IOException is thrown if the object cannot be serialized to a String.
*/
@JsonIgnore
public String getPrettyPrint() throws IOException {
return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(this);
}
public String getNestedComponentDescription() {
StringBuilder sb = new StringBuilder();
sb.append(this.getComponent().getName());
this.satisfactionOfRequiredInterfaces.values().stream().map(x -> " - " + x.stream().map(ci -> ((ComponentInstance) ci).getNestedComponentDescription()).collect(Collectors.joining())).forEach(sb::append);
return sb.toString();
}
@Override
public void putAnnotation(final String key, final String annotation) {
this.annotations.put(key, annotation);
}
@Override
public String getAnnotation(final String key) {
return this.annotations.get(key);
}
@Override
public void appendAnnotation(final String key, final String annotation) {
if (this.annotations.containsKey(key)) {
this.annotations.put(key, this.annotations.get(key) + annotation);
} else {
this.annotations.put(key, annotation);
}
}
@Override
public List<IComponentInstance> getSatisfactionOfRequiredInterface(final String idOfRequiredInterface) {
if (!this.component.hasRequiredInterfaceWithId(idOfRequiredInterface)) {
throw new IllegalArgumentException("\"" + idOfRequiredInterface + "\" is not a valid required interface id of component " + this.component.getName() + ". Valid ids are: "
+ this.component.getRequiredInterfaces().stream().map(ri -> "\n\t- " + ri.getId()).collect(Collectors.joining()));
}
return this.satisfactionOfRequiredInterfaces.get(idOfRequiredInterface);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/ComponentInstanceConstraint.java
|
package ai.libs.jaicore.components.model;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IComponentInstanceConstraint;
public class ComponentInstanceConstraint implements IComponentInstanceConstraint {
private final boolean positive;
private final IComponentInstance premise;
private final IComponentInstance conclusion;
public ComponentInstanceConstraint(final boolean positive, final IComponentInstance premise, final IComponentInstance conclusion) {
super();
this.positive = positive;
this.premise = premise;
this.conclusion = conclusion;
}
@Override
public boolean isPositive() {
return this.positive;
}
@Override
public IComponentInstance getPremisePattern() {
return this.premise;
}
@Override
public IComponentInstance getConclusionPattern() {
return this.conclusion;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/ComponentInstanceUtil.java
|
package ai.libs.jaicore.components.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDependency;
import ai.libs.jaicore.components.api.IParameterDomain;
import ai.libs.jaicore.components.api.IRequiredInterfaceDefinition;
import ai.libs.jaicore.components.serialization.ComponentSerialization;
/**
* The ComponentInstanceUtil provides some utilities to deal with component instances.
* For instance, it may be used to check whether a ComponentInstance conforms the dependencies
* defined in the respective Component.
*
* @author wever
*/
public class ComponentInstanceUtil {
private static final Logger logger = LoggerFactory.getLogger(ComponentInstanceUtil.class);
private ComponentInstanceUtil() {
/* Private constructor to prevent anyone to instantiate this Util class by accident. */
}
/**
* Checks whether a component instance adheres to the defined inter-parameter dependencies defined in the component.
* @param ci The component instance to be verified.
* @return Returns true iff all dependency conditions hold.
*/
public static boolean isValidComponentInstantiation(final ComponentInstance ci) {
try {
checkComponentInstantiation(ci);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Checks whether a component instance adheres to the defined inter-parameter dependencies defined in the component.
* @param ci The component instance to be verified.
* @throws Exception with explanation if it is not valid
*/
public static void checkComponentInstantiation(final ComponentInstance ci) {
Map<IParameter, IParameterDomain> refinedDomainMap = new HashMap<>();
for (IParameter param : ci.getComponent().getParameters()) {
if (param.getDefaultDomain() instanceof NumericParameterDomain) {
double parameterValue = Double.parseDouble(ci.getParameterValue(param));
refinedDomainMap.put(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), parameterValue, parameterValue));
} else if (param.getDefaultDomain() instanceof CategoricalParameterDomain) {
refinedDomainMap.put(param, new CategoricalParameterDomain(Arrays.asList(ci.getParameterValue(param))));
}
}
for (IParameterDependency dependency : ci.getComponent().getParameterDependencies()) {
if (CompositionProblemUtil.isDependencyPremiseSatisfied(dependency, refinedDomainMap) && !CompositionProblemUtil.isDependencyConditionSatisfied(dependency.getConclusion(), refinedDomainMap)) {
throw new IllegalStateException("The dependency " + dependency + " of component " + ci.getComponent().getName() + " in the following component instance is violated: " + new ComponentSerialization().serialize(ci));
}
}
}
public static IComponentInstance getDefaultParametrization(final IComponentInstance ci) {
Map<String, List<IComponentInstance>> defaultRequiredInterfaces = new HashMap<>();
ci.getSatisfactionOfRequiredInterfaces().forEach((name, ciReqList) -> {
List<IComponentInstance> l = ciReqList.stream().map(ComponentInstanceUtil::getDefaultParametrization).collect(Collectors.toList());
defaultRequiredInterfaces.put(name, l);
});
return new ComponentInstance(ci.getComponent(), new HashMap<>(), defaultRequiredInterfaces);
}
public static boolean isDefaultConfiguration(final IComponentInstance instance) {
for (IParameter p : instance.getParametersThatHaveBeenSetExplicitly()) {
if (p.isNumeric()) {
double defaultValue = Double.parseDouble(p.getDefaultValue().toString());
String parameterValue = instance.getParameterValue(p);
boolean isCompatibleWithDefaultValue = false;
if (parameterValue.contains("[")) {
List<String> intervalAsList = SetUtil.unserializeList(instance.getParameterValue(p));
isCompatibleWithDefaultValue = defaultValue >= Double.parseDouble(intervalAsList.get(0)) && defaultValue <= Double.parseDouble(intervalAsList.get(1));
} else {
isCompatibleWithDefaultValue = Math.abs(defaultValue - Double.parseDouble(parameterValue)) < 1E-8;
}
if (!isCompatibleWithDefaultValue) {
logger.info("{} has value {}, which does not subsume the default value {}", p.getName(), instance.getParameterValue(p), defaultValue);
return false;
} else {
logger.info("{} has value {}, which IS COMPATIBLE with the default value {}", p.getName(), instance.getParameterValue(p), defaultValue);
}
} else {
if (!instance.getParameterValue(p).equals(p.getDefaultValue().toString())) {
logger.info("{} has value {}, which is not the default {}", p.getName(), instance.getParameterValue(p), p.getDefaultValue());
return false;
}
}
}
for (Collection<IComponentInstance> childList : instance.getSatisfactionOfRequiredInterfaces().values()) {
for (IComponentInstance child : childList) {
if (!isDefaultConfiguration(child)) {
return false;
}
}
}
return true;
}
/**
* Samples a random component instance with random parameters.
*
* @param requiredInterface The required interface the sampled component instance must conform.
* @param components The components that can be chosen.
* @param rand Random number generator for pseudo randomization.
* @return A randomly sampled component instance with random parameters.
*/
public static ComponentInstance sampleRandomComponentInstance(final String requiredInterface, final Collection<IComponent> components, final Random rand) {
List<IComponent> componentsList = new ArrayList<>(ComponentUtil.getComponentsProvidingInterface(components, requiredInterface));
ComponentInstance ci = ComponentUtil.getRandomParameterizationOfComponent(componentsList.get(rand.nextInt(componentsList.size())), rand);
for (IRequiredInterfaceDefinition i : ci.getComponent().getRequiredInterfaces()) {
ci.getSatisfactionOfRequiredInterfaces().put(i.getId(), Arrays.asList(sampleRandomComponentInstance(i.getName(), components, rand)));
}
return ci;
}
/**
* Samples a random component instance with default parameters.
*
* @param requiredInterface The required interface the sampled component instance must conform.
* @param components The components that can be chosen.
* @param rand Random number generator for pseudo randomization.
* @return A randomly sampled component instance with default parameters.
*/
public static ComponentInstance sampleDefaultComponentInstance(final String requiredInterface, final Collection<? extends IComponent> components, final Random rand) {
List<IComponent> componentsList = new ArrayList<>(ComponentUtil.getComponentsProvidingInterface(components, requiredInterface));
ComponentInstance ci = ComponentUtil.getDefaultParameterizationOfComponent(componentsList.get(rand.nextInt(componentsList.size())));
for (IRequiredInterfaceDefinition i : ci.getComponent().getRequiredInterfaces()) {
ci.getSatisfactionOfRequiredInterfaces().put(i.getId(), Arrays.asList(sampleDefaultComponentInstance(i.getName(), components, rand)));
}
return ci;
}
/**
* This method checks, whether a given list of paths of refinements conforms the constraints for parameter refinements.
*
* @param paths
* A list of paths of refinements to be checked.
* @return Returns true if everything is alright and false if there is an issue with the given paths.
*/
public static boolean matchesPathRestrictions(final ComponentInstance ci, final Collection<List<Pair<String, String>>> paths) {
for (List<Pair<String, String>> path : paths) {
if (!matchesPathRestriction(ci, path)) {
return false;
}
}
return true;
}
/**
* This method checks, whether a path of refinements conforms the constraints for parameter refinements.
*
* @param path
* A path of refinements to be checked.
* @return Returns true if everything is alright and false if there is an issue with the given path.
*/
public static boolean matchesPathRestriction(final ComponentInstance ci, final List<Pair<String, String>> path) {
if (path.isEmpty()) {
return true;
}
/* if the first entry is on null, we interpret it as a filter on this component itself */
int i = 0;
if (path.get(0).getX() == null) {
String requiredComponent = path.get(0).getY();
if (!requiredComponent.equals("*") && !ci.getComponent().getName().equals(requiredComponent)) {
return false;
}
i = 1;
}
/* now go over the rest of the path and check every entry on conformity */
IComponentInstance current = ci;
int n = path.size();
for (; i < n; i++) {
Pair<String, String> selection = path.get(i);
if (current.getComponent().getRequiredInterfaces().stream().noneMatch(ri -> ri.getId().equals(selection.getX()))) {
throw new IllegalArgumentException("Invalid path restriction " + path + ": " + selection.getX() + " is not a required interface of " + current.getComponent().getName());
}
Collection<IComponentInstance> instancesChosenForRequiredInterface = current.getSatisfactionOfRequiredInterfaces().get(selection.getX());
for (IComponentInstance instanceChosenForRequiredInterface : instancesChosenForRequiredInterface) {
if (!selection.getY().equals("*") && !instanceChosenForRequiredInterface.getComponent().getName().equals(selection.getY())) {
return false;
}
current = instanceChosenForRequiredInterface;
}
}
return true;
}
/**
* @return A collection of all components contained (recursively) in this <code>ComponentInstance</code>.
*/
public static Collection<IComponent> getContainedComponents(final IComponentInstance ci) {
Collection<IComponent> components = new HashSet<>();
components.add(ci.getComponent());
for (Collection<IComponentInstance> ciList : ci.getSatisfactionOfRequiredInterfaces().values()) {
for (IComponentInstance ciSub : ciList) {
components.addAll(getContainedComponents(ciSub));
}
}
return components;
}
public static String toComponentNameString(final IComponentInstance ci) {
StringBuilder sb = new StringBuilder();
sb.append(ci.getComponent().getName());
if (!ci.getSatisfactionOfRequiredInterfaces().isEmpty()) {
sb.append("(").append(
ci.getSatisfactionOfRequiredInterfaces().values().stream().map(ciList -> ciList.stream().map(cil -> ((ComponentInstance) cil).toComponentNameString()).collect(Collectors.joining())).collect(Collectors.joining(", ")))
.append(")");
}
return sb.toString();
}
public static String getComponentInstanceAsComponentNames(final IComponentInstance instance) {
StringBuilder sb = new StringBuilder();
sb.append(instance.getComponent().getName());
if (!instance.getSatisfactionOfRequiredInterfaces().isEmpty()) {
sb.append("{").append(instance.getSatisfactionOfRequiredInterfaces().values().stream().map(ciList -> ciList.stream().map(ComponentInstanceUtil::getComponentInstanceAsComponentNames).collect(Collectors.joining()))
.collect(Collectors.joining(","))).append("}");
}
return sb.toString();
}
public static String getComponentInstanceString(final IComponentInstance ci) {
StringBuilder sb = new StringBuilder();
sb.append(ci.getComponent().getName()).append("{");
String parameters = ci.getParameterValues().entrySet().stream().map(x -> x.getKey() + "=" + x.getValue()).collect(Collectors.joining(", "));
sb.append(parameters);
String reqIs = ci.getSatisfactionOfRequiredInterfaces().entrySet().stream().map(ComponentInstanceUtil::satisfiedRequiredInterfaceToString).collect(Collectors.joining(","));
if (!parameters.isEmpty() && !reqIs.isEmpty()) {
sb.append(", ");
}
sb.append(reqIs).append("}");
return sb.toString();
}
private static String satisfiedRequiredInterfaceToString(final Entry<String, List<IComponentInstance>> satisfiedRequiredInterface) {
return satisfiedRequiredInterface.getKey() + "=[" + satisfiedRequiredInterface.getValue().stream().map(ComponentInstanceUtil::getComponentInstanceString).collect(Collectors.joining(",")) + "]";
}
public static boolean isSubInstance(final IComponentInstance sub, final IComponentInstance sup) {
/* check component name */
if (!sub.getComponent().getName().equals(sup.getComponent().getName())) {
return false;
}
/* check parameters */
Map<String, String> parametersOfSub = sub.getParameterValues();
Map<String, String> parametersOfSup = sup.getParameterValues();
for (Entry<String, String> p : parametersOfSub.entrySet()) {
if (!parametersOfSup.containsKey(p.getKey()) || !parametersOfSup.get(p.getKey()).equals(p.getValue())) {
return false;
}
}
/* check required interfaces */
for (Entry<String, List<IComponentInstance>> provisionsOfSub : sub.getSatisfactionOfRequiredInterfaces().entrySet()) {
int n = provisionsOfSub.getValue().size();
List<IComponentInstance> provisionsOfSup = sup.getSatisfactionOfRequiredInterface(provisionsOfSub.getKey());
if (provisionsOfSup.size() < n) {
return false;
}
for (int i = 0; i < n; i++) {
if (!isSubInstance(provisionsOfSub.getValue().get(i), provisionsOfSup.get(i))) {
return false;
}
}
}
/* if no incompatibility was found, return true */
return true;
}
public static String toRecursiveConstructorString(final IComponentInstance ci) {
StringBuilder sb = new StringBuilder();
sb.append(ci.getComponent().getName()).append("(");
sb.append(ci.getParameterValues().entrySet().stream().map(x -> x.getKey() + "=" + x.getValue()).collect(Collectors.joining(", ")));
if (!ci.getParameterValues().isEmpty() && !ci.getSatisfactionOfRequiredInterfaces().isEmpty()) {
sb.append(", ");
}
sb.append(ci.getSatisfactionOfRequiredInterfaces().entrySet().stream()
.map(reqIEntry -> reqIEntry.getKey() + "= [" + reqIEntry.getValue().stream().map(ComponentInstanceUtil::toRecursiveConstructorString).collect(Collectors.joining(", ")) + "]").collect(Collectors.joining(", ")));
sb.append(")");
return sb.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.