Package edu.brown.markov

Examples of edu.brown.markov.MarkovVertex


            throw new RuntimeException(ex);
        }
        assert(state.isInitialized()) :
            "Unexpectted uninitialized MarkovEstimatorState\n" + state;
       
        MarkovVertex start = markov.getStartVertex();
        assert(start != null) : "The start vertex is null. This should never happen!";
        MarkovEstimate initialEst = state.createNextEstimate(start, true);
        this.estimatePath(state, initialEst, catalog_proc, args);
       
        if (debug.val) {
View Full Code Here


       
        // If we get here, then we should definitely have a MarkovGraph
        MarkovGraph markov = state.getMarkovGraph();
        assert(markov != null);
           
        MarkovVertex current = state.getCurrent();
        PartitionSet touchedPartitions = state.getTouchedPartitions();
        MarkovVertex next_v = null;
        MarkovEdge next_e = null;
        Statement last_stmt = null;
        int stmt_idxs[] = null;

        // We can cache what the path is based on the first and last query in the batch
View Full Code Here

        // we don't want to try to update the model, because we will end up
        // connecting the START vertex to the COMMIT vertex, which is not correct
        if (state.isUpdatesEnabled()) {
            // We need to update the counter information in our MarkovGraph so that we know
            // that the procedure may transition to the ABORT vertex from where ever it was before
            MarkovVertex current = state.getCurrent();
            assert(current != null) :
                String.format("Missing current vertex for %s\n%s",
                              TransactionUtil.formatTxnName(markov.getProcedure(), txn_id), state);
           
            // If we don't have the terminal vertex, then we know that we don't care about
            // what this transaction actually did
            MarkovVertex next_v = markov.getFinishVertex(status);
            if (next_v == null) {
                if (this.profiler != null) this.profiler.finish_time.appendTime(timestamp);
                return;
            }
           
View Full Code Here

        if (debug.val)
            LOG.debug(String.format("%s - Estimating execution path (%s)",
                      TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                      (est.isInitialEstimate() ? "INITIAL" : "BATCH #" + est.getBatchId())));
       
        MarkovVertex currentVertex = est.getVertex();
        assert(currentVertex != null);
        if (this.enable_recomputes) {
            this.markovTimes.addInstanceTime(currentVertex, state.getTransactionId(), EstTime.currentTimeMillis());
        }
     
        // TODO: If the current vertex is in the initial estimate's list,
        // then we can just use the truncated list as the estimate, since we know
        // that the path will be the same. We don't need to recalculate everything
        MarkovGraph markov = state.getMarkovGraph();
        assert(markov != null) :
            String.format("Unexpected null MarkovGraph for %s [hashCode=%d]\n%s",
                          TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                          state.hashCode(), state);
        boolean compute_path = true;
        if (hstore_conf.site.markov_fast_path && currentVertex.isStartVertex() == false) {
            List<MarkovVertex> initialPath = ((MarkovEstimate)state.getInitialEstimate()).getMarkovPath();
            if (initialPath.contains(currentVertex)) {
                if (debug.val)
                    LOG.debug(String.format("%s - Using fast path estimation for %s[#%d]",
                              TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()), markov, markov.getGraphId()));
                if (this.profiler != null) timestamp = ProfileMeasurement.getTime();
                try {
                    MarkovPathEstimator.fastEstimation(est, initialPath, currentVertex);
                    compute_path = false;
                } finally {
                    if (this.profiler != null) this.profiler.fastest_time.appendTime(timestamp);
                }
            }
        }
        // We'll reuse the last MarkovPathEstimator (and it's path) if the graph has been accurate for
        // other previous transactions. This prevents us from having to recompute the path every single time,
        // especially for single-partition transactions where the clustered MarkovGraphs are accurate
        else if (hstore_conf.site.markov_path_caching) {
            List<MarkovVertex> cached = this.cached_paths.get(markov);
            if (cached == null) {
                if (debug.val)
                    LOG.debug(String.format("%s - No cached path available for %s[#%d]",
                              TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                              markov, markov.getGraphId()));
            }
            else if (markov.getAccuracyRatio() < hstore_conf.site.markov_path_caching_threshold) {
                if (debug.val)
                    LOG.debug(String.format("%s - MarkovGraph %s[#%d] accuracy is below caching threshold [%.02f < %.02f]",
                              TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                              markov, markov.getGraphId(), markov.getAccuracyRatio(),
                              hstore_conf.site.markov_path_caching_threshold));
            }
            else {
                if (debug.val)
                    LOG.debug(String.format("%s - Using cached path for %s[#%d]",
                              TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                              markov, markov.getGraphId()));
                if (this.profiler != null) timestamp = ProfileMeasurement.getTime();
                try {
                    MarkovPathEstimator.fastEstimation(est, cached, currentVertex);
                    compute_path = false;
                } finally {
                    if (this.profiler != null) this.profiler.cachedest_time.appendTime(timestamp);
                }
            }
        }
       
        // Use the MarkovPathEstimator to estimate a new path for this txn
        if (compute_path) {
            if (debug.val)
                LOG.debug(String.format("%s - Need to compute new path in %s[#%d] using %s",
                          TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId()),
                          markov, markov.getGraphId(),
                          MarkovPathEstimator.class.getSimpleName()));
            MarkovPathEstimator pathEstimator = null;
            try {
                pathEstimator = (MarkovPathEstimator)this.pathEstimatorsPool.borrowObject();
                pathEstimator.init(state.getMarkovGraph(), est, args, state.getBasePartition());
               
                pathEstimator.setForceTraversal(hstore_conf.site.markov_force_traversal);
                pathEstimator.setLearningEnabled(hstore_conf.site.markov_learning_enable);
            } catch (Throwable ex) {
                String txnName = TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId());
                String msg = "Failed to intitialize new MarkovPathEstimator for " + txnName;
                LOG.error(msg, ex);
                throw new RuntimeException(msg, ex);
            }
           
            if (this.profiler != null) timestamp = ProfileMeasurement.getTime();
            try {
                pathEstimator.traverse(est.getVertex());
            } catch (Throwable ex) {
                try {
                    GraphvizExport<MarkovVertex, MarkovEdge> gv = MarkovUtil.exportGraphviz(markov, true, markov.getPath(pathEstimator.getVisitPath()));
                    LOG.error("GRAPH #" + markov.getGraphId() + " DUMP: " + gv.writeToTempFile(catalog_proc));
                } catch (Exception ex2) {
                    throw new RuntimeException(ex2);
                }
                String msg = "Failed to estimate path for " + TransactionUtil.formatTxnName(catalog_proc, state.getTransactionId());
                LOG.error(msg, ex);
                throw new RuntimeException(msg, ex);
            } finally {
                if (this.profiler != null) this.profiler.fullest_time.appendTime(timestamp);
            }
           
            // If our path was incomplete or we created new vertices during the traversal,
            // then we should tell the PartitionExecutor that we need updates about this
            // txn so that we can populate the MarkovGraph
            if (hstore_conf.site.markov_learning_enable && est.isInitialEstimate()) {
                Collection<MarkovVertex> createdVertices = pathEstimator.getCreatedVertices();
                MarkovVertex v = CollectionUtil.last(est.getMarkovPath());
                if ((createdVertices != null && createdVertices.isEmpty() == false) ||
                     (v.isQueryVertex() == true || v.isStartVertex())) {
                    if (debug.val)
                        LOG.debug(String.format("Enabling runtime updates for %s " +
                              "[createdVertices=%s, lastVertex=%s]",
                              state.getTransactionId(), createdVertices, v));
                    state.shouldAllowUpdates(true);
View Full Code Here

        assert(markov != null);
       
        // Examine all of the vertices that are adjacent to our current vertex
        // and see which vertex we are going to move to next
        PartitionSet touchedPartitions = state.getTouchedPartitions();
        MarkovVertex current = state.getCurrent();
        assert(current != null);
        MarkovVertex next_v = null;
        MarkovEdge next_e = null;
       
        // Synchronize on the single vertex so that it's more fine-grained than the entire graph
        synchronized (current) {
            Collection<MarkovEdge> edges = markov.getOutEdges(current);
            if (edges != null) {
                if (debug.val)
                    LOG.debug(String.format("Examining %d edges from %s for txn #%d",
                              edges.size(), current, state.getTransactionId()));
                for (MarkovEdge e : edges) {
                    MarkovVertex v = markov.getDest(e);
                    if (v.isEqual(catalog_stmt, partitions, touchedPartitions, queryCounter)) {
                        if (debug.val)
                            LOG.debug("Found next vertex " + v + " for Txn #" + state.getTransactionId());
                        next_v = v;
                        next_e = e;
                        break;
                    }
                } // FOR
            }
       
            // If we fail to find the next vertex, that means we have to dynamically create a new
            // one. The graph is self-managed, so we don't need to worry about whether
            // we need to recompute probabilities.
            if (next_v == null) {
                next_v = new MarkovVertex(catalog_stmt,
                                          MarkovVertex.Type.QUERY,
                                          queryCounter,
                                          partitions,
                                          touchedPartitions);
                assert(markov.containsVertex(current)) :
View Full Code Here

                      this.next_statements));
           
            // We're allow to create the vertices that we know are missing
            if (this.learning_enabled && this.next_statements.size() == 1) {
                CountedStatement cntStmt = CollectionUtil.first(this.next_statements);
                MarkovVertex v = new MarkovVertex(cntStmt.statement,
                                                  MarkovVertex.Type.QUERY,
                                                  cntStmt.counter,
                                                  this.stmt_partitions,
                                                  this.past_partitions);
                markov.addVertex(v);
               
                // For now we'll set the new edge's probability to 1.0 to just
                // make the calculations down below work. This will get updated
                // overtime when we recompute the probabilities in the entire graph.
                candidate_edge = new MarkovEdge(markov, 1, 1.0f);
                markov.addEdge(candidate_edge, element, v, EdgeType.DIRECTED);
                this.candidate_edges.add(candidate_edge);
               
                if (this.created_vertices == null) this.created_vertices = new HashSet<MarkovVertex>();
                this.created_vertices.add(v);
                if (trace.val)
                    LOG.trace(String.format("Created new vertex %s and connected it to %s", v, element));
               
                // 2012-10-21
                // The problem with allowing the estimator to create a new vertex is that
                // we don't know what it's children are going to be. That means that when
                // we invoke this method again at the next vertex (the one we just made above)
                // then it's not going to have any children, so we don't know what it's
                // going to do. We are actually better off with just grabbing the next best
                // vertex from the existing edges and then updating the graph after
                // the txn has finished, since now we know exactly what it did.
               
            }
            // Otherwise we'll just make all of the outbound edges from the
            // current vertex be our candidates
            else {
                if (trace.val)
                    LOG.trace("No candidate edges were found. Force travesal flag is set to true, so taking all");
                Collection<MarkovEdge> out_edges = markov.getOutEdges(element);
                if (out_edges != null) this.candidate_edges.addAll(out_edges);
            }
            num_candidates = this.candidate_edges.size();
            was_forced = true;
        }
       
        // So now we have our list of candidate edges. We can pick the first one
        // since they will be sorted by their probability
        if (trace.val) LOG.trace("Candidate Edges: " + this.candidate_edges);
        if (num_candidates > 0) {
            MarkovEdge next_edge = CollectionUtil.first(this.candidate_edges);
            assert(next_edge != null) : "Unexpected null edge " + this.candidate_edges;
            MarkovVertex next_vertex = markov.getOpposite(element, next_edge);
            children.addAfter(next_vertex);
            if (was_forced) {
                if (this.forced_vertices == null) this.forced_vertices = new HashSet<MarkovVertex>();
                this.forced_vertices.add(next_vertex);
            }

            if (debug.val) {
                StringBuilder sb = new StringBuilder();
                sb.append(String.format("#%02d CANDIDATES:\n", this.getDepth()));
                int i = 0;
                for (MarkovEdge e : this.candidate_edges) {
                    MarkovVertex v = markov.getOpposite(element, e);
                    sb.append(String.format("  [%d] %s  --[%s]--> %s%s%s",
                              i++, element, e, v,
                              (next_vertex.equals(v) ? " <== SELECTED" : ""),
                              (trace.val && this.candidate_edges.size() > 1 ? "\n"+StringUtil.addSpacers(v.debug()) : "")));
                } // FOR
                LOG.debug(sb.toString());
            } // DEBUG
           
            // If there was only one next Statement that we could possibly execute here,
View Full Code Here

        pathEstimator.setLearningEnabled(true);
        pathEstimator.setForceTraversal(true);
        boolean first = true;
        boolean found_autolearn = false;
        for (TransactionTrace tt : workload) {
            MarkovVertex last_v = graph.getStartVertex();
           
            // We have to inject at least one path through the system first
            // so that it knows what Statements it should be considering
            if (first) {
                assertEquals(estimate.toString(), 0, estimate.getMarkovPath().size());
                Histogram<Statement> stmtCounter = new ObjectHistogram<Statement>();
                PartitionSet allPartitions = new PartitionSet();
                for (QueryTrace qt : tt.getQueries()) {
                    Statement stmt = qt.getCatalogItem(catalogContext.database);
                    int stmtCnt = (int)stmtCounter.get(stmt, 0);
                    PartitionSet partitions = new PartitionSet();
                    p_estimator.getAllPartitions(partitions, qt, BASE_PARTITION);
                   
                    MarkovVertex next_v = new MarkovVertex(stmt,
                                                           MarkovVertex.Type.QUERY,
                                                           stmtCnt,
                                                           partitions,
                                                           allPartitions);
                    graph.addVertex(next_v);
View Full Code Here

   
    /**
     * testSinglePartition
     */
    public void testSinglePartition() throws Exception {
        MarkovVertex start = this.graph.getStartVertex();
        MarkovVertex commit = this.graph.getCommitVertex();
        MarkovVertex abort = this.graph.getAbortVertex();
       
        pathEstimator.init(this.graph, this.estimate, singlep_trace.getParams(), BASE_PARTITION);
        pathEstimator.setForceTraversal(true);
        pathEstimator.traverse(this.graph.getStartVertex());
        assertTrue(estimate.isConfidenceCoefficientSet());
        float confidence = this.estimate.getConfidenceCoefficient();
       
//        System.err.println("INITIAL PATH:\n" + StringUtil.join("\n", path));
//        System.err.println("CONFIDENCE: " + confidence);
//        System.err.println("DUMPED FILE: " + MarkovUtil.exportGraphviz(this.graph, false, this.graph.getPath(path)).writeToTempFile());
//        System.err.println(singlep_trace.debug(catalogContext.database));
//        System.err.println(StringUtil.columns(StringUtil.join("\n", path), this.estimate.toString()));

        ArrayList<MarkovVertex> path = new ArrayList<MarkovVertex>(this.estimate.getMarkovPath());
        assertEquals(path, new ArrayList<MarkovVertex>(pathEstimator.getVisitPath()));
        assertEquals(start, CollectionUtil.first(path));
        assertEquals(commit, CollectionUtil.last(path));
        assertFalse(path.contains(abort));
        assert(confidence > 0.0f);
       
        // All of the vertices should only have the base partition in their partition set
        for (int i = 1, cnt = path.size() - 1; i < cnt; i++) {
            MarkovVertex v = path.get(i);
            assertEquals(1, v.getPartitions().size());
            assert(v.getPartitions().contains(BASE_PARTITION));
        } // FOR
//        GraphvizExport<Vertex, Edge> gv = MarkovUtil.exportGraphviz(this.graph, true, this.graph.getPath(path));
//        FileUtil.writeStringToFile("/tmp/dump.dot", gv.export(this.graph.getProcedure().getName()));
    }
View Full Code Here

     * testMultiPartition
     */
    public void testMultiPartition() throws Exception {
//        System.err.println("MULTI-PARTITION: " + multip_trace);

        MarkovVertex start = this.graph.getStartVertex();
        MarkovVertex commit = this.graph.getCommitVertex();
        MarkovVertex abort = this.graph.getAbortVertex();
       
        pathEstimator.init(this.graph, this.estimate, multip_trace.getParams(), BASE_PARTITION);
        pathEstimator.setForceTraversal(true);
        pathEstimator.traverse(this.graph.getStartVertex());
       
View Full Code Here

            assertTrue(est.toString(), est.getConfidenceCoefficient() >= 0f);
            assertTrue(est.toString(), est.getConfidenceCoefficient() <= 1f);
            assertTrue(est.toString(), est.getMarkovPath().isEmpty() == false);
           
            // The last vertex in each MarkovEstimate should correspond to the last query in each batch
            MarkovVertex last_v = est.getVertex();
            assertNotNull(last_v);
            System.err.println("LAST VERTEX: " + last_v);
            assertEquals(CollectionUtil.last(queries).getCatalogItem(catalogContext.database), last_v.getCatalogItem());
        } // FOR
    }
View Full Code Here

TOP

Related Classes of edu.brown.markov.MarkovVertex

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.