Merge remote-tracking branch 'origin' into new_sim

# Conflicts:
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/HierarchicalSimulation.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/io/HierarchicalWriter.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/methods/HierarchicalFBASimulator.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/methods/HierarchicalMixedSimulator.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/methods/HierarchicalODERKSimulator.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/methods/HierarchicalSSADirectSimulator.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/model/HierarchicalModel.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/HierarchicalUtilities.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/comp/HierarchicalEventComparator.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/comp/ReplacementHandler.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/CompartmentSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/ConstraintSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/CoreSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/EventSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/InitAssignmentSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/ModelSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/ParameterSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/ReactionSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/ReplacementSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/RuleSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/SpeciesReferenceSetup.java
#	analysis/src/main/java/edu/utah/ece/async/analysis/simulation/hierarchical/util/setup/SpeciesSetup.java
This commit is contained in:
leandrohw 2017-04-13 16:47:56 -06:00
commit ae01a4211d
350 changed files with 893 additions and 965 deletions

21
learn/pom.xml Normal file
View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>iBioSim-learn</artifactId>
<parent>
<groupId>edu.utah.ece.async</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
<artifactId>iBioSim</artifactId>
</parent>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>edu.utah.ece.async</groupId>
<artifactId>iBioSim-analysis</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,134 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.AMSModel;
import java.util.*;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class DMVCrun {
private static int numDMVCruns = 0;
//private int id;
private ArrayList<ArrayList<Double>> valueL;
private ArrayList<Integer> startPoints;
private ArrayList<Integer> endPoints;
private ArrayList<Double> avgVals;
public DMVCrun(){
//this.id = DMVCrun.numDMVCruns; // required?? whenever required the absolute id would be different. here it remains the same for all the runs of the same variable.
DMVCrun.numDMVCruns = DMVCrun.numDMVCruns + 1;
valueL = new ArrayList<ArrayList<Double>>();
startPoints = new ArrayList<Integer>();
endPoints = new ArrayList<Integer>();
avgVals = new ArrayList<Double>();
}
public void addStartPoint(int i){
startPoints.add(i);
}
public void addEndPoint(int i){
endPoints.add(i);
calcAvg();
}
public void calcAvg(){ //for the most recently added set of values by default
//ArrayList<Double> vals = this.valueL.get(valueL.size() -1);
Double total = 0.0;
for (Double d:this.valueL.get(valueL.size() -1)){
total+=d;
}
avgVals.add(total/this.valueL.get(valueL.size() -1).size());
}
public Double[] getAvgVals() { // think.. if entire avgVals or just an indexed one
return avgVals.toArray(new Double[avgVals.size()]);
}
public int getNumPoints(){
int numPoints = 0;
for (int i = 0; i<startPoints.size(); i++){
numPoints += ((endPoints.get(i) - startPoints.get(i))+1);
}
return numPoints;
}
public int getEndPoint(int i) {
return endPoints.get(i);
}
public int getStartPoint(int i) {
return startPoints.get(i);
}
public void addValue(double d){
if (valueL.size() == startPoints.size()){//(this.valueL.isEmpty()){
this.valueL.add(valueL.size(),new ArrayList<Double>());
}
this.valueL.get(valueL.size() -1).add(d);
}
public void removeValue(){ // removes the most recent set of dmv values
if (valueL.size() > startPoints.size()){
valueL.remove(valueL.size() -1);
}
}
public Double getLastValue(){ // removes the most recent set of dmv values
Double total = 0.0;
for (Double d:this.valueL.get(valueL.size() -1)){
total+=d;
}
return (total/this.valueL.get(valueL.size() -1).size());
}
public void clearAll(){
startPoints.clear();
endPoints.clear();
valueL.clear();
avgVals.clear();
}
public Double getConstVal(){ //for the most recently added set of values by default
//ArrayList<Double> vals = this.valueL.get(valueL.size() -1);
Double total = 0.0;
for (Double d:this.valueL.get(valueL.size() -1)){
total+=d;
}
return (total/this.valueL.get(valueL.size() -1).size());
}
/*
public boolean belongsToRuns(int i){
for (int j = 0; j<startPoints.size(); j++){
if ((i>=startPoints.get(j)) && (i<=endPoints.get(j))){
return true;
}
}
return false;
}
*/
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,280 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.AMSModel;
//import java.util.*;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Variable implements Comparable<Variable>{
private String name;
private boolean dmvc;
private boolean input;
private boolean output;
private boolean care;
private boolean interpolate;
private DMVCrun runs; // tmp
private Double initValue_vMax,initRate_rMax;
private Double initValue_vMin,initRate_rMin;
private String forceType;
private Double epsilon;
private boolean destab;
public Variable(String name){
this.name = name;
this.runs = new DMVCrun();
this.forceType = null;
this.care = true;
this.epsilon = null; //default
this.destab = false;
this.interpolate = false;
}
public boolean isDmvc() {
return dmvc;
}
public void setDmvc(boolean dmvc) {
this.dmvc = dmvc;
}
public boolean isInput() {
return input;
}
public void setInput(boolean input) {
this.input = input;
}
public boolean isCare() {
return care;
}
public void setCare(boolean care) {
this.care = care;
}
public boolean isInterpolate() {
return interpolate;
}
public void setInterpolate(boolean interpolate) {
this.interpolate = interpolate;
}
public String getName() {
return name;
}
// public void setName(String name) {
// this.name = name;
// }
public boolean isOutput() {
return output;
}
public void setOutput(boolean output) {
this.output = output;
}
public DMVCrun getRuns() {
return runs;
}
public void addInitValues(Double v){
if ((initValue_vMin == null) && (initValue_vMax == null)){
initValue_vMin = v;
initValue_vMax = v;
}
else{
if (v < initValue_vMin){
initValue_vMin = v;
}
else if (v > initValue_vMax){
initValue_vMax = v;
}
}
}
public void addInitRates(Double r){
if ((initRate_rMin == null) && (initRate_rMax == null)){
initRate_rMin = r;
initRate_rMax = r;
}
else{
if (r < initRate_rMin){
initRate_rMin = r;
}
else if (r > initRate_rMax){
initRate_rMax = r;
}
}
}
public void reset(){
initRate_rMax = null;
initRate_rMin = null;
initValue_vMin = null;
initValue_vMax = null;
this.runs = new DMVCrun();
//this.epsilon = null ??
//this.care = true ???
}
public String getInitValue(){
return ("["+(int)Math.floor(initValue_vMin)+","+(int)Math.ceil(initValue_vMax)+"]");
}
public String getInitRate(){
return ("["+(int)Math.floor(initRate_rMin)+","+(int)Math.ceil(initRate_rMax)+"]");
}
public void scaleInitByDelay(Double dScaleFactor){
if (!dmvc){
initRate_rMin /= dScaleFactor;
initRate_rMax /= dScaleFactor;
}
}
public void scaleInitByVar(Double vScaleFactor){
if (!dmvc){
initRate_rMin *= vScaleFactor;
initRate_rMax *= vScaleFactor;
}
initValue_vMax *= vScaleFactor;
initValue_vMin *= vScaleFactor;
}
@Override
public int compareTo(Variable o) {
return (this.getName().compareToIgnoreCase(o.getName()));
}
public void copy(Variable a){
//Private fields in a. We shouldn't access like this?
this.name = a.name;
this.runs = a.runs;
this.dmvc = a.dmvc;
this.input = a.input;
this.output = a.output;
this.forceType = a.forceType;
this.care = a.care;
this.epsilon = a.epsilon;
this.destab = a.destab;
this.interpolate = a.interpolate;
// NOT Copying the init values and rates bcoz they get normalized every time a learn is performed on them.
// So the values get multiplied by the same factor multiple times which is wrong.
// this.initValue_vMax = a.initValue_vMax;
// this.initValue_vMin = a.initValue_vMin;
// this.initRate_rMax = a.initRate_rMax;
// this.initRate_rMin = a.initRate_rMin;
}
public void forceDmvc(Boolean dmvc){
if (dmvc == null){
this.forceType = null;
// this.dmvc = false;
}
else if (!dmvc){
this.forceType = "Cont";
this.dmvc = false;
}
else if (dmvc){
this.forceType = "DMV";
this.dmvc = true;
}
}
public boolean isForcedDmv(){
if (forceType == null)
return false;
else if (forceType.equalsIgnoreCase("DMV"))
return true;
else
return false;
}
public boolean isForcedCont(){
if (forceType == null)
return false;
else if (forceType.equalsIgnoreCase("Cont"))
return true;
else
return false;
}
public void setEpsilon(Double v) {
this.epsilon = v;
}
public Double getEpsilon() {
return(epsilon);
}
public boolean isDestab() {
return destab;
}
public void setDestab(boolean b) {
destab = b;
}
/*
public void addInitValues(Double d, int i){
if (initValues.isEmpty()){
for (int j = 0; j < vars.length; j++){
initValues.add(j, new ArrayList<Double>());
}
initValues.get(i).add(d);
}
else{
initValues.get(i).add(d);
}
//this.initValues[j] = d;
}
public void addInitRates(Double d, int i){
if (initRates.isEmpty()){
for (int j = 0; j < vars.length; j++){
initRates.add(j, new ArrayList<Double>());
}
initRates.get(i).add(d);
}
else{
initRates.get(i).add(d);
}
//this.initRates[j] = d;
}
*/
}

View file

@ -0,0 +1,174 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Connection
{
private double score;
private String child;
private List<String> parents;
private Map<String, Type> parentToType;
public enum Type
{
ACTIVATOR("activator"), REPRESSOR("repressor"), UNKNOWN("unknown");
private final String name;
Type(String name)
{
this.name = name;
}
}
public Connection(String child, double score, String type, String parent)
{
this.child = child;
this.score = score;
this.parents = new ArrayList<String>();
this.parents.add(parent);
this.parentToType = new HashMap<String, Type>();
this.parentToType.put(parent, getType(type));
}
public Connection(String child, double score, List<Connection> connections)
{
this.child = child;
this.score = score;
this.parents = new ArrayList<String>();
this.parentToType = new HashMap<String, Type>();
for (Connection connection : connections)
{
this.parents.addAll(connection.getParents());
for (String parent : connection.getParents())
{
this.parentToType.put(parent, getType(connection.getParentType(parent)));
}
}
}
public Connection(String child, double score, Connection... connections)
{
this.child = child;
this.score = score;
this.parents = new ArrayList<String>();
this.parentToType = new HashMap<String, Type>();
for (Connection connection : connections)
{
this.parents.addAll(connection.getParents());
for (String parent : connection.getParents())
{
this.parentToType.put(parent, getType(connection.getParentType(parent)));
}
}
}
public Type getType(String type)
{
type = type.toLowerCase();
if (type.equals("repressor"))
{
return Type.REPRESSOR;
}
else if (type.equals("activator"))
{
return Type.ACTIVATOR;
}
else
{
return Type.UNKNOWN;
}
}
public double getScore()
{
return score;
}
public List<String> getParents()
{
return parents;
}
public String getChild()
{
return child;
}
public String getParentType(String parent)
{
if (parentToType.containsKey(parent))
{
return parentToType.get(parent).name();
}
else
{
return null;
}
}
public boolean equalParents(List<String> parents)
{
for (String parent : parents)
{
if (!this.parents.contains(parent))
{
return false;
}
}
return true;
}
@Override
public String toString()
{
return "Connection [score=" + score + ", child=" + child + ", parents=" + getParents() + "]";
}
public String getParentString()
{
String list = "";
for (String parent : parents)
{
list = list + parent + " ";
}
return list;
}
}

View file

@ -0,0 +1,114 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Encodings
{
private int numBins;
private Map<Integer, double[]> discreteSpecies;
private List<List<List<Integer>>> levelAssignments;
public Encodings()
{
numBins = 3;
discreteSpecies = new HashMap<Integer, double[]>();
levelAssignments = new ArrayList<List<List<Integer>>>();
}
public Encodings(int bin)
{
numBins = bin;
discreteSpecies = new HashMap<Integer, double[]>();
levelAssignments = new ArrayList<List<List<Integer>>>();
}
public void addDiscreteSpecies(int col, double[] values)
{
discreteSpecies.put(col, values);
}
public void addLevelAssignment(int experiment, int row, int col, double data)
{
while (levelAssignments.size() < experiment + 1)
{
levelAssignments.add(new ArrayList<List<Integer>>());
}
while (levelAssignments.get(experiment).size() < row + 1)
{
levelAssignments.get(experiment).add(new ArrayList<Integer>());
}
while (levelAssignments.get(experiment).get(row).size() < col + 1)
{
levelAssignments.get(experiment).get(row).add(0);
}
levelAssignments.get(experiment).get(row).set(col, getLevelAssignment(col, data));
}
public int getLevelAssignment(int col, double data)
{
double[] discrete = discreteSpecies.get(col);
for (int i = 1; i < discrete.length; i++)
{
if (data <= discrete[i])
{
return i - 1;
}
}
return numBins - 1;
}
public List<List<List<Integer>>> getLevelAssignments()
{
return levelAssignments;
}
public int size()
{
return levelAssignments.size();
}
public void print()
{
for (int i = 0; i < levelAssignments.size(); i++)
{
System.out.println("Experiment :" + i);
for (int j = 0; j < levelAssignments.get(i).size(); j++)
{
for (int k = 1; k < levelAssignments.get(i).get(j).size(); k++)
{
System.out.print(levelAssignments.get(i).get(j).get(k) + " ");
}
System.out.println("");
}
}
}
}

View file

@ -0,0 +1,73 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Experiments
{
private List<List<List<Double>>> experiments;
public Experiments()
{
experiments = new ArrayList<List<List<Double>>>();
}
public void addExperiment(int experiment, int row, int col, double data)
{
while (experiments.size() < experiment + 1)
{
experiments.add(new ArrayList<List<Double>>());
}
while (experiments.get(experiment).size() < row + 1)
{
experiments.get(experiment).add(new ArrayList<Double>());
}
while (experiments.get(experiment).get(row).size() < col + 1)
{
experiments.get(experiment).get(row).add(0.0);
}
experiments.get(experiment).get(row).set(col, data);
}
public double getDataPoint(int experiment, int row, int col)
{
return experiments.get(experiment).get(row).get(col);
}
public Experiments removeMutations(String s)
{
return this;
}
public int getNumOfExperiments()
{
return experiments.size();
}
public List<List<List<Double>>> getExperiments()
{
return experiments;
}
}

View file

@ -0,0 +1,710 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Learn
{
private int bins;
public Learn(int bins)
{
this.bins = bins;
}
public void learnBaselineNetwork(SpeciesCollection S, Experiments E, NetCon C)
{
for (int i = 0; i < S.size(); i++)
{
String s_0 = S.getInterestingSpecies(i);
for (int j = 0; j < S.size(); j++)
{
String s_1 = S.getInterestingSpecies(j);
if (!s_0.equals(s_1))
{
addParent(s_0, s_1, E, S, C);
}
}
}
}
private void addParent(String parent, String child, Experiments E, SpeciesCollection S, NetCon C)
{
int parent_col = S.getColumn(parent);
int child_col = S.getColumn(child);
int repression = 0;
int activation = 0;
int unknown = 0;
double childPrevious, childCurr;
double parentPrevious, parentCurr;
double childRate, previousChildRate;
double parentRate, previousParentRate;
for (int i = 0; i < E.getNumOfExperiments(); i++)
{
previousChildRate = Double.NaN;
previousParentRate = Double.NaN;
for (int j = 1; j < E.getExperiments().get(i).size(); j++)
{
childPrevious = E.getDataPoint(i, j - 1, child_col);
childCurr = E.getDataPoint(i, j, child_col);
parentPrevious = E.getDataPoint(i, j - 1, parent_col);
parentCurr = E.getDataPoint(i, j, parent_col);
childRate = childCurr - childPrevious;
parentRate = parentCurr - parentPrevious;
if (j == 1)
{
previousChildRate = childRate;
previousParentRate = parentRate;
continue;
}
if (childCurr > 10 && parentCurr > 10)
{
if (childRate < previousChildRate)
{
if (parentRate > previousParentRate)
{
repression++;
}
else if (parentRate < previousParentRate)
{
activation++;
}
else
{
unknown++;
}
}
else if (childRate > previousChildRate)
{
if (parentRate > previousParentRate)
{
activation++;
}
else if (parentRate < previousParentRate)
{
repression++;
}
else
{
unknown++;
}
}
}
previousParentRate = parentRate;
previousChildRate = childRate;
}
}
if (repression > activation && repression >= unknown)
{
C.addConnection(child, "repressor", repression, parent);
}
else if (activation > repression && repression >= unknown)
{
C.addConnection(child, "activator", repression, parent);
}
}
public void learnNetwork(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L) throws BioSimException
{
EncodeExpts(S, E, C, T, L);
for (int i = 0; i < S.size(); i++)
{
String s = S.getInterestingSpecies(i);
if (!C.containEdge(s))
{
Experiments new_E = E.removeMutations(s);
selectInitialParents(s, S, new_E, C, T, L);
createMultipleParents(s, S, new_E, C, T, L);
competeMultipleParents(s, S, new_E, C, T, L);
}
}
}
private void EncodeExpts(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L) throws BioSimException
{
for (int i = 0; i < S.size(); i++)
{
String species = S.getInterestingSpecies(i);
if(!S.containsSpeciesData(species))
{
throw new BioSimException("There is no data for " + species + ". Check if species ids in the target model match the ones from the data.", "Error in learning.");
}
getDiscreteLevels(species, S, E, L, bins);
getBinAssign(species, S, E, L, bins);
}
}
private void getBinAssign(String species, SpeciesCollection S, Experiments experiments, Encodings L, int bins)
{
int col = S.getColumn(species);
for (int i = 0; i < experiments.getNumOfExperiments(); i++)
{
List<List<Double>> experiment = experiments.getExperiments().get(i);
for (int j = 0; j < experiment.size(); j++)
{
double value = experiment.get(j).get(col);
L.addLevelAssignment(i, j, col, value);
}
}
}
private void getDiscreteLevels(String species, SpeciesCollection S, Experiments experiments, Encodings L, int levels)
{
int col = S.getColumn(species);
double[] level = new double[levels + 1];
double v = Double.NaN, vp = Double.NaN;
int steps = 0;
level[0] = 0;
level[levels] = Double.POSITIVE_INFINITY;
LinkedList<Double> values = new LinkedList<Double>();
for (List<List<Double>> experiment : experiments.getExperiments())
{
for (int i = 0; i < experiment.size(); i++)
{
double value = experiment.get(i).get(col);
values.add(value);
}
}
Collections.sort(values);
for (int j = 1; j < levels - 1; j++)
{
int count = 0;
level[j] = Double.POSITIVE_INFINITY;
steps = values.size() / (levels - j + 1);
while (values.size() > 0 && count < steps)
{
v = values.pop();
count++;
}
do
{
vp = values.pop();
}
while (values.size() > 0 && v == vp);
if (values.size() > 0)
{
level[j] = v;
values.addFirst(vp);
}
}
L.addDiscreteSpecies(col, level);
}
private static double scoreParents(String s, SpeciesCollection S, Set<String> P, Set<String> G, Experiments E, Thresholds T, Encodings L)
{
int votes_a = 0, votes_r = 0, votes_u = 0;
int totalDen = 0, den = 0, totalNum = 0, num = 0;
int targetCol = S.getColumn(s);
double probRatio = 0;
List<Integer> levelAssignmentsP = getLevelAssignments(P, S, L);
Collections.sort(levelAssignmentsP);
List<Integer> levelAssignmentsG = getLevelAssignments(G, S, L);
Collections.sort(levelAssignmentsP);
int l0 = levelAssignmentsP.remove(0);
for (int l : levelAssignmentsG)
{
for (int lp : levelAssignmentsP)
{
for (int i = 0; i < E.getNumOfExperiments(); i++)
{
for (int j = 0; j < E.getExperiments().get(i).size(); j++)
{
boolean g = checkSameLevel(G, i, j, l, S, L);
boolean p = checkSameLevel(P, i, j, lp, S, L);
boolean p0 = checkSameLevel(P, i, j, l0, S, L);
if (g && p)
{
if (isIncreasing(i, j, targetCol, E))
{
num++;
}
totalNum++;
}
else if (g && p0)
{
if (isIncreasing(i, j, targetCol, E))
{
den++;
}
totalDen++;
}
}
}
}
if (num == 0 || den == 0)
{
probRatio = 1;
}
else
{
probRatio = (1.0 * num / totalNum) / (1.0 * den / totalDen);
}
if (probRatio > T.getTa())
{
votes_a++;
}
else if (probRatio < T.getTr())
{
votes_r++;
}
else
{
votes_u++;
}
}
return 1.0 * (votes_a - votes_r) / (votes_a + votes_r + votes_u);
}
private static boolean checkSameLevel(Set<String> species, int experiment, int row, int bin, SpeciesCollection S, Encodings L)
{
for (String s : species)
{
int col = S.getColumn(s);
if (L.getLevelAssignments().get(experiment).get(row).get(col) != bin)
{
return false;
}
}
return true;
}
private static boolean isIncreasing(int experiment, int row, int targetCol, Experiments E)
{
List<List<Double>> list = E.getExperiments().get(experiment);
if (row + 1 < list.size())
{
if (list.get(row).get(targetCol) < list.get(row + 1).get(targetCol))
{
return true;
}
}
if (row - 1 >= 0)
{
if (list.get(row - 1).get(targetCol) < list.get(row).get(targetCol))
{
return true;
}
}
return false;
}
private static List<Integer> getLevelAssignments(Set<String> P, SpeciesCollection S, Encodings L)
{
List<Integer> set = new ArrayList<Integer>();
for (String species : P)
{
int col = S.getColumn(species);
for (int i = 0; i < L.size(); i++)
{
List<List<Integer>> encodings = L.getLevelAssignments().get(i);
for (int j = 0; j < encodings.size(); j++)
{
int value = encodings.get(j).get(col);
if (!set.contains(value))
{
set.add(encodings.get(j).get(col));
}
}
}
}
return set;
}
private static void selectInitialParents(String s, SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L)
{
List<String> interestingSpecies = new ArrayList<String>(S.getInterestingSpecies());
interestingSpecies.remove(s);
double score;
for (String p : interestingSpecies)
{
score = scoreParents(s, S, new HashSet<String>(Arrays.asList(p)), new HashSet<String>(Arrays.asList(s)), E, T, L);
if (score >= T.getTv())
{
C.addConnection(s, "activator", score, p);
}
else if (score <= -T.getTv())
{
C.addConnection(s, "repressor", score, p);
}
}
}
private static void createMultipleParents(String s, SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L)
{
double score1, score2, scoreb;
List<Connection> connectionsToDelete = new ArrayList<Connection>();
List<Connection> multipleParents = new ArrayList<Connection>();
List<Connection> singleParent = C.getListOfConnections(s);
if (singleParent == null)
{
return;
}
for (int i = 0; i < singleParent.size(); i++)
{
Connection connection1 = singleParent.get(i);
score1 = connection1.getScore();
for (int j = i + 1; j < singleParent.size(); j++)
{
Connection connection2 = singleParent.get(j);
score2 = connection2.getScore();
Set<String> parents = new HashSet<String>();
parents.addAll(connection1.getParents());
parents.addAll(connection2.getParents());
scoreb = scoreParents(s, S, parents, new HashSet<String>(Arrays.asList(s)), E, T, L);
if (Math.abs(scoreb) >= Math.abs(score1) && Math.abs(scoreb) >= Math.abs(score2))
{
multipleParents.add(new Connection(s, scoreb, connection1, connection2));
connectionsToDelete.add(connection1);
connectionsToDelete.add(connection2);
}
}
}
for (Connection connection : connectionsToDelete)
{
C.removeConnection(s, connection);
}
for (Connection connection : multipleParents)
{
C.addConnection(s, connection);
}
}
private static void competeMultipleParents(String s, SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L)
{
List<Connection> potentialParents = C.getListOfConnections(s);
double scoreq, smallestScore;
if (potentialParents == null)
{
return;
}
double Ta = T.getTa();
double Tr = T.getTr();
while (potentialParents.size() > 1)
{
List<List<String>> Q = getContenders(s, C);
List<Double> scores = new ArrayList<Double>();
smallestScore = Double.POSITIVE_INFINITY;
for (List<String> q : Q)
{
HashSet<String> P = new HashSet<String>(q);
HashSet<String> G = new HashSet<String>();
for (List<String> qp : Q)
{
if (qp != q)
{
G.addAll(qp);
}
}
G.add(s);
scoreq = scoreParents(s, S, P, G, E, T, L);
scores.add(Math.abs(scoreq));
if (Math.abs(scoreq) < smallestScore)
{
smallestScore = Math.abs(scoreq);
}
}
boolean isScoreTied = isTied(smallestScore, Q, scores);
if (isScoreTied)
{
if (T.getTa() > 4 || T.getTr() < 0)
{
removeLosers(s, C, Q);
}
else
{
T.setTa(T.getTa() + T.getTt());
T.setTr(T.getTr() - T.getTt());
}
}
else
{
removeLosers(s, C, Q, scores, smallestScore);
}
}
T.setTa(Ta);
T.setTr(Tr);
}
private static boolean checkNumParents(List<List<String>> Q)
{
boolean sameNum = true;
if (Q.size() > 0)
{
int size = Q.get(0).size();
for (int i = 1; i < Q.size(); i++)
{
if (Q.get(i).size() != size)
{
sameNum = false;
break;
}
}
}
return sameNum;
}
private static boolean isTied(double smallestScore, List<List<String>> Q, List<Double> scores)
{
boolean isScoreTied = true;
for (int i = 0; i < Q.size(); i++)
{
if (scores.get(i) != smallestScore)
{
isScoreTied = false;
break;
}
}
return isScoreTied;
}
private static void removeLosers(String s, NetCon C, List<List<String>> Q)
{
if (checkNumParents(Q))
{
int minParents = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < Q.size(); i++)
{
if (Q.get(i).size() < minParents)
{
minParents = Q.get(i).size();
index = i;
}
}
C.removeConnectionByParent(s, Q.get(index));
}
else
{
C.removeConnection(s, 0);
}
}
private static void removeLosers(String s, NetCon C, List<List<String>> Q, List<Double> scores, double smallestScore)
{
for (int i = 0; i < Q.size(); i++)
{
if (scores.get(i) == smallestScore)
{
C.removeConnectionByParent(s, Q.get(i));
}
}
}
private static List<List<String>> getContenders(String s, NetCon C)
{
List<List<String>> contenders = new ArrayList<List<String>>();
List<Connection> potentialParents = C.getListOfConnections(s);
double maxScore = Double.MIN_VALUE;
double minScore = Double.MAX_VALUE;
if (potentialParents != null)
{
for (Connection connection : potentialParents)
{
if (connection.getScore() > maxScore)
{
maxScore = connection.getScore();
}
else if (connection.getScore() < minScore)
{
minScore = connection.getScore();
}
}
for (Connection connection : potentialParents)
{
if (connection.getScore() == maxScore || connection.getScore() == minScore)
{
contenders.add(connection.getParents());
}
}
}
return contenders;
}
public void getDotFile(String filename, String directory, SpeciesCollection collection, NetCon network) throws BioSimException
{
Map<String, String> speciesToNode;
File fout = new File(directory + GlobalConstants.separator + filename);
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
int index = 0;
speciesToNode = new HashMap<String, String>();
fos = new FileOutputStream(fout);
osw = new OutputStreamWriter(fos);
osw.write("digraph G { \n");
for (String s : collection.getInterestingSpecies())
{
String node = "s" + ++index;
osw.write(node + " [shape=ellipse,color=black,label=\"" + s + "\"];\n");
speciesToNode.put(s, node);
}
for (String s : network.getConnections().keySet())
{
for (Connection connection : network.getConnections().get(s))
{
for (String parent : connection.getParents())
{
String type = connection.getParentType(parent).toLowerCase();
if (type.equals("activator"))
{
osw.write(speciesToNode.get(parent) + " -> " + speciesToNode.get(s) + " [color=\"blue4\",arrowhead=vee]\n");
}
else if (type.equals("repressor"))
{
osw.write(speciesToNode.get(parent) + " -> " + speciesToNode.get(s) + " [color=\"firebrick4\",arrowhead=tee]\n");
}
}
}
}
osw.write("} \n");
}
catch (FileNotFoundException e)
{
throw new BioSimException("Could not write dot file. File could not be found.", "Error in Learning");
}
catch (IOException e)
{
throw new BioSimException("Error when writing dot file.", "Error in Learning");
}
finally
{
try
{
if (osw != null)
{
osw.close();
}
}
catch (IOException e)
{
throw new BioSimException("Failed to close writer", "Error in Learning");
}
try
{
if (fos != null)
{
fos.close();
}
}
catch (IOException e)
{
throw new BioSimException("Failed to close outputstream", "Error in Learning");
}
}
}
}

View file

@ -0,0 +1,111 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class NetCon
{
private Map<String, List<Connection>> connections;
public NetCon()
{
connections = new HashMap<String, List<Connection>>();
}
public boolean containEdge(String s)
{
return false;
}
public void addConnection(String child, String type, double score, String parent)
{
if (!connections.containsKey(child))
{
connections.put(child, new ArrayList<Connection>());
}
connections.get(child).add(new Connection(child, score, type, parent));
}
public void addConnection(String child, Connection connection)
{
if (!connections.containsKey(child))
{
connections.put(child, new ArrayList<Connection>());
}
connections.get(child).add(connection);
}
public void addConnection(String child, double score, Connection... collections)
{
if (!connections.containsKey(child))
{
connections.put(child, new ArrayList<Connection>());
}
connections.get(child).add(new Connection(child, score, collections));
}
public void removeConnection(String child, Connection connection)
{
if (connections.containsKey(child))
{
connections.get(child).remove(connection);
}
}
public void removeConnectionByParent(String child, List<String> parents)
{
List<Connection> listOfConnections = connections.get(child);
for (int i = listOfConnections.size() - 1; i >= 0; i--)
{
if (listOfConnections.get(i).equalParents(parents))
{
listOfConnections.remove(i);
}
}
}
public void removeConnection(String child, int index)
{
if (connections.containsKey(child))
{
connections.get(child).remove(index);
}
}
public List<Connection> getListOfConnections(String s)
{
return connections.get(s);
}
public Map<String, List<Connection>> getConnections()
{
return connections;
}
}

View file

@ -0,0 +1,281 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import javax.xml.stream.XMLStreamException;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.SBMLReader;
import org.sbml.jsbml.Species;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Run
{
private static int experiment;
public static boolean run(String filename, String directory) throws BioSimException
{
experiment = 0;
SpeciesCollection S = new SpeciesCollection();
Experiments E = new Experiments();
Encodings L = new Encodings();
Thresholds T = new Thresholds();
NetCon C = new NetCon();
init(filename, S);
loadExperiments(directory, S, E);
if(experiment < 1)
{
return false;
}
Learn learn = new Learn(3);
learn.learnNetwork(S, E, C, T, L);
learn.getDotFile("method.gcm", directory, S, C);
learn.getDotFile("method.dot", directory, S, C);
return true;
}
public static void loadExperiments(String directory, SpeciesCollection S, Experiments E) throws BioSimException
{
File path = new File(directory);
for (File file : path.listFiles())
{
String name = file.getAbsolutePath();
if (name.endsWith(".tsd"))
{
parse(name, S, E);
experiment++;
}
else if (name.endsWith(".csv"))
{
parseCSV(name, S, E);
experiment++;
}
}
}
public static void init(String filename, SpeciesCollection S)
{
try
{
SBMLDocument doc = SBMLReader.read(new File(filename));
Model model = doc.getModel();
for (Species species : model.getListOfSpecies())
{
S.addInterestingSpecies(species.getId());
}
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static void parseCSV(String filename, SpeciesCollection S, Experiments E)
{
Scanner scan = null;
boolean isFirst = true;
try
{
scan = new Scanner(new File(filename));
int row = 0;
while (scan.hasNextLine())
{
String line = scan.nextLine();
String[] values = line.split(",");
if (isFirst)
{
for (int i = 0; i < values.length; i++)
{
S.addSpecies(values[i], i);
}
isFirst = false;
}
else
{
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
row++;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find the file!");
}
finally
{
if (scan != null)
{
scan.close();
}
}
}
private static void parse(String filename, SpeciesCollection S, Experiments E) throws BioSimException
{
InputStream input = null;
try
{
String buffer = "";
char state = 1;
char read = 0;
int row = 0;
input = new FileInputStream(filename);
int data = input.read();
while (data != -1)
{
data = input.read();
read = (char) data;
if (read == ' ' || read == '\n')
{
continue;
}
switch (state)
{
case 1:
if (read == '(')
{
state = 2;
buffer = "";
break;
}
else
{
return;
}
case 2:
if (read == ')')
{
state = 3;
row = 0;
String[] ids = buffer.split(",");
if (experiment == 0)
{
for (int i = 0; i < ids.length; i++)
{
S.addSpecies(ids[i].substring(1, ids[i].length() - 1), i);
}
}
break;
}
else
{
buffer += read;
break;
}
case 3:
if (read == '(')
{
state = 4;
buffer = "";
break;
}
if (read == ',')
{
break;
}
if (read == ')')
{
return;
}
else
{
return;
}
default:
if (read == ')')
{
state = 3;
String[] values = buffer.replace(" ", "").split(",");
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
row++;
}
else
{
buffer += read;
}
}
}
}
catch (FileNotFoundException e)
{
throw new BioSimException("Could not find the file!", "Error in Learning");
}
catch (IOException e)
{
throw new BioSimException("There was a problem when reading the file!", "Error in Learning");
}
finally
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException e)
{
throw new BioSimException("Failed to close input stream", "Error in Learning");
}
}
}
}

View file

@ -0,0 +1,78 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class SpeciesCollection
{
private List<String> interestingSpecies;
private Map<Integer, String> columnSpecies;
private Map<String, Integer> speciesColumn;
public SpeciesCollection()
{
interestingSpecies = new ArrayList<String>();
columnSpecies = new HashMap<Integer, String>();
speciesColumn = new HashMap<String, Integer>();
}
public void addSpecies(String id, int index)
{
speciesColumn.put(id, index);
columnSpecies.put(index, id);
}
public void addInterestingSpecies(String id)
{
interestingSpecies.add(id);
}
public int getColumn(String species)
{
return speciesColumn.get(species);
}
public String getInterestingSpecies(int index)
{
return interestingSpecies.get(index);
}
public int size()
{
return interestingSpecies.size();
}
public List<String> getInterestingSpecies()
{
return interestingSpecies;
}
public boolean containsSpeciesData(String species)
{
return speciesColumn.containsKey(species);
}
}

View file

@ -0,0 +1,79 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.genenet;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Thresholds
{
private double Ta, Tr, Tv, Tt;
public Thresholds()
{
Ta = 1.15;
Tr = 0.75;
Tv = 0.5;
Tt = 0.025;
}
public Thresholds(double Ta, double Tr, double Tv)
{
this.Ta = Ta;
this.Tr = Tr;
this.Tv = Tv;
this.Tt = 0.025;
}
public double getTa()
{
return Ta;
}
public double getTr()
{
return Tr;
}
public double getTv()
{
return Tv;
}
public void setTa(double Ta)
{
this.Ta = Ta;
}
public void setTr(double Tr)
{
this.Tr = Tr;
}
public void setTv(double Tv)
{
this.Tv = Tv;
}
public double getTt()
{
return Tt;
}
}

View file

@ -0,0 +1,91 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.sbml.jsbml.SBMLDocument;
import edu.utah.ece.async.analysis.simulation.hierarchical.HierarchicalSimulation;
import edu.utah.ece.async.analysis.simulation.hierarchical.methods.HierarchicalODERKSimulator;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.learn.genenet.Experiments;
import edu.utah.ece.async.learn.genenet.SpeciesCollection;
import edu.utah.ece.async.learn.parameterestimator.methods.sres.EvolutionMethodSetting;
import edu.utah.ece.async.learn.parameterestimator.methods.sres.Modelsettings;
import edu.utah.ece.async.learn.parameterestimator.methods.sres.ObjectiveSqureError;
import edu.utah.ece.async.learn.parameterestimator.methods.sres.SRES;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ParameterEstimator
{
static double relativeError = 1e-6;
static double absoluteError = 1e-9;
static int numSteps;
static double maxTimeStep = Double.POSITIVE_INFINITY;
static double minTimeStep = 0.0;
static long randomSeed = 0;
static int runs = 1;
static double stoichAmpValue = 1.0;
static boolean genStats = false;
static String selectedSimulator = "";
static ArrayList<String> interestingSpecies = new ArrayList<String>();
static String quantityType = "amount";
public static SBMLDocument estimate(String SBMLFileName, String root, List<String> parameterList, Experiments experiments, SpeciesCollection speciesCollection) throws IOException, XMLStreamException, BioSimException
{
int numberofparameters = parameterList.size();
int sp = 0;
int n = experiments.getExperiments().get(0).size() - 1;
double ep = experiments.getExperiments().get(0).get(n).get(0);
double[] lowerbounds = new double[numberofparameters];
double[] upperbounds = new double[numberofparameters];
HierarchicalSimulation sim = new HierarchicalODERKSimulator(SBMLFileName, root, 0);
sim.initialize(randomSeed, 0);
for (int i = 0; i < numberofparameters; i++)
{
lowerbounds[i] = sim.getTopLevelValue(parameterList.get(i)) / 100;
upperbounds[i] = sim.getTopLevelValue(parameterList.get(i)) * 100;
}
Modelsettings M1 = new Modelsettings(experiments.getExperiments().get(0).get(0), speciesCollection.size(), sp, (int) ep, lowerbounds, upperbounds, false);
// Objective objective1 = new ObjectiveSqureError(M1,0.1);
EvolutionMethodSetting EMS = new EvolutionMethodSetting();
ObjectiveSqureError TP = new ObjectiveSqureError(sim, experiments, parameterList, speciesCollection, M1, 0.1);
SRES sres = new SRES(TP, EMS);
// System.out.println("test");
SRES.Solution solution = sres.run(200).getBestSolution();
// TODO: report results: take average of error
// TODO: weight mean square error. Add small value
System.out.println(solution.toString());
// TODO: copy best parameter to a new SBML document
return null;
}
}

View file

@ -0,0 +1,27 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public interface AbstractEstimator
{
}

View file

@ -0,0 +1,133 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.pedi;
public class GeneProduct
{
private double mRNADegradationConstant;
private double translationConstant;
private double proteinDegradationConstant;
private double[] unkownTranscriptionConstants;
private GeneProduct[] transcFactors;
private double[] getLowerBounds;
private double[] getUpperBounds;
private double mRNALevel;
private double proteinLevel;
public GeneProduct()
{
}
public double evaluateTranscriptionRate(double[] proteins)
{
return 0;
}
/**
* RNA degradation constants for each gene. NaN if the constant is unknown,
* value if the constant is known.
*
* @return
*/
public double getmRNADegradationConstant()
{
return mRNADegradationConstant;
}
public void setmRNADegradationConstant(double mRNADegradationConstant)
{
this.mRNADegradationConstant = mRNADegradationConstant;
}
public double getTranslationConstant()
{
return translationConstant;
}
public void setTranslationConstant(double translationConstant)
{
this.translationConstant = translationConstant;
}
public double getProteinDegradationConstant()
{
return proteinDegradationConstant;
}
public void setProteinDegradationConstant(double proteinDegradationConstant)
{
this.proteinDegradationConstant = proteinDegradationConstant;
}
public double[] getUnkownTranscriptionConstants()
{
return unkownTranscriptionConstants;
}
public void setUnkownTranscriptionConstants(double[] unkownTranscriptionConstants)
{
this.unkownTranscriptionConstants = unkownTranscriptionConstants;
}
public GeneProduct[] getTranscFactors()
{
return transcFactors;
}
public void setTranscFactors(GeneProduct[] transcFactors)
{
this.transcFactors = transcFactors;
}
public double[] getGetLowerBounds()
{
return getLowerBounds;
}
public void setGetLowerBounds(double[] getLowerBounds)
{
this.getLowerBounds = getLowerBounds;
}
public double[] getGetUpperBounds()
{
return getUpperBounds;
}
public void setGetUpperBounds(double[] getUpperBounds)
{
this.getUpperBounds = getUpperBounds;
}
public double getmRNALevel()
{
return mRNALevel;
}
public void setmRNALevel(double mRNALevel)
{
this.mRNALevel = mRNALevel;
}
public double getProteinLevel()
{
return proteinLevel;
}
public void setProteinLevel(double proteinLevel)
{
this.proteinLevel = proteinLevel;
}
}

View file

@ -0,0 +1,21 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.pedi;
public interface PEDIBridge
{
public double[][] simulate(GeneProduct[] genes, double startTime, double endTime, double printInterval);
}

View file

@ -0,0 +1,139 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.sres;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class EvolutionMethodSetting
{
/*
* * @param verbose if set to true, will print the number of generations
* passed and other statistics to {@code stderr}
*
* @param lambda solution set size
*
* @param mu number of top-ranking solutions selected to produce new
* solution set at each generation
*
* @param expectedConvergenceRate expected convergence rate
*
* @param numberOfSweeps number of times stochastic ranking bubble-sort is
* applied to solution set
*
* @param rankingPenalizationFactor constraint breaking penalization factor,
* should be in { [0, 1]};
*/
boolean verbose;
int lambda;
int mu;
// double tau;
double expectedConvergenceRate;
int numberOfSweeps;
double rankingPenalizationFactor;
double tauDash;
int numberOfgenerations;
public EvolutionMethodSetting()
{
this(true, 200, 30, 1.0, 200, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose)
{
this(verbose, 200, 30, 1.0, 200, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda)
{
this(verbose, lambda, 30, 1.0, 200, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda, int mu)
{
this(verbose, lambda, mu, 1.0, 200, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda, int mu, double expectedConvergenceRate)
{
this(verbose, lambda, mu, expectedConvergenceRate, 200, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda, int mu, double expectedConvergenceRate, int numberOfSweeps)
{
this(verbose, lambda, mu, expectedConvergenceRate, numberOfSweeps, 1000, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda, int mu, double expectedConvergenceRate, int numberOfSweeps, int numberofgenerations)
{
this(verbose, lambda, mu, expectedConvergenceRate, numberOfSweeps, numberofgenerations, 0.45);
}
public EvolutionMethodSetting(boolean verbose, int lambda, int mu, double expectedConvergenceRate, int numberOfSweeps, int numberofgenerations, double rankingPenalizationFactor)
{
this.verbose = verbose;
this.lambda = lambda;
this.mu = mu;
// this.tau = expectedConvergenceRate / Math.sqrt(2 *
// Math.sqrt(numberOfFeatures));
// this.tauDash = expectedConvergenceRate / Math.sqrt(2 *
// numberOfFeatures);
this.numberOfSweeps = numberOfSweeps;
this.rankingPenalizationFactor = rankingPenalizationFactor;
this.numberOfgenerations = numberofgenerations;
this.expectedConvergenceRate = expectedConvergenceRate;
}
public boolean getverbose()
{
return verbose;
}
public int getlamda()
{
return lambda;
}
public int getmu()
{
return mu;
}
public double getexpectedConvergenceRate()
{
return expectedConvergenceRate;
}
public int getnumberOfSweeps()
{
return numberOfSweeps;
}
public double getrankingPenalizationFactor()
{
return rankingPenalizationFactor;
}
public double getnumberOfgenerations()
{
return numberOfgenerations;
}
}

View file

@ -0,0 +1,109 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.sres;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class Modelsettings
{
public List<Double> IC;
public int ngenes;
public int startp;
public int endp;
double[] lowerBounds;
double[] upperBounds;
boolean verbose;
int nums;
public Modelsettings(List<Double> ic, int ngenes, int sp, int ep, double[] lowerbounds, double[] upperbounds, boolean verbose)
{
this.IC = ic;
this.ngenes = ngenes;
this.startp = sp;
this.endp = ep;
this.lowerBounds = lowerbounds;
this.upperBounds = upperbounds;
this.verbose = verbose;
}
public double[][] loaddata(String filename)
{
// StringBuffer sb=new StringBuffer();
String tempstr = null;
int lines = 0;
int rows = 0;
double[][] tmps = new double[100][100];
try
{
// String path="/Users/mfan/Documents/program/data/model1.txt";
String path = new String(filename);
File file = new File(path);
if (!file.exists())
{
throw new FileNotFoundException();
}
// BufferedReader br=new BufferedReader(new FileReader(file));
// while((tempstr=br.readLine())!=null)
// sb.append(tempstr);
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((tempstr = br.readLine()) != null)
{
String s[] = tempstr.split(" ");
// System.out.println(s.length);
for (int i = 0; i < s.length; ++i)
{
tmps[lines][i] = Double.parseDouble(s[i]);
}
lines = lines + 1;
rows = s.length;
}
br.close();
// double rows=tmps[0].length;
}
catch (IOException ex)
{
System.out.println(ex.getStackTrace());
}
double[][] data = new double[lines][rows];
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < rows; j++)
{
data[i][j] = tmps[i][j];
}
}
return data;
// return sb.toString();
}
}

View file

@ -0,0 +1,257 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.sres;
import java.util.Arrays;
/**
* A class representing a real multivariate objective function and constraints
* that are subject to optimization. The objective functionmethod is left for
* the user to specify. Arbitrary value range is allowed for objective function.
* Constraints are provided as { constraint_value <= 0} inequalities, the
* computation of array should be implemented by user.
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public abstract class Objective
{
private final int numberOfFeatures;
private final double[] featureLowerBounds, featureUpperBounds;
private final double[] mutationRates;
private final boolean maximizationProblem;
/**
* Generates an objective function instance and specifies the feature
* (argument) space.
*
* @param featureLowerBounds
* lower bounds of feature space
* @param featureUpperBounds
* upper bounds of feature space
* @param maximizationProblem
* if set to true, the objective function is subject to
* maximization task, minimization will be performed otherwise
*/
public Objective(Modelsettings Ms)
{
// this.numberOfFeatures = featureLowerBounds.length;
this.numberOfFeatures = Ms.lowerBounds.length;
if (Ms.upperBounds.length != numberOfFeatures)
{
throw new IllegalArgumentException("Lengths of upper and lower bounds should match.");
}
this.featureLowerBounds = Ms.lowerBounds;
this.featureUpperBounds = Ms.upperBounds;
for (int i = 0; i < numberOfFeatures; i++)
{
if (featureUpperBounds[i] < featureLowerBounds[i])
{
throw new IllegalArgumentException("Feature upper bound is smaller than lower bound for index " + i + ".");
}
}
this.maximizationProblem = Ms.verbose;
this.mutationRates = new double[numberOfFeatures];
double factor = Math.sqrt(numberOfFeatures);
for (int i = 0; i < numberOfFeatures; i++)
{
mutationRates[i] = (featureUpperBounds[i] - featureLowerBounds[i]) / factor;
}
}
/**
* Generate a random feature array based on feature space constraints.
*
* @return a random array from feature space
*/
double[] generateFeatureVector()
{
double[] features = new double[numberOfFeatures];
for (int i = 0; i < numberOfFeatures; i++)
{
double x = SRES.random.nextDouble();
features[i] = featureLowerBounds[i] + x * (featureUpperBounds[i] - featureLowerBounds[i]);
}
return features;
}
/**
* Gets the mutation rates for { SRES} algorithm.
*
* @return an array of feature mutation rates
*/
final double[] getMutationRates()
{
return mutationRates;
}
/**
* Check whether a given feature value belongs to feature space.
*
* @param feature
* feature value
* @param index
* feature index
* @return true if feature value is in specified bounds, false otherwise
*/
final boolean inBounds(double feature, int index)
{
return featureLowerBounds[index] <= feature && feature <= featureUpperBounds[index];
}
/**
* A user-implemented function that computes the value of objective function
* and constraint values using provided features (parameters).
*
* @param features
* an array of objective function features
* @return objective function evaluation result
* @see com.antigenomics.jsres.Objective.Result
*/
public abstract Result evaluate(double[] features);
/**
* Gets the dimensionality of feature (parameter) space.
*
* @return length of feature arrays
*/
public final int getNumberOfFeatures()
{
return numberOfFeatures;
}
public double[] getfeatureLowerBounds()
{
return featureLowerBounds;
}
public double[] getfeatureUpperBounds()
{
return featureUpperBounds;
}
/**
* Tells if the problem is maximization or minimization one.
*
* @return true for maximization task, false for minimization
*/
public boolean isMaximizationProblem()
{
return maximizationProblem;
}
/**
* An object containing results of objective function and constraint
* evaluation.
*/
public class Result
{
private final double value, penalty;
private final double[] constraintValues;
/**
* Creates a new instance of objective function evaluation result.
*
* @param value
* objective function value
*/
public Result(double value)
{
this.value = value;
this.constraintValues = new double[0];
this.penalty = 0;
}
/**
* Creates a new instance of objective function evaluation result.
* Constraints should be re-written as {constraint_value <= 0}
* inequalities and {@code constraint_value} array should be provided.
*
* @param value
* objective function value
* @param constraintValues
* constraint values
*/
public Result(double value, double[] constraintValues)
{
this.value = value;
this.constraintValues = constraintValues;
double penalty = 0;
for (double p : constraintValues)
{
double pp = Math.max(0, p);
penalty += pp * pp;
}
this.penalty = penalty;
}
/**
* Get the array of constraint values.
*
* @return constraint value array
*/
public double[] getConstraintValues()
{
return constraintValues;
}
/**
* Gets the objective function value.
*
* @return objective function value
*/
public double getValue()
{
return value;
}
/**
* Gets the { SRES} penalty computed from objective values. Penalty
* value is computed as {@code sum(max(0, constraint_value)^2}.
*
* @return penalty value
*/
double getPenalty()
{
return penalty;
}
/**
* Gets the parent objective function instance.
*
* @return parent objective function instance
*/
public Objective getObjective()
{
return Objective.this;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "RESULT objective function value is " + value + ", constraint values are " + Arrays.toString(constraintValues);
}
}
}

View file

@ -0,0 +1,148 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.sres;
import static java.lang.Math.abs;
import java.util.List;
import edu.utah.ece.async.analysis.simulation.hierarchical.HierarchicalSimulation;
import edu.utah.ece.async.analysis.simulation.hierarchical.methods.HierarchicalODERKSimulator;
import edu.utah.ece.async.learn.genenet.Experiments;
import edu.utah.ece.async.learn.genenet.SpeciesCollection;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ObjectiveSqureError extends Objective
{
private final double valueAtSolution;
private final double absolutePrecision, relativePrecision;
private final int allowedViolatedConstraintsCount;
private final Modelsettings Models;
private Experiments experiment;
private List<String> listOfParams;
private String[] speciesCollection;
private HierarchicalSimulation sim;
/*
* public TestProblem(double[] featureUpperBounds, double[]
* featureLowerBounds, boolean maximizationProblem, double valueAtSolution)
* { this(featureUpperBounds, featureLowerBounds, maximizationProblem,
* valueAtSolution, 0); }
*
* public TestProblem(double[] featureUpperBounds, double[]
* featureLowerBounds, boolean maximizationProblem, double valueAtSolution,
* int allowedViolatedConstraintsCount) { this(featureUpperBounds,
* featureLowerBounds, maximizationProblem, valueAtSolution,
* allowedViolatedConstraintsCount, 1e-6, 1e-3); }
*/
public ObjectiveSqureError(HierarchicalSimulation sim, Experiments experiments, List<String> parameterList, SpeciesCollection speciesCollection, Modelsettings Ms, double valueAtSolution)
{
super(Ms);
this.valueAtSolution = valueAtSolution;
this.relativePrecision = 0;
this.allowedViolatedConstraintsCount = 0;
this.absolutePrecision = 0;
this.Models = Ms;
this.experiment = experiments;
this.listOfParams = parameterList;
this.speciesCollection = new String[speciesCollection.size() + 1];
for (String species : speciesCollection.getInterestingSpecies())
{
this.speciesCollection[speciesCollection.getColumn(species)] = species;
}
this.sim = sim;
}
public ObjectiveSqureError(Modelsettings Ms, double valueAtSolution, int allowedViolatedConstraintsCount, double absolutePrecision, double relativePrecision)
{
super(Ms);
this.valueAtSolution = valueAtSolution;
this.absolutePrecision = absolutePrecision;
this.relativePrecision = relativePrecision;
this.allowedViolatedConstraintsCount = allowedViolatedConstraintsCount;
this.Models = Ms;
}
@Override
public Result evaluate(double[] features)
{
double sum = 0;
List<List<Double>> experiment = this.experiment.getExperiments().get(0);
HierarchicalODERKSimulator odeSim = (HierarchicalODERKSimulator) sim;
for (int i = 1; i < speciesCollection.length; i++)
{
odeSim.setTopLevelValue(speciesCollection[i], experiment.get(0).get(i));
}
for (int i = 0; i < listOfParams.size(); i++)
{
odeSim.setTopLevelValue(listOfParams.get(i), features[i]);
}
for (int i = 0; i < experiment.size() - 1; i++)
{
odeSim.setTimeLimit(experiment.get(i + 1).get(0));
odeSim.simulate();
for (int j = 1; j < speciesCollection.length; j++)
{
double tmp = odeSim.getTopLevelValue(speciesCollection[j]) - experiment.get(i + 1).get(j);
tmp = tmp * tmp;
sum = sum + tmp;
}
}
odeSim.setCurrentTime(0);
odeSim.setTimeLimit(0);
odeSim.setupForNewRun(0);
return new Result(sum);
}
public boolean isSolved(SRES.Solution solution)
{
Objective.Result result = solution.getObjectiveResult();
int violatedConstraints = 0;
for (int i = 0; i < result.getConstraintValues().length; i++)
{
if (result.getConstraintValues()[i] > 0)
{
violatedConstraints++;
}
}
double absoluteError = abs(valueAtSolution - result.getValue()), relativeError = absoluteError / abs(valueAtSolution);
System.out.print(allowedViolatedConstraintsCount);
System.out.print(absolutePrecision);
System.out.print(valueAtSolution);
System.out.print(violatedConstraints <= allowedViolatedConstraintsCount && absoluteError <= absolutePrecision && (abs(valueAtSolution) < relativePrecision || relativeError <= relativePrecision));
return violatedConstraints <= allowedViolatedConstraintsCount && absoluteError <= absolutePrecision && (abs(valueAtSolution) < relativePrecision || relativeError <= relativePrecision);
}
}

View file

@ -0,0 +1,484 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.learn.parameterestimator.methods.sres;
import java.util.Arrays;
import java.util.Random;
import edu.utah.ece.async.learn.parameterestimator.methods.AbstractEstimator;
/**
* A class that implements Stochastic Ranking Evolutionary Strategy (SRES), an
* evolutionary algorithm for constrained optimization of real multivariate
* objective functions. User should provide an objective function instance
* inherited from abstract {@link com.antigenomics.jsres.Objective} class. The
* algorithm is executed via { #run} method. Objective function evaluation is
* optimized by implementing .
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public final class SRES implements AbstractEstimator
{
static final Random random = new Random(51102);
private static final int defaultNumberOfGenerations = 1000, boundingTries = 10;
private final Objective objective;
private final double tau, tauDash, rankingPenalizationFactor;
private final int lambda, mu, numberOfFeatures, numberOfSweeps;
private final double[] featureLowerBounds;
private final double[] featureUpperBounds;
private final boolean verbose;
/**
* Creates an instance of SRES algorithm for a given objective function.
* Default algorithm parameters from Runarsson TP and Yao X work are used.
*
* @param objective
* objective function instance
*/
/*
* public SRES(Objective objective) { this(objective, true); }
*/
/**
* Creates an instance of SRES algorithm for a given objective function.
* Default algorithm parameters from Runarsson TP and Yao X work are used.
*
* @param objective
* objective function instance
* @param verbose
* if set to true, will print the number of generations passed
* and other statistics to {@code stderr}
*/
/*
* public SRES(Objective objective, boolean verbose) { this(objective,
* verbose, 200, 30, 1.0, 200, 0.45); }
*/
/**
* Creates an instance of SRES algorithm for a given objective function.
*
* @param objective
* objective function instance
* @param verbose
* if set to true, will print the number of generations passed
* and other statistics to {@code stderr}
* @param lambda
* solution set size
* @param mu
* number of top-ranking solutions selected to produce new
* solution set at each generation
* @param expectedConvergenceRate
* expected convergence rate
* @param numberOfSweeps
* number of times stochastic ranking bubble-sort is applied to
* solution set
* @param rankingPenalizationFactor
* constraint breaking penalization factor, should be in { [0,
* 1]}; no penalization is performed if set to 1, all solutions
* will be penalized if set to 0
*/
/*
* public SRES(Objective objective, boolean verbose, int lambda, int mu,
* double expectedConvergenceRate, int numberOfSweeps, double
* rankingPenalizationFactor) { this.objective = objective; this.verbose =
* verbose; this.numberOfFeatures = objective.getNumberOfFeatures();
* this.featureLowerBounds = objective.getfeatureLowerBounds();
* this.featureUpperBounds = objective.getfeatureUpperBounds(); this.lambda
* = lambda; this.mu = mu; this.tau = expectedConvergenceRate / Math.sqrt(2
* * Math.sqrt(numberOfFeatures)); this.tauDash = expectedConvergenceRate /
* Math.sqrt(2 * numberOfFeatures); this.numberOfSweeps = numberOfSweeps;
* this.rankingPenalizationFactor = rankingPenalizationFactor; }
*/
public SRES(Objective objective, EvolutionMethodSetting EMS)
{
this.objective = objective;
this.verbose = EMS.getverbose();
this.numberOfFeatures = objective.getNumberOfFeatures();
this.featureLowerBounds = objective.getfeatureLowerBounds();
this.featureUpperBounds = objective.getfeatureUpperBounds();
this.lambda = EMS.getlamda();
this.mu = EMS.getmu();
this.tau = EMS.getexpectedConvergenceRate() / Math.sqrt(2 * Math.sqrt(numberOfFeatures));
this.tauDash = EMS.getexpectedConvergenceRate() / Math.sqrt(2 * numberOfFeatures);
this.numberOfSweeps = EMS.getnumberOfSweeps();
this.rankingPenalizationFactor = EMS.getrankingPenalizationFactor();
}
/**
* Runs the SRES algorithm for {@value #defaultNumberOfGenerations}
* generations.
*
* @return a sorted (from best to worst) set of solutions obtained after
* running the algorithm
*/
public SolutionSet run()
{
return run(defaultNumberOfGenerations);
}
/**
* Generate a random feature array based on feature space constraints.
*
* @return a random array from feature space
*/
double[] generateFeatureVector()
{
double[] features = new double[numberOfFeatures];
for (int i = 0; i < numberOfFeatures; i++)
{
double x = random.nextDouble();
features[i] = featureLowerBounds[i] + x * (featureUpperBounds[i] - featureLowerBounds[i]);
}
return features;
}
/**
* Runs the SRES algorithm for {@code numberOfGenerations} generations.
*
* @param numberOfGenerations
* number of generations to run
* @return a sorted (from best to worst) set of solutions obtained after
* running the algorithm
*/
public SolutionSet run(int numberOfGenerations)
{
SolutionSet solutionSet = new SolutionSet();
for (int i = 0; i < numberOfGenerations; i++)
{
solutionSet.evaluate();
solutionSet.sort();
if (verbose && i % 100 == 0)
{
Solution bestSolution = solutionSet.getBestSolution();
System.err.println("SRES ran for " + i + " generations, best solution fitness is " + bestSolution.getFitness() + ", penalty is " + bestSolution.getPenalty());
}
solutionSet = solutionSet.evolve();
}
solutionSet.evaluate();
solutionSet.sort();
if (verbose)
{
Solution bestSolution = solutionSet.getBestSolution();
System.err.println("SRES finished, best solution fitness is " + bestSolution.getFitness() + ", penalty is " + bestSolution.getPenalty());
}
return solutionSet;
}
/**
* A set of solutions for the objective function and constraints.
*/
public class SolutionSet
{
private final Solution[] solutions;
/**
* Generates initial solution set at random.
*/
SolutionSet()
{
this.solutions = new Solution[lambda];
for (int i = 0; i < lambda; i++)
{
solutions[i] = new Solution(generateFeatureVector(), objective.getMutationRates());
}
}
/**
* Constructs a new instance of solution set.
*
* @param solutions
* solutions array
*/
SolutionSet(Solution[] solutions)
{
this.solutions = solutions;
}
/**
* Sorts solutions using stochastic ranking bubble sort.
*/
void sort()
{
for (int i = 0; i < numberOfSweeps; i++)
{
boolean swapped = false;
for (int j = 0; j < lambda - 1; j++)
{
double p = random.nextDouble(), p1 = solutions[j].getPenalty(), p2 = solutions[j + 1].getPenalty();
if (p < rankingPenalizationFactor || (p1 == 0 && p2 == 0))
{
// no solution break constraints or penalization is not
// applied
if (solutions[j].getFitness() < solutions[j + 1].getFitness())
{
swap(j, j + 1);
swapped = true;
}
}
else if (p1 > p2)
{
// constraint penalization
swap(j, j + 1);
swapped = true;
}
}
if (!swapped)
{
// sorted
break;
}
}
}
/**
* Evolve the population by selecting top { #mu} solutions and
* generating new population of { #lambda} solutions using recombination
* of mutation rates and random weighted mutation of features.
*
* @return evolved solution set, no evaluation of objective function is
* constraints is performed on this step
*/
SolutionSet evolve()
{
Solution[] newSolutions = new Solution[lambda];
int j = 0;
for (int i = 0; i < lambda; i++)
{
// mutation rates are sampled from top solutions
double[] sampledMutationRates = new double[numberOfFeatures];
for (int k = 0; k < numberOfFeatures; k++)
{
sampledMutationRates[k] = solutions[random.nextInt(mu)].mutationRates[k];
}
// top individual generates offspring
newSolutions[i] = solutions[j].generateOffspring(sampledMutationRates);
if (j++ > mu)
{
// cycle top mu solutions
j = 0;
}
}
return new SolutionSet(newSolutions);
}
/**
* Evaluates objective function and constraints for the solution set in
* parallel.
*/
void evaluate()
{
// Arrays.stream(solutions).parallel().forEach(Solution::evaluate);
for (Solution solution : solutions)
{
solution.evaluate();
}
}
/**
* Swaps two solutions.
*
* @param i
* index of fist solution
* @param j
* index of second solution
*/
private void swap(int i, int j)
{
Solution tmp = solutions[i];
solutions[i] = solutions[j];
solutions[j] = tmp;
}
/**
* Gets the solutions array.
*
* @return array of solutions in this set
*/
public Solution[] getSolutions()
{
return solutions;
}
/**
* Gets the best solution from solution set.
*
* @return best solution
*/
public Solution getBestSolution()
{
return solutions[0];
}
}
/**
* A class representing solution to a problem that consists of objective
* function and constraints.
*/
public class Solution
{
private final double[] features, mutationRates;
private Objective.Result objectiveResult = null;
/**
* Creates a solution, features and mutation rates are not set.
*/
Solution()
{
this.features = new double[numberOfFeatures];
this.mutationRates = new double[numberOfFeatures];
}
/**
* Creates a solution with specified features and mutation rates. Used
* to instantiate a descendants of solutions selected by stochastic
* ranking.
*
* @param features
* feature array
* @param mutationRates
* array of mutation rates
*/
Solution(double[] features, double[] mutationRates)
{
this.features = features;
this.mutationRates = mutationRates;
}
/**
* Gets the features (objective function parameters) for this solution.
*
* @return objective function parameters
*/
public double[] getFeatures()
{
return features;
}
/**
* Gets the result of evaluation of objective function and constraints
* for this solution.
*
* @return objective function and constraints evaluation results
*/
public Objective.Result getObjectiveResult()
{
return objectiveResult;
}
/**
* Gets the fitness of this solution.
*
* @return {@code value} of objective function for maximization problem,
* {@code -value} for minimization problem
* @see com.antigenomics.jsres.Objective.Result#getValue
*/
double getFitness()
{
return objectiveResult.getObjective().isMaximizationProblem() ? objectiveResult.getValue() : -objectiveResult.getValue();
}
/**
* Gets the penalty value of this solution.
*
* @return penalty value, sum of squares of constraint values for
* constraints that are violated
* @see com.antigenomics.jsres.Objective.Result#getPenalty
*/
double getPenalty()
{
return objectiveResult.getPenalty();
}
/**
* Generates an offspring for this solution. Mutation rates are
* recombined and applied to randomly mutate the feature vector.
*
* @param sampledMutationRates
* random sample of mutation rates from top {@link #mu}
* solutions for recombination
* @return a recombined and mutated offspring
*/
Solution generateOffspring(double[] sampledMutationRates)
{
Solution offspring = new Solution();
double globalLearningRate = tauDash * random.nextGaussian();
double[] mutationRateConstraints = objective.getMutationRates();
for (int i = 0; i < numberOfFeatures; i++)
{
// global intermediate recombination for mutation rates
double newMutationRate = (mutationRates[i] + sampledMutationRates[i]) / 2 *
// lognormal update for mutation rates
Math.exp(globalLearningRate + tau * random.nextGaussian());
// important: prevent mutation rates from growing to infinity
offspring.mutationRates[i] = Math.min(newMutationRate, mutationRateConstraints[i]);
// generate offspring features
offspring.features[i] = features[i]; // in case fail to bound
double newFeatureValue;
for (int j = 0; j < boundingTries; j++)
{
// try generating new feature value and check whether it is
// in bounds
newFeatureValue = features[i] + newMutationRate * random.nextGaussian();
if (objective.inBounds(newFeatureValue, i))
{
offspring.features[i] = newFeatureValue;
break;
}
}
}
return offspring;
}
/**
* Evaluates given solution using objective function and constraints
* specified in parent {@code SRES} algorithm.
*/
void evaluate()
{
objectiveResult = objective.evaluate(features);
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "SOLUTION " + Arrays.toString(features) + ",fitness is " + getFitness() + ", penalty is " + getPenalty() + "\n" + (objectiveResult == null ? "OBJECTIVE NOT EVALUATED" : objectiveResult.toString());
}
}
}