Example usage for org.apache.commons.math.stat Frequency addValue

List of usage examples for org.apache.commons.math.stat Frequency addValue

Introduction

In this page you can find the example usage for org.apache.commons.math.stat Frequency addValue.

Prototype

public void addValue(char v) 

Source Link

Document

Adds 1 to the frequency count for v.

Usage

From source file:com.sse.abtester.VariationAssignerTest.java

/**
 * Test n variants./*  w ww.  ja  va 2 s  . c  om*/
 *
 * @param num_variants the num_variants
 */
public void testNVariants(int num_variants) {
    // make up some variants
    AbstractMap<String, IVariant<VariantBean>> coll = new HashMap<String, IVariant<VariantBean>>();

    for (int i = 0; i < num_variants; i++) {
        String name = "Bean_" + i;
        IVariant<VariantBean> vb = new VariantBean(name);
        vb.setDispatchable(true); // else non of the bean is
        // copied into normalized/weighted collections
        vb.setTargetFreq(1.0 / num_variants);
        vb.setVariationStrategy(new Default());
        coll.put(name, vb);
    }
    VariationAssigner<VariantBean> va = new VariationAssigner<VariantBean>();

    va.setIVariantCollection(coll);
    Frequency f = new Frequency();
    MockHttpServletRequest req = new MockHttpServletRequest();
    int TEST_LOOPS = 1000;
    double ALLOWABLE_DELTA = 100.0 / TEST_LOOPS; // rough check
    for (int i = 0; i < TEST_LOOPS; i++) {
        IVariant<VariantBean> assigned = va.enrollRequest(req);
        if (assigned != null)
            f.addValue(assigned.getName());
    }
    for (IVariant<VariantBean> vrb : coll.values()) {
        assertEquals(1.0 / num_variants, f.getPct(vrb.getName()), // NaN here can mean unknown name
                ALLOWABLE_DELTA);
    }
}

From source file:geogebra.kernel.AlgoFrequency.java

protected final void compute() {

    // Validate input arguments
    //=======================================================

    if (!dataList.isDefined() || dataList.size() == 0) {
        frequency.setUndefined();//from  w ww .  j a va2s  . c om
        return;
    }

    if (!(dataList.getElementType() == GeoElement.GEO_CLASS_TEXT
            || dataList.getElementType() == GeoElement.GEO_CLASS_NUMERIC)) {
        frequency.setUndefined();
        return;
    }

    if (classList != null) {
        if (classList.getElementType() != GeoElement.GEO_CLASS_NUMERIC || classList.size() < 2) {
            frequency.setUndefined();
            return;
        }
    }

    if (density != null) {
        if (density.getDouble() <= 0) {
            frequency.setUndefined();
            return;
        }
    }

    frequency.setDefined(true);
    frequency.clear();
    if (value != null)
        value.clear();

    double numMax = 0, numMin = 0;
    boolean doCumulative = isCumulative != null && isCumulative.getBoolean();

    // Load the data into f, an instance of Frequency class 
    //=======================================================

    Frequency f = new Frequency();
    for (int i = 0; i < dataList.size(); i++) {
        if (dataList.getElementType() == GeoElement.GEO_CLASS_TEXT)
            f.addValue(((GeoText) dataList.get(i)).toValueString());
        if (dataList.getElementType() == GeoElement.GEO_CLASS_NUMERIC)
            f.addValue(((GeoNumeric) dataList.get(i)).getDouble());
    }

    // If classList does not exist, 
    // get the unique value list and compute frequencies for this list  
    //=======================================================

    // handle string data
    if (dataList.getElementType() == GeoElement.GEO_CLASS_TEXT) {

        Iterator itr = f.valuesIterator();
        String strMax = (String) itr.next();
        String strMin = strMax;
        itr = f.valuesIterator();

        while (itr.hasNext()) {
            String s = (String) itr.next();
            if (s.compareTo(strMax) > 0)
                strMax = s;
            if (s.compareTo(strMin) < 0)
                strMin = s;
            GeoText text = new GeoText(cons);
            text.setTextString(s);
            value.add(text);
            if (classList == null)
                if (doCumulative)
                    frequency.add(new GeoNumeric(cons, f.getCumFreq((Comparable) s)));
                else
                    frequency.add(new GeoNumeric(cons, f.getCount((Comparable) s)));
        }
    }

    // handle numeric data
    else {
        Iterator itr = f.valuesIterator();
        numMax = (Double) itr.next();
        numMin = numMax;
        itr = f.valuesIterator();

        while (itr.hasNext()) {
            Double n = (Double) itr.next();
            if (n > numMax)
                numMax = n.doubleValue();
            if (n < numMin)
                numMin = n.doubleValue();
            value.add(new GeoNumeric(cons, n));

            if (classList == null)
                if (doCumulative)
                    frequency.add(new GeoNumeric(cons, f.getCumFreq((Comparable) n)));
                else
                    frequency.add(new GeoNumeric(cons, f.getCount((Comparable) n)));
        }
    }

    // If classList exists, compute frequencies using the classList
    //=======================================================

    if (classList != null) {

        double lowerClassBound = 0;
        double upperClassBound = 0;
        double classFreq = 0;

        //set density conditions
        boolean hasDensity = false;
        if (useDensity != null)
            hasDensity = useDensity.getBoolean();

        double densityValue = 1; // default density
        if (density != null) {
            densityValue = density.getDouble();
        }

        double cumulativeClassFreq = 0;
        double swap;
        int length = classList.size();
        for (int i = 1; i < length; i++) {

            lowerClassBound = ((GeoNumeric) classList.get(i - 1)).getDouble();
            upperClassBound = ((GeoNumeric) classList.get(i)).getDouble();
            boolean increasing = true;
            if (lowerClassBound > upperClassBound) {
                swap = upperClassBound;
                upperClassBound = lowerClassBound;
                lowerClassBound = swap;
                increasing = false;
            }
            classFreq = f.getCumFreq((Comparable) upperClassBound) - f.getCumFreq((Comparable) lowerClassBound)
                    + f.getCount((Comparable) lowerClassBound);
            if ((i != length - 1 && increasing) || (i != 1 && !increasing))
                classFreq -= f.getCount((Comparable) upperClassBound);

            //   System.out.println(" =================================");
            //   System.out.println("class freq: " + classFreq + "   " + density);
            if (hasDensity) {
                classFreq = densityValue * classFreq / (upperClassBound - lowerClassBound);
            }
            if (doCumulative)
                cumulativeClassFreq += classFreq;
            //   System.out.println("class freq: " + classFreq);

            // add the frequency to the output GeoList
            frequency.add(new GeoNumeric(cons, doCumulative ? cumulativeClassFreq : classFreq));

        }

        // handle the last (highest) class frequency specially
        // it must also count values equal to the highest class bound  

    }
}

From source file:herbie.running.analysis.CalcLegTimesKTI.java

private void handleActivityStartOrEnd(Id personId, double time) {
    String mode;// w w  w .  ja  v  a  2 s  .  co  m
    if (this.agentPerformsPtInteraction.containsKey(personId)) {
        mode = standardPtMode;
    } else {
        mode = onlyPtWalk;
    }

    Frequency frequency = null;
    ResizableDoubleArray rawData = null;
    if (!this.frequencies.containsKey(mode)) {
        frequency = new Frequency();
        this.frequencies.put(mode, frequency);
        rawData = new ResizableDoubleArray();
        this.rawData.put(mode, rawData);
    } else {
        frequency = this.frequencies.get(mode);
        rawData = this.rawData.get(mode);
    }

    if (this.ptPerformingTime.get(personId) >= 0.0 && eventIsInTimeWindow(time)) {
        frequency.addValue(this.ptPerformingTime.get(personId));
        rawData.addElement(this.ptPerformingTime.get(personId));
    }

    this.agentPerformsAnyPt.remove(personId);
    this.agentPerformsPtInteraction.remove(personId);
    this.ptPerformingTime.remove(personId);
}

From source file:geogebra.common.kernel.statistics.AlgoFrequency.java

@Override
public final void compute() {

    if (isContingencyTable) {
        computeContingencyTable();//from w ww  .  ja  v a2 s .c o  m
        return;
    }

    // Validate input arguments
    // =======================================================

    if (!dataList.isDefined() || dataList.size() == 0) {
        frequency.setUndefined();
        return;
    }

    if (!(dataList.getElementType().equals(GeoClass.TEXT)
            || dataList.getElementType().equals(GeoClass.NUMERIC))) {
        frequency.setUndefined();
        return;
    }

    if (classList != null) {
        if (!classList.getElementType().equals(GeoClass.NUMERIC) || classList.size() < 2) {
            frequency.setUndefined();
            return;
        }
    }

    if (density != null) {
        if (density.getDouble() <= 0) {
            frequency.setUndefined();
            return;
        }
    }

    if (scale != null) {
        if (!scale.isDefined()) {
            frequency.setUndefined();
            return;
        }
        scaleFactor = scale.getValue();
    }

    frequency.setDefined(true);
    frequency.clear();
    if (value != null)
        value.clear();

    double numMax = 0, numMin = 0;
    boolean doCumulative = isCumulative != null && isCumulative.getBoolean();

    // Load the data into f, an instance of Frequency class
    // =======================================================

    Frequency f = new FrequencyGgb();
    for (int i = 0; i < dataList.size(); i++) {
        if (dataList.getElementType().equals(GeoClass.TEXT))
            f.addValue(((GeoText) dataList.get(i)).toValueString(StringTemplate.defaultTemplate));
        if (dataList.getElementType().equals(GeoClass.NUMERIC))
            f.addValue(((GeoNumeric) dataList.get(i)).getDouble());
    }

    // If classList does not exist,
    // get the unique value list and compute frequencies for this list
    // =======================================================

    // handle string data
    if (dataList.getElementType().equals(GeoClass.TEXT)) {

        Iterator<Comparable<?>> itr = f.valuesIterator();
        String strMax = (String) itr.next();
        String strMin = strMax;
        itr = f.valuesIterator();

        while (itr.hasNext()) {
            String s = (String) itr.next();
            if (s.compareTo(strMax) > 0)
                strMax = s;
            if (s.compareTo(strMin) < 0)
                strMin = s;
            GeoText text = new GeoText(cons);
            text.setTextString(s);
            value.add(text);
            if (classList == null) {
                if (doCumulative) {
                    addValue(f.getCumFreq(s));
                } else {
                    addValue(f.getCount(s));
                }
            }
        }
    }

    // handle numeric data
    else {
        Iterator<Comparable<?>> itr = f.valuesIterator();
        numMax = (Double) itr.next();
        numMin = numMax;
        itr = f.valuesIterator();

        while (itr.hasNext()) {
            Double n = (Double) itr.next();
            if (n > numMax)
                numMax = n.doubleValue();
            if (n < numMin)
                numMin = n.doubleValue();
            value.add(new GeoNumeric(cons, n));

            if (classList == null)
                if (doCumulative)
                    addValue(f.getCumFreq(n));
                else
                    addValue(f.getCount(n));
        }
    }

    // If classList exists, compute frequencies using the classList
    // =======================================================

    if (classList != null) {

        double lowerClassBound = 0;
        double upperClassBound = 0;
        double classFreq = 0;

        // set density conditions
        boolean hasDensity = false;
        if (useDensity != null)
            hasDensity = useDensity.getBoolean();

        double densityValue = 1; // default density
        if (density != null) {
            densityValue = density.getDouble();
        }

        double cumulativeClassFreq = 0;
        double swap;
        int length = classList.size();
        for (int i = 1; i < length; i++) {

            lowerClassBound = ((GeoNumeric) classList.get(i - 1)).getDouble();
            upperClassBound = ((GeoNumeric) classList.get(i)).getDouble();

            // handle roundoff errror in class list values (this is possible
            // if auto-generated by another cmd)
            lowerClassBound = Kernel.checkDecimalFraction(lowerClassBound);
            upperClassBound = Kernel.checkDecimalFraction(upperClassBound);

            boolean increasing = true;
            if (lowerClassBound > upperClassBound) {
                swap = upperClassBound;
                upperClassBound = lowerClassBound;
                lowerClassBound = swap;
                increasing = false;
            }
            classFreq = f.getCumFreq(upperClassBound) - f.getCumFreq(lowerClassBound)
                    + f.getCount(lowerClassBound);
            if ((i != length - 1 && increasing) || (i != 1 && !increasing))
                classFreq -= f.getCount(upperClassBound);

            // System.out.println(" =================================");
            // System.out.println("class freq: " + classFreq + "   " +
            // density);

            if (doCumulative)
                cumulativeClassFreq += classFreq;

            // adjust the frequency and add to the output GeoList
            double v = doCumulative ? cumulativeClassFreq : classFreq;
            if (hasDensity) {
                v = densityValue * v / (upperClassBound - lowerClassBound);
            }
            addValue(v);
        }

        // handle the last (highest) class frequency specially
        // it must also count values equal to the highest class bound

    }
}

From source file:com.gtwm.pb.model.manageData.WordCloud.java

/**
 * @param textLowerCase/*  w  w w .ja va 2 s . co  m*/
 *            Input text, must be lower case
 * @param minWeight
 *            Minimum tag weight, e.g. a font size
 * @param maxWeight
 *            Max. tag weight
 * @param maxTags
 *            Maximum number of tags to return, -1 for all tags
 * @param additionalStopWords
 *            Set of words to specifically exclude, in addition to the
 *            standard set [and, not, after, yes, no, ...]
 */
public WordCloud(String textLowerCase, int minWeight, int maxWeight, int maxTags,
        Set<String> additionalStopWords) {
    String[] wordArray = textLowerCase.split("\\W");
    Set<String> stopWords = new HashSet<String>(Arrays.asList(stopWordsArray));
    for (String additionalStopWord : additionalStopWords) {
        stopWords.add(additionalStopWord.toLowerCase().trim());
    }
    LancasterStemmer stemmer = new LancasterStemmer();
    String wordStem;
    Frequency frequencies = new Frequency();
    for (String wordString : wordArray) {
        if ((!stopWords.contains(wordString)) && (wordString.length() >= minWordLength)) {
            wordStem = stemmer.stripSuffixes(wordString);
            // Record the mapping of the stem to its origin so the most
            // common origin can be re-introduced when the cloud is
            // generated
            this.recordStemOrigin(wordString, wordStem);
            frequencies.addValue(wordStem);
        }
    }
    // Compute std. dev of frequencies so we can remove outliers
    DescriptiveStatistics stats = new DescriptiveStatistics();
    Iterator freqIt = frequencies.valuesIterator();
    long stemFreq;
    while (freqIt.hasNext()) {
        stemFreq = frequencies.getCount(freqIt.next());
        stats.addValue(stemFreq);
    }
    double mean = stats.getMean();
    double stdDev = stats.getStandardDeviation();
    long minFreq = Long.MAX_VALUE;
    long maxFreq = 0;
    // Remove outliers
    freqIt = frequencies.valuesIterator();
    int upperLimit = (int) (mean + (stdDev * 10));
    int lowerLimit = (int) (mean - stdDev);
    if (lowerLimit < 2) {
        lowerLimit = 2;
    }
    int numWords = 0;
    int numRawWords = wordArray.length;
    boolean removeLowOutliers = (numRawWords > (maxTags * 10));
    while (freqIt.hasNext()) {
        wordStem = (String) freqIt.next();
        stemFreq = frequencies.getCount(wordStem);
        // For a large input set, remove high and low outliers.
        // For a smaller set, just high freq. outliers
        if ((stemFreq > upperLimit) || ((stemFreq < lowerLimit) && removeLowOutliers)) {
            freqIt.remove();
        } else {
            numWords++;
            if (stemFreq > maxFreq) {
                maxFreq = stemFreq;
            } else if (stemFreq < minFreq) {
                minFreq = stemFreq;
            }
        }
    }
    // Cut down to exact required number of tags by removing smallest
    if (lowerLimit < minFreq) {
        lowerLimit = (int) minFreq;
    }
    if (numWords > maxTags) {
        while (numWords > maxTags) {
            freqIt = frequencies.valuesIterator();
            SMALLREMOVAL: while (freqIt.hasNext()) {
                stemFreq = frequencies.getCount(freqIt.next());
                if (stemFreq < lowerLimit) {
                    freqIt.remove();
                    numWords--;
                    if (numWords == maxTags) {
                        break SMALLREMOVAL;
                    }
                }
            }
            int step = (int) ((mean - lowerLimit) / 3);
            if (step < 1) {
                step = 1;
            }
            lowerLimit += step;
        }
        // The new min. freq. may have changed
        minFreq = Long.MAX_VALUE;
        freqIt = frequencies.valuesIterator();
        while (freqIt.hasNext()) {
            stemFreq = frequencies.getCount(freqIt.next());
            if (stemFreq < minFreq) {
                minFreq = stemFreq;
            }
        }
    }
    // Scale and create tag objects
    double scaleFactor;
    if (maxFreq == minFreq) {
        scaleFactor = (double) (maxWeight - minWeight) / 4; // TODO: a realistic
        // scale factor in this
        // case
    } else {
        scaleFactor = (double) (maxWeight - minWeight) / (maxFreq - minFreq);
    }
    freqIt = frequencies.valuesIterator();
    int weight;
    while (freqIt.hasNext()) {
        wordStem = (String) freqIt.next();
        stemFreq = frequencies.getCount(wordStem);
        // Might still be some left less than the min. threshold
        if (stemFreq <= minFreq) {
            weight = minWeight;
        } else {
            weight = (int) (Math.ceil((double) (stemFreq - minFreq) * scaleFactor) + minWeight);
        }
        SortedSet<WordInfo> origins = this.stemOriginMap.get(wordStem);
        String mostCommonOrigin = origins.last().getName();
        Set<String> synonyms = new TreeSet<String>();
        for (WordInfo origin : origins) {
            synonyms.add(origin.getName());
        }
        WordInfo word = new Word(mostCommonOrigin, weight, synonyms);
        this.words.add(word);
    }
}

From source file:herbie.running.analysis.CalcLegTimesKTI.java

@Override
public void handleEvent(PersonArrivalEvent event) {
    Double depTime = this.agentDepartures.remove(event.getPersonId());
    Person agent = this.population.getPersons().get(event.getPersonId());

    if (depTime != null && agent != null) {

        Id personId = event.getPersonId();
        double travelTime = event.getTime() - depTime;
        String mode = event.getLegMode();

        if (mode.equals("transit_walk") || mode.equals("pt")) {
            this.agentPerformsAnyPt.put(personId, true);

            if (this.ptPerformingTime.containsKey(personId)) {
                travelTime = travelTime + this.ptPerformingTime.get(personId);
            }//from   w  w w . ja v  a2s  .  c om
            this.ptPerformingTime.put(personId, travelTime);
        } else {
            Frequency frequency = null;
            ResizableDoubleArray rawData = null;
            if (!this.frequencies.containsKey(mode)) {
                frequency = new Frequency();
                this.frequencies.put(mode, frequency);
                rawData = new ResizableDoubleArray();
                this.rawData.put(mode, rawData);
            } else {
                frequency = this.frequencies.get(mode);
                rawData = this.rawData.get(mode);
            }
            if (travelTime >= 0.0 && eventIsInTimeWindow(event.getTime())) {
                frequency.addValue(travelTime);
                rawData.addElement(travelTime);
            }
        }
    }
}

From source file:herbie.running.analysis.ModeSharesEventHandler.java

@Override
public void handleEvent(final PersonArrivalEvent arrivalEvent) {
    this.doReset();
    PersonDepartureEvent departureEvent = this.pendantDepartures.remove(arrivalEvent.getPersonId());
    String mode = arrivalEvent.getLegMode();
    Frequency frequency;
    ResizableDoubleArray rawDataElement;
    Link departureLink;/*from   w  w  w  .  j  a  v a  2 s. c  om*/
    Link arrivalLink;
    double distance;

    // Consistency check...
    if (departureEvent == null) {
        log.warn("One arrival do not correspond to any departure for agent " + arrivalEvent.getPersonId());
        return;
    } else if (!mode.equals(departureEvent.getLegMode())) {
        log.warn("Departure and arrival have uncompatible modes!");
        return;
    }
    // consistency check... DONE

    if (this.frequencies.containsKey(mode)) {
        frequency = this.frequencies.get(mode);
        rawDataElement = this.rawData.get(mode);
    } else {
        frequency = new Frequency();
        rawDataElement = new ResizableDoubleArray();

        this.frequencies.put(mode, frequency);
        this.rawData.put(mode, rawDataElement);
    }

    // compute data
    departureLink = this.network.getLinks().get(departureEvent.getLinkId());
    arrivalLink = this.network.getLinks().get(arrivalEvent.getLinkId());

    distance = CoordUtils.calcDistance(departureLink.getCoord(), arrivalLink.getCoord());

    // remember data
    frequency.addValue(distance);
    rawDataElement.addElement(distance);
    this.maxDistance = Math.max(distance, this.maxDistance);
}

From source file:herbie.running.population.algorithms.PopulationLegDistanceDistribution.java

@Override
public void run(Plan plan) {

    boolean isPtLeg = false;
    double distForPt = 0.0;
    String ptMode = "standardPt";
    String onlyPtWalkMode = "onlyPtWalk";
    boolean containsPt = false;

    for (PlanElement pe : plan.getPlanElements()) {

        if (pe instanceof Leg) {

            Leg leg = (Leg) pe;// www.ja  va2s  . com

            String mode = leg.getMode();

            if (mode.equals("transit_walk") || mode.equals("pt")) {
                if (mode.equals("pt"))
                    containsPt = true;

                mode = ptMode;

                if (!isPtLeg)
                    distForPt = 0.0;
                isPtLeg = true;

            } else {
                isPtLeg = false;
            }

            Frequency frequency = null;
            ResizableDoubleArray rawData = null;
            if (!this.frequencies.containsKey(mode)) {
                frequency = new Frequency();
                this.frequencies.put(mode, frequency);
                rawData = new ResizableDoubleArray();
                this.rawData.put(mode, rawData);
            } else {
                frequency = this.frequencies.get(mode);
                rawData = this.rawData.get(mode);
            }

            double distance = 0.0;
            if (leg.getMode().equals("transit_walk")) {
                distance = DistanceCalculations.getWalkDistance((GenericRouteImpl) leg.getRoute(), network);
            } else {
                if (leg instanceof LegImpl && leg.getRoute() == null
                        && !(leg.getRoute() instanceof LinkNetworkRouteImpl)
                        && !(leg.getRoute() instanceof ExperimentalTransitRoute)) {
                    log.warn(
                            "Not enough information on leg-object. Distance is set to 0.0 for this leg. Therefore no distance contribution....");
                } else {
                    distance = DistanceCalculations.getLegDistance(leg.getRoute(), network);
                }
            }

            if (isPtLeg) {
                distForPt += distance;
            } else {
                if (distance >= 0.0) {
                    frequency.addValue(distance);
                    rawData.addElement(distance);
                }
            }

            //            frequency.addValue(leg.getRoute().getDistance());
            //            rawData.addElement(leg.getRoute().getDistance());
        } else {
            if (pe instanceof Activity) {
                Activity act = (Activity) pe;
                if (isPtLeg && !act.getType().equals("pt interaction")) {
                    String mode;
                    if (!containsPt)
                        mode = onlyPtWalkMode;
                    else
                        mode = ptMode;

                    Frequency frequency = null;
                    ResizableDoubleArray rawData = null;
                    if (!this.frequencies.containsKey(mode)) {
                        frequency = new Frequency();
                        this.frequencies.put(mode, frequency);
                        rawData = new ResizableDoubleArray();
                        this.rawData.put(mode, rawData);
                    } else {
                        frequency = this.frequencies.get(mode);
                        rawData = this.rawData.get(mode);
                    }

                    if (distForPt >= 0.0) {
                        frequency.addValue(distForPt);
                        rawData.addElement(distForPt);
                    }

                    distForPt = 0.0;
                    isPtLeg = false;
                    containsPt = false;
                }
            }
        }
    }
}

From source file:de.tum.bgu.msm.syntheticPopulationGenerator.capeTown.SyntheticPopCT.java

private void assignSchools() {
    //method to assign the school location for students. They should be registered on the microdata as students

    //todo. Things to consider:
    //The location of the school is stored under "schoolplace location"
    //Students from Berufschule are considered to be working full-time and therefore they don't attend class
    //If there are no more school places for the student, they are sent outside the area (schoolplace = -2)
    //For the following years, we school transition should be accomplished

    logger.info("   Started assigning schools");
    int count = 0;

    //Calculate distance impedance for students
    double alphaUniversity = ResourceUtil.getDoubleProperty(rb, PROPERTIES_UNIVERSITY_ALPHA);
    double gammaUniversity = ResourceUtil.getDoubleProperty(rb, PROPERTIES_UNIVERSITY_GAMMA);
    Matrix universityDistanceImpedance = new Matrix(distanceMatrix.getRowCount(),
            distanceMatrix.getColumnCount());
    Matrix schoolDistanceImpedance = new Matrix(distanceMatrix.getRowCount(), distanceMatrix.getColumnCount());
    for (int i = 1; i <= distanceMatrix.getRowCount(); i++) {
        for (int j = 1; j <= distanceMatrix.getColumnCount(); j++) {
            universityDistanceImpedance.setValueAt(i, j, (float) Math
                    .exp(alphaUniversity * Math.exp(distanceMatrix.getValueAt(i, j) * gammaUniversity)));
            schoolDistanceImpedance.setValueAt(i, j, distanceMatrix.getValueAt(i, j));
        }// w  w  w.jav a2  s  .c  o m
    }

    //Identify vacant schools by zone and type
    identifyVacantSchoolsByZoneByType();

    //For validation - obtain the trip length distribution
    Frequency travelSecondary = new Frequency();
    Frequency travelUniversity = new Frequency();
    Frequency travelPrimary = new Frequency();
    validationCommutersFlow(); //Generates the validation tabledatasets
    int[] flow = SiloUtil.createArrayWithValue(odMunicipalityFlow.getRowCount(), 0);
    odMunicipalityFlow.appendColumn(flow, Integer.toString(count));

    //Produce one array list with students' ID
    Map<Integer, Person> personMap = (Map<Integer, Person>) dataContainer.getHouseholdData().getPersons();
    ArrayList<Person> studentArrayList = new ArrayList<>();
    int[] studentsByType2 = new int[schoolTypes.length];
    for (Map.Entry<Integer, Person> pair : personMap.entrySet()) {
        int school = pair.getValue().getSchoolType();
        if (school > 0) { //They are studying
            studentArrayList.add(pair.getValue());
            studentsByType2[school - 1] = studentsByType2[school - 1] + 1;
        }
    }
    //Randomize the order of the students
    Collections.shuffle(studentArrayList);

    //Start the selection of schools in random order to avoid geographical bias
    logger.info("   Started assigning schools");
    int assignedSchools = 0;
    RealEstateDataManager realEstate = dataContainer.getRealEstateData();
    int[] studentsOutside = new int[schoolTypes.length];
    int[] studentsByType = new int[schoolTypes.length];
    for (Person pp : studentArrayList) {

        //Select the zones with vacant schools for that person, given the school type
        int schoolType = pp.getSchoolType();
        studentsByType[schoolType - 1] = studentsByType[schoolType - 1] + 1;
        int[] keys = idZonesVacantSchoolsByType.get(schoolType);
        int lengthKeys = numberZonesWithVacantSchoolsByType.get(schoolType);
        if (lengthKeys > 0) {//if there are still TAZ with school capacity in the region, select one of them. If not, assign them outside the area

            //Select the school location (which raster cell) for that person given his/her job type
            int[] schoolPlace = new int[2];
            Household hh = pp.getHousehold();
            int origin = realEstate.getDwelling(hh.getDwellingId()).getZoneId();
            if (schoolType == 3) {
                schoolPlace = selectWorkplace(origin, numberVacantSchoolsByZoneByType, keys, lengthKeys,
                        universityDistanceImpedance);
                travelUniversity.addValue((int) distanceMatrix.getValueAt(origin, schoolPlace[0] / 100));
            } else {
                schoolPlace = selectClosestSchool(origin, numberVacantSchoolsByZoneByType, keys, lengthKeys,
                        schoolDistanceImpedance);
                if (schoolType == 1) {
                    travelPrimary.addValue((int) distanceMatrix.getValueAt(origin, schoolPlace[0] / 100));
                } else if (schoolType == 2) {
                    travelSecondary.addValue((int) distanceMatrix.getValueAt(origin, schoolPlace[0] / 100));
                }
            }

            //Assign values to job and person
            pp.setSchoolPlace(schoolPlace[0] / 100);
            //pp.setTravelTime(distanceMatrix.getValueAt(pp.getZone(), pp.getSchoolPlace()));

            //For validation OD TableDataSet
            int homeMun = (int) cellsMatrix.getIndexedValueAt(origin, "smallID");
            int workMun = (int) cellsMatrix.getIndexedValueAt(pp.getSchoolPlace(), "smallID");
            int odPair = homeMun * 1000 + workMun;
            odMunicipalityFlow.setIndexedValueAt(odPair, Integer.toString(count),
                    odMunicipalityFlow.getIndexedValueAt(odPair, Integer.toString(count)) + 1);

            //Update counts of vacant school places
            numberVacantSchoolsByZoneByType.put(schoolPlace[0],
                    numberVacantSchoolsByZoneByType.get(schoolPlace[0]) - 1);
            if (numberVacantSchoolsByZoneByType.get(schoolPlace[0]) < 1) {
                numberVacantSchoolsByZoneByType.put(schoolPlace[0], 0);
                keys[schoolPlace[1]] = keys[numberZonesWithVacantSchoolsByType.get(schoolType) - 1];
                idZonesVacantSchoolsByType.put(schoolType, keys);
                numberZonesWithVacantSchoolsByType.put(schoolType,
                        numberZonesWithVacantSchoolsByType.get(schoolType) - 1);
                if (numberZonesWithVacantSchoolsByType.get(schoolType) < 1) {
                    numberZonesWithVacantSchoolsByType.put(schoolType, 0);
                }
            }
            assignedSchools++;
        } else {//No more school capacity in the study area. This person will study outside the area
            pp.setSchoolPlace(-2); //they attend one school out of the area
            studentsOutside[schoolType - 1] = studentsOutside[schoolType - 1] + 1;
        }
    }

    //For validation - trip length distribution
    checkTripLengthDistribution(travelPrimary, 0, 0, "microData/interimFiles/tripLengthDistributionPrimary.csv",
            1);
    checkTripLengthDistribution(travelSecondary, 0, 0,
            "microData/interimFiles/tripLengthDistributionSecondary.csv", 1); //Trip length frequency distribution
    checkTripLengthDistribution(travelUniversity, alphaJob, gammaJob,
            "microData/interimFiles/tripLengthDistributionUniversity.csv", 1);
    SiloUtil.writeTableDataSet(odMunicipalityFlow, "microData/interimFiles/odMunicipalityFlow.csv");
    for (int i = 0; i < schoolTypes.length; i++) {
        logger.info("  School type: " + schoolTypes[i] + ". " + studentsOutside[schoolTypes[i] - 1]
                + " students out of " + studentsByType[schoolTypes[i] - 1] + " study outside the area");
    }
}

From source file:org.broad.igv.renderer.SpliceJunctionRenderer.java

/**
 * Note:  assumption is that featureList is sorted by pStart position.
 *
 * @param featureList/*w  ww .j  a va  2  s.  c  o m*/
 * @param context
 * @param trackRectangle
 * @param track
 */
@Override
public void render(List<IGVFeature> featureList, RenderContext context, Rectangle trackRectangle, Track track) {

    double origin = context.getOrigin();
    double locScale = context.getScale();

    // TODO -- use enum instead of string "Color"
    if ((featureList != null) && !featureList.isEmpty()) {

        // Create a graphics object to draw font names.  Graphics are not cached
        // by font, only by color, so its neccessary to create a new one to prevent
        // affecting other tracks.
        Font font = FontManager.getFont(track.getFontSize());
        Graphics2D fontGraphics = (Graphics2D) context.getGraphic2DForColor(Color.BLACK).create();

        if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_ANTIALISING)) {
            fontGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        }
        fontGraphics.setFont(font);

        //determine whether to show flanking regions
        PreferenceManager prefs = PreferenceManager.getInstance();
        boolean shouldShowFlankingRegions = prefs
                .getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_FLANKINGREGIONS);

        // Track coordinates
        double trackRectangleX = trackRectangle.getX();
        double trackRectangleMaxX = trackRectangle.getMaxX();

        SpliceJunctionFeature selectedFeature = (SpliceJunctionFeature) ((FeatureTrack) track)
                .getSelectedFeature();

        // Start of Roche-Tessella modification
        if (track.getAutoScale()) {
            Frequency f = new Frequency();
            List<Integer> scores = new ArrayList<Integer>();

            for (IGVFeature feature : featureList) {
                SpliceJunctionFeature junctionFeature = (SpliceJunctionFeature) feature;
                f.addValue(junctionFeature.getScore());
                scores.add((int) junctionFeature.getScore());
            }

            Collections.sort(scores);
            Collections.reverse(scores);
            for (int s : scores) {
                if (f.getCumPct(s) < 0.99) {
                    maxDepth = s;
                    break;
                }
            }

        }
        // End of Roche-Tessella modification

        for (IGVFeature feature : featureList) {
            SpliceJunctionFeature junctionFeature = (SpliceJunctionFeature) feature;
            //if same junction as selected feature, highlight
            boolean shouldHighlight = false;
            if (selectedFeature != null && selectedFeature.isSameJunction(junctionFeature)) {
                setHighlightFeature(junctionFeature);
                shouldHighlight = true;
            }

            // Get the pStart and pEnd of the entire feature.  at extreme zoom levels the
            // virtual pixel value can be too large for an int, so the computation is
            // done in double precision and cast to an int only when its confirmed its
            // within the field of view.
            int flankingStart = junctionFeature.getStart();
            int flankingEnd = junctionFeature.getEnd();

            int junctionStart = junctionFeature.getJunctionStart();
            int junctionEnd = junctionFeature.getJunctionEnd();

            double virtualPixelStart = Math.round((flankingStart - origin) / locScale);
            double virtualPixelEnd = Math.round((flankingEnd - origin) / locScale);

            double virtualPixelJunctionStart = Math.round((junctionStart - origin) / locScale);
            double virtualPixelJunctionEnd = Math.round((junctionEnd - origin) / locScale);

            // If the any part of the feature fits in the
            // Track rectangle draw it
            if ((virtualPixelEnd >= trackRectangleX) && (virtualPixelStart <= trackRectangleMaxX)) {

                //
                int displayPixelEnd = (int) Math.min(trackRectangleMaxX, virtualPixelEnd);
                int displayPixelStart = (int) Math.max(trackRectangleX, virtualPixelStart);

                float depth = junctionFeature.getJunctionDepth();
                Color color = feature.getColor();

                drawFeature((int) virtualPixelStart, (int) virtualPixelEnd, (int) virtualPixelJunctionStart,
                        (int) virtualPixelJunctionEnd, depth, trackRectangle, context, feature.getStrand(),
                        junctionFeature, shouldHighlight, color, shouldShowFlankingRegions);
            }
        }

        //draw a central horizontal line
        Graphics2D g2D = context.getGraphic2DForColor(COLOR_CENTERLINE);
        g2D.drawLine((int) trackRectangleX, (int) trackRectangle.getCenterY(), (int) trackRectangleMaxX,
                (int) trackRectangle.getCenterY());

    }
}