List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:eu.stratosphere.nephele.multicast.MulticastManager.java
/** * Returns a list of (physical) Nodes (=hosts) within the multicast tree. Each node contains the local ChannelIDs, * records//w ww.j a va2s . c o m * must be forwarded to. The first node in the List is the only multicast sender. * * @param sourceChannelID * @return */ private LinkedList<TreeNode> extractTreeNodes(final InstanceConnectionInfo source, final JobID jobID, final ChannelID sourceChannelID, final boolean randomize) { final ExecutionGraph eg = this.scheduler.getExecutionGraphByID(jobID); final ExecutionEdge outputChannel = eg.getEdgeByID(sourceChannelID); final ExecutionGate broadcastGate = outputChannel.getOutputGate(); final LinkedList<ExecutionEdge> outputChannels = new LinkedList<ExecutionEdge>(); // Get all broadcast output channels final int numberOfOutputChannels = broadcastGate.getNumberOfEdges(); for (int i = 0; i < numberOfOutputChannels; ++i) { final ExecutionEdge c = broadcastGate.getEdge(i); if (c.isBroadcast()) { outputChannels.add(c); } } final LinkedList<TreeNode> treeNodes = new LinkedList<TreeNode>(); LinkedList<ChannelID> actualLocalTargets = new LinkedList<ChannelID>(); int firstConnectionID = 0; // search for local targets for the tree node for (Iterator<ExecutionEdge> iter = outputChannels.iterator(); iter.hasNext();) { final ExecutionEdge actualOutputChannel = iter.next(); // the connection ID should not be needed for the root node (as it is not set as remote receiver) // but in order to maintain consistency, it also gets the connectionID of the first channel pointing to it firstConnectionID = actualOutputChannel.getConnectionID(); final ExecutionVertex targetVertex = actualOutputChannel.getInputGate().getVertex(); // is the target vertex running on the same instance? if (targetVertex.getAllocatedResource().getInstance().getInstanceConnectionInfo().equals(source)) { actualLocalTargets.add(actualOutputChannel.getInputChannelID()); iter.remove(); } } // create sender node (root) with source instance TreeNode actualNode = new TreeNode( eg.getVertexByChannelID(sourceChannelID).getAllocatedResource().getInstance(), source, firstConnectionID, actualLocalTargets); treeNodes.add(actualNode); // now we have the root-node.. lets extract all other nodes LinkedList<TreeNode> receiverNodes = new LinkedList<TreeNode>(); while (outputChannels.size() > 0) { final ExecutionEdge firstChannel = outputChannels.pollFirst(); // each receiver nodes' endpoint is associated with the connection ID // of the first channel pointing to this node. final int connectionID = firstChannel.getConnectionID(); final ExecutionVertex firstTarget = firstChannel.getInputGate().getVertex(); final InstanceConnectionInfo actualInstance = firstTarget.getAllocatedResource().getInstance() .getInstanceConnectionInfo(); actualLocalTargets = new LinkedList<ChannelID>(); // add first local target actualLocalTargets.add(firstChannel.getInputChannelID()); // now we iterate through the remaining channels to find other local targets... for (Iterator<ExecutionEdge> iter = outputChannels.iterator(); iter.hasNext();) { final ExecutionEdge actualOutputChannel = iter.next(); final ExecutionVertex actualTarget = actualOutputChannel.getInputGate().getVertex(); // is the target vertex running on the same instance? if (actualTarget.getAllocatedResource().getInstance().getInstanceConnectionInfo() .equals(actualInstance)) { actualLocalTargets.add(actualOutputChannel.getInputChannelID()); iter.remove(); } } // end for // create tree node for current instance actualNode = new TreeNode(firstTarget.getAllocatedResource().getInstance(), actualInstance, connectionID, actualLocalTargets); receiverNodes.add(actualNode); } // end while // Do we want to shuffle the receiver nodes? // Only randomize the receivers, as the sender (the first one) has to stay the same if (randomize) { Collections.shuffle(receiverNodes); } else { // Sort Tree Nodes according to host name.. Collections.sort(receiverNodes); } treeNodes.addAll(receiverNodes); return treeNodes; }
From source file:business.ImageManager.java
public ImageIcon getTeaser() { List<String> listTeaser = new ArrayList<String>(); listTeaser.add("/images/teaser/Walker_image.png"); listTeaser.add("/images/teaser/Esparta_image.png"); listTeaser.add("/images/teaser/Hobbit_image.png"); listTeaser.add("/images/teaser/All3_image.png"); Collections.shuffle(listTeaser); final ImageIcon ret = new ImageIcon(getClass().getResource(listTeaser.get(0))); return (ret); }
From source file:clummy.classes.DataHandlingClass.java
/** * get the list of gender/*from ww w .ja v a2s . co m*/ * @return */ public List<String> getListOfGender() { ArrayList<String> genderList = new ArrayList<>(); if (genderFormat.equalsIgnoreCase("MaFe")) { for (int i = 0; genderList.size() < totalListFromName; i++) { if (random.nextBoolean()) genderList.add(MALE_GENDER_LONG); else genderList.add(FEMALE_GENDER_LONG); } } else { for (int i = 0; genderList.size() < totalListFromName; i++) { if (random.nextBoolean()) genderList.add(MALE_GENDER_SHORT); else genderList.add(FEMALE_GENDER_SHORT); } } Collections.shuffle(genderList); return genderList; }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * @return all KNOWN servers of the cluster *//*from w ww . j av a 2 s .c o m*/ public Collection<Member> getServersInCluster() { List<Member> servers = new LinkedList<Member>(); for (Member node : getController().getNodeManager().getNodesAsCollection()) { if (node.isServer()) { servers.add(node); } } // Every day I'm shuffleing Collections.shuffle(servers); return servers; }
From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.NetworkLikelihoodFromGTTBL.java
protected double findOptimalBranchLength(final Network<Object> speciesNetwork, final Map<String, List<String>> species2alleles, final List gts, final List gtCorrespondence, final Set<String> singleAlleleSpecies) { boolean continueRounds = true; // keep trying to improve network if (_pair2time == null) { computePairwiseCoalesceTime(gts, species2alleles); }//from ww w.j a v a 2 s .c o m //System.out.println("\n"+speciesNetwork); final Map<NetNode, Double> node2constraints = new Hashtable<NetNode, Double>(); computeNodeHeightUpperbound(speciesNetwork, node2constraints); final Map<NetNode<Object>, Double> node2height = new Hashtable<NetNode<Object>, Double>(); initializeNetwork(speciesNetwork, node2constraints, node2height); double initialProb = computeProbability(speciesNetwork, gts, species2alleles, gtCorrespondence); final Container<Double> lnGtProbOfSpeciesNetwork = new Container<Double>(initialProb); // records the GTProb of the network at all times final Container<Map<NetNode<Object>, Double>> node2heightContainer = new Container<Map<NetNode<Object>, Double>>( node2height); int roundIndex = 0; for (; roundIndex < _maxRounds && continueRounds; roundIndex++) { double lnGtProbLastRound = lnGtProbOfSpeciesNetwork.getContents(); List<Proc> assigmentActions = new ArrayList<Proc>(); // store adjustment commands here. Will execute them one by one later. for (final NetNode<Object> child : speciesNetwork.getNetworkNodes()) // find every hybrid node { Iterator<NetNode<Object>> hybridParents = child.getParents().iterator(); final NetNode hybridParent1 = hybridParents.next(); final NetNode hybridParent2 = hybridParents.next(); assigmentActions.add(new Proc() { public void execute() { UnivariateFunction functionToOptimize = new UnivariateFunction() { public double value(double suggestedProb) { double incumbentHybridProbParent1 = child.getParentProbability(hybridParent1); child.setParentProbability(hybridParent1, suggestedProb); child.setParentProbability(hybridParent2, 1.0 - suggestedProb); double lnProb = computeProbability(speciesNetwork, gts, species2alleles, gtCorrespondence); if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // change improved GTProb, keep it { lnGtProbOfSpeciesNetwork.setContents(lnProb); } else // change did not improve, roll back { child.setParentProbability(hybridParent1, incumbentHybridProbParent1); child.setParentProbability(hybridParent2, 1.0 - incumbentHybridProbParent1); } return lnProb; } }; BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent. try { optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE, 0, 1.0); } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded { } } }); } for (final NetNode<Object> node : Networks.postTraversal(speciesNetwork)) { if (node.isLeaf()) { continue; } assigmentActions.add(new Proc() { public void execute() { final Container<Double> minHeight = new Container<Double>(0.0); final Container<Double> maxHeight = new Container<Double>(Double.MAX_VALUE); for (NetNode<Object> child : node.getChildren()) { double childHeight = node2heightContainer.getContents().get(child); minHeight.setContents(Math.max(minHeight.getContents(), childHeight)); } double minParent = Double.MAX_VALUE; if (!node.isRoot()) { for (NetNode<Object> parent : node.getParents()) { double parentHeight = node2heightContainer.getContents().get(parent); minParent = Math.min(minParent, parentHeight); } } else { minParent = minHeight.getContents() + _maxBranchLength; } maxHeight.setContents(Math.min(minParent, node2constraints.get(node))); //System.out.println("\nChanging node " + node.getName() + " from " + minHeight.getContents() + " to " + maxHeight.getContents()); UnivariateFunction functionToOptimize = new UnivariateFunction() { public double value(double suggestedHeight) { // brent suggests a new branch length double incumbentHeight = node2heightContainer.getContents().get(node); for (NetNode<Object> child : node.getChildren()) { child.setParentDistance(node, suggestedHeight - node2heightContainer.getContents().get(child)); } if (!node.isRoot()) { for (NetNode<Object> parent : node.getParents()) { node.setParentDistance(parent, node2heightContainer.getContents().get(parent) - suggestedHeight); } } double lnProb = computeProbability(speciesNetwork, gts, species2alleles, gtCorrespondence); //System.out.print("suggest: "+ suggestedHeight + " " + lnProb + " vs. " + lnGtProbOfSpeciesNetwork.getContents() + ": "); if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // did improve, keep change { lnGtProbOfSpeciesNetwork.setContents(lnProb); node2heightContainer.getContents().put(node, suggestedHeight); //System.out.println( " better "); } else // didn't improve, roll back change { for (NetNode<Object> child : node.getChildren()) { child.setParentDistance(node, incumbentHeight - node2heightContainer.getContents().get(child)); } if (!node.isRoot()) { for (NetNode<Object> parent : node.getParents()) { node.setParentDistance(parent, node2heightContainer.getContents().get(parent) - incumbentHeight); } } //System.out.println( " worse "); } return lnProb; } }; BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent. try { optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE, minHeight.getContents(), maxHeight.getContents()); } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded { } //System.out.println(network2String(speciesNetwork) + " " + lnGtProbOfSpeciesNetwork.getContents()); } }); } Collections.shuffle(assigmentActions); for (Proc assigment : assigmentActions) // for each change attempt, perform attempt { assigment.execute(); } if (((double) lnGtProbOfSpeciesNetwork.getContents()) == lnGtProbLastRound) // if no improvement was made wrt to last around, stop trying to find a better assignment { continueRounds = false; } else if (lnGtProbOfSpeciesNetwork.getContents() > lnGtProbLastRound) // improvement was made, ensure it is large enough wrt to improvement threshold to continue searching { double improvementPercentage = Math.pow(Math.E, (lnGtProbOfSpeciesNetwork.getContents() - lnGtProbLastRound)) - 1.0; // how much did we improve over last round //System.out.println(improvementPercentage + " vs. " + _improvementThreshold); if (improvementPercentage < _improvementThreshold) // improved, but not enough to keep searching { continueRounds = false; } } else { throw new IllegalStateException("Should never have decreased prob."); } } //System.out.print("\n" + lnGtProbOfSpeciesNetwork.getContents() + ": " + speciesNetwork); return lnGtProbOfSpeciesNetwork.getContents(); }
From source file:com.cloud.storage.StorageManagerImpl.java
@Override public List<StoragePoolVO> ListByDataCenterHypervisor(long datacenterId, HypervisorType type) { List<StoragePoolVO> pools = _storagePoolDao.listByDataCenterId(datacenterId); List<StoragePoolVO> retPools = new ArrayList<StoragePoolVO>(); for (StoragePoolVO pool : pools) { if (pool.getStatus() != StoragePoolStatus.Up) { continue; }/*from w ww .j a v a 2 s .c o m*/ if (pool.getScope() == ScopeType.ZONE) { if (pool.getHypervisor() != null && pool.getHypervisor() == type) { retPools.add(pool); } } else { ClusterVO cluster = _clusterDao.findById(pool.getClusterId()); if (type == cluster.getHypervisorType()) { retPools.add(pool); } } } Collections.shuffle(retPools); return retPools; }
From source file:net.sourceforge.subsonic.ajax.PlayQueueService.java
public PlayQueueInfo playShuffle(String albumListType, int offset, int count, String genre, String decade) throws Exception { HttpServletRequest request = WebContextFactory.get().getHttpServletRequest(); HttpServletResponse response = WebContextFactory.get().getHttpServletResponse(); String username = securityService.getCurrentUsername(request); UserSettings userSettings = settingsService.getUserSettings(securityService.getCurrentUsername(request)); MusicFolder selectedMusicFolder = settingsService.getSelectedMusicFolder(username); List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(username, selectedMusicFolder == null ? null : selectedMusicFolder.getId()); List<MediaFile> albums; if ("highest".equals(albumListType)) { albums = ratingService.getHighestRatedAlbums(offset, count, musicFolders); } else if ("frequent".equals(albumListType)) { albums = mediaFileService.getMostFrequentlyPlayedAlbums(offset, count, musicFolders); } else if ("recent".equals(albumListType)) { albums = mediaFileService.getMostRecentlyPlayedAlbums(offset, count, musicFolders); } else if ("newest".equals(albumListType)) { albums = mediaFileService.getNewestAlbums(offset, count, musicFolders); } else if ("starred".equals(albumListType)) { albums = mediaFileService.getStarredAlbums(offset, count, username, musicFolders); } else if ("random".equals(albumListType)) { albums = searchService.getRandomAlbums(count, musicFolders); } else if ("alphabetical".equals(albumListType)) { albums = mediaFileService.getAlphabeticalAlbums(offset, count, true, musicFolders); } else if ("decade".equals(albumListType)) { int fromYear = Integer.parseInt(decade); int toYear = fromYear + 9; albums = mediaFileService.getAlbumsByYear(offset, count, fromYear, toYear, musicFolders); } else if ("genre".equals(albumListType)) { albums = mediaFileService.getAlbumsByGenre(offset, count, genre, musicFolders); } else {/* ww w . j ava2s . co m*/ albums = Collections.emptyList(); } List<MediaFile> songs = new ArrayList<MediaFile>(); for (MediaFile album : albums) { songs.addAll(mediaFileService.getChildrenOf(album, true, false, false)); } Collections.shuffle(songs); songs = songs.subList(0, Math.min(40, songs.size())); Player player = getCurrentPlayer(request, response); return doPlay(request, player, songs).setStartPlayerAt(0); }
From source file:edu.cornell.med.icb.clustering.TestMCLClusterer.java
/** * Tests clustering with lists of object types. */// www . j a va 2s .c om @Test public void clusterObjectCollections() { final List<Object> peoplePlacesAndThings = new ArrayList<Object>(); final Person tom = new Person() { }; final Person dick = new Person() { }; final Person harry = new Person() { }; peoplePlacesAndThings.add(tom); peoplePlacesAndThings.add(dick); peoplePlacesAndThings.add(harry); final Place home = new Place() { }; final Place work = new Place() { }; final Place school = new Place() { }; peoplePlacesAndThings.add(home); peoplePlacesAndThings.add(work); peoplePlacesAndThings.add(school); final Thing pencil = new Thing() { }; final Thing pen = new Thing() { }; final Thing paper = new Thing() { }; final Thing stapler = new Thing() { }; peoplePlacesAndThings.add(pencil); peoplePlacesAndThings.add(pen); peoplePlacesAndThings.add(paper); peoplePlacesAndThings.add(stapler); // put things in a random order just to make things interesting Collections.shuffle(peoplePlacesAndThings); final Clusterer clusterer = new MCLClusterer(peoplePlacesAndThings.size()); final List<int[]> clusters = clusterer.cluster(new MaxLinkageDistanceCalculator() { public double distance(final int i, final int j) { final Object object1 = peoplePlacesAndThings.get(i); final Object object2 = peoplePlacesAndThings.get(j); if (object1 instanceof Person && object2 instanceof Person) { return 0; } else if (object1 instanceof Place && object2 instanceof Place) { return 0; } else if (object1 instanceof Thing && object2 instanceof Thing) { return 0; } else { return 42; } } }, 1.0f); assertNotNull("Cluster should not be null", clusters); assertEquals("There should be 3 clusters", 3, clusters.size()); boolean peopleClustered = false; boolean placesClustered = false; boolean thingsClustered = false; for (final int[] cluster : clusters) { // check the type of the first, so we know what we're dealing with final Object object = peoplePlacesAndThings.get(cluster[0]); if (object instanceof Person) { assertEquals("There should be 3 people", 3, cluster.length); assertFalse("There appears to be more than one cluster of people", peopleClustered); peopleClustered = true; for (int i = 1; i < cluster.length; i++) { final Object person = peoplePlacesAndThings.get(cluster[i]); assertTrue("Cluster contains more than people", person instanceof Person); } } else if (object instanceof Place) { assertEquals("There should be 3 places", 3, cluster.length); assertFalse("There appears to be more than one cluster of places", placesClustered); placesClustered = true; for (int i = 1; i < cluster.length; i++) { final Object place = peoplePlacesAndThings.get(cluster[i]); assertTrue("Cluster contains more than places", place instanceof Place); } } else if (object instanceof Thing) { assertEquals("There should be 4 things", 4, cluster.length); assertFalse("There appears to be more than one cluster of things", thingsClustered); thingsClustered = true; for (int i = 1; i < cluster.length; i++) { final Object thing = peoplePlacesAndThings.get(cluster[i]); assertTrue("Cluster contains more than things", thing instanceof Thing); } } else { fail("Cluster contains an unknown object type: " + object.getClass().getName()); } } assertTrue("People should have been clustered", peopleClustered); assertTrue("Places should have been clustered", placesClustered); assertTrue("Things should have been clustered", thingsClustered); }
From source file:ch.epfl.eagle.daemon.scheduler.Scheduler.java
/** * Adds constraints such that tasks in the job will be spread evenly across * the cluster./* w w w . j a va2 s.c o m*/ * * We expect three of these special jobs to be submitted; 3 sequential calls * to this method will result in spreading the tasks for the 3 jobs across * the cluster such that no more than 1 task is assigned to each machine. */ private TSchedulingRequest addConstraintsToSpreadTasks(TSchedulingRequest req) throws TException { LOG.info("Handling spread tasks request: " + req); int specialCaseIndex = specialCaseCounter.incrementAndGet(); if (specialCaseIndex < 1 || specialCaseIndex > 3) { LOG.error("Invalid special case index: " + specialCaseIndex); } // No tasks have preferences and we have the magic number of tasks TSchedulingRequest newReq = new TSchedulingRequest(); newReq.user = req.user; newReq.app = req.app; newReq.probeRatio = req.probeRatio; List<InetSocketAddress> allBackends = Lists.newArrayList(); List<InetSocketAddress> backends = Lists.newArrayList(); // We assume the below always returns the same order (invalid // assumption?) for (InetSocketAddress backend : state.getBackends(req.app)) { allBackends.add(backend); } // Each time this is called, we restrict to 1/3 of the nodes in the // cluster for (int i = 0; i < allBackends.size(); i++) { if (i % 3 == specialCaseIndex - 1) { backends.add(allBackends.get(i)); } } Collections.shuffle(backends); if (!(allBackends.size() >= (req.getTasks().size() * 3))) { LOG.error("Special case expects at least three times as many machines as tasks."); return null; } LOG.info(backends); for (int i = 0; i < req.getTasksSize(); i++) { TTaskSpec task = req.getTasks().get(i); TTaskSpec newTask = new TTaskSpec(); newTask.message = task.message; newTask.taskId = task.taskId; newTask.preference = new TPlacementPreference(); newTask.preference.addToNodes(backends.get(i).getHostName()); newReq.addToTasks(newTask); } LOG.info("New request: " + newReq); return newReq; }
From source file:gov.nasa.jpf.constraints.solvers.cw.CWSolver.java
private Result solveWithAdaptiveVariableSearch(Expression<Boolean> linearConstraint, Valuation linearSolution, Expression<Boolean> nonlinearConstraint, Valuation result) { // Partially based on the paper "Yet Another Local Search Method for Constraint Solving" // by Philippe Codognet and Daniel Diaz, 2001. // NOTE: End-of-line comments give the variable names and line numbers // used in Algorithms 1 and 2 of the paper. // Interpret every variable in the path condition as a dimension // in a real-valued vector space. Set<Variable<?>> vars = union(ExpressionUtil.freeVariables(linearConstraint), ExpressionUtil.freeVariables(nonlinearConstraint)); RealVectorSpace vectorSpace = RealVectorSpace.forDimensions(vars); int numberOfVariables = vectorSpace.dimensions().size(); RealVector p = makeVectorFromSolutions(vectorSpace, linearSolution); // Alg. 1: \alpha, line 4 printDebug(CWSolver.class, "Linear PC: ", linearConstraint); printDebug(CWSolver.class, "Linear PC solution: ", p); printDebug(CWSolver.class, "Solving non-linear PC\n", nonlinearConstraint); List<Expression<Boolean>> nonLinearConstraintsLst = ExpressionClassifier .splitToConjuncts(nonlinearConstraint); // Initialize lookup tables and local variables Map<Expression<Boolean>, BitSet> variableIndicesByConstraint = new IdentityHashMap<>( nonLinearConstraintsLst.size()); @SuppressWarnings("unchecked") List<Expression<Boolean>>[] constraintsByVariableIndex = new List[numberOfVariables]; populateLookupTables(vectorSpace, nonLinearConstraintsLst, constraintsByVariableIndex, variableIndicesByConstraint); double[] errorByVariables = new double[numberOfVariables]; // Alg. 1: \epsilon int[] tabuVariables = new int[numberOfVariables]; // Alg. 1: \tau int iterationCount = 1; // i int iterationLimit = nonLinearConstraintsLst.size() * ITERATIONS_PER_CONSTRAINT; // Alg. 1: I //iterate as long as non linear constraint is not satisfied while (!nonlinearConstraint.evaluate(p.convertToJconstraintsValuation())) { // Alg. 1: line 7 if (iterationCount > iterationLimit) { // Alg. 1: line 8 printDebug(CWSolver.class, "Could not find solution within ", iterationLimit, " iterations"); return Result.DONT_KNOW; }/* w w w. j ava2s.co m*/ ++iterationCount; // Alg. 1: line 9 // Compute errors double errorAtP = 0.0; // Alg. 1: e_\alpha Arrays.fill(errorByVariables, 0.0); // Alg. 1: line 14 for (Expression<Boolean> c : nonLinearConstraintsLst) { // Alg. 1: lines 15--20 if (c instanceof PropositionalCompound) { System.out.println("propositional compound. Skipping"); continue; } //TODO: fix the list; it must be composed of NumericBooleanExpressions (stronger type) if (!(c instanceof NumericBooleanExpression)) throw new IllegalStateException("constraint must be " + NumericBooleanExpression.class.getName() + " and not of type " + c.getClass().getName()); NumericBooleanExpression nc = (NumericBooleanExpression) c; double e = computeError(nc, p.convertToJconstraintsValuation()); errorAtP += e; incrementElements(errorByVariables, variableIndicesByConstraint.get(c), e); } printDebug(CWSolver.class, "p = ", p, " -> error ", errorAtP); // Try to find a better solution by modifying the "worst" non-tabu variable int wiggleVarIndex = indexOfMaxIgnoringTabu(errorByVariables, tabuVariables); if (wiggleVarIndex == -1) { // All variables might be tabu, Alg. 1: lines 10--13 for (int i = 0; i < tabuVariables.length; ++i) { p = makeRandomNeighborInPolytope(p, linearConstraint, vectorSpace.dimensions().get(i)); if (p == null) { //no point could be found, so dont_know? return Result.DONT_KNOW; } tabuVariables[i] = 0; } printDebug(CWSolver.class, "All variables are tabu. Took random step to ", p); continue; } Variable<?> wiggleVar = vectorSpace.dimensions().get(wiggleVarIndex); // Alg. 1: x, line 21 printDebug(CWSolver.class, "Wiggling ", wiggleVar); // Find best neighbor (Algorithm 3) double minError = Double.POSITIVE_INFINITY; // Alg. 3: e_\mu RealVector minNeighbor = null; for (int i = 0; i < NEIGHBORS_GENERATED_PER_ITERATION; ++i) { RealVector q = makeRandomNeighborInPolytope(p, linearConstraint, wiggleVar); // Alg. 3: \beta RealVector r = null; // Alg. 3: \gamma if (q == null) { // No random neighbor could be found break; } double errorAtQ = computeError(nonLinearConstraintsLst, q.convertToJconstraintsValuation()); // Alg. 3: e_\beta, line 7 double errorAtR = Double.POSITIVE_INFINITY; // Alg. 3: e_\gamma if (ENABLE_BISECTION && constraintsByVariableIndex[wiggleVarIndex] != null) { // Alg. 3: line 5 // Pick a random unsatisfied constraint List<Expression<Boolean>> constraintsForVar = new ArrayList<>( constraintsByVariableIndex[wiggleVarIndex]); Collections.shuffle(constraintsForVar); Expression<Boolean> constraint = null; for (int k = 0; k < constraintsForVar.size(); ++k) { constraint = constraintsForVar.get(k); boolean sat = constraint.evaluate(p.convertToJconstraintsValuation()); if (!sat) { break; } } Number valueAtP = evaluateAndSubtractSides((NumericBooleanExpression) constraint, p.convertToJconstraintsValuation()); Number valueAtQ = evaluateAndSubtractSides((NumericBooleanExpression) constraint, q.convertToJconstraintsValuation()); r = linearlyEstimateZero(p, valueAtP, q, valueAtQ, ((NumericBooleanExpression) constraint).getComparator()); // Alg. 3: line 6 boolean sat = linearConstraint.evaluate(r.convertToJconstraintsValuation()); if (sat) { errorAtR = computeError(nonLinearConstraintsLst, r.convertToJconstraintsValuation()); } } printDebug(CWSolver.class, "Random neighbors"); printDebug(CWSolver.class, " q = ", q, " -> error ", errorAtQ); printDebug(CWSolver.class, " r = ", r, " -> error ", errorAtR); if (errorAtQ < minError) { // Alg. 3: lines 9--12 minError = errorAtQ; minNeighbor = q; } if (errorAtR < minError) { // Alg. 3: lines 13--16 minError = errorAtR; minNeighbor = r; } } if (ENABLE_SEEDING) { for (double seed : SEEDED_VALUES) { RealVector s = vectorSpace.makeVector(p).set(wiggleVar, seed).build(); double errorAtS = computeError(nonLinearConstraintsLst, s.convertToJconstraintsValuation()); boolean sat = linearConstraint.evaluate(s.convertToJconstraintsValuation()); if (sat && errorAtS < minError) { minError = errorAtS; minNeighbor = s; } } } if (minError < errorAtP) { // Alg. 1: lines 23--27 printDebug(CWSolver.class, "Found new neighbor"); p = minNeighbor; decrementElements(tabuVariables); } else { // Alg 1: lines 27--29 printDebug(CWSolver.class, "Could not find better neighbor"); tabuVariables[wiggleVarIndex] = Math.max( Math.round(TABU_ITERATIONS_PER_VARIABLE * vectorSpace.dimensions().size()), MIN_TABU_ITERATIONS); printDebug(CWSolver.class, "Tabu ", Arrays.toString(tabuVariables)); } } printDebug(CWSolver.class, "Found solution: ", p); for (Variable<?> v : vars) { double vectorVal = p.get(v); if (v.getType() instanceof IntegerType<?>) { result.setValue((Variable<Integer>) v, (int) vectorVal); } else if (v.getType() instanceof RealType<?>) { result.setValue((Variable<Double>) v, vectorVal); } } System.out.println("cwsolver solution: " + result.toString()); return Result.SAT; }