Example usage for java.util Collections min

List of usage examples for java.util Collections min

Introduction

In this page you can find the example usage for java.util Collections min.

Prototype

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) 

Source Link

Document

Returns the minimum element of the given collection, according to the natural ordering of its elements.

Usage

From source file:storybook.toolkit.DateUtil.java

public static void expandDatesToPast(List<Date> dates, int count) {
    if (dates.isEmpty()) {
        return;/*from  w  w w .ja va2  s. c  o m*/
    }
    dates.removeAll(Collections.singletonList(null));
    for (int i = 0; i < count; ++i) {
        Date firstDate = Collections.min(dates);
        firstDate = new Date(DateUtils.addDays(firstDate, -1).getTime());
        dates.add(firstDate);
    }
}

From source file:fr.ericlab.mabed.structure.Corpus.java

public void prepareCorpus() {
    System.out.println(Util.getDate() + " Preparing corpus...");
    String[] fileArray = new File("input/").list();
    nbTimeSlices = 0;/*from  w w w . j a  va 2s.  c o  m*/
    NumberFormat formatter = new DecimalFormat("00000000");
    ArrayList<Integer> list = new ArrayList<>();
    for (String filename : fileArray) {
        if (filename.endsWith(".text")) {
            try {
                list.add(formatter.parse(filename.substring(0, 8)).intValue());
            } catch (ParseException ex) {
                Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex);
            }
            nbTimeSlices++;
        }
    }
    int a = Collections.min(list), b = Collections.max(list);
    LineIterator it = null;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
        it = FileUtils.lineIterator(new File("input/" + formatter.format(a) + ".time"), "UTF-8");
        if (it.hasNext()) {
            Date parsedDate = dateFormat.parse(it.nextLine());
            startTimestamp = new java.sql.Timestamp(parsedDate.getTime());
        }
        it = FileUtils.lineIterator(new File("input/" + formatter.format(b) + ".time"), "UTF-8");
        String lastLine = "";
        while (it.hasNext()) {
            lastLine = it.nextLine();
        }
        Date parsedDate = dateFormat.parse(lastLine);
        endTimestamp = new java.sql.Timestamp(parsedDate.getTime());
    } catch (IOException | ParseException ex) {
        Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        LineIterator.closeQuietly(it);
    }
    System.out.print("   - Computing word frequencies");
    GlobalIndexer indexer = new GlobalIndexer(configuration.numberOfThreads, false);
    try {
        indexer.index("input/", configuration.stopwords);
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex);
    }
    indexer = new GlobalIndexer(configuration.numberOfThreads, true);
    try {
        indexer.index("input/", configuration.stopwords);
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(", 100% done.");
}

From source file:com.compomics.cell_coord.gui.controller.summary.VisualizeTracksController.java

/**
 * Compute both the raw and the shifted-to-zero coordinates ranges.
 *//*from   ww w. j  a  v a2  s . com*/
public void computeRanges() {
    coordRanges = new Double[2][2];
    shiftedCoordRange = new Double[2][2];

    List<Double> xRawMinList = new ArrayList<>();
    List<Double> xRawMaxList = new ArrayList<>();
    List<Double> yRawMinList = new ArrayList<>();
    List<Double> yRawMaxList = new ArrayList<>();

    List<Double> xShiftMinList = new ArrayList<>();
    List<Double> xShiftMaxList = new ArrayList<>();
    List<Double> yShiftMinList = new ArrayList<>();
    List<Double> yShiftMaxList = new ArrayList<>();
    List<Sample> samples = loadTracksController.getSamples();
    for (Sample sample : samples) {
        List<Track> tracks = sample.getTracks();
        for (Track track : tracks) {
            Double[][] coordinateRanges = track.getCoordinateRanges();
            Double[][] shiftedCoordinateRanges = track.getShiftedCoordinateRanges();

            xRawMinList.add(coordinateRanges[0][0]);
            xRawMaxList.add(coordinateRanges[0][1]);
            yRawMinList.add(coordinateRanges[1][0]);
            yRawMaxList.add(coordinateRanges[1][1]);

            xShiftMinList.add(shiftedCoordinateRanges[0][0]);
            xShiftMaxList.add(shiftedCoordinateRanges[0][1]);
            yShiftMinList.add(shiftedCoordinateRanges[1][0]);
            yShiftMaxList.add(shiftedCoordinateRanges[1][1]);
        }
    }
    Double xRawMin = Collections.min(xRawMinList);
    Double xRawMax = Collections.max(xRawMaxList);
    Double yRawMin = Collections.min(yRawMinList);
    Double yRawMax = Collections.max(yRawMaxList);
    coordRanges[0] = new Double[] { xRawMin, xRawMax };
    coordRanges[1] = new Double[] { yRawMin, yRawMax };
    Double xShiftMin = Collections.min(xShiftMinList);
    Double xShiftMax = Collections.max(xShiftMaxList);
    Double yShiftMin = Collections.min(yShiftMinList);
    Double yShiftMax = Collections.max(yShiftMaxList);
    shiftedCoordRange[0] = new Double[] { xShiftMin, xShiftMax };
    shiftedCoordRange[1] = new Double[] { yShiftMin, yShiftMax };
}

From source file:jav.correctionBackend.parser.WagnerFischer.java

private MinArg getMinArg(int i, int j) {
    if (i > 0 && j > 0) {
        int choices[] = { matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1] };
        int min = Collections.min(Arrays.asList(ArrayUtils.toObject(choices)));
        int index = Arrays.asList(ArrayUtils.toObject(choices)).indexOf(min);
        switch (index) {
        case 0://from w w  w . j  a  v a 2s . c om
            return new MinArg(i - 1, j - 1);
        case 1:
            return new MinArg(i - 1, j);
        case 2:
            return new MinArg(i, j - 1);
        default:
            throw new IllegalArgumentException("Index out of bounds: " + index);
        }
    } else if (i > 0) {
        return new MinArg(i - 1, j);
    } else { // j > 0
        return new MinArg(i, j - 1);
    }
}

From source file:org.kalypso.observation.result.TupleResultUtilities.java

/**
 * @author thuel2//  w  w  w  .ja  v  a2 s.  co m
 * @return returns minimum value for component of a tupleResult.<br>
 *         Works for components of XmlType XS_BOOLEAN, XS_DOUBLE, XS_DATE, XS_STRING. <br>
 *         For all others <code>object.toString</code> will be used for comparison.
 */
public static Object findComponentMinById(final TupleResult result, final String compID) {
    final IComponent comp = TupleResultUtilities.findComponentById(result, compID);
    if (comp == null) {
        return null;
    }
    final int iComp = result.indexOfComponent(comp);
    final QName valueTypeName = comp.getValueTypeName();

    if (XmlTypes.XS_BOOLEAN.equals(valueTypeName)) {
        final List<Boolean> values = new ArrayList<>();
        for (final IRecord record : result) {
            values.add((Boolean) record.getValue(iComp));
        }
        if (values.size() < 1) {
            return null;
        }
        return Collections.min(values);
    } else if (XmlTypes.XS_DOUBLE.equals(valueTypeName)) {
        // TODO think about other numerical types:
        // XmlTypes.XS_BYTE, XmlTypes.XS_DECIMAL, XmlTypes.XS_FLOAT, XmlTypes.XS_INT, XmlTypes.XS_INTEGER,
        // XmlTypes.XS_LONG, XmlTypes.XS_SHORT
        final List<java.lang.Double> values = new ArrayList<>();
        for (final IRecord record : result) {
            values.add((java.lang.Double) record.getValue(iComp));
        }
        if (values.size() < 1) {
            return null;
        }
        return Collections.min(values);
    } else if (XmlTypes.XS_DATE.equals(valueTypeName)) {
        // TODO think about other date types
        // XmlTypes.XS_DATETIME, XmlTypes.XS_DURATION, XmlTypes.XS_TIME
        final List<Date> values = new ArrayList<>();
        for (final IRecord record : result) {
            values.add((Date) record.getValue(iComp));
        }
        if (values.size() < 1) {
            return null;
        }
        return Collections.min(values);
    } else if (XmlTypes.XS_STRING.equals(valueTypeName)) {
        final List<String> values = new ArrayList<>();
        for (final IRecord record : result) {
            values.add((String) record.getValue(iComp));
        }
        if (values.size() < 1) {
            return null;
        }
        return Collections.min(values);
    } else {
        final List<String> values = new ArrayList<>();
        for (final IRecord record : result) {
            values.add(record.getValue(iComp).toString());
        }
        if (values.size() < 1) {
            return null;
        }
        return Collections.min(values);
    }
}

From source file:org.mrgeo.aggregators.MinAvgPairAggregator.java

@Override
public int aggregate(int[] values, int nodata) {
    boolean data0 = values[0] != nodata;
    boolean data1 = values[1] != nodata;
    boolean data2 = values[2] != nodata;
    boolean data3 = values[3] != nodata;

    Collection<Integer> averages = new ArrayList<Integer>();
    if (data0 && data1)
        averages.add(Integer.valueOf((values[0] + values[1]) / 2));
    if (data0 && data2)
        averages.add(Integer.valueOf((values[0] + values[2]) / 2));
    if (data0 && data3)
        averages.add(Integer.valueOf((values[0] + values[3]) / 2));
    if (data1 && data2)
        averages.add(Integer.valueOf((values[1] + values[2]) / 2));
    if (data1 && data3)
        averages.add(Integer.valueOf((values[1] + values[3]) / 2));
    if (data2 && data3)
        averages.add(Integer.valueOf((values[2] + values[3]) / 2));

    return (averages.isEmpty()) ? nodata : Collections.min(averages).intValue();
}

From source file:com.marvelution.jira.plugins.hudson.charts.BuildResultsRatioChartGenerator.java

/**
 * {@inheritDoc}/*from ww w .  j  av a  2 s. c o  m*/
 */
@Override
public ChartHelper generateChart() {
    final Map<Integer, Build> buildMap = new HashMap<Integer, Build>();
    final CategoryTableXYDataset dataSet = new CategoryTableXYDataset();
    for (Build build : builds) {
        buildMap.put(Integer.valueOf(build.getBuildNumber()), build);
        dataSet.add(Double.valueOf(build.getBuildNumber()), Double.valueOf(build.getDuration()),
                getI18n().getText("hudson.charts.duration"));
    }
    final JFreeChart chart = ChartFactory.createXYBarChart("", "", false,
            getI18n().getText("hudson.charts.duration"), dataSet, PlotOrientation.VERTICAL, false, false,
            false);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderVisible(false);
    final BuildResultRenderer renderer = new BuildResultRenderer(server, buildMap);
    renderer.setBaseItemLabelFont(ChartDefaults.defaultFont);
    renderer.setBaseItemLabelsVisible(false);
    renderer.setMargin(0.0D);
    renderer.setBasePositiveItemLabelPosition(
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
    renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
    renderer.setBaseToolTipGenerator(renderer);
    renderer.setURLGenerator(renderer);
    final XYPlot xyPlot = chart.getXYPlot();
    xyPlot.setAxisOffset(new RectangleInsets(1.0D, 1.0D, 1.0D, 1.0D));
    xyPlot.setRenderer(renderer);
    final NumberAxis domainAxis = new NumberAxis();
    domainAxis.setLowerBound(Collections.min(buildMap.keySet()));
    domainAxis.setUpperBound(Collections.max(buildMap.keySet()));
    final TickUnitSource ticks = NumberAxis.createIntegerTickUnits();
    domainAxis.setStandardTickUnits(ticks);
    xyPlot.setDomainAxis(domainAxis);
    final DateAxis rangeAxis = new DateAxis();
    final DurationFormat durationFormat = new DurationFormat();
    rangeAxis.setDateFormatOverride(durationFormat);
    rangeAxis.setLabel(getI18n().getText("hudson.charts.duration"));
    xyPlot.setRangeAxis(rangeAxis);
    ChartUtil.setupPlot(xyPlot);
    return new ChartHelper(chart);
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.persongrantcount.PersonGrantCountVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode/*from  www. j ava2 s  .co m*/
 * @param visContainer
 * @param authorDocuments
 * @return 
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();
    sparklineData.setYearToActivityCount(yearToGrantCount);

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which
     * the vis was rendered we dont want to be influenced by the
     * "DEFAULT_GRANT_YEAR".
     */
    Set<String> grantYears = new HashSet<String>(yearToGrantCount.keySet());
    grantYears.remove(VOConstants.DEFAULT_GRANT_YEAR);

    /*
     * We are setting the default value of minGrantYear to be 10 years
     * before the current year (which is suitably represented by the
     * shortSparkMinYear), this in case we run into invalid set of grant
     * years.
     */
    int minGrantYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToGrantCount.size() > 0) {
        try {
            minGrantYear = Integer.parseInt(Collections.min(grantYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToGrantCount.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToGrantCount.toString());
        }
    }

    int minGrantYearConsidered = 0;

    /*
     * There might be a case that the author investigated his first grant
     * within the last 10 years but we want to make sure that the sparkline
     * is representative of at least the last 10 years, so we will set the
     * minGrantYearConsidered to "currentYear - 10" which is also given by
     * "shortSparkMinYear".
     */
    if (minGrantYear > shortSparkMinYear) {
        minGrantYearConsidered = shortSparkMinYear;
    } else {
        minGrantYearConsidered = minGrantYear;
    }

    numOfYearsToBeRendered = currentYear - minGrantYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int grantCounter = 0;

    /*
     * For the purpose of this visualization I have come up with a term
     * "Sparks" which essentially means data points. Sparks that will be
     * rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     */
    int renderedFullSparks = 0;

    List<YearToEntityCountDataElement> yearToGrantCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int grantYear = minGrantYearConsidered; grantYear <= currentYear; grantYear++) {

        String stringInvestigatedYear = String.valueOf(grantYear);
        Integer currentGrants = yearToGrantCount.get(stringInvestigatedYear);

        if (currentGrants == null) {
            currentGrants = 0;
        }

        yearToGrantCountDataTable
                .add(new YearToEntityCountDataElement(grantCounter, stringInvestigatedYear, currentGrants));

        /*
         * Sparks that will be rendered will always be the one's which has
         * any year associated with it. Hence.
         */
        renderedFullSparks += currentGrants;
        grantCounter++;

    }

    sparklineData.setYearToEntityCountDataTable(yearToGrantCountDataTable);
    sparklineData.setRenderedSparks(renderedFullSparks);

    /*
     * Total grants will also consider grants that have no year
     * associated with it. Hence.
     */
    Integer unknownYearGrants = 0;
    if (yearToGrantCount.get(VOConstants.DEFAULT_GRANT_YEAR) != null) {
        unknownYearGrants = yearToGrantCount.get(VOConstants.DEFAULT_GRANT_YEAR);
    }

    sparklineData.setUnknownYearGrants(unknownYearGrants);

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VIS_CONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in
     * case of "short" sparkline mode we will set the Earliest
     * RenderedGrant year to "currentYear - 10".
     */
    sparklineData.setEarliestYearConsidered(minGrantYearConsidered);
    sparklineData.setEarliestRenderedGrantYear(minGrantYear);
    sparklineData.setLatestRenderedGrantYear(currentYear);

    /*
     * The Full Sparkline will be rendered by default. Only if the url has
     * specific mention of SHORT_SPARKLINE_MODE_URL_HANDLE then we render
     * the short sparkline and not otherwise.
     */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedGrantYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    if (yearToGrantCount.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COPI_VIS_MODE));

        sparklineData.setDownloadDataLink(UtilityFunctions.getCSVDownloadURL(individualURI,
                VisualizationFrameworkConstants.PERSON_GRANT_COUNT_VIS, ""));
    }
    return sparklineData;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.PersonPublicationCountVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode//  www  . ja v  a2  s  .  c o m
 * @param visContainer
 * @return 
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();
    sparklineData.setYearToActivityCount(yearToPublicationCount);

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which the vis
     * was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
     * */
    Set<String> publishedYears = new HashSet<String>(yearToPublicationCount.keySet());
    publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);

    /*
     * We are setting the default value of minPublishedYear to be 10 years before 
     * the current year (which is suitably represented by the shortSparkMinYear),
     * this in case we run into invalid set of published years.
     * */
    int minPublishedYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToPublicationCount.size() > 0) {
        try {
            minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToPublicationCount.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToPublicationCount.toString());
        }
    }

    int minPubYearConsidered = 0;

    /*
     * There might be a case that the author has made his first publication within the 
     * last 10 years but we want to make sure that the sparkline is representative of 
     * at least the last 10 years, so we will set the minPubYearConsidered to 
     * "currentYear - 10" which is also given by "shortSparkMinYear".
     * */
    if (minPublishedYear > shortSparkMinYear) {
        minPubYearConsidered = shortSparkMinYear;
    } else {
        minPubYearConsidered = minPublishedYear;
    }

    numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int publicationCounter = 0;

    /*
     * For the purpose of this visualization I have come up with a term "Sparks" which 
     * essentially means data points. 
     * Sparks that will be rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     * */
    int renderedFullSparks = 0;

    List<YearToEntityCountDataElement> yearToPublicationCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int publicationYear = minPubYearConsidered; publicationYear <= currentYear; publicationYear++) {

        String stringPublishedYear = String.valueOf(publicationYear);
        Integer currentPublications = yearToPublicationCount.get(stringPublishedYear);

        if (currentPublications == null) {
            currentPublications = 0;
        }

        yearToPublicationCountDataTable.add(
                new YearToEntityCountDataElement(publicationCounter, stringPublishedYear, currentPublications));

        /*
         * Sparks that will be rendered will always be the one's which has 
         * any year associated with it. Hence.
         * */
        renderedFullSparks += currentPublications;
        publicationCounter++;
    }

    sparklineData.setYearToEntityCountDataTable(yearToPublicationCountDataTable);
    sparklineData.setRenderedSparks(renderedFullSparks);

    /*
     * Total publications will also consider publications that have no year associated with
     * it. Hence.
     * */
    Integer unknownYearPublications = 0;
    if (yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
        unknownYearPublications = yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
    }

    sparklineData.setUnknownYearPublications(unknownYearPublications);

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VIS_CONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in case of
     * "short" sparkline mode we will set the Earliest RenderedPublication year to
     * "currentYear - 10". 
     * */
    sparklineData.setEarliestYearConsidered(minPubYearConsidered);
    sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
    sparklineData.setLatestRenderedPublicationYear(currentYear);

    if (yearToPublicationCount.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));

        sparklineData.setDownloadDataLink(UtilityFunctions.getCSVDownloadURL(individualURI,
                VisualizationFrameworkConstants.PERSON_PUBLICATION_COUNT_VIS, ""));
    }

    /*
     * The Full Sparkline will be rendered by default. Only if the url has specific mention of
     * SHORT_SPARKLINE_MODE_URL_HANDLE then we render the short sparkline and not otherwise.
     * */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    return sparklineData;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.coauthorship.CoAuthorshipVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode// w  ww.  j a v  a 2s . c o m
 * @param visContainer
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which the vis
     * was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
     * */
    Set<String> publishedYears = new HashSet<String>(yearToUniqueCoauthors.keySet());
    publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);

    /*
     * We are setting the default value of minPublishedYear to be 10 years before 
     * the current year (which is suitably represented by the shortSparkMinYear),
     * this in case we run into invalid set of published years.
     * */
    int minPublishedYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToUniqueCoauthors.size() > 0) {
        try {
            minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToUniqueCoauthors.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToUniqueCoauthors.toString());
        }
    }

    int minPubYearConsidered = 0;

    /*
     * There might be a case that the author has made his first publication within the 
     * last 10 years but we want to make sure that the sparkline is representative of 
     * at least the last 10 years, so we will set the minPubYearConsidered to 
     * "currentYear - 10" which is also given by "shortSparkMinYear".
     * */
    if (minPublishedYear > shortSparkMinYear) {
        minPubYearConsidered = shortSparkMinYear;
    } else {
        minPubYearConsidered = minPublishedYear;
    }

    numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int uniqueCoAuthorCounter = 0;
    Set<Collaborator> allCoAuthorsWithKnownAuthorshipYears = new HashSet<Collaborator>();
    List<YearToEntityCountDataElement> yearToUniqueCoauthorsCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int publicationYear = minPubYearConsidered; publicationYear <= currentYear; publicationYear++) {

        String publicationYearAsString = String.valueOf(publicationYear);
        Set<Collaborator> currentCoAuthors = yearToUniqueCoauthors.get(publicationYearAsString);

        Integer currentUniqueCoAuthors = null;

        if (currentCoAuthors != null) {
            currentUniqueCoAuthors = currentCoAuthors.size();
            allCoAuthorsWithKnownAuthorshipYears.addAll(currentCoAuthors);
        } else {
            currentUniqueCoAuthors = 0;
        }

        yearToUniqueCoauthorsCountDataTable.add(new YearToEntityCountDataElement(uniqueCoAuthorCounter,
                publicationYearAsString, currentUniqueCoAuthors));
        uniqueCoAuthorCounter++;
    }

    /*
     * For the purpose of this visualization I have come up with a term "Sparks" which 
     * essentially means data points. 
     * Sparks that will be rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     * */
    sparklineData.setRenderedSparks(allCoAuthorsWithKnownAuthorshipYears.size());

    sparklineData.setYearToEntityCountDataTable(yearToUniqueCoauthorsCountDataTable);

    /*
     * This is required only for the sparklines which convey collaborationships like 
     * coinvestigatorships and coauthorship. There are edge cases where a collaborator can be 
     * present for in a collaboration with known & unknown year. We do not want to repeat the 
     * count for this collaborator when we present it in the front-end. 
     * */
    Set<Collaborator> totalUniqueCoInvestigators = new HashSet<Collaborator>(
            allCoAuthorsWithKnownAuthorshipYears);

    /*
     * Total publications will also consider publications that have no year associated with
     * them. Hence.
     * */
    Integer unknownYearCoauthors = 0;
    if (yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
        unknownYearCoauthors = yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();

        totalUniqueCoInvestigators.addAll(yearToUniqueCoauthors.get(VOConstants.DEFAULT_GRANT_YEAR));
    }

    sparklineData.setUnknownYearPublications(unknownYearCoauthors);

    sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in case of
     * "short" sparkline mode we will set the Earliest RenderedPublication year to
     * "currentYear - 10". 
     * */
    sparklineData.setEarliestYearConsidered(minPubYearConsidered);
    sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
    sparklineData.setLatestRenderedPublicationYear(currentYear);

    /*
     * The Full Sparkline will be rendered by default. Only if the url has specific mention of
     * SHORT_SPARKLINE_MODE_KEY then we render the short sparkline and not otherwise.
     * */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    if (yearToUniqueCoauthors.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));

        sparklineData.setDownloadDataLink(UtilityFunctions.getCSVDownloadURL(individualURI,
                VisualizationFrameworkConstants.COAUTHORSHIP_VIS,
                VisualizationFrameworkConstants.COAUTHORS_COUNT_PER_YEAR_VIS_MODE));

        Map<String, Integer> yearToUniqueCoauthorsCount = new HashMap<String, Integer>();

        for (Map.Entry<String, Set<Collaborator>> currentYearToCoAuthors : yearToUniqueCoauthors.entrySet()) {
            yearToUniqueCoauthorsCount.put(currentYearToCoAuthors.getKey(),
                    currentYearToCoAuthors.getValue().size());
        }

        sparklineData.setYearToActivityCount(yearToUniqueCoauthorsCount);
    }

    return sparklineData;
}