code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
@SuppressWarnings("unchecked") @Override public ApiRoom execute() { Room sfsRoom = CommandUtil.getSfsRoom(agent, extension); User sfsUser = CommandUtil.getSfsUser(user, api); //check null if(sfsRoom == null) return null; //get variables from agent AgentClassUnwrapper unwrapper = context.getRoomAgentClass( agent.getClass()).getUnwrapper(); List<RoomVariable> variables = new RoomAgentSerializer().serialize(unwrapper, agent); List<RoomVariable> answer = variables; if(includedVars.size() > 0) answer = getVariables(variables, includedVars); answer.removeAll(getVariables(answer, excludedVars)); //notify to client and serverself if(toClient) api.setRoomVariables(sfsUser, sfsRoom, answer); //only for server else sfsRoom.setVariables(answer); return agent; }
Execute update room variables
public static IntNaryTreebank readTreesInPtbFormat(IntObjectBimap<String> lexAlphabet, IntObjectBimap<String> ntAlphabet, Reader reader) throws IOException { IntNaryTreebank trees = new IntNaryTreebank(); while (true) { IntNaryTree tree = IntNaryTree.readTreeInPtbFormat(lexAlphabet, ntAlphabet, reader); if (tree != null) { trees.add(tree); } if (tree == null) { break; } } return trees; }
Reads a list of trees in Penn Treebank format.
public void writeTreesInPtbFormat(File outFile) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); for (IntNaryTree tree : this) { writer.write(tree.getAsPennTreebankString()); writer.write("\n\n"); } writer.close(); }
Writes the trees to a file. @param outFile The output file. @throws IOException
@SuppressWarnings("unchecked") @Override public Boolean execute() { try { api.changeRoomCapacity(CommandUtil.getSfsUser(owner, api), CommandUtil.getSfsRoom(targetRoom, extension), maxUsers, maxSpectators); } catch (SFSRoomException e) { throw new IllegalStateException(e); } return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
public void runEvalb(File goldTrees, File testTrees, File logFile) { String[] cmd = new String[]{ evalbFile.getAbsolutePath(), "-p", prmFile.getAbsolutePath(), goldTrees.getAbsolutePath(), testTrees.getAbsolutePath(), }; System.runCommand(cmd, logFile, new File(".")); QFiles.cat(logFile); }
}
public static <T extends MVec> int count(T[] beliefs) { int count = 0; if (beliefs != null) { for (int i = 0; i < beliefs.length; i++) { if (beliefs[i] != null) { count += beliefs[i].size(); } } } return count; }
Java seems confused by. This is similar to the way the JDK handles Arrays.copyOf().
public static Pair<O1DpHypergraph, Scores> insideSingleRootEntropyFoe(double[] fracRoot, double[][] fracChild) { final Algebra semiring = LogSignAlgebra.getInstance(); return insideSingleRootEntropyFoe(fracRoot, fracChild, semiring); }
Runs the inside-outside algorithm for dependency parsing. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @return The parse chart.
public static EdgeScores insideOutsideO2AllGraSingleRoot(DependencyScorer scorer, Algebra s) { return insideOutside02AllGra(scorer, s, true); }
Runs inside outside on an all-grandparents hypergraph and returns the edge marginals in the real semiring.
public static EdgeScores insideOutsideO2AllGraMultiRoot(DependencyScorer scorer, Algebra s) { return insideOutside02AllGra(scorer, s, false); }
Runs inside outside on an all-grandparents hypergraph and returns the edge marginals in the real semiring.
public static EdgeScores getEdgeMarginalsRealSemiring(O2AllGraDpHypergraph graph, Scores sc) { Algebra s = graph.getAlgebra(); int nplus = graph.getNumTokens()+1; Hypernode[][][][] c = graph.getChart(); EdgeScores marg = new EdgeScores(graph.getNumTokens(), 0.0); for (int width = 1; width < nplus; width++) { for (int i = 0; i < nplus - width; i++) { int j = i + width; for (int g=0; g<nplus; g++) { if (i <= g && g <= j && !(i==0 && g==O2AllGraDpHypergraph.NIL)) { continue; } if (j > 0) { marg.incrScore(i-1, j-1, s.toReal(sc.marginal[c[i][j][g][O2AllGraDpHypergraph.INCOMPLETE].getId()])); } if (i > 0) { marg.incrScore(j-1, i-1, s.toReal(sc.marginal[c[j][i][g][O2AllGraDpHypergraph.INCOMPLETE].getId()])); } } } } return marg; }
Gets the edge marginals in the real semiring from an all-grandparents hypergraph and its marginals in scores.
public static boolean hasOneParentPerToken(int n, VarConfig vc) { int[] parents = new int[n]; Arrays.fill(parents, -2); for (Var v : vc.getVars()) { if (v instanceof LinkVar) { LinkVar link = (LinkVar) v; if (vc.getState(v) == LinkVar.TRUE) { if (parents[link.getChild()] != -2) { // Multiple parents defined for the same child. return false; } parents[link.getChild()] = link.getParent(); } } } return !ArrayUtils.contains(parents, -2); }
Returns whether this variable assignment specifies one parent per token.
public static int[] getParents(int n, VarConfig vc) { int[] parents = new int[n]; Arrays.fill(parents, -2); for (Var v : vc.getVars()) { if (v instanceof LinkVar) { LinkVar link = (LinkVar) v; if (vc.getState(v) == LinkVar.TRUE) { if (parents[link.getChild()] != -2) { throw new IllegalStateException( "Multiple parents defined for the same child. Is this VarConfig for only one example?"); } parents[link.getChild()] = link.getParent(); } } } return parents; }
Extracts the parents as defined by a variable assignment for a single sentence. NOTE: This should NOT be used for decoding since a proper decoder will enforce the tree constraint. @param n The sentence length. @param vc The variable assignment. @return The parents array.
private Tensor getMsgs(VarTensor[] inMsgs, int tf) { Algebra s = inMsgs[0].getAlgebra(); EdgeScores es = new EdgeScores(n, s.zero()); for (VarTensor inMsg : inMsgs) { LinkVar link = (LinkVar) inMsg.getVars().get(0); double val = inMsg.getValue(tf); es.setScore(link.getParent(), link.getChild(), val); } return es.toTensor(s); }
Gets messages from the Messages[]. @param inMsgs The input messages. @param tf Whether to get TRUE or FALSE messages. @return The messages as a Tensor.
private void addMsgs(VarTensor[] msgs, Tensor t, int tf) { assert msgs[0].getAlgebra().equals(t.getAlgebra()); EdgeScores es = EdgeScores.tensorToEdgeScores(t); for (VarTensor msg : msgs) { LinkVar link = (LinkVar) msg.getVars().get(0); double val = es.getScore(link.getParent(), link.getChild()); msg.addValue(tf, val); } }
Adds to messages on a Messages[]. @param msgs The output messages. @param t The input messages. @param tf Whether to set TRUE or FALSE messages.
private EdgeScores getLogOddsRatios(VarTensor[] inMsgs) { EdgeScores es = new EdgeScores(n, Double.NEGATIVE_INFINITY); Algebra s = inMsgs[0].getAlgebra(); // Compute the odds ratios of the messages for each edge in the tree. for (VarTensor inMsg : inMsgs) { LinkVar link = (LinkVar) inMsg.getVars().get(0); double logOdds = s.toLogProb(inMsg.getValue(LinkVar.TRUE)) - s.toLogProb(inMsg.getValue(LinkVar.FALSE)); if (link.getParent() == -1) { es.root[link.getChild()] = logOdds; } else { es.child[link.getParent()][link.getChild()] = logOdds; } } return es; }
Computes the log odds ratio for each edge. w_i = \mu_i(1) / \mu_i(0)
private double getLogProductOfAllFalseMessages(VarTensor[] inMsgs) { // Precompute the product of all the "false" messages. // pi = \prod_i \mu_i(0) // Here we store log pi. Algebra s = inMsgs[0].getAlgebra(); double logPi = 0.0; for (VarTensor inMsg : inMsgs) { logPi += s.toLogProb(inMsg.getValue(LinkVar.FALSE)); } return logPi; }
Computes pi = \prod_i \mu_i(0).
public boolean verify(String publicKeyId, byte[] message, byte[] signature) { Verifier verifier = cache.get(publicKeyId); if (verifier != null) { return verifier.verify(message, signature); } VerifierImpl verifierImpl = new VerifierImpl(); verifierImpl.setAlgorithm(algorithm); verifierImpl.setProvider(provider); PublicKey publicKey = publicKeyMap.get(publicKeyId); if (publicKey == null) { throw new SignatureException("public key not found: publicKeyId=" + publicKeyId); } verifierImpl.setPublicKey(publicKey); cache.put(publicKeyId, verifierImpl); return verifierImpl.verify(message, signature); }
Verifies the authenticity of a message using a digital signature. @param publicKeyId the logical name of the public key as configured in the public key map @param message the original message to verify @param signature the digital signature @return true if the original message is verified by the digital signature @see #setPublicKeyMap(java.util.Map)
private static VarTensor getProductOfAllFactors(FactorGraph fg, Algebra s) { VarTensor joint = new VarTensor(s, new VarSet(), s.one()); for (int a=0; a<fg.getNumFactors(); a++) { Factor f = fg.getFactor(a); VarTensor factor = safeNewVarTensor(s, f); assert !factor.containsBadValues() : factor; joint.prod(factor); } return joint; }
Gets the product of all the factors in the factor graph. If working in the log-domain, this will do factor addition. @return The product of all the factors.
public static VarTensor safeNewVarTensor(Algebra s, Factor f) { VarTensor factor; // Create a VarTensor which the values of this non-explicitly represented factor. factor = new VarTensor(s, f.getVars()); for (int c=0; c<factor.size(); c++) { factor.setValue(c, s.fromLogProb(f.getLogUnormalizedScore(c))); } return factor; }
Gets this factor as a VarTensor. This will always return a new object. See also safeGetVarTensor().
@Override protected void init() { handlers = new ZoneEventHandlerCenter() .addHandlers(handlerClasses, context.getUserClass(), context.getGameUserClasses()); }
/* (non-Javadoc) @see com.tvd12.ezyfox.sfs2x.serverhandler.ServerUserEventHandler#init()
@Override public void handleServerEvent(ISFSEvent event) throws SFSException { User sfsUser = (User) event.getParameter(SFSEventParam.USER); Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE); ApiZone apiZone = getApiZone(sfsZone); notifyHandlers(apiZone, sfsUser); }
/* (non-Javadoc) @see com.smartfoxserver.v2.extensions.IServerEventHandler#handleServerEvent( com.smartfoxserver.v2.core.ISFSEvent)
private void notifyHandlers(ApiZone apiZone, User sfsUser) { ApiUser apiUser = fetchUserAgent(sfsUser); for (ZoneHandlerClass handler : handlers) { Object userAgent = checkUserAgent(handler, apiUser); if (!checkHandler(handler, apiZone)) continue; notifyHandler(handler, apiZone, userAgent); } }
Propagate event to handlers @param apiZone api zone reference @param sfsUser smartfox user object
private void notifyHandler(ZoneHandlerClass handler, ApiZone apiZone, Object userAgent) { Object instance = handler.newInstance(); callHandleMethod(handler.getHandleMethod(), instance, apiZone, userAgent); }
Propagate event to handler @param handler structure of handler class @param apiZone api zone reference @param userAgent user agent reference
protected boolean checkHandler(ZoneHandlerClass handler, ApiZone apiZone) { return apiZone.getName().startsWith(handler.getZoneName()); }
Check zone name @param handler structure of handle class @param apiZone api zone reference @return true of false
private void callHandleMethod(Method method, Object instance, ApiZone apiZone, Object userAgent) { ReflectMethodUtil.invokeHandleMethod(method, instance, context, apiZone, userAgent); }
Call handle method @param method handle method @param instance object to call method @param apiZone api zone reference @param userAgent user agent reference
@SuppressWarnings("unchecked") @Override public Boolean execute() { SmartFoxServer.getInstance() .getAPIManager() .getGameApi() .sendInvitation(CommandUtil.getSfsUser(inviter, api), CommandUtil.getSFSUserList(invitees, api), expirySeconds, createCallback(), MapUtill.map2SFSObject(context, params)); return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
@Override public SendInvitation invitees(ApiBaseUser... users) { this.invitees.addAll(Arrays.asList(users)); return this; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.SendInvitation#invitees(com.tvd12.ezyfox.core.entities.ApiBaseUser[])
@Override public SendInvitation param(String name, Object value) { params.put(name, value); return this; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.SendInvitation#param(java.lang.String, java.lang.Object)
@Override public void setPlayerId(int id, ApiRoom room) { sfsUser.setPlayerId(id, getSfsRoom(room, extension)); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.UpdateUserInfo#setPlayerId(int, com.tvd12.ezyfox.core.entities.ApiRoom)
@SuppressWarnings("unchecked") @Override public <T extends ApiRoom> T getLastJoinedRoom() { return (T)sfsUser.getLastJoinedRoom().getProperty(APIKey.ROOM); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FetchUserInfo#getLastJoinedRoom()
@Override public Map<ApiRoom, Integer> getPlayerIds() { Map<ApiRoom, Integer> anwser = new HashMap<>(); Map<Room, Integer> ids = sfsUser.getPlayerIds(); for(Entry<Room, Integer> entry : ids.entrySet()) anwser.put((ApiRoom) entry.getKey().getProperty(APIKey.ROOM), entry.getValue()); return anwser; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.FetchUserInfo#getReconnectionSeconds() */ @Override public int getReconnectionSeconds() { return sfsUser.getReconnectionSeconds(); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.FetchUserInfo#getSubscribedGroups() */ @Override public List<String> getSubscribedGroups() { return sfsUser.getSubscribedGroups(); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.FetchUserInfo#getVariablesCount() */ @Override public int getVariablesCount() { return sfsUser.getVariablesCount(); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.FetchUserInfo#getZone() */ @Override public ApiZone getZone() { return (ApiZone) sfsUser.getZone().getProperty(APIKey.ZONE); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.UpdateUserInfo#removeAllVariables() */ @Override public void removeAllVariables() { List<UserVariable> vars = sfsUser.getVariables(); for(UserVariable var : vars) var.setNull(); api.setUserVariables(sfsUser, vars); } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.UserInfo#user(com.tvd12.ezyfox.core.entities.ApiBaseUser) */ @Override public UserInfo user(ApiBaseUser user) { sfsUser = getSfsUser(user, api); return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.UserInfo#user(java.lang.String) */ @Override public UserInfo user(String username) { sfsUser = getSfsUser(username, api); return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.UserInfo#user(int) */ @Override public UserInfo user(int userId) { sfsUser = api.getUserById(userId); return this; } /* (non-Javadoc) * @see com.tvd12.ezyfox.core.command.UpdateUserInfo#disconnect(byte) */ @Override public void disconnect(final byte reasonId) { sfsUser.disconnect(new IDisconnectionReason() { @Override public int getValue() { return getByteValue(); } @Override public byte getByteValue() { return reasonId; } }); } }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FetchUserInfo#getPlayerIds()
public static double probabilityTruncZero(double a, double b, double mu, double sigma) { // clip at zero a = Math.max(a, 0.0); b = Math.max(b, 0.0); final double denom = sigma * SQRT2; final double scaledSDA = (a - mu) / denom; final double scaledSDB = (b - mu) / denom; // compute prob final double probNormTimes2 = Erf.erf(scaledSDA, scaledSDB); // renormalize final double scaledSD0 = -mu / denom; final double reZTimes2 = Erf.erfc(scaledSD0); return probNormTimes2 / reZTimes2; }
returns the probability of x falling within the range of a to b under a normal distribution with mean mu and standard deviation sigma if the distribution is truncated below 0 and renormalized a and b should both be greater than or equal to 0 but this is not checked
public static double meanTruncLower(double mu, double sigma, double lowerBound) { double alpha = (lowerBound - mu) / sigma; double phiAlpha = densityNonTrunc(alpha, 0, 1.0); double cPhiAlpha = cumulativeNonTrunc(alpha, 0, 1.0); return mu + sigma * phiAlpha / (1.0 - cPhiAlpha); }
Returns the mean of the normal distribution truncated to 0 for values of x < lowerBound
public Tensor forward() { VarTensor[] varBeliefs = inf.getOutput().varBeliefs; double l2dist = s.zero(); for (Var v : vc.getVars()) { if (v.getType() == VarType.PREDICTED) { VarTensor marg = varBeliefs[v.getId()]; int goldState = vc.getState(v); for (int c=0; c<marg.size(); c++) { double goldMarg = (c == goldState) ? s.one() : s.zero(); double predMarg = marg.getValue(c); double diff = s.minus(Math.max(goldMarg, predMarg), Math.min(goldMarg, predMarg)); l2dist = s.plus(l2dist, s.times(diff, diff)); } } } if (s.lt(l2dist, s.zero())) { log.warn("L2 distance shouldn't be less than 0: " + l2dist); } y = Tensor.getScalarTensor(s, l2dist); return y; }
Forward pass: y = \sum_i \sum_{x_i} (b(x_i) - b*(x_i))^2 , where b*(x_i) are the marginals given by taking the gold variable assignment as a point mass distribution. Note the sum is over all variable assignments to the predicted variables.
public void backward() { double l2distAdj = yAdj.getValue(0); VarTensor[] varBeliefs = inf.getOutput().varBeliefs; VarTensor[] varBeliefsAdjs = inf.getOutputAdj().varBeliefs; // Fill in the non-zero adjoints with the adjoint of the expected recall. for (Var v : vc.getVars()) { if (v.getType() == VarType.PREDICTED) { VarTensor marg = varBeliefs[v.getId()]; int goldState = vc.getState(v); for (int c=0; c<marg.size(); c++) { double goldMarg = (c == goldState) ? s.one() : s.zero(); double predMarg = marg.getValue(c); // dG/db(x_i) = dG/dy 2(b(x_i) - b*(x_i)) double diff = s.minus(predMarg, goldMarg); double adj_b = s.times(l2distAdj, s.plus(diff, diff)); // Increment adjoint of the belief. varBeliefsAdjs[v.getId()].addValue(c, adj_b); } } } }
Backward pass: Expanding the square, we get y = \sum_i \sum_{x_i} b(x_i)^2 - 2b(x_i)b*(x_i) + b*(x_i)^2 dG/db(x_i) = dG/dy dy/db(x_i) = dG/dy 2(b(x_i) - b*(x_i)), \forall x_i.
@SuppressWarnings("unchecked") @Override public Boolean execute() { try { api.changeRoomName(CommandUtil.getSfsUser(owner, api), CommandUtil.getSfsRoom(targetRoom, extension), roomName); } catch (SFSRoomException e) { throw new IllegalStateException(e); } return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
void set(int row, int column, V value) { this.row = row; this.column = column; this.value = value; }
Sets the content of the cell. @param row the row index @param column the column index @param value the value
public DeviceRegConfirmUserResponseEnvelope confirmUser(DeviceRegConfirmUserRequest registrationInfo) throws ApiException { ApiResponse<DeviceRegConfirmUserResponseEnvelope> resp = confirmUserWithHttpInfo(registrationInfo); return resp.getData(); }
Confirm User This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device. @param registrationInfo Device Registration information. (required) @return DeviceRegConfirmUserResponseEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceRegConfirmUserResponseEnvelope> confirmUserWithHttpInfo(DeviceRegConfirmUserRequest registrationInfo) throws ApiException { com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, null, null); Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Confirm User This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device. @param registrationInfo Device Registration information. (required) @return ApiResponse&lt;DeviceRegConfirmUserResponseEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call confirmUserAsync(DeviceRegConfirmUserRequest registrationInfo, final ApiCallback<DeviceRegConfirmUserResponseEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Confirm User (asynchronously) This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device. @param registrationInfo Device Registration information. (required) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public DeviceRegStatusResponseEnvelope getRequestStatusForUser(String requestId) throws ApiException { ApiResponse<DeviceRegStatusResponseEnvelope> resp = getRequestStatusForUserWithHttpInfo(requestId); return resp.getData(); }
Get Request Status For User This call checks the status of the request so users can poll and know when registration is complete. @param requestId Request ID. (required) @return DeviceRegStatusResponseEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceRegStatusResponseEnvelope> getRequestStatusForUserWithHttpInfo(String requestId) throws ApiException { com.squareup.okhttp.Call call = getRequestStatusForUserValidateBeforeCall(requestId, null, null); Type localVarReturnType = new TypeToken<DeviceRegStatusResponseEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get Request Status For User This call checks the status of the request so users can poll and know when registration is complete. @param requestId Request ID. (required) @return ApiResponse&lt;DeviceRegStatusResponseEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public UnregisterDeviceResponseEnvelope unregisterDevice(String deviceId) throws ApiException { ApiResponse<UnregisterDeviceResponseEnvelope> resp = unregisterDeviceWithHttpInfo(deviceId); return resp.getData(); }
Unregister Device This call clears any associations from the secure device registration. @param deviceId Device ID. (required) @return UnregisterDeviceResponseEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<UnregisterDeviceResponseEnvelope> unregisterDeviceWithHttpInfo(String deviceId) throws ApiException { com.squareup.okhttp.Call call = unregisterDeviceValidateBeforeCall(deviceId, null, null); Type localVarReturnType = new TypeToken<UnregisterDeviceResponseEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Unregister Device This call clears any associations from the secure device registration. @param deviceId Device ID. (required) @return ApiResponse&lt;UnregisterDeviceResponseEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public static double Highprecision_Exp(double x) { return (362880 + x * (362880 + x * (181440 + x * (60480 + x * (15120 + x * (3024 + x * (504 + x * (72 + x * (9 + x))))))))) * 2.75573192e-6; }
Calculate Exp. Exp by Taylor series (9). @param x Value. @return Exponential.
public static double Lowprecision_Sin(double x) { //always wrap input angle to -PI..PI if (x < -3.14159265) x += 6.28318531; else if (x > 3.14159265) x -= 6.28318531; //compute sine if (x < 0) return 1.27323954 * x + .405284735 * x * x; else return 1.27323954 * x - 0.405284735 * x * x; }
Calculate Sin using Quadratic curve. @param x An angle, in radians. @return Result.
public static double Highprecision_Sin(double x) { //always wrap input angle to -PI..PI if (x < -3.14159265) x += 6.28318531; else if (x > 3.14159265) x -= 6.28318531; //compute sine if (x < 0) { double sin = 1.27323954 * x + .405284735 * x * x; if (sin < 0) return .225 * (sin * -sin - sin) + sin; else return .225 * (sin * sin - sin) + sin; } else { double sin = 1.27323954 * x - 0.405284735 * x * x; if (sin < 0) return .225 * (sin * -sin - sin) + sin; else return .225 * (sin * sin - sin) + sin; } }
Calculate Sin using Quadratic curve. @param x An angle, in radians. @return Result.
public static double atan2(double y, double x) { double coeff_1 = 0.78539816339744830961566084581988;//Math.PI / 4d; double coeff_2 = 3d * coeff_1; double abs_y = Math.abs(y); double angle; if (x >= 0d) { double r = (x - abs_y) / (x + abs_y); angle = coeff_1 - coeff_1 * r; } else { double r = (x + abs_y) / (abs_y - x); angle = coeff_2 - coeff_1 * r; } return y < 0d ? -angle : angle - 0.06; }
Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). This method computes the phase theta by computing an arc tangent of y/x in the range of -pi to pi. @param y Y axis coordinate. @param x X axis coordinate. @return The theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.
public DeviceEnvelope addDevice(Device device) throws ApiException { ApiResponse<DeviceEnvelope> resp = addDeviceWithHttpInfo(device); return resp.getData(); }
Add Device Create a device @param device Device to be added to the user (required) @return DeviceEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceEnvelope> addDeviceWithHttpInfo(Device device) throws ApiException { com.squareup.okhttp.Call call = addDeviceValidateBeforeCall(device, null, null); Type localVarReturnType = new TypeToken<DeviceEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Add Device Create a device @param device Device to be added to the user (required) @return ApiResponse&lt;DeviceEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceEnvelope deleteDevice(String deviceId) throws ApiException { ApiResponse<DeviceEnvelope> resp = deleteDeviceWithHttpInfo(deviceId); return resp.getData(); }
Delete Device Deletes a device @param deviceId deviceId (required) @return DeviceEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceEnvelope> deleteDeviceWithHttpInfo(String deviceId) throws ApiException { com.squareup.okhttp.Call call = deleteDeviceValidateBeforeCall(deviceId, null, null); Type localVarReturnType = new TypeToken<DeviceEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Delete Device Deletes a device @param deviceId deviceId (required) @return ApiResponse&lt;DeviceEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceTokenEnvelope deleteDeviceToken(String deviceId) throws ApiException { ApiResponse<DeviceTokenEnvelope> resp = deleteDeviceTokenWithHttpInfo(deviceId); return resp.getData(); }
Delete Device Token Deletes a device&#39;s token @param deviceId deviceId (required) @return DeviceTokenEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceEnvelope getDevice(String deviceId) throws ApiException { ApiResponse<DeviceEnvelope> resp = getDeviceWithHttpInfo(deviceId); return resp.getData(); }
Get Device Retrieves a device @param deviceId deviceId (required) @return DeviceEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public PresenceEnvelope getDevicePresence(String deviceId) throws ApiException { ApiResponse<PresenceEnvelope> resp = getDevicePresenceWithHttpInfo(deviceId); return resp.getData(); }
Get device presence information Return the presence status of the given device along with the time it was last seen @param deviceId Device ID. (required) @return PresenceEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<PresenceEnvelope> getDevicePresenceWithHttpInfo(String deviceId) throws ApiException { com.squareup.okhttp.Call call = getDevicePresenceValidateBeforeCall(deviceId, null, null); Type localVarReturnType = new TypeToken<PresenceEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get device presence information Return the presence status of the given device along with the time it was last seen @param deviceId Device ID. (required) @return ApiResponse&lt;PresenceEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceTokenEnvelope getDeviceToken(String deviceId) throws ApiException { ApiResponse<DeviceTokenEnvelope> resp = getDeviceTokenWithHttpInfo(deviceId); return resp.getData(); }
Get Device Token Retrieves a device&#39;s token @param deviceId deviceId (required) @return DeviceTokenEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceTokenEnvelope> getDeviceTokenWithHttpInfo(String deviceId) throws ApiException { com.squareup.okhttp.Call call = getDeviceTokenValidateBeforeCall(deviceId, null, null); Type localVarReturnType = new TypeToken<DeviceTokenEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get Device Token Retrieves a device&#39;s token @param deviceId deviceId (required) @return ApiResponse&lt;DeviceTokenEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceEnvelope updateDevice(String deviceId, Device device) throws ApiException { ApiResponse<DeviceEnvelope> resp = updateDeviceWithHttpInfo(deviceId, device); return resp.getData(); }
Update Device Updates a device @param deviceId deviceId (required) @param device Device to be updated (required) @return DeviceEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<DeviceEnvelope> updateDeviceWithHttpInfo(String deviceId, Device device) throws ApiException { com.squareup.okhttp.Call call = updateDeviceValidateBeforeCall(deviceId, device, null, null); Type localVarReturnType = new TypeToken<DeviceEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Update Device Updates a device @param deviceId deviceId (required) @param device Device to be updated (required) @return ApiResponse&lt;DeviceEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public DeviceTokenEnvelope updateDeviceToken(String deviceId) throws ApiException { ApiResponse<DeviceTokenEnvelope> resp = updateDeviceTokenWithHttpInfo(deviceId); return resp.getData(); }
Update Device Token Updates a device&#39;s token @param deviceId deviceId (required) @return DeviceTokenEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public SubscriptionEnvelope createSubscription(SubscriptionInfo subscriptionInfo) throws ApiException { ApiResponse<SubscriptionEnvelope> resp = createSubscriptionWithHttpInfo(subscriptionInfo); return resp.getData(); }
Create Subscription Create Subscription @param subscriptionInfo Subscription details (required) @return SubscriptionEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<SubscriptionEnvelope> createSubscriptionWithHttpInfo(SubscriptionInfo subscriptionInfo) throws ApiException { com.squareup.okhttp.Call call = createSubscriptionValidateBeforeCall(subscriptionInfo, null, null); Type localVarReturnType = new TypeToken<SubscriptionEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Create Subscription Create Subscription @param subscriptionInfo Subscription details (required) @return ApiResponse&lt;SubscriptionEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call createSubscriptionAsync(SubscriptionInfo subscriptionInfo, final ApiCallback<SubscriptionEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createSubscriptionValidateBeforeCall(subscriptionInfo, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<SubscriptionEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Create Subscription (asynchronously) Create Subscription @param subscriptionInfo Subscription details (required) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public SubscriptionEnvelope deleteSubscription(String subId) throws ApiException { ApiResponse<SubscriptionEnvelope> resp = deleteSubscriptionWithHttpInfo(subId); return resp.getData(); }
Delete Subscription Delete Subscription @param subId Subscription ID. (required) @return SubscriptionEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public SubscriptionsEnvelope getAllSubscriptions(String uid, Integer offset, Integer count) throws ApiException { ApiResponse<SubscriptionsEnvelope> resp = getAllSubscriptionsWithHttpInfo(uid, offset, count); return resp.getData(); }
Get All Subscriptions Get All Subscriptions @param uid User ID (optional) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @return SubscriptionsEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<SubscriptionsEnvelope> getAllSubscriptionsWithHttpInfo(String uid, Integer offset, Integer count) throws ApiException { com.squareup.okhttp.Call call = getAllSubscriptionsValidateBeforeCall(uid, offset, count, null, null); Type localVarReturnType = new TypeToken<SubscriptionsEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get All Subscriptions Get All Subscriptions @param uid User ID (optional) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @return ApiResponse&lt;SubscriptionsEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call getAllSubscriptionsAsync(String uid, Integer offset, Integer count, final ApiCallback<SubscriptionsEnvelope> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getAllSubscriptionsValidateBeforeCall(uid, offset, count, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<SubscriptionsEnvelope>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Get All Subscriptions (asynchronously) Get All Subscriptions @param uid User ID (optional) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public NotifMessagesResponse getMessages(String notifId, Integer offset, Integer count, String order) throws ApiException { ApiResponse<NotifMessagesResponse> resp = getMessagesWithHttpInfo(notifId, offset, count, order); return resp.getData(); }
Get Messages Get Messages @param notifId Notification ID. (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param order Sort order of results by ts. Either &#39;asc&#39; or &#39;desc&#39;. (optional) @return NotifMessagesResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<NotifMessagesResponse> getMessagesWithHttpInfo(String notifId, Integer offset, Integer count, String order) throws ApiException { com.squareup.okhttp.Call call = getMessagesValidateBeforeCall(notifId, offset, count, order, null, null); Type localVarReturnType = new TypeToken<NotifMessagesResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get Messages Get Messages @param notifId Notification ID. (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param order Sort order of results by ts. Either &#39;asc&#39; or &#39;desc&#39;. (optional) @return ApiResponse&lt;NotifMessagesResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public com.squareup.okhttp.Call getMessagesAsync(String notifId, Integer offset, Integer count, String order, final ApiCallback<NotifMessagesResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getMessagesValidateBeforeCall(notifId, offset, count, order, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<NotifMessagesResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
Get Messages (asynchronously) Get Messages @param notifId Notification ID. (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set. (optional) @param order Sort order of results by ts. Either &#39;asc&#39; or &#39;desc&#39;. (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
public SubscriptionEnvelope getSubscription(String subId) throws ApiException { ApiResponse<SubscriptionEnvelope> resp = getSubscriptionWithHttpInfo(subId); return resp.getData(); }
Get Subscription Get Subscription @param subId Subscription ID. (required) @return SubscriptionEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<SubscriptionEnvelope> getSubscriptionWithHttpInfo(String subId) throws ApiException { com.squareup.okhttp.Call call = getSubscriptionValidateBeforeCall(subId, null, null); Type localVarReturnType = new TypeToken<SubscriptionEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Get Subscription Get Subscription @param subId Subscription ID. (required) @return ApiResponse&lt;SubscriptionEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public SubscriptionEnvelope validateSubscription(String subId, ValidationCallbackInfo validationCallbackRequest) throws ApiException { ApiResponse<SubscriptionEnvelope> resp = validateSubscriptionWithHttpInfo(subId, validationCallbackRequest); return resp.getData(); }
Validate Subscription Validate Subscription @param subId Subscription ID. (required) @param validationCallbackRequest Subscription validation callback request (required) @return SubscriptionEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
public ApiResponse<SubscriptionEnvelope> validateSubscriptionWithHttpInfo(String subId, ValidationCallbackInfo validationCallbackRequest) throws ApiException { com.squareup.okhttp.Call call = validateSubscriptionValidateBeforeCall(subId, validationCallbackRequest, null, null); Type localVarReturnType = new TypeToken<SubscriptionEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
Validate Subscription Validate Subscription @param subId Subscription ID. (required) @param validationCallbackRequest Subscription validation callback request (required) @return ApiResponse&lt;SubscriptionEnvelope&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
private void init(DelaunayTriangulation delaunay, int xCellCount, int yCellCount, BoundingBox region) { indexDelaunay = delaunay; indexRegion = region; x_size = region.getWidth() / yCellCount; y_size = region.getHeight() / xCellCount; // The grid will hold a trinagle for each cell, so a point (x,y) will lie // in the cell representing the grid partition of region to a // xCellCount on yCellCount grid grid = new Triangle[xCellCount][yCellCount]; Triangle colStartTriangle = indexDelaunay.find(middleOfCell(0, 0)); updateCellValues(0, 0, xCellCount - 1, yCellCount - 1, colStartTriangle); }
Initialize the grid index @param delaunay delaunay triangulation to index @param xCellCount number of grid cells in a row @param yCellCount number of grid cells in a column @param region geographic region to index
public Triangle findCellTriangleOf(Point3D point) { int x_index = (int) ((point.x - indexRegion.minX()) / x_size); int y_index = (int) ((point.y - indexRegion.minY()) / y_size); return grid[x_index][y_index]; }
Finds a triangle near the given point @param point a query point @return a triangle at the same cell of the point
public void updateIndex(Iterator<Triangle> updatedTriangles) { // Gather the bounding box of the updated area BoundingBox updatedRegion = new BoundingBox(); while (updatedTriangles.hasNext()) { updatedRegion = updatedRegion.unionWith(updatedTriangles.next().getBoundingBox()); } if (updatedRegion.isNull()) // No update... return; // Bad news - the updated region lies outside the indexed region. // The whole index must be recalculated if (!indexRegion.contains(updatedRegion)) { init(indexDelaunay, (int) (indexRegion.getWidth() / x_size), (int) (indexRegion.getHeight() / y_size), indexRegion.unionWith(updatedRegion)); } else { // Find the cell region to be updated Vector2i minInvalidCell = getCellOf(updatedRegion.getMinPoint()); Vector2i maxInvalidCell = getCellOf(updatedRegion.getMaxPoint()); // And update it with fresh triangles Triangle adjacentValidTriangle = findValidTriangle(minInvalidCell); updateCellValues(minInvalidCell.getX(), minInvalidCell.getY(), maxInvalidCell.getX(), maxInvalidCell.getY(), adjacentValidTriangle); } }
Updates the grid index to reflect changes to the triangulation. Note that added triangles outside the indexed region will force to recompute the whole index with the enlarged region. @param updatedTriangles changed triangles of the triangulation. This may be added triangles, removed triangles or both. All that matter is that they cover the changed area.
private Triangle findValidTriangle(Vector2i minInvalidCell) { // If the invalid cell is the minimal one in the grid we are forced to search the // triangulation for a trinagle at that location if (minInvalidCell.getX() == 0 && minInvalidCell.getY() == 0) return indexDelaunay.find(middleOfCell(minInvalidCell.getX(), minInvalidCell.getY()), null); else // Otherwise we can take an adjacent cell triangle that is still valid return grid[Math.min(0, minInvalidCell.getX())][Math.min(0, minInvalidCell.getY())]; }
Finds a valid (existing) trinagle adjacent to a given invalid cell @param minInvalidCell minimum bounding box invalid cell @return a valid triangle adjacent to the invalid cell
private Vector2i getCellOf(Point3D coordinate) { int xCell = (int) ((coordinate.x - indexRegion.minX()) / x_size); int yCell = (int) ((coordinate.y - indexRegion.minY()) / y_size); return new Vector2i(xCell, yCell); }
Locates the grid cell point covering the given coordinate @param coordinate world coordinate to locate @return cell covering the coordinate
private Vector3 middleOfCell(int x_index, int y_index) { float middleXCell = (float) (indexRegion.minX() + x_index * x_size + x_size / 2); float middleYCell = (float) (indexRegion.minY() + y_index * y_size + y_size / 2); return new Vector3(middleXCell, middleYCell, 0); }
Create a point at the center of a cell @param x_index horizontal cell index @param y_index vertical cell index @return Point at the center of the cell at (x_index, y_index)
public static double Function(double x) { double[] P = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, 9.99999999999999996796E-1 }; double[] Q = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; double p, z; double q = Math.abs(x); if (q > 33.0) { if (x < 0.0) { p = Math.floor(q); if (p == q) { try { throw new ArithmeticException("Overflow"); } catch (Exception e) { e.printStackTrace(); } } z = q - p; if (z > 0.5) { p += 1.0; z = q - p; } z = q * Math.sin(Math.PI * z); if (z == 0.0) { try { throw new ArithmeticException("Overflow"); } catch (Exception e) { e.printStackTrace(); } } z = Math.abs(z); z = Math.PI / (z * Stirling(q)); return -z; } else { return Stirling(x); } } z = 1.0; while (x >= 3.0) { x -= 1.0; z *= x; } while (x < 0.0) { if (x == 0.0) { throw new ArithmeticException(); } else if (x > -1.0E-9) { return (z / ((1.0 + 0.5772156649015329 * x) * x)); } z /= x; x += 1.0; } while (x < 2.0) { if (x == 0.0) { throw new ArithmeticException(); } else if (x < 1.0E-9) { return (z / ((1.0 + 0.5772156649015329 * x) * x)); } z /= x; x += 1.0; } if ((x == 2.0) || (x == 3.0)) return z; x -= 2.0; p = Special.Polevl(x, P, 6); q = Special.Polevl(x, Q, 7); return z * p / q; }
Gamma function of the specified value. @param x Value. @return Result.
public static double Stirling(double x) { double[] STIR = { 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3, 3.47222221605458667310E-3, 8.33333333333482257126E-2, }; double MAXSTIR = 143.01608; double w = 1.0 / x; double y = Math.exp(x); w = 1.0 + w * Special.Polevl(w, STIR, 4); if (x > MAXSTIR) { double v = Math.pow(x, 0.5 * x - 0.25); y = v * (v / y); } else { y = Math.pow(x, x - 0.5) / y; } y = 2.50662827463100050242E0 * y * w; return y; }
Gamma function as computed by Stirling's formula. @param x Value. @return Result.
public static double Digamma(double x) { double s = 0; double w = 0; double y = 0; double z = 0; double nz = 0; boolean negative = false; if (x <= 0.0) { negative = true; double q = x; double p = (int) Math.floor(q); if (p == q) { try { throw new ArithmeticException("Function computation resulted in arithmetic overflow."); } catch (Exception e) { e.printStackTrace(); } } nz = q - p; if (nz != 0.5) { if (nz > 0.5) { p = p + 1.0; nz = q - p; } nz = Math.PI / Math.tan(Math.PI * nz); } else { nz = 0.0; } x = 1.0 - x; } if (x <= 10.0 && x == Math.floor(x)) { y = 0.0; int n = (int) Math.floor(x); for (int i = 1; i <= n - 1; i++) { w = i; y = y + 1.0 / w; } y = y - 0.57721566490153286061; } else { s = x; w = 0.0; while (s < 10.0) { w = w + 1.0 / s; s = s + 1.0; } if (s < 1.0E17) { z = 1.0 / (s * s); double polv = 8.33333333333333333333E-2; polv = polv * z - 2.10927960927960927961E-2; polv = polv * z + 7.57575757575757575758E-3; polv = polv * z - 4.16666666666666666667E-3; polv = polv * z + 3.96825396825396825397E-3; polv = polv * z - 8.33333333333333333333E-3; polv = polv * z + 8.33333333333333333333E-2; y = z * polv; } else { y = 0.0; } y = Math.log(s) - 0.5 / s - y - w; } if (negative == true) { y = y - nz; } return y; }
Digamma function. @param x Value. @return Result.
public static double ComplementedIncomplete(double a, double x) { final double big = 4.503599627370496e15; final double biginv = 2.22044604925031308085e-16; double ans, ax, c, yc, r, t, y, z; double pk, pkm1, pkm2, qk, qkm1, qkm2; if (x <= 0 || a <= 0) return 1.0; if (x < 1.0 || x < a) return 1.0 - Incomplete(a, x); ax = a * Math.log(x) - x - Log(a); if (ax < -Constants.LogMax) return 0.0; ax = Math.exp(ax); // continued fraction y = 1.0 - a; z = x + y + 1.0; c = 0.0; pkm2 = 1.0; qkm2 = x; pkm1 = x + 1.0; qkm1 = z * x; ans = pkm1 / qkm1; do { c += 1.0; y += 1.0; z += 2.0; yc = y * c; pk = pkm1 * z - pkm2 * yc; qk = qkm1 * z - qkm2 * yc; if (qk != 0) { r = pk / qk; t = Math.abs((ans - r) / r); ans = r; } else t = 1.0; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (Math.abs(pk) > big) { pkm2 *= biginv; pkm1 *= biginv; qkm2 *= biginv; qkm1 *= biginv; } } while (t > Constants.DoubleEpsilon); return ans * ax; }
Complemented incomplete gamma function. @param a Value. @param x Value. @return Result.
public static double Incomplete(double a, double x) { double ans, ax, c, r; if (x <= 0 || a <= 0) return 0.0; if (x > 1.0 && x > a) return 1.0 - ComplementedIncomplete(a, x); ax = a * Math.log(x) - x - Log(a); if (ax < -Constants.LogMax) return (0.0); ax = Math.exp(ax); r = a; c = 1.0; ans = 1.0; do { r += 1.0; c *= x / r; ans += c; } while (c / ans > Constants.DoubleEpsilon); return (ans * ax / a); }
Incomplete gamma function. @param a Value. @param x Value. @return Result.
public static double Log(double x) { double p, q, w, z; double[] A = { 8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4, -2.77777777730099687205E-3, 8.33333333333331927722E-2 }; double[] B = { -1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5, -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5 }; double[] C = { -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6 }; if (x < -34.0) { q = -x; w = Log(q); p = Math.floor(q); if (p == q) { try { throw new ArithmeticException("Overflow."); } catch (Exception e) { e.printStackTrace(); } } z = q - p; if (z > 0.5) { p += 1.0; z = p - q; } z = q * Math.sin(Math.PI * z); if (z == 0.0) { try { throw new ArithmeticException("Overflow."); } catch (Exception e) { e.printStackTrace(); } } z = Constants.LogPI - Math.log(z) - w; return z; } if (x < 13.0) { z = 1.0; while (x >= 3.0) { x -= 1.0; z *= x; } while (x < 2.0) { if (x == 0.0) { try { throw new ArithmeticException("Overflow."); } catch (Exception e) { e.printStackTrace(); } } z /= x; x += 1.0; } if (z < 0.0) z = -z; if (x == 2.0) return Math.log(z); x -= 2.0; p = x * Special.Polevl(x, B, 5) / Special.P1evl(x, C, 6); return (Math.log(z) + p); } if (x > 2.556348e305) { try { throw new ArithmeticException("Overflow."); } catch (Exception e) { e.printStackTrace(); } } q = (x - 0.5) * Math.log(x) - x + 0.91893853320467274178; if (x > 1.0e8) return (q); p = 1.0 / (x * x); if (x >= 1000.0) { q += ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x; } else { q += Special.Polevl(p, A, 4) / x; } return q; }
Natural logarithm of gamma function. @param x Value. @return Result.
public void Forward(ImageSource fastBitmap) { this.width = fastBitmap.getWidth(); this.height = fastBitmap.getHeight(); if (!isTransformed) { if (fastBitmap.isGrayscale()) { if (Tools.isPowerOf2(width) && Tools.isPowerOf2(height)) { data = new double[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { data[i][j] = Tools.Scale(0, 255, 0, 1, fastBitmap.getRGB(i, j)); } } DiscreteCosineTransform.Forward(data); isTransformed = true; } else { try { throw new IllegalArgumentException("Image width and height should be power of 2."); } catch (Exception e) { e.printStackTrace(); } } } else { try { throw new IllegalArgumentException("Only grayscale images are supported."); } catch (Exception e) { e.printStackTrace(); } } } }
Applies forward Cosine transformation to an image. @param fastBitmap Image.
public ImageSource toFastBitmap() { OneBandSource l = new OneBandSource(width, height); PowerSpectrum(); double max = Math.log(PowerMax + 1.0); double scale = 1.0; if (scaleValue > 0) scale = scaleValue / max; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { double p = Power[i][j]; double plog = Math.log(p + 1.0); l.setRGB(i, j, (int) (plog * scale * 255)); } } return l; }
Convert image's data to FastBitmap. @return FastBitmap.
private void PowerSpectrum() { Power = new double[data.length][data[0].length]; PowerMax = 0; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[0].length; j++) { double p = data[i][j]; if (p < 0) p = -p; Power[i][j] = p; if (p > PowerMax) PowerMax = p; } } }
compute the Power Spectrum;
@Override public ImageSource apply(ImageSource input) { int w = input.getWidth(); int h = input.getHeight(); MatrixSource output = new MatrixSource(w, h); Vector3 s = new Vector3(1, 0, 0); Vector3 t = new Vector3(0, 1, 0); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x < border || x == w - border || y < border || y == h - border) { output.setRGB(x, y, VectorHelper.Z_NORMAL); continue; } float dh = input.getR(x + 1, y) - input.getR(x - 1, y); float dv = input.getR(x, y + 1) - input.getR(x, y - 1); s.set(scale, 0, dh); t.set(0, scale, dv); Vector3 cross = s.crs(t).nor(); int rgb = VectorHelper.vectorToColor(cross); output.setRGB(x, y, rgb); } } return new MatrixSource(output); }
Simple method to generate bump map from a height map @param input - A height map @return bump map
protected <L extends Listener, E extends Event<?, ?>> void checkDispatchArgs( E event, Object bc, ExceptionCallback ec) { if (event == null) { throw new IllegalArgumentException("event is null"); } else if (bc == null) { throw new IllegalArgumentException("bc is null"); } else if (ec == null) { throw new IllegalArgumentException("ec is null"); } }
Helper method which serves for throwing {@link IllegalArgumentException} if any of the passed arguments is null. @param <L> Type of the listeners which will be notified. @param <E> Type of the event which will be passed to a listener. @param event The event. @param bc The method to call on the listener @param ec The ExceptionCallback @throws IllegalArgumentException If any argument is <code>null</code>.
protected <L extends Listener, E extends Event<?, L>> void notifyListeners( E event, BiConsumer<L, E> bc, ExceptionCallback ec) { notifyListeners(getListenerSource(), event, bc, ec); }
Notifies all listeners registered for the provided class with the provided event. This method is failure tolerant and will continue notifying listeners even if one of them threw an exception. Exceptions are passed to the provided {@link ExceptionCallback}. <p> This method does not check whether this provider is ready for dispatching and might thus throw an exception when trying to dispatch an event while the provider is not ready. </p> @param <L> Type of the listeners which will be notified. @param <E> Type of the event which will be passed to a listener. @param event The event to pass to each listener. @param bc The method of the listener to call. @param ec The callback which gets notified about exceptions. @throws AbortionException If the ExceptionCallback threw an AbortionException
protected <L extends Listener, E extends Event<?, L>> void notifyListeners( ListenerSource source, E event, BiConsumer<L, E> bc, ExceptionCallback ec) { final Stream<L> listeners = source.get(event.getListenerClass()); final Iterator<L> it = listeners.iterator(); while (it.hasNext() && checkInterrupt()) { final L listener = it.next(); notifySingle(listener, event, bc, ec); } }
Notifies all listeners registered for the provided class with the provided event. This method is failure tolerant and will continue notifying listeners even if one of them threw an exception. Exceptions are passed to the provided {@link ExceptionCallback}. <p> This method does not check whether this provider is ready for dispatching and might thus throw an exception when trying to dispatch an event while the provider is not ready. </p> @param <L> Type of the listeners which will be notified. @param <E> Type of the event which will be passed to a listener. @param source The source to get listeners from. @param event The event to pass to each listener. @param bc The method of the listener to call. @param ec The callback which gets notified about exceptions. @throws AbortionException If the ExceptionCallback threw an AbortionException
protected <L extends Listener, E extends Event<?, L>> void notifySingle( L listener, E event, BiConsumer<L, E> bc, ExceptionCallback ec) { createInvocation(listener, event, bc, ec).notifyListener(); }
Notifies a single listener and internally handles exceptions using the {@link ExceptionCallback}. @param <L> Type of the listeners which will be notified. @param <E> Type of the event which will be passed to a listener. @param listener The single listener to notify. @param event The event to pass to the listener. @param bc The method of the listener to call. @param ec The callback which gets notified about exceptions. @throws AbortionException If the {@code ExceptionCallback} or the {@code listener} threw an {@code AbortionException}. @since 1.1.0
protected <L extends Listener, E extends Event<?, L>> EventInvocation createInvocation(L listener, E event, BiConsumer<L, E> bc, ExceptionCallback ec) { return this.invocationFactory.create(listener, event, bc, ec); }
Creates a new {@link EventInvocation} object for dispatching the given event to the given listener. @param <L> Type of the listeners which will be notified. @param <E> Type of the event which will be passed to a listener. @param listener The listener to notify. @param event The event to pass to the listener @param bc The method of the listener to call. @param ec The callback which gets notified about exceptions. @return The EventInvocation instance. @since 3.0.0
public void insertPoint(Set<Vector3> vertices, Vector3 p) { modCount++; updateBoundingBox(p); vertices.add(p); Triangle t = insertPointSimple(vertices, p); if (t == null) // return; Triangle tt = t; //currT = t; // recall the last point for - fast (last) update iterator. do { flip(tt, modCount); tt = tt.canext; } while (tt != t && !tt.halfplane); // Update index with changed triangles /*if(gridIndex != null) { gridIndex.updateIndex(getLastUpdatedTriangles()); }*/ }
insert the point to this Delaunay Triangulation. Note: if p is null or already exist in this triangulation p is ignored. @param vertices @param p new vertex to be inserted the triangulation.
public Vector3 findClosePoint(Vector3 pointToDelete) { Triangle triangle = find(pointToDelete); Vector3 p1 = triangle.p1(); Vector3 p2 = triangle.p2(); double d1 = distanceXY(p1, pointToDelete); double d2 = distanceXY(p2, pointToDelete); if(triangle.isHalfplane()) { if(d1<=d2) { return p1; } else { return p2; } } else { Vector3 p3 = triangle.p3(); double d3 = distanceXY(p3, pointToDelete); if(d1<=d2 && d1<=d3) { return p1; } else if(d2<=d1 && d2<=d3) { return p2; } else { return p3; } } }
return a point from the trangulation that is close to pointToDelete @param pointToDelete the point that the user wants to delete @return a point from the trangulation that is close to pointToDelete By Eyal Roth & Doron Ganel (2009).
public Vector3[] calcVoronoiCell(Triangle triangle, Vector3 p) { // handle any full triangle if (!triangle.isHalfplane()) { // get all neighbors of given corner point List<Triangle> neighbors = findTriangleNeighborhood(triangle, p); Iterator<Triangle> itn = neighbors.iterator(); Vector3[] vertices = new Vector3[neighbors.size()]; // for each neighbor, including the given triangle, add // center of circumscribed circle to cell polygon int index = 0; while (itn.hasNext()) { Triangle tmp = itn.next(); vertices[index++] = tmp.circumcircle().getCenter(); } return vertices; } // handle half plane // in this case, the cell is a single line // which is the perpendicular bisector of the half plane line else { // local friendly alias Triangle halfplane = triangle; // third point of triangle adjacent to this half plane // (the point not shared with the half plane) Vector3 third = null; // triangle adjacent to the half plane Triangle neighbor = null; // find the neighbor triangle if (!halfplane.next_12().isHalfplane()) { neighbor = halfplane.next_12(); } else if (!halfplane.next_23().isHalfplane()) { neighbor = halfplane.next_23(); } else if (!halfplane.next_23().isHalfplane()) { neighbor = halfplane.next_31(); } // find third point of neighbor triangle // (the one which is not shared with current half plane) // this is used in determining half plane orientation if (!neighbor.p1().equals(halfplane.p1()) && !neighbor.p1().equals(halfplane.p2()) ) third = neighbor.p1(); if (!neighbor.p2().equals(halfplane.p1()) && !neighbor.p2().equals(halfplane.p2()) ) third = neighbor.p2(); if (!neighbor.p3().equals(halfplane.p1()) && !neighbor.p3().equals(halfplane.p2()) ) third = neighbor.p3(); // delta (slope) of half plane edge float halfplane_delta = (halfplane.p1().y - halfplane.p2().y) / (halfplane.p1().x - halfplane.p2().x); // delta of line perpendicular to current half plane edge float perp_delta = (1.0f / halfplane_delta) * (-1.0f); // determine orientation: find if the third point of the triangle // lies above or below the half plane // works by finding the matching y value on the half plane line equation // for the same x value as the third point float y_orient = halfplane_delta * (third.x - halfplane.p1().x)+ halfplane.p1().y; boolean above = true; if (y_orient > third.y) above = false; // based on orientation, determine cell line direction // (towards right or left side of window) float sign = 1.0f; if ((perp_delta < 0 && !above) || (perp_delta > 0 && above)) { sign = -1.0f; } // the cell line is a line originating from the circumcircle to infinity // x = 500.0 is used as a large enough value Vector3 circumcircle = neighbor.circumcircle().getCenter(); float x_cell_line = (circumcircle.x + (500.0f * sign)); float y_cell_line = perp_delta * (x_cell_line - circumcircle.x) + circumcircle.y; Vector3[] result = new Vector3[2]; result[0] = circumcircle; result[1] = new Vector3(x_cell_line, y_cell_line, 0); return result; } }
Calculates a Voronoi cell for a given neighborhood in this triangulation. A neighborhood is defined by a triangle and one of its corner points. By Udi Schneider @param triangle a triangle in the neighborhood @param p corner point whose surrounding neighbors will be checked @return set of Points representing the cell polygon
private Triangle insertPointSimple(Set<Vector3> vertices, Vector3 p) { if (!allCollinear) { return insertNonColinear(p); } else { return insertColinear(vertices, p); } }
/*private void allTriangles(Triangle curr, List<Triangle> front, int mc) { if (curr != null && curr.modCounter == mc && !front.contains(curr)) { front.add(curr); allTriangles(curr.abnext, front, mc); allTriangles(curr.bcnext, front, mc); allTriangles(curr.canext, front, mc); } }