code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static <R> ImmutableGrid<R> copyOf(Grid<R> grid) {
if (grid == null) {
throw new IllegalArgumentException("Grid must not be null");
}
if (grid instanceof ImmutableGrid) {
return (ImmutableGrid<R>) grid;
}
validateCounts(grid.rowCount(), grid.columnCount());
if (grid.size() == 0) {
return new EmptyGrid<R>(grid.rowCount(), grid.columnCount());
}
if (grid.size() == 1) {
Cell<R> cell = grid.cells().iterator().next();
return new SingletonGrid<R>(grid.rowCount(), grid.columnCount(), cell);
}
if (grid.size() >= (grid.rowCount() * grid.columnCount() / 2)) {
return DenseImmutableGrid.create(grid);
}
return new SparseImmutableGrid<R>(grid);
} | Obtains an immutable grid by copying another grid.
<p>
If you need to change the row-column count, use {@link #copyOf(int, int, Iterable)}
passing in the set of cells from the grid.
@param <R> the type of the value
@param grid the grid to copy, not null
@return the immutable grid, not null
@throws IndexOutOfBoundsException if either index is less than zero |
@Override
public Tensor forward() {
Tensor x = modIn.getOutput();
y = new Tensor(s, 1);
y.setValue(0, x.getSum());
return y;
} | Foward pass: y = \sum_{i=1}^n x_i |
@Override
public void backward() {
Tensor xAdj = modIn.getOutputAdj();
xAdj.add(yAdj.getValue(0));
} | Backward pass: dG/dx_i = dG/dy dy/dx_i = dG/dy |
public FgInferencer decode(FgModel model, UFgExample ex) {
// Run inference.
FactorGraph fgLatPred = ex.getFactorGraph();
fgLatPred.updateFromModel(model);
FgInferencer infLatPred = prm.infFactory.getInferencer(fgLatPred);
infLatPred.run();
decode(infLatPred, ex);
return infLatPred;
} | Runs inference and computes the MBR variable configuration. The outputs
are stored on the class, and can be queried after this call to decode.
@param model The input model.
@param ex The input data.
@return the FgInferencer that was used. |
public void decode(FgInferencer infLatPred, UFgExample ex) {
FactorGraph fgLatPred = ex.getFactorGraph();
mbrVarConfig = new VarConfig();
margs = new ArrayList<VarTensor>();
varMargMap = new HashMap<Var,Double>();
// Get the MBR configuration of all the latent and predicted
// variables.
if (prm.loss == Loss.L1 || prm.loss == Loss.MSE) {
for (int varId = 0; varId < fgLatPred.getNumVars(); varId++) {
Var var = fgLatPred.getVar(varId);
VarTensor marg = infLatPred.getMarginalsForVarId(varId);
margs.add(marg);
int argmaxState = marg.getArgmaxConfigId();
mbrVarConfig.put(var, argmaxState);
varMargMap.put(var, marg.getValue(argmaxState));
if (log.isTraceEnabled()) {
log.trace("Variable marginal: " + marg);
}
}
} else {
throw new RuntimeException("Loss type not implemented: " + prm.loss);
}
} | Computes the MBR variable configuration from the marginals cached in the
inferencer, which is assumed to have already been run. The outputs are
stored on the class, and can be queried after this call to decode. |
public Map<Var, VarTensor> getVarMarginalsIndexed() {
Map<Var, VarTensor> m = new HashMap<Var, VarTensor>();
for(VarTensor df : margs) {
assert df.getVars().size() == 1;
m.put(df.getVars().get(0), df);
}
return m;
} | Convenience wrapper around getVarMarginals().
Does not memoize, so use sparingly. |
protected AttributeList getAttributeList() throws IOException {
int i;
int quote;
String name = null;
String value = null;
StringBuilder buffer = new StringBuilder();
Map<String, String> attributes = new LinkedHashMap<String, String>();
Stream stream = this.stream;
while(true) {
// skip invalid character
while((i = stream.peek()) != Stream.EOF) {
if(Character.isLetter(i) || Character.isDigit(i) || i == ':' || i == '-' || i == '_' || i == '%' || i == '/' || i == '>') {
break;
}
else {
stream.read();
}
}
// check end
if(i == Stream.EOF) {
break;
}
if(i == '>') {
break;
}
else if(i == '%' || i == '/') {
if(stream.peek(1) == '>') {
break;
}
continue;
}
else {
}
// read name
while((i = stream.peek()) != -1) {
if(Character.isLetter(i) || Character.isDigit(i) || i == ':' || i == '-' || i == '_') {
buffer.append((char)i);
stream.read();
}
else {
break;
}
}
name = buffer.toString();
buffer.setLength(0);
if(name.length() < 1) {
continue;
}
this.stream.skipWhitespace();
i = this.stream.peek();
// next character must be '='
if(i != '=') {
attributes.put(name, "");
continue;
}
else {
this.stream.read();
}
this.stream.skipWhitespace();
i = stream.peek();
if(i == '"') {
quote = '"';
stream.read();
}
else if(i == '\'') {
quote = '\'';
stream.read();
}
else {
quote = ' ';
}
if(quote == ' ') {
value = this.getAttributeValue(buffer);
}
else {
value = this.getAttributeValue(buffer, quote);
}
attributes.put(name, value);
buffer.setLength(0);
}
this.stream.skipWhitespace();
return this.getAttributeList(attributes);
} | read node name, after read nodeName
@return String
@throws IOException |
public final double getScore(int s, int t, int d, int ic) {
return scores[getIndex(s, t, d, ic)];
} | TODO: Consider using this method and making chart/bps private. |
@SuppressWarnings("unchecked")
private static List<Object> filterConstantMsgs(List<Object> order, FactorGraph fg) {
ArrayList<Object> filt = new ArrayList<Object>();
for (Object item : order) {
if (item instanceof List) {
List<Object> items = filterConstantMsgs((List<Object>) item, fg);
if (items.size() > 0) {
filt.add(items);
}
} else if (item instanceof Integer) {
// If the parent node is not a leaf.
if (!isConstantMsg((Integer) item, fg)) {
filt.add(item);
}
} else if (item instanceof GlobalFactor) {
filt.add(item);
} else {
throw new RuntimeException("Invalid type in order: " + item.getClass());
}
}
return filt;
} | Filters edges from a leaf node. |
public static boolean isConstantMsg(int edge, FactorGraph fg) {
BipartiteGraph<Var,Factor> bg = fg.getBipgraph();
int numNbs = bg.isT1T2(edge) ? bg.numNbsT1(bg.parentE(edge)) : bg.numNbsT2(bg.parentE(edge));
return numNbs == 1;
} | Returns true iff the edge corresponds to a message which is constant (i.e. sent from a leaf
node). |
@Override
public void backward() {
// TODO: This is less numerically stable than the O(n^2) method of
// multiplying \prod_{j=1}^{i-1} x_j \prod_{j+1}^n x_j
Tensor x = modIn.getOutput();
Tensor xAdj = modIn.getOutputAdj();
Tensor tmp = new Tensor(xAdj); // copy
tmp.fill(yAdj.getValue(0));
tmp.multiply(y.getValue(0));
tmp.elemDivide(x);
xAdj.elemAdd(tmp);
} | Backward pass: dG/dx_i += dG/dy dy/dx_i = dG/dy \prod_{j \neq i} x_j |
public String getAsPennTreebankString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
getAsPennTreebankString(1, 1, sb);
sb.append(")");
return sb.toString();
} | Gets a string representation of this parse that looks like the typical
Penn Treebank style parse.
Example:
((ROOT (S (NP (NN time))
(VP (VBZ flies)
(PP (IN like)
(NP (DT an)
(NN arrow)))))))
@return A string representing this parse. |
public static IntNaryTree readTreeInPtbFormat(IntObjectBimap<String> lexAlphabet, IntObjectBimap<String> ntAlphabet, Reader reader) throws IOException {
QFiles.readUntilCharacter(reader, '(');
IntNaryTree root = IntNaryTree.readSubtreeInPtbFormat(lexAlphabet, ntAlphabet, reader);
QFiles.readUntilCharacter(reader, ')');
if (root == null) {
return null;
}
root.updateStartEnd();
return root;
} | Reads a full tree in Penn Treebank format. Such a tree should include an
outer set of parentheses. The returned tree will have initialized the
start/end fields. |
private static IntNaryTree readSubtreeInPtbFormat(IntObjectBimap<String> lexAlphabet, IntObjectBimap<String> ntAlphabet, Reader reader) throws IOException {
ReaderState state = ReaderState.START;
StringBuilder symbolSb = new StringBuilder();
ArrayList<IntNaryTree> children = null;
boolean isLexical = false;
char[] cbuf = new char[1];
while (reader.read(cbuf) != -1) {
//for (int i=0; i<treeStr.length(); i++) {
//char c = treeStr.charAt(i);
char c = cbuf[0];
if (state == ReaderState.START) {
if (c == '(') {
state = ReaderState.NONTERMINAL;
} else if (c == ')') {
// This was the tail end of a tree.
break;
} else if (!isWhitespace(c)) {
symbolSb.append(c);
state = ReaderState.LEXICAL;
isLexical = true;
}
} else if (state == ReaderState.LEXICAL) {
if (isWhitespace(c) || c == ')') {
state = ReaderState.DONE;
break;
} else {
symbolSb.append(c);
}
} else if (state == ReaderState.NONTERMINAL) {
if (isWhitespace(c)) {
state = ReaderState.CHILDREN;
children = readTreesInPtbFormat(lexAlphabet, ntAlphabet, reader);
state = ReaderState.DONE;
break;
} else {
symbolSb.append(c);
}
} else {
throw new IllegalStateException("Invalid state: " + state);
}
}
if (state != ReaderState.DONE) {
// This reader did not start with a valid PTB style tree.
return null;
}
int start = NOT_INITIALIZED;
int end = NOT_INITIALIZED;
IntObjectBimap<String> alphabet = (isLexical ? lexAlphabet : ntAlphabet);
String symbolStr = symbolSb.toString();
String l = isLexical ? symbolStr : symbolStr;
int symbol = alphabet.lookupIndex(l);
if (symbol == -1) {
throw new IllegalStateException("Unknown "
+ (isLexical ? "word" : "nonterminal") + ": "
+ symbolSb.toString());
}
IntNaryTree root = new IntNaryTree(symbol, start, end, children, isLexical, alphabet);
return root;
} | Reads an NaryTreeNode from a string.
Example:
(NP (DT the) (NN board) )
Note that the resulting tree will NOT have the start/end fields initialized.
@param lexAlphabet TODO
@param ntAlphabet
@param reader
@return
@throws IOException |
public ArrayList<IntNaryTree> getLeaves() {
LeafCollector leafCollector = new LeafCollector();
postOrderTraversal(leafCollector);
return leafCollector.leaves;
} | Gets the leaves of this tree in left-to-right order. |
public void postOrderFilterNodes(final NaryTreeNodeFilter filter) {
postOrderTraversal(new FnO1ToVoid<IntNaryTree>() {
@Override
public void call(IntNaryTree node) {
if (!node.isLeaf()) {
ArrayList<IntNaryTree> filtChildren = new ArrayList<IntNaryTree>();
for (IntNaryTree child : node.children) {
if (filter.accept(child)) {
filtChildren.add(child);
}
}
node.children = filtChildren;
}
}
});
updateStartEnd();
} | Keep only those nodes which the filter accepts. |
public int[] getSentenceIds() {
ArrayList<IntNaryTree> leaves = getLeaves();
int[] sent = new int[leaves.size()];
for (int i=0; i<sent.length; i++) {
sent[i] = leaves.get(i).symbol;
}
return sent;
} | Gets the lexical item ids comprising the sentence. |
public IntBinaryTree leftBinarize(IntObjectBimap<String> ntAlphabet) {
IntObjectBimap<String> alphabet = isLexical ? this.alphabet : ntAlphabet;
// Reset the symbol id according to the new alphabet.
int symbol = alphabet.lookupIndex(getSymbolLabel());
IntBinaryTree leftChild;
IntBinaryTree rightChild;
if (isLeaf()) {
leftChild = null;
rightChild = null;
} else if (children.size() == 1) {
leftChild = children.get(0).leftBinarize(ntAlphabet);
rightChild = null;
} else if (children.size() == 2) {
leftChild = children.get(0).leftBinarize(ntAlphabet);
rightChild = children.get(1).leftBinarize(ntAlphabet);
} else {
// Define the label of the new parent node as in the Berkeley grammar.
int xbarParent = alphabet.lookupIndex(GrammarConstants
.getBinarizedTag(getSymbolStr()));
LinkedList<IntNaryTree> queue = new LinkedList<IntNaryTree>(children);
// Start by binarizing the left-most child, and store as L.
leftChild = queue.removeFirst().leftBinarize(ntAlphabet);
while (true) {
// Working left-to-right, remove and binarize the next-left-most child, and store as R.
rightChild = queue.removeFirst().leftBinarize(ntAlphabet);
// Break once we've acquired the right-most child.
if (queue.isEmpty()) {
break;
}
// Then form a new binary node that has left/right children: L and R.
// That is, a node (@symbolStr --> (L) (R)).
// Store this new node as L and repeat.
leftChild = new IntBinaryTree(xbarParent, leftChild.getStart(),
rightChild.getEnd(), leftChild, rightChild, isLexical,
alphabet);
}
}
return new IntBinaryTree(symbol, start, end, leftChild, rightChild , isLexical, alphabet);
} | Get a left-binarized form of this tree.
This returns a binarized form that relabels the nodes just as in the
Berkeley parser.
@param ntAlphabet The alphabet to use for the non-lexical nodes. |
public VarConfig getGoldConfigPred(int factorId) {
VarSet vars = fgLatPred.getFactor(factorId).getVars();
return goldConfig.getIntersection(VarSet.getVarsOfType(vars, VarType.PREDICTED));
} | Gets the gold configuration of the predicted variables ONLY for the given factor. |
public int getGoldConfigIdxPred(int factorId) {
VarSet vars = VarSet.getVarsOfType(fgLatPred.getFactor(factorId).getVars(), VarType.PREDICTED);
return goldConfig.getConfigIndexOfSubset(vars);
} | Gets the gold configuration index of the predicted variables for the given factor. |
protected void clip(Node node, int type) {
if(node.getNodeType() != NodeType.TEXT) {
return;
}
char c;
int j = 0;
String content = node.getTextContent();
if(type == 1) {
/**
* 删除该文本节点的后缀空格
* 也就是删除下�?��标签节点的前导空�? * 只删除空格不删除其他不可见字�? */
for(j = content.length() - 1; j > -1; j--) {
c = content.charAt(j);
if(c == ' ' || c == '\t') {
continue;
}
else {
break;
}
}
content = content.substring(0, j + 1);
}
else {
/**
* 删除该文本节点的前导回车
* 也就是删除前�?��标签节点的后�?���? * 只删除回车不删除其他不可见字�? */
int length = content.length();
for(j = 0; j < length; j++) {
c = content.charAt(j);
if(c == '\r') {
continue;
}
else if(c == '\n') {
j++;
break;
}
else {
break;
}
}
if(j <= length) {
content = content.substring(j, length);
}
}
((TextNode)node).setTextContent(content);
} | type == 1 prefix clip
type == 2 suffix clip
@param node
@param type |
public byte[] encrypt(String keyId, byte[] message) {
final Key key = keyMap.get(keyId);
if (key == null) {
throw new AsymmetricEncryptionException("key not found: keyId=" + keyId);
}
try {
final Cipher cipher = (((provider == null) || (provider.length() == 0)) ? Cipher.getInstance(algorithm) : Cipher
.getInstance(algorithm, provider));
switch (mode) {
case ENCRYPT:
cipher.init(Cipher.ENCRYPT_MODE, key);
break;
case DECRYPT:
cipher.init(Cipher.DECRYPT_MODE, key);
break;
default:
throw new AsymmetricEncryptionException("error encrypting/decrypting message: invalid mode; mode="
+ mode);
}
return cipher.doFinal(message);
} catch (Exception e) {
throw new AsymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
}
} | Encrypts/decrypts a message based on the underlying mode of operation.
@param keyId the key id
@param message if in encryption mode, the clear-text message, otherwise
the message to decrypt
@return if in encryption mode, the encrypted message, otherwise the
decrypted message
@throws AsymmetricEncryptionException on runtime errors
@see #setMode(Mode) |
public static boolean childContains(double[][] child, double value, double delta) {
for (int i=0; i<child.length; i++) {
for (int j=0; j<child.length; j++) {
if (i == j) { continue; }
if (Primitives.equals(child[i][j], value, delta)) {
return true;
}
}
}
return false;
} | Safely checks whether the child array contains a value -- ignoring diagonal entries. |
public static Tensor edgeScoresToTensor(EdgeScores es, Algebra s) {
int n = es.child.length;
Tensor m = new Tensor(s, n, n);
for (int p = -1; p < n; p++) {
for (int c = 0; c < n; c++) {
if (p == c) { continue; }
int pp = getTensorParent(p, c);
m.set(es.getScore(p, c), pp, c);
}
}
return m;
} | Convert an EdgeScores object to a Tensor, where the wall node is indexed as position n+1 in the Tensor.
@param s TODO |
public static EdgeScores tensorToEdgeScores(Tensor t) {
if (t.getDims().length != 2) {
throw new IllegalArgumentException("Tensor must be an nxn matrix.");
}
int n = t.getDims()[1];
EdgeScores es = new EdgeScores(n, 0);
for (int p = -1; p < n; p++) {
for (int c = 0; c < n; c++) {
if (p == c) { continue; }
int pp = getTensorParent(p, c);
es.setScore(p, c, t.get(pp, c));
}
}
return es;
} | Convert a Tensor object to an EdgeScores, where the wall node is indexed as position n+1 in the Tensor. |
public static double[][] combine(double[] fracRoot, double[][] fracChild) {
int nplus = fracChild.length + 1;
double[][] scores = new double[nplus][nplus];
for (int p=0; p<nplus; p++) {
for (int c=0; c<nplus; c++) {
if (c == 0) {
scores[p][c] = Double.NEGATIVE_INFINITY;
} else if (p == 0 && c > 0) {
scores[p][c] = fracRoot[c-1];
} else {
scores[p][c] = fracChild[p-1][c-1];
}
}
}
return scores;
} | Combines a set of edge weights represented as wall and child weights into a single set of
weights. The combined weights are indexed such that the wall has index 0 and the tokens of
the sentence are 1-indexed.
@param fracRoot The edge weights from the wall to each child.
@param fracChild The edge weights from parent to child.
@return The combined weights. |
public static FactorGraph getFgLat(FactorGraph fgLatPred, VarConfig goldConfig) {
// TODO: instead, have this just look at whether or not the var is in the gold config
List<Var> predictedVars = VarSet.getVarsOfType(fgLatPred.getVars(), VarType.PREDICTED);
VarConfig predConfig = goldConfig.getIntersection(predictedVars);
FactorGraph fgLat = fgLatPred.getClamped(predConfig);
assert (fgLatPred.getNumFactors() <= fgLat.getNumFactors());
return fgLat;
} | Get a copy of the factor graph where the predicted variables are clamped.
@param fgLatPred The original factor graph.
@param goldConfig The assignment to the predicted variables.
@return The clamped factor graph. |
public static FeatureVector getExpectedFeatureCounts(FgExampleList data, FgInferencerFactory infFactory, FgModel model, double[] params) {
model.updateModelFromDoubles(params);
FgModel feats = model.getDenseCopy();
feats.zero();
for (int i=0; i<data.size(); i++) {
LFgExample ex = data.get(i);
FactorGraph fgLatPred = ex.getFactorGraph();
fgLatPred.updateFromModel(model);
FgInferencer infLatPred = infFactory.getInferencer(fgLatPred);
infLatPred.run();
addExpectedPartials(fgLatPred, infLatPred, 1.0 * ex.getWeight(), feats);
}
double[] f = new double[model.getNumParams()];
feats.updateDoublesFromModel(f);
return new FeatureVector(f);
} | Gets the "expected" feature counts. |
public static FeatureVector getObservedFeatureCounts(FgExampleList data, FgInferencerFactory infFactory, FgModel model, double[] params) {
model.updateModelFromDoubles(params);
FgModel feats = model.getDenseCopy();
feats.zero();
for (int i=0; i<data.size(); i++) {
LFgExample ex = data.get(i);
FactorGraph fgLat = getFgLat(ex.getFactorGraph(), ex.getGoldConfig());
fgLat.updateFromModel(model);
FgInferencer infLat = infFactory.getInferencer(fgLat);
infLat.run();
addExpectedPartials(fgLat, infLat, 1.0 * ex.getWeight(), feats);
}
double[] f = new double[model.getNumParams()];
feats.updateDoublesFromModel(f);
return new FeatureVector(f);
} | Gets the "observed" feature counts. |
static void addExpectedPartials(FactorGraph fg, FgInferencer inferencer, double multiplier, IFgModel gradient) {
// For each factor...
for (int factorId=0; factorId<fg.getNumFactors(); factorId++) {
Factor f = fg.getFactor(factorId);
if (f instanceof GlobalFactor) {
((GlobalFactor) f).addExpectedPartials(gradient, multiplier, inferencer, factorId);
} else {
VarTensor marg = inferencer.getMarginalsForFactorId(factorId);
f.addExpectedPartials(gradient, marg, multiplier);
}
}
} | Computes the expected partials (i.e. feature counts for exponential family factors) for a
factor graph, and adds them to the gradient after scaling them.
@param fg The factor graph.
@param inferencer The inferencer for a clamped factor graph, which has already been run.
@param multiplier The value which the expected partials will be multiplied by.
@param gradient The OUTPUT gradient vector to which the scaled expected partials will be
added. |
@SuppressWarnings("unchecked")
static <V> DenseImmutableGrid<V> create(Grid<? extends V> grid) {
if (grid instanceof DenseGrid) {
return new DenseImmutableGrid<V>((DenseGrid<V>) grid);
}
int rowCount = grid.rowCount();
int columnCount = grid.columnCount();
validateCounts(rowCount, columnCount);
V[] values = (V[]) new Object[rowCount * columnCount];
for (Cell<? extends V> cell : grid.cells()) {
values[cell.getRow() * columnCount + cell.getColumn()] = cell.getValue();
}
return new DenseImmutableGrid<V>(rowCount, columnCount, grid.size(), values);
} | Creates a {@code DenseImmutableGrid} copying from another grid.
@param <V> the type of the value
@param grid the grid to copy, not null
@return the mutable grid, not null |
@Override
@SuppressWarnings("unchecked")
public ImmutableCollection<V> values() {
Object[] array = new Object[size];
int index = 0;
for (Object object : values) {
if (object != null) {
array[index++] = object;
}
}
return ImmutableList.copyOf((V[]) array);
} | ----------------------------------------------------------------------- |
@Override
public List<V> row(int row) {
Preconditions.checkElementIndex(row, rowCount(), "Row index");
int base = row * rowCount;
return new Inner<V>(this, base, columnCount, 1);
} | ----------------------------------------------------------------------- |
public static int choose(int n, int k) {
assert(n >= k);
double val = 1;
for (int i=1; i<=k; i++) {
val *= (n - (k-i))/(double)i;
}
return (int)val;
} | N choose K |
public static long binomialCoefficient(int n, int k)
{
if(n - k == 1 || k == 1)
return n;
long [][] b = new long[n+1][n-k+1];
b[0][0] = 1;
for(int i = 1; i < b.length; i++)
{
for(int j = 0; j < b[i].length; j++)
{
if(i == j || j == 0)
b[i][j] = 1;
else if(j == 1 || i - j == 1)
b[i][j] = i;
else
b[i][j] = b[i-1][j-1] + b[i-1][j];
}
}
return b[n][n-k];
} | N choose K |
public PublicKey get(KeyStoreChooser keyStoreChooser, PublicKeyChooserByAlias publicKeyChooserByAlias) {
CacheKey cacheKey = new CacheKey(keyStoreChooser.getKeyStoreName(), publicKeyChooserByAlias.getAlias());
PublicKey retrievedPublicKey = cache.get(cacheKey);
if (retrievedPublicKey != null) {
return retrievedPublicKey;
}
KeyStore keyStore = keyStoreRegistry.get(keyStoreChooser);
if (keyStore != null) {
PublicKeyFactoryBean factory = new PublicKeyFactoryBean();
factory.setKeystore(keyStore);
factory.setAlias(publicKeyChooserByAlias.getAlias());
try {
factory.afterPropertiesSet();
PublicKey publicKey = (PublicKey) factory.getObject();
if (publicKey != null) {
cache.put(cacheKey, publicKey);
}
return publicKey;
} catch (Exception e) {
throw new PublicKeyException("error initializing the public key factory bean", e);
}
}
return null;
} | Returns the selected public key or null if not found.
@param keyStoreChooser the keystore chooser
@param publicKeyChooserByAlias the public key chooser by alias
@return the selected public key or null if not found |
protected SFSDataWrapper transformNotNullValue(Object object) {
Object value = serializeObject(object);
if(value instanceof Parameters)
return transformParams((Parameters)value);
if(value instanceof Parameters[])
return transformParamsArray((Parameters[])value);
return super.transformNotNullValue(value);
} | /*
(non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.data.impl.SimpleTransformer#transformNotNullValue(java.lang.Object) |
public void add(N node) {
if (! node.added) {
nodes.add(node);
node.added = true;
}
} | Adds the node if it's not already present in the graph. |
public void add(E edge) {
if (! edge.added) {
edges.add(edge);
edge.added = true;
add(edge.getChild());
add(edge.getParent());
}
} | Adds the edge and its nodes if not already present in the graph. |
public void remove(E edge) {
if (! edge.added){
return;
}
boolean contained;
contained = edges.remove(edge);
assert(contained);
contained = edge.getChild().inEdges.remove(edge);
assert(contained);
contained = edge.getParent().outEdges.remove(edge);
assert(contained);
edge.added = false;
} | Removes an edge if it was in the graph. Does not remove its parent/child nodes. |
public List<N> getConnectedComponents() {
setMarkedAllNodes(false);
ArrayList<N> roots = new ArrayList<N>();
//for (int i=0; i<nodes.size(); i++) {
for (N n : nodes) {
if (!n.isMarked()) {
roots.add(n);
dfs(n);
}
}
return roots;
} | Gets the connected components of the graph.
@return A list containing an arbitrary node in each each connected component. |
private void dfs(Node root) {
root.setMarked(true);
for (Edge e : root.getOutEdges()) {
N n = e.getChild();
if (!n.isMarked()) {
dfs(n);
}
}
} | Runs depth-first search on the graph starting at node n, marking each node as it is encountered.
@param root |
public List<N> bfs(N root) {
List<N> order = new ArrayList<>();
Queue<N> queue = new ArrayDeque<>();
queue.add(root);
// Unmark all the nodes.
this.setMarkedAllNodes(false);
while (!queue.isEmpty()) {
// Process the next node in the queue.
N node = queue.remove();
if (!node.isMarked()) {
// Add node only if not marked.
order.add(node);
node.setMarked(true);
}
// For each neighbor...
for (E edge : node.getOutEdges()) {
N neighbor = edge.getChild();
if (!neighbor.isMarked()) {
// Queue if not marked.
queue.add(neighbor);
}
}
}
return order;
} | Runs a breadth-first-search starting at the root node. |
public void preOrderTraversal(N root, Visitor<N> v) {
setMarkedAllNodes(false);
preOrderTraveralRecursive(root, v);
} | Visits the nodes in a pre-order traversal. |
public static void initDefaultPool(int numThreads, boolean isDaemon) {
if (numThreads == 1) {
Threads.defaultPool = MoreExecutors.newDirectExecutorService();
Threads.numThreads = 1;
} else {
log.info("Initialized default thread pool to {} threads. (This must be closed by Threads.shutdownDefaultPool)", numThreads);
Threads.defaultPool = Executors.newFixedThreadPool(numThreads, new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(isDaemon);
return t;
}
});
Threads.numThreads = numThreads;
// Shutdown the thread pool on System.exit().
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
Threads.shutdownDefaultPool();
}
});
}
} | Initializes the default thread pool and adds a shutdown hook which will attempt to shutdown
the thread pool on a call to System.exit().
If numThreads > 1 and isDaemon = true, then System.exit() or Threads.shutdownDefaultPool()
must be explicitly called. Otherwise, the JVM may hang.
@param numThreads The number of threads.
@param isDaemon Whether the thread pool should consist of daemon threads. |
public static <T> List<Future<T>> invokeAndAwaitAll(ExecutorService pool, List<Callable<T>> tasks) {
List<Future<T>> futures = executeAll(pool, tasks);
awaitAll(pool, futures);
return futures;
} | /* ------------------- Functions using a given pool ----------------- |
@Override
public void backward() {
Tensor x = modInX.getOutput();
double w_k = modInW.getOutput().getValue(k);
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.multiply(w_k);
modInX.getOutputAdj().elemAdd(tmp);
}
{
Tensor tmp = new Tensor(yAdj); // copy
tmp.elemMultiply(x);
modInW.getOutputAdj().addValue(k, tmp.getSum());
}
} | Backward pass:
dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i w_k
dG/dw_k += \sum_{i=1}^n dG/dy_i dy_i/dw_k = \sum_{i=1}^n dG/dy_i x_i |
private void checkCell(int start, int end) {
if (start > nplus - 1 || end > nplus || start < 0 || end < 1) {
throw new IllegalStateException(String.format("Invalid cell: start=%d end=%d", start, end));
}
} | Checks that start \in [0, n-1] and end \in [1, n], where nplus is the sentence length plus 1. |
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<ApiBuddy> execute() {
BuddyList buddyList = extension.getParentZone()
.getBuddyListManager()
.getBuddyList(user);
return (List) buddyList.getBuddies();
} | /*
(non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountAuthenticatorResponse =
getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
if (mAccountAuthenticatorResponse != null) {
mAccountAuthenticatorResponse.onRequestContinued();
}
} | Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
icicle is non-zero.
@param icicle the save instance data of this Activity, may be null |
public void finish() {
if (mAccountAuthenticatorResponse != null) {
// send the result bundle back if set, otherwise send an error.
if (mResultBundle != null) {
mAccountAuthenticatorResponse.onResult(mResultBundle);
} else {
mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
"canceled");
}
mAccountAuthenticatorResponse = null;
}
super.finish();
} | Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present. |
private Tensor forwardAllEdgesClamped(Tensor tmFalseIn, Tensor tmTrueIn) {
// Compute the product of all non-zero incoming messages.
Algebra s = tmFalseIn.getAlgebra();
double prod = s.one();
for (int c=0; c<tmFalseIn.size(); c++) {
if (tmFalseIn.getValue(c) != s.zero()) {
prod = s.times(prod, tmFalseIn.getValue(c));
} else {
prod = s.times(prod, tmTrueIn.getValue(c));
}
}
log.trace("prod: {}", prod);
// For each outgoing message, return zero or the product dividing out the non-zero message.
Tensor out = new Tensor(s, 2, tmFalseIn.getDim(0), tmFalseIn.getDim(1));
for (int i=0; i<out.getDim(1); i++) {
for (int j=0; j<out.getDim(2); j++) {
if (tmFalseIn.get(i,j) != s.zero()) {
out.set(s.divide(prod, tmFalseIn.get(i,j)), 0, i, j);
out.set(s.zero(), 1, i, j);
} else if (tmTrueIn.get(i,j) != s.zero()) {
out.set(s.zero(), 0, i, j);
out.set(s.divide(prod, tmTrueIn.get(i,j)), 1, i, j);
} else {
out.set(s.zero(), 0, i, j);
out.set(s.zero(), 1, i, j);
}
log.trace("out[0][{}][{}] = {}", i, j, out.get(0, i, j));
log.trace("out[1][{}][{}] = {}", i, j, out.get(1, i, j));
assert !s.isNaN(out.get(0, i,j));
assert !s.isNaN(out.get(1, i,j));
}
}
comb = new Identity<Tensor>(out);
return out;
} | Special case: all edges are clamped to a specific value.
We only implement the forward pass for this case.
@param tmTrueIn
@param tmFalseIn |
public static boolean containsZeros(Tensor tmFalseIn) {
Algebra s = tmFalseIn.getAlgebra();
for (int c=0; c<tmFalseIn.size(); c++) {
if (tmFalseIn.getValue(c) == s.zero()) {
return true;
}
}
return false;
} | Returns true if the tensor contains zeros. |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
api.unsubscribeRoomGroup(CommandUtil.getSfsUser(user, api), groupId);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
@SuppressWarnings("unchecked")
@Override
public String execute() {
User sfsUser = CommandUtil.getSfsUser(username, api);
return (sfsUser == null) ? "" : sfsUser.getIpAddress();
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public static final void parseSentence(final int[] sent, final CnfGrammar grammar, final LoopOrder loopOrder, final Chart chart, final Scorer scorer) {
// Apply lexical rules to each word.
for (int i = 0; i <= sent.length - 1; i++) {
ChartCell cell = chart.getCell(i, i+1);
for (final Rule r : grammar.getLexicalRulesWithChild(sent[i])) {
double score = scorer.score(r, i, i+1, i+1);
cell.updateCell(r.getParent(), score, i+1, r);
}
}
// For each cell in the chart. (width increasing)
for (int width = 1; width <= sent.length; width++) {
for (int start = 0; start <= sent.length - width; start++) {
int end = start + width;
ChartCell cell = chart.getCell(start, end);
// Apply binary rules.
if (loopOrder == LoopOrder.CARTESIAN_PRODUCT) {
processCellCartesianProduct(grammar, chart, start, end, cell, scorer);
} else if (loopOrder == LoopOrder.LEFT_CHILD) {
processCellLeftChild(grammar, chart, start, end, cell, scorer);
} else if (loopOrder == LoopOrder.RIGHT_CHILD) {
processCellRightChild(grammar, chart, start, end, cell, scorer);
} else {
throw new RuntimeException("Not implemented: " + loopOrder);
}
processCellUnaryRules(grammar, start, end, cell, scorer);
if (width == sent.length) {
processCellUnaryRules(grammar, start, end, cell, scorer);
}
cell.close();
}
}
} | Runs CKY and populates the chart.
@param sent The input sentence.
@param grammar The input grammar.
@param loopOrder The loop order to use when parsing.
@param chart The output chart. |
private static final void processCellUnaryRules(final CnfGrammar grammar, final int start, final int end,
final ChartCell cell, final Scorer scorer) {
// Apply unary rules.
ScoresSnapshot scoresSnapshot = cell.getScoresSnapshot();
int[] nts = cell.getNts();
for(final int parentNt : nts) {
for (final Rule r : grammar.getUnaryRulesWithChild(parentNt)) {
double score = scorer.score(r, start, end, end)
+ scoresSnapshot.getScore(r.getLeftChild());
cell.updateCell(r.getParent(), score, end, r);
}
}
} | Process a cell, unary rules only. |
private static final void processCellCartesianProduct(final CnfGrammar grammar, final Chart chart, final int start,
final int end, final ChartCell cell, final Scorer scorer) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through all possible pairs of left/right non-terminals.
for (final int leftChildNt : leftCell.getNts()) {
double leftScoreForNt = leftCell.getScore(leftChildNt);
for (final int rightChildNt : rightCell.getNts()) {
double rightScoreForNt = rightCell.getScore(rightChildNt);
// Lookup the rules with those left/right children.
for (final Rule r : grammar.getBinaryRulesWithChildren(leftChildNt, rightChildNt)) {
double score = scorer.score(r, start, mid, end)
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(r.getParent(), score, mid, r);
}
}
}
}
} | Process a cell (binary rules only) using the Cartesian product of the children's rules.
This follows the description in (Dunlop et al., 2010). |
private static final void processCellLeftChild(final CnfGrammar grammar, final Chart chart, final int start,
final int end, final ChartCell cell, final Scorer scorer) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through each left child non-terminal.
for (final int leftChildNt : leftCell.getNts()) {
double leftScoreForNt = leftCell.getScore(leftChildNt);
// Lookup all rules with that left child.
for (final Rule r : grammar.getBinaryRulesWithLeftChild(leftChildNt)) {
// Check whether the right child of that rule is in the right child cell.
double rightScoreForNt = rightCell.getScore(r.getRightChild());
if (rightScoreForNt > Double.NEGATIVE_INFINITY) {
double score = scorer.score(r, start, mid, end)
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(r.getParent(), score, mid, r);
}
}
}
}
} | Process a cell (binary rules only) using the left-child to constrain the set of rules we consider.
This follows the description in (Dunlop et al., 2010). |
private static final void processCellRightChild(final CnfGrammar grammar, final Chart chart, final int start,
final int end, final ChartCell cell, final Scorer scorer) {
// Apply binary rules.
for (int mid = start + 1; mid <= end - 1; mid++) {
ChartCell leftCell = chart.getCell(start, mid);
ChartCell rightCell = chart.getCell(mid, end);
// Loop through each right child non-terminal.
for (final int rightChildNt : rightCell.getNts()) {
double rightScoreForNt = rightCell.getScore(rightChildNt);
// Lookup all rules with that right child.
for (final Rule r : grammar.getBinaryRulesWithRightChild(rightChildNt)) {
// Check whether the left child of that rule is in the left child cell.
double leftScoreForNt = leftCell.getScore(r.getLeftChild());
if (leftScoreForNt > Double.NEGATIVE_INFINITY) {
double score = scorer.score(r, start, mid, end)
+ leftScoreForNt
+ rightScoreForNt;
cell.updateCell(r.getParent(), score, mid, r);
}
}
}
}
} | Process a cell (binary rules only) using the left-child to constrain the set of rules we consider.
This follows the description in (Dunlop et al., 2010). |
public static NaryTree readTreeInPtbFormat(Reader reader) throws IOException {
QFiles.readUntilCharacter(reader, '(');
NaryTree root = NaryTree.readSubtreeInPtbFormat(reader);
QFiles.readUntilCharacter(reader, ')');
if (root == null) {
return null;
}
root.updateStartEnd();
return root;
} | Reads a full tree in Penn Treebank format. Such a tree should include an
outer set of parentheses. The returned tree will have initialized the
start/end fields. |
private static NaryTree readSubtreeInPtbFormat(Reader reader) throws IOException {
ReaderState state = ReaderState.START;
StringBuilder symbolSb = new StringBuilder();
ArrayList<NaryTree> children = null;
boolean isLexical = false;
char[] cbuf = new char[1];
while (reader.read(cbuf) != -1) {
//for (int i=0; i<treeStr.length(); i++) {
//char c = treeStr.charAt(i);
char c = cbuf[0];
if (state == ReaderState.START) {
if (c == '(') {
state = ReaderState.NONTERMINAL;
} else if (c == ')') {
// This was the tail end of a tree.
break;
} else if (!isWhitespace(c)) {
symbolSb.append(c);
state = ReaderState.LEXICAL;
isLexical = true;
}
} else if (state == ReaderState.LEXICAL) {
if (isWhitespace(c) || c == ')') {
state = ReaderState.DONE;
break;
} else {
symbolSb.append(c);
}
} else if (state == ReaderState.NONTERMINAL) {
if (isWhitespace(c)) {
state = ReaderState.CHILDREN;
children = readTreesInPtbFormat(reader);
state = ReaderState.DONE;
break;
} else {
symbolSb.append(c);
}
} else {
throw new IllegalStateException("Invalid state: " + state);
}
}
if (state != ReaderState.DONE) {
// This reader did not start with a valid PTB style tree.
return null;
}
int start = NOT_INITIALIZED;
int end = NOT_INITIALIZED;
String symbol = symbolSb.toString();
NaryTree root = new NaryTree(symbol, start, end, children, isLexical);
return root;
} | Reads an NaryTreeNode from a string.
Example:
(NP (DT the) (NN board) )
Note that the resulting tree will NOT have the start/end fields initialized.
@param lexAlphabet TODO
@param ntAlphabet
@param reader
@return
@throws IOException |
public ArrayList<NaryTree> getLeaves() {
LeafCollector leafCollector = new LeafCollector();
postOrderTraversal(leafCollector);
return leafCollector.leaves;
} | Gets the leaves of this tree in left-to-right order. |
public ArrayList<NaryTree> getLexicalLeaves() {
LexicalLeafCollector leafCollector = new LexicalLeafCollector();
postOrderTraversal(leafCollector);
return leafCollector.leaves;
} | Gets the lexical leaves of this tree in left-to-right order. |
public NaryTree getLeafAt(int idx) {
NaryTree leaf = null;
for (NaryTree l : this.getLeaves()) {
if (l.start <= idx && idx < l.end) {
leaf = l;
}
}
return leaf;
} | Gets the leaf containing the specified token index. |
public int[] getSentenceIds(IntObjectBimap<String> lexAlphabet) {
ArrayList<NaryTree> leaves = getLexicalLeaves();
int[] sent = new int[leaves.size()];
for (int i=0; i<sent.length; i++) {
sent[i] = lexAlphabet.lookupIndex(leaves.get(i).symbol);
}
return sent;
} | Gets the lexical item ids comprising the sentence. |
public BinaryTree leftBinarize() {
BinaryTree leftChild;
BinaryTree rightChild;
if (isLeaf()) {
leftChild = null;
rightChild = null;
} else if (children.size() == 1) {
leftChild = children.get(0).leftBinarize();
rightChild = null;
} else if (children.size() == 2) {
leftChild = children.get(0).leftBinarize();
rightChild = children.get(1).leftBinarize();
} else {
// Define the label of the new parent node as in the Berkeley grammar.
String xbarParent = GrammarConstants.getBinarizedTag(symbol);
LinkedList<NaryTree> queue = new LinkedList<NaryTree>(children);
// Start by binarizing the left-most child, and store as L.
leftChild = queue.removeFirst().leftBinarize();
while (true) {
// Working left-to-right, remove and binarize the next-left-most child, and store as R.
rightChild = queue.removeFirst().leftBinarize();
// Break once we've acquired the right-most child.
if (queue.isEmpty()) {
break;
}
// Then form a new binary node that has left/right children: L and R.
// That is, a node (@symbolStr --> (L) (R)).
// Store this new node as L and repeat.
leftChild = new BinaryTree(xbarParent, leftChild.getStart(),
rightChild.getEnd(), leftChild, rightChild, isLexical);
}
}
return new BinaryTree(symbol, start, end, leftChild, rightChild , isLexical);
} | Get a left-binarized form of this tree.
This returns a binarized form that relabels the nodes just as in the
Berkeley parser. |
public void intern() {
symbol = symbol.intern();
if (children != null) {
for (NaryTree node : children) {
node.intern();
}
}
} | Intern all the strings. |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
BuddyClassUnwrapper unwrapper = context.getUserAgentClass(owner.getClass())
.getBuddyClass().getUnwrapper();
List<BuddyVariable> variables = buddyAgentSerializer().serialize(unwrapper, owner);
List<BuddyVariable> answer = variables;
if(includedVars.size() > 0)
answer = getVariables(variables, includedVars);
answer.removeAll(getVariables(answer, excludedVars));
try {
User sfsUser = CommandUtil.getSfsUser(owner, api);
SmartFoxServer.getInstance().getAPIManager().getBuddyApi()
.setBuddyVariables(sfsUser, answer,
fireClientEvent, fireServerEvent);
} catch (SFSBuddyListException e) {
throw new IllegalStateException(e);
}
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public static <V> DenseGrid<V> create(int rowCount, int columnCount) {
return new DenseGrid<V>(rowCount, columnCount);
} | Creates an empty {@code DenseGrid} of the specified size.
@param <V> the type of the value
@param rowCount the number of rows, zero or greater
@param columnCount the number of rows, zero or greater
@return the mutable grid, not null |
@SuppressWarnings("unchecked")
public static <V> DenseGrid<V> create(Grid<? extends V> grid) {
if (grid == null) {
throw new IllegalArgumentException("Grid must not be null");
}
if (grid instanceof DenseImmutableGrid) {
return new DenseGrid<V>((DenseImmutableGrid<V>) grid);
}
DenseGrid<V> created = DenseGrid.create(grid.rowCount(), grid.columnCount());
created.putAll(grid);
return created;
} | Creates a {@code DenseGrid} copying from another grid.
@param <V> the type of the value
@param grid the grid to copy, not null
@return the mutable grid, not null |
public static <V> DenseGrid<V> create(V[][] array) {
if (array == null) {
throw new IllegalArgumentException("Array must not be null");
}
int rowCount = array.length;
if (rowCount == 0) {
return new DenseGrid<V>(0, 0);
}
int columnCount = array[0].length;
for (int i = 1; i < rowCount; i++) {
columnCount = Math.max(columnCount, array[i].length);
}
DenseGrid<V> created = DenseGrid.create(rowCount, columnCount);
for (int row = 0; row < array.length; row++) {
V[] rowValues = array[row];
for (int column = 0; column < rowValues.length; column++) {
V cellValue = rowValues[column];
if (cellValue != null) {
created.values[row * columnCount + column] = cellValue;
created.size++;
}
}
}
return created;
} | Creates a {@code DenseGrid} copying from an array.
<p>
The row count and column count are derived from the maximum size of the array.
The grid is initialized from the non-null values.
@param <V> the type of the value
@param array the array, first by row, then by column
@return the mutable grid, not null |
@Override
public void createMessages(VarTensor[] inMsgs, VarTensor[] outMsgs) {
Identity<MVecArray<VarTensor>> modIn = new Identity<MVecArray<VarTensor>>(new MVecArray<VarTensor>(inMsgs));
MutableModule<MVecArray<VarTensor>> modOut = getCreateMessagesModule(modIn, null);
modOut.setOutput(new MVecArray<VarTensor>(outMsgs));
modOut.forward();
} | TODO: This could be put in an abstract class. |
public static LinkVar[] getVarsByDist(int head, boolean isRight, LinkVar[] rootVars, LinkVar[][] childVars) {
int dir = isRight ? 1 : -1;
int maxDist = isRight ? rootVars.length - head - 1: head - 1;
LinkVar[] varsByDist = new LinkVar[maxDist];
for (int cDist = 1; cDist <= maxDist; cDist++) {
int c = head + dir*cDist;
if (head == -1) {
varsByDist[cDist-1] = rootVars[c];
} else {
varsByDist[cDist-1] = childVars[head][c];
}
}
return varsByDist;
} | Gets the variables for this factor ordered from the head outward.
@param head The 0-indexed head (i.e. -1 denotes the wall).
@param isRight Whether or not this is a right or left head automata.
@param rootVars The link vars with the wall as parent.
@param childVars The other child variables.
@return An array of variables order by increasing distance from the head. |
@SuppressWarnings("unchecked")
@Override
public ApiBuddy execute() {
return (ApiBuddy) extension.getParentZone()
.getBuddyListManager()
.getBuddyList(owner)
.getBuddy(buddy);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
@Override
protected void init() {
Class<?>[] roomClasses = context.getRoomClasses()
.toArray(new Class[context.getRoomClasses().size()]);
handlers = new ZoneRoomHandlerCenter()
.addHandlers(handlerClasses, roomClasses);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.ServerBaseEventHandler#init() |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE);
Room sfsRoom = (Room) event.getParameter(SFSEventParam.ROOM);
notifyHandlers((ApiZone)sfsZone.getProperty(APIKey.ZONE),
(ApiRoom)sfsRoom.getProperty(APIKey.ROOM));
} | /* (non-Javadoc)
@see com.smartfoxserver.v2.extensions.IServerEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
private static int[] getDims(VarSet vars) {
int[] dims = new int[vars.size()];
for (int i=0; i<vars.size(); i++) {
dims[i] = vars.get(i).getNumStates();
}
return dims;
} | Gets the tensor dimensions: dimension i corresponds to the i'th variable, and the size of
that dimension is the number of states for the variable. |
public VarTensor getMarginal(VarSet vars, boolean normalize) {
VarSet margVars = new VarSet(this.vars);
margVars.retainAll(vars);
VarTensor marg = new VarTensor(s, margVars, s.zero());
if (margVars.size() == 0) {
return marg;
}
IntIter iter = margVars.getConfigIter(this.vars);
for (int i=0; i<this.values.length; i++) {
int j = iter.next();
marg.values[j] = s.plus(marg.values[j], this.values[i]);
}
if (normalize) {
marg.normalize();
}
return marg;
} | Gets the marginal distribution over a subset of the variables in this
factor, optionally normalized.
@param vars The subset of variables for the marginal distribution. This will sum over all variables not in this set.
@param normalize Whether to normalize the resulting distribution.
@return The marginal distribution. |
public void add(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.Add());
internalSet(newFactor);
} | Adds a factor to this one.
From libDAI:
The sum of two factors is defined as follows: if
\f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
\f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f] |
public void prod(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.Prod());
internalSet(newFactor);
} | Multiplies a factor to this one.
From libDAI:
The product of two factors is defined as follows: if
\f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
\f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f] |
public void divBP(VarTensor f) {
VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.DivBP());
internalSet(newFactor);
} | this /= f
indices matching 0 /= 0 are set to 0. |
private void internalSet(VarTensor newFactor) {
this.vars = newFactor.vars;
this.dims = newFactor.dims;
this.strides = newFactor.strides;
this.values = newFactor.values;
} | This set method is used to internally update ALL the fields. |
private static VarTensor applyBinOp(final VarTensor f1, final VarTensor f2, final AlgebraLambda.LambdaBinOp op) {
checkSameAlgebra(f1, f2);
Algebra s = f1.s;
if (f1.vars.size() == 0) {
// Return a copy of f2.
return new VarTensor(f2);
} else if (f2.vars.size() == 0) {
// Don't use the copy constructor, just return f1.
return f1;
} else if (f1.vars == f2.vars || f1.vars.equals(f2.vars)) {
// Special case where the factors have identical variable sets.
assert (f1.values.length == f2.values.length);
for (int c = 0; c < f1.values.length; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[c]);
}
return f1;
} else if (f1.vars.isSuperset(f2.vars)) {
// Special case where f1 is a superset of f2.
IntIter iter2 = f2.vars.getConfigIter(f1.vars);
int n = f1.vars.calcNumConfigs();
for (int c = 0; c < n; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[iter2.next()]);
}
assert(!iter2.hasNext());
return f1;
} else {
// The union of the two variable sets must be created.
VarSet union = new VarSet(f1.vars, f2.vars);
VarTensor out = new VarTensor(s, union);
IntIter iter1 = f1.vars.getConfigIter(union);
IntIter iter2 = f2.vars.getConfigIter(union);
int n = out.vars.calcNumConfigs();
for (int c = 0; c < n; c++) {
out.values[c] = op.call(s, f1.values[iter1.next()], f2.values[iter2.next()]);
}
assert(!iter1.hasNext());
assert(!iter2.hasNext());
return out;
}
} | Applies the binary operator to factors f1 and f2.
This method will opt to be destructive on f1 (returning it instead of a
new factor) if time/space can be saved by doing so.
Note: destructive if necessary.
@param f1 The first factor. (returned if it will save time/space)
@param f2 The second factor.
@param op The binary operator.
@return The new factor. |
private static void elemApplyBinOp(final VarTensor f1, final VarTensor f2, final AlgebraLambda.LambdaBinOp op) {
checkSameAlgebra(f1, f2);
Algebra s = f1.s;
if (f1.size() != f2.size()) {
throw new IllegalArgumentException("VarTensors are different sizes");
}
for (int c = 0; c < f1.values.length; c++) {
f1.values[c] = op.call(s, f1.values[c], f2.values[c]);
}
} | Applies the operation to each element of f1 and f2, which are assumed to be of the same size.
The result is stored in f1.
@param f1 Input factor 1 and the output factor.
@param f2 Input factor 2.
@param op The operation to apply. |
public void set(VarTensor f) {
if (!this.vars.equals(f.vars)) {
throw new IllegalStateException("The varsets must be equal.");
}
super.setValuesOnly(f);
} | TODO: Is this called, if so, it should become setValuesOnly. |
public boolean containsBadValues() {
for(int i=0; i<values.length; i++) {
if(s.isNaN(values[i])) {
return true;
}
if (s.lt(values[i], s.zero()) || values[i] == s.posInf()) {
return true;
}
}
return false;
} | TODO: Move this to BeliefPropagation.java. |
public double evaluate(List<VarConfig> goldConfigs, List<VarConfig> predictedConfigs) {
int numCorrect = 0;
int numTotal = 0;
assert (goldConfigs.size() == predictedConfigs.size());
for (int i=0; i<goldConfigs.size(); i++) {
VarConfig gold = goldConfigs.get(i);
VarConfig pred = predictedConfigs.get(i);
//assert (gold.getVars().equals(pred.getVars()));
for (Var v : gold.getVars()) {
if (v.getType() == VarType.PREDICTED) {
int goldState = gold.getState(v);
int predState = pred.getState(v);
if (goldState == predState) {
numCorrect++;
}
numTotal++;
}
}
}
return (double) numCorrect / numTotal;
} | Computes the accuracy on the PREDICTED variables. |
public void updateFromModel(FgModel model) {
initialized = true;
int numConfigs = this.getVars().calcNumConfigs();
for (int c=0; c<numConfigs; c++) {
double dot = getDotProd(c, model);
assert !Double.isNaN(dot) && dot != Double.POSITIVE_INFINITY : "Invalid value for factor: " + dot;
this.setValue(c, dot);
}
} | If this factor depends on the model, this method will updates this
factor's internal representation accordingly.
@param model The model. |
protected double getDotProd(int config, FgModel model) {
FeatureVector fv = getFeatures(config);
return model.dot(fv);
} | Provide the dot product of the features and model weights for this configuration
(make sure to exp that value if !logDomain).
Note that this method can be overridden for an efficient product of an ExpFamFactor
and a hard factor (that rules out some configurations). Just return -infinity
here before extracting features for configurations that are eliminated by the
hard factor. If you do this, the corresponding (by config) implementation of
getFeatures should return an empty vector. This is needed because addExpectedFeatureCounts
expects to be able to call getFeatures, regardless of whether or not getDotProd has
ruled it out as having any mass. |
public static Tensor getVectorFromReals(Algebra s, double... values) {
Tensor t0 = getVectorFromValues(RealAlgebra.getInstance(), values);
return t0.copyAndConvertAlgebra(s);
} | Gets a tensor in the s semiring, where the input values are assumed to be in the reals. |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
User user = (User) event.getParameter(SFSEventParam.USER);
boolean online = (Boolean)event.getParameter(SFSBuddyEventParam.BUDDY_IS_ONLINE);
updateBuddyProperties((ApiBaseUser) user.getProperty(APIKey.USER), online);
super.handleServerEvent(event);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.UserZoneEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
User sfsSender = CommandUtil.getSfsUser(sender, api);
User sfsRecipient = CommandUtil.getSfsUser(recipient, api);
if(sfsSender == null || sfsRecipient == null)
return Boolean.FALSE;
message = (message == null) ? "" : message;
ISFSObject sfsParams = null;
if(params != null) {
MessageParamsClass clazz = context.getMessageParamsClass(params.getClass());
if(clazz != null)
sfsParams = new ResponseParamSerializer().object2params(clazz.getUnwrapper(), params);
}
if(sfsParams == null) sfsParams = new SFSObject();
try {
api.sendBuddyMessage(sfsSender, sfsRecipient, message, sfsParams);
} catch (SFSBuddyListException e) {
throw new IllegalStateException(e);
}
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public static String[] mappingGroovyName(String url,String version) {
Iterator it = urlMap.entrySet().iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
String key = (String) entry.getKey();
if(key.equals(url)){
MicroUrlBean urlBean=(MicroUrlBean) entry.getValue();
if(version==null || "".equals(version)){
return urlBean.getDefaultInfo();
}else{
version=versionFormat(version);
}
Entry fEntry=urlBean.getTreeMap().floorEntry(version);
String[] ret=null;
if(fEntry!=null){
ret=(String[]) fEntry.getValue();
}
return ret;
}
}
return null;
} | public static Map urlMethodMap = new HashMap(); |
@Override
public void setSystemProperty(String name, Object value) {
session.setSystemProperty(name, value);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Session#setSystemProperty(java.lang.String, java.lang.Object) |
@Override
public void setProperty(String name, Object value) {
session.setProperty(name, value);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Session#setProperty(java.lang.String, java.lang.Object) |
public int getConfigIndexOfSubset(VarSet vars) {
int configIndex = 0;
int numStatesProd = 1;
for (int v=vars.size()-1; v >= 0; v--) {
Var var = vars.get(v);
int state = config.get(var);
configIndex += state * numStatesProd;
numStatesProd *= var.getNumStates();
if (numStatesProd <= 0) {
throw new IllegalStateException("Integer overflow when computing config index -- this can occur if trying to compute the index of a high arity factor: " + numStatesProd);
}
}
return configIndex;
} | Gets the index of this configuration for the given variable set.
This is used to provide a unique index for each setting of the the
variables in a VarSet. |
public void put(VarConfig other) {
this.config.putAll(other.config);
this.vars.addAll(other.vars);
} | Sets all variable assignments in other. |
public void put(Var var, String stateName) {
int state = var.getState(stateName);
if (state == -1) {
throw new IllegalArgumentException("Unknown state name " + stateName + " for var " + var);
}
put(var, state);
} | Sets the state value to stateName for the given variable, adding it if necessary. |
public void put(Var var, int state) {
if (state < 0 || state >= var.getNumStates()) {
throw new IllegalArgumentException("Invalid state idx " + state + " for var " + var);
}
config.put(var, state);
vars.add(var);
} | Sets the state value to state for the given variable, adding it if necessary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.