List of usage examples for java.util ArrayList set
public E set(int index, E element)
From source file:com.ecyrd.jspwiki.ui.TemplateManager.java
/** * List all available timeformats, read from the jspwiki.properties * //from www.j a v a 2s . c om * @param pageContext * @return map of TimeFormats * @since 2.7.x */ public Map listTimeFormats(PageContext pageContext) { WikiContext context = WikiContext.findContext(pageContext); Properties props = m_engine.getWikiProperties(); ArrayList<String> tfArr = new ArrayList<String>(40); LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>(); /* filter timeformat properties */ for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith(TIMEFORMATPROPERTIES)) { tfArr.add(name); } } /* fetch actual formats */ if (tfArr.size() == 0) /* * no props found - make sure some default * formats are avail */ { tfArr.add("dd-MMM-yy"); tfArr.add("d-MMM-yyyy"); tfArr.add("EEE, dd-MMM-yyyy, zzzz"); } else { Collections.sort(tfArr); for (int i = 0; i < tfArr.size(); i++) { tfArr.set(i, props.getProperty(tfArr.get(i))); } } String prefTimeZone = Preferences.getPreference(context, "TimeZone"); //TimeZone tz = TimeZone.getDefault(); TimeZone tz = TimeZone.getTimeZone(prefTimeZone); /*try { tz.setRawOffset(Integer.parseInt(prefTimeZone)); } catch (Exception e) { }*/ Date d = new Date(); // current date try { // dummy format pattern SimpleDateFormat fmt = Preferences.getDateFormat(context, TimeFormat.DATETIME); fmt.setTimeZone(tz); for (int i = 0; i < tfArr.size(); i++) { try { String f = tfArr.get(i); fmt.applyPattern(f); resultMap.put(f, fmt.format(d)); } catch (IllegalArgumentException e) { } // skip parameter } } catch (IllegalArgumentException e) { } // skip parameter return resultMap; }
From source file:org.kuali.ole.gl.batch.BatchSortUtil.java
private static void mergeFiles(File tempSortDir, int numFiles, String outputFileName, Comparator<String> comparator) { try {/*from www . jav a2s . com*/ ArrayList<FileReader> mergefr = new ArrayList<FileReader>(numFiles); ArrayList<BufferedReader> mergefbr = new ArrayList<BufferedReader>(numFiles); // temp buffer for writing - contains the minimum record from each file ArrayList<String> fileRows = new ArrayList<String>(numFiles); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFileName)); boolean someFileStillHasRows = false; // Iterate over all the files, getting the first line in each file for (int i = 0; i < numFiles; i++) { // open a file reader for each file mergefr.add(new FileReader(new File(tempSortDir, "chunk_" + i))); mergefbr.add(new BufferedReader(mergefr.get(i))); // get the first row String line = mergefbr.get(i).readLine(); if (line != null) { fileRows.add(line); someFileStillHasRows = true; } else { fileRows.add(null); } } while (someFileStillHasRows) { String min = null; int minIndex = 0; // index of the file with the minimum record // init for later compare - assume the first file has the minimum String line = fileRows.get(0); if (line != null) { min = line; minIndex = 0; } else { min = null; minIndex = -1; } // determine the minimum record of the top lines of each file // check which one is min for (int i = 1; i < fileRows.size(); i++) { line = fileRows.get(i); if (line != null) { if (min != null) { if (comparator.compare(line, min) < 0) { minIndex = i; min = line; } } else { min = line; minIndex = i; } } } if (minIndex < 0) { someFileStillHasRows = false; } else { // write to the sorted file bw.append(fileRows.get(minIndex)).append('\n'); // get another row from the file that had the min line = mergefbr.get(minIndex).readLine(); if (line != null) { fileRows.set(minIndex, line); } else { // file is out of rows, set to null so it is ignored fileRows.set(minIndex, null); } } // check if one still has rows for (int i = 0; i < fileRows.size(); i++) { someFileStillHasRows = false; if (fileRows.get(i) != null) { if (minIndex < 0) { throw new RuntimeException( "minIndex < 0 and row found in chunk file " + i + " : " + fileRows.get(i)); } someFileStillHasRows = true; break; } } // check the actual files one more time if (!someFileStillHasRows) { //write the last one not covered above for (int i = 0; i < fileRows.size(); i++) { if (fileRows.get(i) == null) { line = mergefbr.get(i).readLine(); if (line != null) { someFileStillHasRows = true; fileRows.set(i, line); } } } } } // close all the files bw.close(); for (BufferedReader br : mergefbr) { br.close(); } for (FileReader fr : mergefr) { fr.close(); } } catch (Exception ex) { LOG.error("Exception merging the sorted files", ex); throw new RuntimeException("Exception merging the sorted files", ex); } }
From source file:org.dspace.app.bulkedit.DSpaceCSV.java
/** * Add an item to the CSV file, from a CSV line of elements * * @param line The line of elements//from w ww . java2 s . c o m * @throws Exception Thrown if an error occurs when adding the item */ public final void addItem(String line) throws Exception { // Check to see if the last character is a field separator, which hides the last empty column boolean last = false; if (line.endsWith(fieldSeparator)) { // Add a space to the end, then remove it later last = true; line += " "; } // Split up on field separator String[] parts = line.split(escapedFieldSeparator); ArrayList<String> bits = new ArrayList<>(); bits.addAll(Arrays.asList(parts)); // Merge parts with embedded separators boolean alldone = false; while (!alldone) { boolean found = false; int i = 0; for (String part : bits) { int bitcounter = part.length() - part.replaceAll("\"", "").length(); if ((part.startsWith("\"")) && ((!part.endsWith("\"")) || ((bitcounter & 1) == 1))) { found = true; String add = bits.get(i) + fieldSeparator + bits.get(i + 1); bits.remove(i); bits.add(i, add); bits.remove(i + 1); break; } i++; } alldone = !found; } // Deal with quotes around the elements int i = 0; for (String part : bits) { if ((part.startsWith("\"")) && (part.endsWith("\""))) { part = part.substring(1, part.length() - 1); bits.set(i, part); } i++; } // Remove embedded quotes i = 0; for (String part : bits) { if (part.contains("\"\"")) { part = part.replaceAll("\"\"", "\""); bits.set(i, part); } i++; } // Add elements to a DSpaceCSVLine String id = parts[0].replaceAll("\"", ""); DSpaceCSVLine csvLine; // Is this an existing item, or a new item (where id = '+') if ("+".equals(id)) { csvLine = new DSpaceCSVLine(); } else { try { csvLine = new DSpaceCSVLine(UUID.fromString(id)); } catch (NumberFormatException nfe) { System.err.println("Invalid item identifier: " + id); System.err.println("Please check your CSV file for information. " + "Item id must be numeric, or a '+' to add a new item"); throw (nfe); } } // Add the rest of the parts i = 0; for (String part : bits) { if (i > 0) { // Is this a last empty item? if ((last) && (i == headings.size())) { part = ""; } // Make sure we register that this column was there if (headings.size() < i) { throw new MetadataImportInvalidHeadingException("", MetadataImportInvalidHeadingException.MISSING, i + 1); } csvLine.add(headings.get(i - 1), null); String[] elements = part.split(escapedValueSeparator); for (String element : elements) { if ((element != null) && (!"".equals(element))) { csvLine.add(headings.get(i - 1), element); } } } i++; } lines.add(csvLine); counter++; }
From source file:de.helmholtz_muenchen.ibis.ngs.bwa.BWANodeModel.java
private void bwa_aln(ExecutionContext exec, String readType, String basePath, String outBaseName, String outBaseName1, String outBaseName2, String path2refFile, String path2bwa, String path2readFile, String path2readFile2, boolean isBam, int Threads) throws Exception { ArrayList<String> command = new ArrayList<String>(); // Constant values command.add(path2bwa + " aln"); String outName = basePath + outBaseName + "_aln_sa.sai"; String out11Name = basePath + outBaseName1 + "_aln_sa_1.sai"; String out12Name = basePath + outBaseName2 + "_aln_sa_2.sai"; String outfile = outName;/* w w w. j av a 2 s . c o m*/ //Multi-Threading command.add("-t " + Threads); command.add(m_Optional_Aln.getStringValue()); //If Inputfile is in bam format if (readType.equals("paired-end")) { outfile = out11Name; //Set Outfile for forward reads if (isBam) { command.add("-b1"); } } else { // Single-end if (isBam) { command.add("-b0"); } } //Perform aln for forward reads OR single end reads command.add(path2refFile); command.add(path2readFile); command.add("-f " + outfile); String lockFile = outfile + SuccessfulRunChecker.LOCK_ENDING; /**Execute**/ super.executeCommand(new String[] { StringUtils.join(command, " ") }, outfile, exec, new File(lockFile)); //If paired end, repeat previous step if (readType.equals("paired-end")) { if (isBam) { command.set(2, "-b2"); command.set(4, path2readFile2); command.set(5, " -f " + out12Name); } else { command.set(3, path2readFile2); command.set(4, " -f " + out12Name); } /**Execute**/ lockFile = out12Name + SuccessfulRunChecker.LOCK_ENDING; super.executeCommand(new String[] { StringUtils.join(command, " ") }, out12Name, exec, new File(lockFile)); } }
From source file:com.annanovas.bestprice.DashBoardEditActivity.java
private void generateBrandRecyclerView() { sectionAdapter = new SectionedRecyclerViewAdapter(); myDB.open();/*from w w w .j av a2s .c o m*/ for (int i = 0; i < selectedProductIdList.size(); i++) { chosenBrandList.add(new ArrayList<String>()); ArrayList<BrandObject> brandArrayList = myDB.getAllBrands(selectedProductIdList.get(i)); showLog("Size " + chosenBrandIdList.size()); if (chosenBrandIdList.size() != 0) { for (int j = 0; j < brandArrayList.size(); j++) { String cellId = String.valueOf(brandArrayList.get(j).getId()); if (chosenBrandIdList.contains(cellId)) { BrandObject loop = brandArrayList.get(j); loop.setChecked(true); brandArrayList.set(j, loop); chosenBrandList.get(i).add(loop.getName()); showLog("Brand " + loop.getName()); } } } String sectionTag = String.format("section%sTag", getRandomStringNumber()); sectionAdapter.addSection(sectionTag, new BrandSectionAdapter(i, getApplicationContext(), sectionTag, selectedProductList.get(i), brandArrayList)); } if (chosenBrandIdList.size() != 0) { brandName = ""; for (int i = 0; i < chosenBrandList.size(); i++) { if (chosenBrandList.get(i).size() > 0) { //brandName += productTypeList[i] + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; brandName += selectedProductList.get(i) + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; showLog("Product " + selectedProductList.get(i)); } } tvDealerShipWith.setText(brandName); } myDB.close(); LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(DashBoardEditActivity.this); brandRecyclerView.setLayoutManager(linearLayoutManager3); brandRecyclerView.setItemAnimator(new DefaultItemAnimator()); brandRecyclerView.setAdapter(sectionAdapter); brandRecyclerView.setNestedScrollingEnabled(false); etBrandSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString(); for (Section section : sectionAdapter.getSectionsMap().values()) { if (section instanceof FilterableSection) { ((FilterableSection) section).filter(newText); } } sectionAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); }
From source file:biomine.bmvis2.pipeline.RepresentiveHighlightOperation.java
public ArrayList<VisualNode> initList(VisualGraph g) { SimpleVisualGraph sg = new SimpleVisualGraph(g.getRootNode().getDescendants()); ArrayList<ProbDijkstra> positive = new ArrayList<ProbDijkstra>(); ArrayList<ProbDijkstra> negative = new ArrayList<ProbDijkstra>(); int poicount = 0; LinkedHashSet<Integer> remaining = new LinkedHashSet<Integer>(); for (int i = 0; i < sg.n; i++) remaining.add(i);//w w w.ja v a 2 s . c o m for (Map.Entry<VisualNode, Double> ent : g.getNodesOfInterest().entrySet()) { VisualNode vn = ent.getKey(); double val = ent.getValue(); int ivn = sg.getInt(vn); remaining.remove(ivn); ProbDijkstra pd = new ProbDijkstra(sg, ivn); if (val > 0) positive.add(pd); else negative.add(pd); poicount++; } ArrayList<VisualNode> rlist = new ArrayList<VisualNode>(); ArrayList<Double> posProb = new ArrayList<Double>(); ArrayList<Double> posSquareSum = new ArrayList<Double>(); for (int i = 0; i < sg.n; i++) { double p = 1; double ss = 0; for (ProbDijkstra pd : positive) { p *= pd.getProbTo(i); ss += Math.pow(pd.getProbTo(i), 2); } posProb.add(p); posSquareSum.add(ss); } ArrayList<Double> negProb = new ArrayList<Double>(); for (int i = 0; i < sg.n; i++) { double p = 1; for (ProbDijkstra pd : negative) { p *= (1 - pd.getProbTo(i)); } negProb.add(p); } int it = 0; while (negative.size() + positive.size() < sg.n) { it++; //add //select n with highest posProb[n]*(1-negProb[n]) //in case of a tie, select n with lowest square sum distance from //positive nodes int best = -1; double bestSS = 100000; double bestProb = 0; for (int n : remaining) { double prob = posProb.get(n) * (negProb.get(n)); double ss = posSquareSum.get(n); if (prob == bestProb) { if (ss < bestSS) { bestSS = ss; best = n; } } if (prob > bestProb) { bestProb = prob; bestSS = ss; best = n; } } if (best < 0) break; System.out.println("it " + it + " best = " + best + " prob = " + bestProb); rlist.add(sg.getVisualNode(best)); ProbDijkstra newPD = new ProbDijkstra(sg, best); negative.add(newPD); remaining.remove(best); for (int i : remaining) { double ol = negProb.get(i); ol *= 1 - newPD.getProbTo(i); negProb.set(i, ol); } } return rlist; }
From source file:org.kuali.kfs.gl.batch.BatchSortUtil.java
private static void mergeFiles(File tempSortDir, int numFiles, String outputFileName, Comparator<String> comparator) { try {/*ww w .ja v a2 s .c o m*/ ArrayList<FileReader> mergefr = new ArrayList<FileReader>(numFiles); ArrayList<BufferedReader> mergefbr = new ArrayList<BufferedReader>(numFiles); // temp buffer for writing - contains the minimum record from each file ArrayList<String> fileRows = new ArrayList<String>(numFiles); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFileName)); //LOG.info("Successfully opened output file " + outputFileName); boolean someFileStillHasRows = false; // Iterate over all the files, getting the first line in each file for (int i = 0; i < numFiles; i++) { // open a file reader for each file mergefr.add(new FileReader(new File(tempSortDir, "chunk_" + i))); mergefbr.add(new BufferedReader(mergefr.get(i))); // get the first row String line = mergefbr.get(i).readLine(); if (line != null) { fileRows.add(line); someFileStillHasRows = true; } else { fileRows.add(null); } } while (someFileStillHasRows) { String min = null; int minIndex = 0; // index of the file with the minimum record // init for later compare - assume the first file has the minimum String line = fileRows.get(0); if (line != null) { min = line; minIndex = 0; } else { min = null; minIndex = -1; } // determine the minimum record of the top lines of each file // check which one is min for (int i = 1; i < fileRows.size(); i++) { line = fileRows.get(i); if (line != null) { if (min != null) { if (comparator.compare(line, min) < 0) { minIndex = i; min = line; } } else { min = line; minIndex = i; } } } if (minIndex < 0) { someFileStillHasRows = false; } else { // write to the sorted file bw.append(fileRows.get(minIndex)).append('\n'); // get another row from the file that had the min line = mergefbr.get(minIndex).readLine(); if (line != null) { fileRows.set(minIndex, line); } else { // file is out of rows, set to null so it is ignored fileRows.set(minIndex, null); } } // check if one still has rows for (int i = 0; i < fileRows.size(); i++) { someFileStillHasRows = false; if (fileRows.get(i) != null) { if (minIndex < 0) { throw new RuntimeException( "minIndex < 0 and row found in chunk file " + i + " : " + fileRows.get(i)); } someFileStillHasRows = true; break; } } // check the actual files one more time if (!someFileStillHasRows) { //write the last one not covered above for (int i = 0; i < fileRows.size(); i++) { if (fileRows.get(i) == null) { line = mergefbr.get(i).readLine(); if (line != null) { someFileStillHasRows = true; fileRows.set(i, line); } } } } } // close all the files bw.close(); //LOG.info("Successfully closed output file " + outputFileName); for (BufferedReader br : mergefbr) { br.close(); } for (FileReader fr : mergefr) { fr.close(); } } catch (Exception ex) { LOG.error("Exception merging the sorted files", ex); throw new RuntimeException("Exception merging the sorted files", ex); } }
From source file:org.bimserver.charting.SupportFunctions.java
public static String getNameOfMaterialsFromMaterialLike(IfcMaterialSelect materialLike, boolean includeIfcMaterialOID, boolean includeLayerPercentages) { String materialName = null;//from www . j a va 2 s . c o m if (materialLike instanceof IfcMaterial) { IfcMaterial ifcMaterial = (IfcMaterial) materialLike; materialName = ifcMaterial.getName(); if (includeIfcMaterialOID) materialName += String.format(" (%d)", ifcMaterial.getOid()); } else if (materialLike instanceof IfcMaterialList) { IfcMaterialList ifcMaterialList = (IfcMaterialList) materialLike; ArrayList<String> materials = new ArrayList<>(); for (IfcMaterial ifcMaterial : ifcMaterialList.getMaterials()) { String thisName = getNameOfMaterialsFromMaterialLike(ifcMaterial, includeIfcMaterialOID, includeLayerPercentages); materials.add(thisName); } materialName = StringUtils.join(materials, ", "); } else if (materialLike instanceof IfcMaterialLayerSetUsage) { IfcMaterialLayerSetUsage ifcMaterialLayerSetUsage = (IfcMaterialLayerSetUsage) materialLike; IfcMaterialLayerSet ifcMaterialLayerSet = ifcMaterialLayerSetUsage.getForLayerSet(); return getNameOfMaterialsFromMaterialLike(ifcMaterialLayerSet, includeIfcMaterialOID, includeLayerPercentages); } else if (materialLike instanceof IfcMaterialLayerSet) { IfcMaterialLayerSet ifcMaterialLayerSet = (IfcMaterialLayerSet) materialLike; ArrayList<String> materials = new ArrayList<>(); ArrayList<Double> thicknesses = new ArrayList<>(); double thicknessSum = 0.0; for (IfcMaterialLayer ifcMaterialLayer : ifcMaterialLayerSet.getMaterialLayers()) { String thisName = getNameOfMaterialsFromMaterialLike(ifcMaterialLayer.getMaterial(), includeIfcMaterialOID, includeLayerPercentages); materials.add(thisName); // if (includeLayerPercentages) { double layerThickness = ifcMaterialLayer.getLayerThickness(); thicknesses.add(layerThickness); thicknessSum += layerThickness; } } // Calculate percentages and add them to names. if (includeLayerPercentages && thicknessSum > 0) for (int i = 0; i < materials.size(); i++) { double thisPercent = 100 * thicknesses.get(i) / thicknessSum; String newMaterialName = String.format("%.2f%% %s", thisPercent, materials.get(i)); materials.set(i, newMaterialName); } // Create the joined name. materialName = StringUtils.join(materials, ", "); } else if (materialLike instanceof IfcMaterialLayer) { IfcMaterialLayer ifcMaterialLayer = (IfcMaterialLayer) materialLike; return getNameOfMaterialsFromMaterialLike(ifcMaterialLayer.getMaterial(), includeIfcMaterialOID, includeLayerPercentages); } return materialName; }
From source file:pt.webdetails.cda.utils.mondrian.CompactBandedMDXTableModel.java
public CompactBandedMDXTableModel(final Result resultSet, final int rowLimit) { if (resultSet == null) { throw new NullPointerException("ResultSet returned was null"); }// w ww . j a v a 2 s .c om this.resultSet = resultSet; // rowcount is the product of all axis-sizes. If an axis contains more than one member, then // Mondrian already performs the crossjoin for us. // column count is the count of all hierachies of all axis. final Axis[] axes = this.resultSet.getAxes(); this.rowCount = 0; this.axesSize = new int[axes.length]; final int[] axesMembers = new int[axes.length]; @SuppressWarnings("unchecked") final List<Dimension>[] dimensionsForMembersPerAxis = new List[axes.length]; @SuppressWarnings("unchecked") final List<Integer>[] membersPerAxis = new List[axes.length]; // process the column axis first .. if (axesSize.length > 0) { final Axis axis = axes[0]; final List<Position> positions = axis.getPositions(); axesSize[0] = positions.size(); if (positions.isEmpty()) { noMeasures = true; } } // Axis contains (zero or more) positions, which contains (zero or more) members for (int axesIndex = axes.length - 1; axesIndex >= 1; axesIndex -= 1) { final Axis axis = axes[axesIndex]; final List<Position> positions = axis.getPositions(); axesSize[axesIndex] = positions.size(); if (positions.isEmpty()) { noMeasures = true; } final ArrayList<Integer> memberList = new ArrayList<Integer>(); final ArrayList<Dimension> dimensionsForMembers = new ArrayList<Dimension>(); for (int positionsIndex = 0; positionsIndex < positions.size(); positionsIndex++) { final Position position = positions.get(positionsIndex); for (int positionIndex = 0; positionIndex < position.size(); positionIndex++) { Member m = position.get(positionIndex); final Dimension dimension = m.getDimension(); int hierarchyLevelCount = 1; // Originally was 0 // // Change compared to BandedMDXTM - we don't want all levels // while (false && m != null) // { // m = m.getParentMember(); // hierarchyLevelCount += 1; // } if (memberList.size() <= positionIndex) { memberList.add(hierarchyLevelCount); dimensionsForMembers.add(dimension); } else { final Integer existingLevel = memberList.get(positionIndex); if (existingLevel.intValue() < hierarchyLevelCount) { memberList.set(positionIndex, hierarchyLevelCount); dimensionsForMembers.set(positionIndex, dimension); } } } } int memberCount = 0; for (int i = 0; i < memberList.size(); i++) { memberCount += memberList.get(i); } axesMembers[axesIndex] = memberCount; dimensionsForMembersPerAxis[axesIndex] = dimensionsForMembers; membersPerAxis[axesIndex] = memberList; } if (axesSize.length > 1) { rowCount = axesSize[1]; for (int i = 2; i < axesSize.length; i++) { final int size = axesSize[i]; rowCount *= size; } } if (noMeasures == false) { rowCount = Math.max(1, rowCount); } if (axesSize.length == 0) { columnCount = 1; } else if (axesSize.length > 0) { columnCount = axesSize[0]; } for (int i = 1; i < axesMembers.length; i++) { columnCount += axesMembers[i]; } columnNames = new String[columnCount]; columnToDimensionMapping = new Dimension[columnCount]; columnToAxisPosition = new int[columnCount]; int columnIndex = 0; int dimColIndex = 0; // final FastStack memberStack = new FastStack(); for (int axesIndex = axes.length - 1; axesIndex >= 1; axesIndex -= 1) { final Axis axis = axes[axesIndex]; final List<Position> positions = axis.getPositions(); final LinkedHashSet<String> columnNamesSet = new LinkedHashSet<String>(); for (int positionsIndex = 0; positionsIndex < positions.size(); positionsIndex++) { final Position position = positions.get(positionsIndex); for (int positionIndex = 0; positionIndex < position.size(); positionIndex++) { // memberStack.clear(); Member m = position.get(positionIndex); // Get member's hierarchy final String name = m.getHierarchy().getName(); if (columnNamesSet.contains(name) == false) { columnNamesSet.add(name); } } } if (columnNamesSet.size() != axesMembers[axesIndex]) { logger.error("ERROR: Number of names is not equal the pre-counted number."); } final List<Dimension> dimForMemberPerAxis = dimensionsForMembersPerAxis[axesIndex]; final List<Integer> memberCntPerAxis = membersPerAxis[axesIndex]; for (int i = 0; i < memberCntPerAxis.size(); i++) { final Integer count = memberCntPerAxis.get(i); final Dimension dim = dimForMemberPerAxis.get(i); for (int x = 0; x < count.intValue(); x += 1) { this.columnToDimensionMapping[dimColIndex + x] = dim; this.columnToAxisPosition[dimColIndex + x] = axesIndex; } dimColIndex = count.intValue() + dimColIndex; } final String[] names = columnNamesSet.toArray(new String[columnNamesSet.size()]); System.arraycopy(names, 0, this.columnNames, columnIndex, names.length); columnIndex += names.length; } if (axesSize.length > 0) { // now create the column names for the column-axis final Axis axis = axes[0]; final List<Position> positions = axis.getPositions(); for (int i = 0; i < positions.size(); i++) { final Position position = positions.get(i); final StringBuffer positionName = new StringBuffer(100); for (int j = 0; j < position.size(); j++) { if (j != 0) { positionName.append('/'); } final Member member = position.get(j); //positionName.append(MondrianUtil.getUniqueMemberName(member)); positionName.append(member.getName()); } columnNames[columnIndex] = positionName.toString(); columnIndex += 1; } } if (axesSize.length == 0) { columnNames[0] = "Measure"; } if (rowLimit > 0) { rowCount = Math.min(rowLimit, rowCount); } }
From source file:uk.ac.ebi.phenotype.service.StatisticalResultService.java
public StackedBarsData getUnidimensionalData(Parameter p, List<String> genes, ArrayList<String> strains, String biologicalSample, String[] center, String[] sex) throws SolrServerException { String urlParams = ""; SolrQuery query = new SolrQuery() .addFilterQuery(StatisticalResultDTO.PARAMETER_STABLE_ID + ":" + p.getStableId()); String q = "*:*"; query.addFilterQuery((strains.size() > 1) ? "(" + StatisticalResultDTO.STRAIN_ACCESSION_ID + ":\"" + StringUtils.join(strains.toArray(), "\" OR " + StatisticalResultDTO.STRAIN_ACCESSION_ID + ":\"") + "\")" : StatisticalResultDTO.STRAIN_ACCESSION_ID + ":\"" + strains.get(0) + "\""); if (strains.size() > 0) { urlParams += "&strain=" + StringUtils.join(strains.toArray(), "&strain="); }/*from ww w .java 2 s .c om*/ if (center != null && center.length > 0) { query.addFilterQuery( "(" + ((center.length > 1) ? StatisticalResultDTO.PHENOTYPING_CENTER + ":\"" + StringUtils.join(center, "\" OR " + StatisticalResultDTO.PHENOTYPING_CENTER + ":\"") + "\"" : StatisticalResultDTO.PHENOTYPING_CENTER + ":\"" + center[0] + "\"") + ")"); urlParams += "&phenotyping_center=" + StringUtils.join(center, "&phenotyping_center="); } if (sex != null && sex.length == 1) { if (sex[0].equalsIgnoreCase("male")) { query.addFilterQuery(StatisticalResultDTO.MALE_CONTROL_COUNT + ":[4 TO 100000]"); query.addFilterQuery(StatisticalResultDTO.MALE_MUTANT_COUNT + ":[4 TO 100000]"); } else { query.addFilterQuery(StatisticalResultDTO.FEMALE_CONTROL_COUNT + ":[4 TO 100000]"); query.addFilterQuery(StatisticalResultDTO.FEMALE_MUTANT_COUNT + ":[4 TO 100000]"); } } query.setQuery(q); query.addFilterQuery("(" + StatisticalResultDTO.FEMALE_CONTROL_COUNT + ":[4 TO 100000] OR " + StatisticalResultDTO.MALE_CONTROL_COUNT + ":[4 TO 100000])"); query.setRows(10000000); query.setFields(StatisticalResultDTO.MARKER_ACCESSION_ID, StatisticalResultDTO.FEMALE_CONTROL_MEAN, StatisticalResultDTO.MARKER_SYMBOL, StatisticalResultDTO.FEMALE_MUTANT_MEAN, StatisticalResultDTO.MALE_CONTROL_MEAN, StatisticalResultDTO.MALE_MUTANT_MEAN, StatisticalResultDTO.FEMALE_CONTROL_COUNT, StatisticalResultDTO.FEMALE_MUTANT_COUNT, StatisticalResultDTO.MALE_CONTROL_COUNT, StatisticalResultDTO.MALE_MUTANT_COUNT); query.set("group", true); query.set("group.field", StatisticalResultDTO.COLONY_ID); query.set("group.limit", 1); List<Group> groups = solr.query(query).getGroupResponse().getValues().get(0).getValues(); double[] meansArray = new double[groups.size()]; String[] genesArray = new String[groups.size()]; String[] geneSymbolArray = new String[groups.size()]; int size = 0; for (Group gr : groups) { SolrDocumentList resDocs = gr.getResult(); String sexToDisplay = null; OverviewRatio overviewRatio = new OverviewRatio(); for (SolrDocument doc : resDocs) { sexToDisplay = getSexToDisplay(sex, sexToDisplay, doc); overviewRatio.add(doc); } if (sexToDisplay != null) { Double ratio = overviewRatio.getPlotRatio(sexToDisplay); if (ratio != null) { genesArray[size] = (String) resDocs.get(0).get(StatisticalResultDTO.MARKER_ACCESSION_ID); geneSymbolArray[size] = (String) resDocs.get(0).get(StatisticalResultDTO.MARKER_SYMBOL); meansArray[size] = ratio; size++; } } } // we do the binning for all the data but fill the bins after that to // keep tract of phenotype associations int binCount = Math.min((int) Math.floor((double) groups.size() / 2), 20); ArrayList<String> mutantGenes = new ArrayList<String>(); ArrayList<String> controlGenes = new ArrayList<String>(); ArrayList<String> mutantGeneAcc = new ArrayList<String>(); ArrayList<String> controlGeneAcc = new ArrayList<String>(); ArrayList<Double> upperBounds = new ArrayList<Double>(); EmpiricalDistribution distribution = new EmpiricalDistribution(binCount); if (size > 0) { distribution.load(ArrayUtils.subarray(meansArray, 0, size - 1)); for (double bound : distribution.getUpperBounds()) { upperBounds.add(bound); } // we we need to distribute the control mutants and the // phenotype-mutants in the bins ArrayList<Double> controlM = new ArrayList<Double>(); ArrayList<Double> phenMutants = new ArrayList<Double>(); for (int j = 0; j < upperBounds.size(); j++) { controlM.add((double) 0); phenMutants.add((double) 0); controlGenes.add(""); mutantGenes.add(""); controlGeneAcc.add(""); mutantGeneAcc.add(""); } for (int j = 0; j < size; j++) { // find out the proper bin int binIndex = getBin(upperBounds, meansArray[j]); if (genes.contains(genesArray[j])) { phenMutants.set(binIndex, 1 + phenMutants.get(binIndex)); String genesString = mutantGenes.get(binIndex); if (!genesString.contains(geneSymbolArray[j])) { if (genesString.equals("")) { mutantGenes.set(binIndex, geneSymbolArray[j]); mutantGeneAcc.set(binIndex, "accession=" + genesArray[j]); } else { mutantGenes.set(binIndex, genesString + ", " + geneSymbolArray[j]); mutantGeneAcc.set(binIndex, mutantGeneAcc.get(binIndex) + "&accession=" + genesArray[j]); } } } else { // treat as control because they don't have this phenotype association String genesString = controlGenes.get(binIndex); if (!genesString.contains(geneSymbolArray[j])) { if (genesString.equalsIgnoreCase("")) { controlGenes.set(binIndex, geneSymbolArray[j]); controlGeneAcc.set(binIndex, "accession=" + genesArray[j]); } else { controlGenes.set(binIndex, genesString + ", " + geneSymbolArray[j]); controlGeneAcc.set(binIndex, controlGeneAcc.get(binIndex) + "&accession=" + genesArray[j]); } } controlM.set(binIndex, 1 + controlM.get(binIndex)); } } // System.out.println(" Mutants list " + phenMutants); // add the rest of parameters to the graph urls for (int t = 0; t < controlGeneAcc.size(); t++) { controlGeneAcc.set(t, controlGeneAcc.get(t) + urlParams); mutantGeneAcc.set(t, mutantGeneAcc.get(t) + urlParams); } StackedBarsData data = new StackedBarsData(); data.setUpperBounds(upperBounds); data.setControlGenes(controlGenes); data.setControlMutatns(controlM); data.setMutantGenes(mutantGenes); data.setPhenMutants(phenMutants); data.setControlGeneAccesionIds(controlGeneAcc); data.setMutantGeneAccesionIds(mutantGeneAcc); return data; } return null; }