⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 measure.java

📁 一个用于排队系统仿真的开源软件,有非常形象的图象仿真过程!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        //is a multiple of pointSize (x % y is equal to the rest of the division x/y)

        //OLD
        //if (counter % pointSize == 0 || counter != 0)
        //NEW
        //In the old way, mean was updated for each new sample (because counter was >0 !!)
        //instead of waiting for every point size samples
        //@author Stefano Omini
        if (counter % pointSize == 0 && (counter % pointSize) < size_samples && counter >= 0)
            samples[counter / pointSize] = mean.getMean();
        counter++;

        if (analyzer.addSample(sample, weight)) {
            //data analysis finished

            if (!finish) {
                //simulation not finished yet
                finish = true;

                if (output != null) {
                    //writes the final measure
                    output.writeMeasure();
                }
            }
            //simulation already finished

            if (logger.isDebugEnabled()) {
                boolean log_success = analyzer.getSuccess();
                double log_mean = getExtimatedMeanValue();
                logger.debug("Measure " + name + " finished. Mean value: " + log_mean +
                        " Success = " + log_success);
            }


            return true;

        } else if (verbose) {
            //data analysis not finished yet

            if (output != null) {
                //writes the new sample
                output.write(sample, weight);
            }

        }
        //NEW
        //@author Stefano Omini
        if (measureType == SimConstants.RESIDENCE_TIME) {
            scaleMeasure();
        }
        //end NEW
        if (counter == fireEventSize) {
            counter = 0;
            changed = true;

        }
        return false;
    }

    /**Gets the name of the measure.
     * @return name property value.
     */
    public String getName() {
        return name;
    }

    //NEW
    //@author Stefano Omini
    public DynamicDataAnalyzer getAnalyzer() {
        return analyzer;
    }
    //end NEW


    /** Returns analyzed samples percentage.
     * @return analyzed samples percentage.
     */
    public double getSamplesAnalyzedPercentage() {
        return (double) analyzer.getSamples() / analyzer.getMaxData();
    }

    /** Returns max precision percentage reached.
     * @return Max precision percentage reached.
     */
    public double getMaxPrecisionPercentage() {
        double p;
        p = analyzer.getPrecision() * analyzer.getMean() / analyzer.getConfInt();
        if (maxPrecisionPercentage < p)
            maxPrecisionPercentage = p;
        return maxPrecisionPercentage;
    }

    /**
     * Has the simulation already finished?
     * @return true, if the simulation has already finished; false otherwise
     */
    public boolean hasFinished() {
        return finish;
    }

    //DEK (Federico Granata)
    /**
     * gets all requested quantiles
     *
     * @return vector of quatiles, null if quantiles computation wasn't requested
     * while creating the Measure object. See constructor's parameters.
     */
    public double[] getQuantileResults() {
        double[] results;
        if (analyzer instanceof QuantileDataAnalyzer) {
            results = ((QuantileDataAnalyzer) analyzer).getQuantiles();
        } else {
            results = null;
        }
        return results;
    }

    //DEK (Federico Granata)
    /**
     * Checks whether the data is changed
     * @return true iff data is changed
     */
    public boolean isChanged() {
        return changed;
    }

    /**
     * Gets the new analyzed data. Data are divided in batches. Every batch is
     * the sample mean of a group of data weighted.
     * @return data array
     */
    public final double[] getData() {
        return samples;
    }

    /**
     * gets the new data that have been generated; returns null if there aren't
     * new data.
     */
    public Document getNewData() {
        if (!changed) {
            Element root = data.getDocumentElement();
            root.setAttribute("name", name);
            return data;
        }
        changed = false;
        Element root = data.getDocumentElement();
        root.setAttribute("name", name);
        root.setAttribute("meanValue", Double.toString(analyzer.getMean()));
        root.setAttribute("upperBound", Double.toString(getUpperLimit()));
        root.setAttribute("lowerBound", Double.toString(getLowerLimit()));
        root.setAttribute("progress", Double.toString(getSamplesAnalyzedPercentage()));

        root.setAttribute("finished", Boolean.toString(finish));
        root.setAttribute("discarded", Integer.toString(getDiscardedSamples() / pointSize));

        newValues = "";
        for (int i = 0; i < samples.length; i++) {
            newValues += Double.toString(samples[i]) + "/n";
        }
        root.setAttribute("data", newValues);
        root.setAttribute("numData", Integer.toString(samples.length));
        return data;
    }

    /**
     * Creates a DOM (Document Object Model) <code>Document<code>.
     */
    private void createDOM() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            //data is a Document
            data = builder.newDocument();

            Element root = data.createElement("measure");

            root.setAttribute("name", name);
            root.setAttribute("meanValue", "null");
            root.setAttribute("upperBound", "null");
            root.setAttribute("lowerBound", "null");
            root.setAttribute("progress", Double.toString(getSamplesAnalyzedPercentage()));
            root.setAttribute("data", "null");
            root.setAttribute("finished", "false");
            root.setAttribute("discarded", "0");
            root.setAttribute("precision", Double.toString(analyzer.getPrecision()));
            root.setAttribute("maxSamples", Double.toString(getMaxSamples()));

            data.appendChild(root);

        } catch (FactoryConfigurationError factoryConfigurationError) {
            factoryConfigurationError.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

    }





    //NEW
    //@author Stefano Omini


    /**
     * jSIM architecture does not allow to correctly compute residence time for
     * all visits.
     * for this reason a scaling operation is needed.
     * the scale factor is the mean number of accesses to the resource (i.e.
     * the visit ratio = number of accesses to this station / number of
     * accesses to the reference station)
     */

    private void scaleMeasure() {

        //retrieves JobClass object using its name
        JobClass jobClass = network.getJobClass(jobClassName);
        double visitRatio = 1.0;
        //current measure node
        NetNode thisNode = network.getNode(nodeName);

        // If measure is class specific
        if (jobClass != null) {
            //reference node for this job class
            String referenceNodeName = jobClass.getReferenceNodeName();
            NetNode referenceNode = network.getNode(referenceNodeName);
            int visitsReferenceNode, visitsThisNode;
            try {
                //visits to the reference node
                NodeSection refOutputSection = referenceNode.getSection(NodeSection.OUTPUT);
                visitsReferenceNode = refOutputSection.getIntSectionProperty(
                        NodeSection.PROPERTY_ID_ARRIVED_JOBS, jobClass);

                //visits to this node node
                NodeSection thisNodeInputSection = thisNode.getSection(NodeSection.INPUT);

                visitsThisNode = thisNodeInputSection.getIntSectionProperty(
                        NodeSection.PROPERTY_ID_ARRIVED_JOBS, jobClass);


                // the reference source generates a certain number of jobs
                // - some of them have reached this station
                // - other have been dropped before enetering this station or
                // elsewhere in the network
                int droppedJobs = network.getDroppedJobs(jobClass);

                if (thisNodeInputSection instanceof BlockingQueue) {

                    // if the input section is a BlockingQueue,
                    // remove (from the total number of visits)
                    // the jobs dropped by the BlockingQueue itself,
                    // because they have been counted
                    // in arrived jobs
                    visitsThisNode -= ((BlockingQueue) thisNode.getSection(NodeSection.INPUT)).
                            getDroppedJobPerClass(jobClass.getId());

                }

                //visit ratio
                //
                // we must consider only not dropped jobs:
                // --> visit ratio = visits to this node / (visits to ref node - dropped jobs)
                visitRatio = (double) (visitsThisNode) / (visitsReferenceNode -  droppedJobs);

                //System.out.println("refNode: " + Integer.toString(visitsReferenceNode));
                //System.out.println("thisNode: " + Integer.toString(visitsThisNode));
                //System.out.println("dropped: " + droppedJobs);
                //System.out.println("visit ratio: " + Double.toString(visitRatio));

            } catch (NetException ne) {
                visitRatio = 1;
                logger.error("Error in computing visit ratio.");
                ne.printStackTrace();
            }
        }
        // Measure is class-independent --> Bertoli Marco
        else {
            try {
                Iterator it = network.getJobClasses().listIterator();
                double ratioSum= 0.0, weight = 0.0;
                while (it.hasNext()) {
                    JobClass jobC = (JobClass) it.next();
                    //reference node for this job class
                    String referenceNodeName = jobC.getReferenceNodeName();
                    NetNode referenceNode = network.getNode(referenceNodeName);
                    int visitsReferenceNode, visitsThisNode;
                    //visits to the reference node
                    NodeSection refOutputSection = referenceNode.getSection(NodeSection.OUTPUT);
                    visitsReferenceNode = refOutputSection.getIntSectionProperty(
                            NodeSection.PROPERTY_ID_ARRIVED_JOBS, jobC);

                    //visits to this node node
                    NodeSection thisNodeInputSection = thisNode.getSection(NodeSection.INPUT);

                    visitsThisNode = thisNodeInputSection.getIntSectionProperty(
                            NodeSection.PROPERTY_ID_ARRIVED_JOBS, jobC);

                    int droppedJobs = network.getDroppedJobs(jobC);

                    if (thisNodeInputSection instanceof BlockingQueue) {
                        visitsThisNode -= ((BlockingQueue) thisNode.getSection(NodeSection.INPUT)).
                                getDroppedJobPerClass(jobC.getId());

                    }
                    double currVisitRatio = (double) (visitsThisNode) / (visitsReferenceNode -  droppedJobs);

                    // Uses new calculated visit ratio to compute a weighted visit ratio
                    // This is done only if currVisitRatio value is valid
                    if (!Double.isNaN(currVisitRatio) && !Double.isInfinite(currVisitRatio)) {
                        ratioSum += currVisitRatio*visitsThisNode;
                        weight+=visitsThisNode;
                        visitRatio = ratioSum / weight;
                    }
                }
            } catch (NetException ne) {
                visitRatio = 1;
                logger.error("Error in computing visit ratio.");
                ne.printStackTrace();
            }
        }


        //correggere mean upper lower ecc....


        //sets scaled = true (to avoid other scaling operations)
        scaled = true;
        scaleFactor = visitRatio;

    }



    //end NEW




    //******************ABORT**********************//

    public synchronized boolean abortMeasure() {

        if (finish) {
            //measure already finished
            //nothing to do
            return false;
        } else {
            //abort measure
            aborted = true;
            finish = true;
            //stops analyzer
            stopMeasure();

        }

        return true;

    }

// --- Dead Measures Test - Bertoli Marco --------------------------------------------
    /**
     * This method will check if a measure is dead i.e. no samples are received
     * for a long period (so the measure will probably be zero). This is needed to
     * abort measures in stations that are not reachable after initial transient
     * @return true iff measure has been marked as dead and was stopped
     */
    public boolean testDeadMeasure() {
        if (deadState > maxDeadState) {
            stop_NoSamples();
            return true;
        }
        deadState++;
        return false;
    }

// -----------------------------------------------------------------------------------


    //*****************NO SAMPLES TEST*******************//

    //NEW
    //@author Stefano Omini

    public boolean receivedNoSamples() {
        return noSamplesTest;
    }

    public void stop_NoSamples() {
        finish = true;
        noSamplesTest = true;

        //stop measure with success
        stopMeasure(true);
    }


    protected void stopMeasure(boolean success) {
        //stops measure
        analyzer.stopMeasure(success);

        //writes measure output on log
        if (logger.isDebugEnabled()) {

            double log_mean = getExtimatedMeanValue();
            boolean log_success = analyzer.getSuccess();

            logger.debug("Measure " + name + " finished. Mean value: " + log_mean +
                    " Success = " + log_success);
        }

    }
    
    protected void stopMeasure() {
        boolean success = analyzer.getSuccess();
        //stops measure
        analyzer.stopMeasure(success);

        //writes measure output on log
        if (logger.isDebugEnabled()) {

            double log_mean = getExtimatedMeanValue();
            boolean log_success = analyzer.getSuccess();

            logger.debug("Measure " + name + " finished. Mean value: " + log_mean +
                    " Success = " + log_success);
        }
    }




    public boolean hasBeenAborted() {
        return aborted;
    }

    //end NEW


    //NEW
    //@author Stefano Omini
    public void setSimParameters(SimParameters param) {
        analyzer.setParameters(param);
        maxDeadState = param.getDeadMeasureMaxChecks();
    }
    //end NEW


}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -