Пример #1
0
  /**
   * Clones the attributes of one NetCDF file into another.
   *
   * @param infile - The source NetCDF file
   * @param inVarName - The variable name to be copied
   * @param outfile - The destination NetCDF file
   * @param outVarName - The output variable name
   */
  private void cloneAttributes(
      NetcdfFile infile, String inVarName, NetcdfFileWriteable outfile, String outVarName) {

    // Find the variable

    Variable vi = infile.findVariable(inVarName);

    // Grab all of its attributes - unchecked, but should be OK.

    List<Attribute> l = vi.getAttributes();
    for (Attribute a : l) {
      if (a.getName().equalsIgnoreCase("units") && inVarName.equalsIgnoreCase("time")) {
        Attribute aa = new Attribute("units", "days since 1900-12-31 00:00:00");
        outfile.addVariableAttribute(outVarName, aa);
      } else if (a.getName().equalsIgnoreCase("time_origin")
          && inVarName.equalsIgnoreCase("time")) {
        Attribute aa = new Attribute("time_origin", "1900-12-31 00:00:00");
        outfile.addVariableAttribute(outVarName, aa);
      } else if (a.getName().equalsIgnoreCase("calendar")) {
        Attribute aa = new Attribute("calendar", "standard");
        outfile.addVariableAttribute(outVarName, aa);
      } else {
        outfile.addVariableAttribute(outVarName, a);
      }
    }
  }
Пример #2
0
  private int addAttributes(opendap.dap.AttributeTable table, Variable v, Iterator iter) {
    int count = 0;

    // add attribute table for this variable
    while (iter.hasNext()) {
      Attribute att = (Attribute) iter.next();
      int dods_type = DODSNetcdfFile.convertToDODSType(att.getDataType(), false);

      try {
        String attName = NcDDS.escapeName(att.getName());
        if (att.isString()) {
          /* FIX String value = escapeAttributeStringValues(att.getStringValue());
          table.appendAttribute(attName, dods_type, "\""+value+"\"");
          */
          table.appendAttribute(attName, dods_type, att.getStringValue());
        } else {
          // cant send signed bytes
          if (att.getDataType() == DataType.BYTE) {
            boolean signed = false;
            for (int i = 0; i < att.getLength(); i++) {
              if (att.getNumericValue(i).byteValue() < 0) signed = true;
            }
            if (signed) // promote to signed short
            dods_type = opendap.dap.Attribute.INT16;
          }

          for (int i = 0; i < att.getLength(); i++)
            table.appendAttribute(attName, dods_type, att.getNumericValue(i).toString());
        }
        count++;

      } catch (Exception e) {
        log.error(
            "Error appending attribute " + att.getName() + " = " + att.getStringValue() + "\n" + e);
      }
    } // loop over variable attributes

    // kludgy thing to map char arrays to DODS Strings
    if ((v != null) && (v.getDataType().getPrimitiveClassType() == char.class)) {
      int rank = v.getRank();
      int strlen = (rank == 0) ? 0 : v.getShape(rank - 1);
      Dimension dim = (rank == 0) ? null : v.getDimension(rank - 1);
      try {
        opendap.dap.AttributeTable dodsTable = table.appendContainer("DODS");
        dodsTable.appendAttribute("strlen", opendap.dap.Attribute.INT32, Integer.toString(strlen));
        if ((dim != null) && dim.isShared())
          dodsTable.appendAttribute("dimName", opendap.dap.Attribute.STRING, dim.getName());
        count++;
      } catch (Exception e) {
        log.error("Error appending attribute strlen\n" + e);
      }
    }

    return count;
  }
  /* (non-Javadoc)
   * @see loci.formats.NetCDFService#getVariableAttributes(java.lang.String)
   */
  public Hashtable<String, Object> getVariableAttributes(String name) {
    String groupName = getDirectory(name);
    String variableName = getName(name);
    Group group = getGroup(groupName);

    Variable variable = group.findVariable(variableName);
    List<Attribute> attributes = variable.getAttributes();
    Hashtable<String, Object> toReturn = new Hashtable<String, Object>();
    for (Attribute attribute : attributes) {
      toReturn.put(attribute.getName(), arrayToString(attribute.getValues()));
    }
    return toReturn;
  }
 /**
  * Recursively parses attribute and variable paths, filling <code>attributeList</code> and <code>
  * variableList</code>.
  *
  * @param groups List of groups to recursively parse.
  */
 private void parseAttributesAndVariables(List<Group> groups) {
   for (Group group : groups) {
     String groupName = group.getName();
     List<Attribute> attributes = group.getAttributes();
     for (Attribute attribute : attributes) {
       String attributeName = attribute.getName();
       if (!groupName.endsWith("/")) attributeName = "/" + attributeName;
       attributeList.add(groupName + attributeName);
     }
     List<Variable> variables = group.getVariables();
     for (Variable variable : variables) {
       String variableName = variable.getName();
       if (!groupName.endsWith("/")) variableName = "/" + variableName;
       variableList.add(variableName);
     }
     groups = group.getGroups();
     parseAttributesAndVariables(groups);
   }
 }
  public void read5kmlatlong() {
    NetcdfFile ncfile = null;
    try {
      ncfile = NetcdfFile.open("/home/kerryn/Desktop/Temp/treecover_30pts_lat.nc");
      String xrange = "Band1";
      Variable xrangeVar = ncfile.findVariable(xrange);
      Array xrangeData = xrangeVar.read();
      NCdump.printArray(xrangeData, xrange, System.out, null);

      String yrange = "GDAL_Geographics";
      Variable yrangeVar = ncfile.findVariable(yrange);
      Array yrangeData = yrangeVar.read();
      NCdump.printArray(yrangeData, yrange, System.out, null);

      List<ucar.nc2.Attribute> yattr = yrangeVar.getAttributes();
      for (ucar.nc2.Attribute attr : yattr) {
        String attrName = attr.getName();
        Array attrValue = attr.getValues();
        attrValue.getElementType();
        double value = attrValue.getDouble(0);

        System.out.println(attrName + "=" + value);
      }

      // [Northernmost_Northing = -37.51903101958847, Southernmost_Northing = -38.49309598467985,
      // Easternmost_Easting = 145.56979076552813, Westernmost_Easting = 144.4949604592204,
      // spatial_ref = "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS
      // 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433],AUTHORITY[\"EPSG\",\"4326\"]]", GeoTransform = "144.495 0.0335884 0 -37.519 0 -0.0335884 ", grid_mapping_name = "Geographics Coordinate System", long_name = "Grid_latitude"]

      //			String zrange = "z_range";
      //			Variable zrangeVar = ncfile.findVariable(zrange);
      //			Array zrangeData = zrangeVar.read();
      //			NCdump.printArray(zrangeData, zrange, System.out, null);
      //
      //			String spacing = "spacing";
      //			Variable spacingVar = ncfile.findVariable(spacing);
      //			Array spacingData = spacingVar.read();
      //			NCdump.printArray(spacingData, spacing, System.out, null);
      //
      //			String dimension = "dimension";
      //			Variable dimensionVar = ncfile.findVariable(dimension);
      //			Array dimensionData = dimensionVar.read();
      //			NCdump.printArray(dimensionData, dimension, System.out, null);
      //
      //			String z = "z";
      //			Variable zVar = ncfile.findVariable(z);
      //			Array zData = zVar.read();
      //			NCdump.printArray(zData, z, System.out, null);

      //			int count = 0;
      //			//for (int x=0;x<94;x++)
      //			for (int x=0;x<30;x++)  // 106.92 km
      //			{
      //				//for (int y=0;y<108;y++)
      //				for (int y=0;y<30;y++) // 93.06 km
      //				{
      //					double item = zData.getDouble(count);
      //					long percent = Math.round(item * 100);
      //					if (percent < 0)
      //					{
      //						percent = 0;
      //					}
      //					String percentStr = new Integer((int)percent).toString();
      //					if (percentStr.length() == 1)
      //					{
      //						percentStr = "0" + percentStr;
      //					}
      //					if (percentStr.equals("00"))
      //					{
      //						percentStr = "  ";
      //					}
      //
      //					//System.out.println(x + " " + y + " " + item);
      //					System.out.print( " " + percentStr);
      //					count ++;
      //				}
      //				System.out.println();
      //			}

    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
Пример #6
0
  Write2ncRect(NetcdfFile bufr, String fileOutName, boolean fill)
      throws IOException, InvalidRangeException {

    NetcdfFileWriteable ncfile = NetcdfFileWriteable.createNew(fileOutName, fill);
    if (debug) {
      System.out.println("FileWriter write " + bufr.getLocation() + " to " + fileOutName);
    }

    // global attributes
    List<Attribute> glist = bufr.getGlobalAttributes();
    for (Attribute att : glist) {
      String useName = N3iosp.makeValidNetcdfObjectName(att.getName());
      Attribute useAtt;
      if (att.isArray()) useAtt = ncfile.addGlobalAttribute(useName, att.getValues());
      else if (att.isString()) useAtt = ncfile.addGlobalAttribute(useName, att.getStringValue());
      else useAtt = ncfile.addGlobalAttribute(useName, att.getNumericValue());
      if (debug) System.out.println("add gatt= " + useAtt);
    }

    // global dimensions
    Dimension recordDim = null;
    Map<String, Dimension> dimHash = new HashMap<String, Dimension>();
    for (Dimension oldD : bufr.getDimensions()) {
      String useName = N3iosp.makeValidNetcdfObjectName(oldD.getName());
      boolean isRecord = useName.equals("record");
      Dimension newD = ncfile.addDimension(useName, oldD.getLength(), true, false, false);
      dimHash.put(newD.getName(), newD);
      if (isRecord) recordDim = newD;
      if (debug) System.out.println("add dim= " + newD);
    }

    // Variables
    Structure recordStruct = (Structure) bufr.findVariable(BufrIosp.obsRecord);
    for (Variable oldVar : recordStruct.getVariables()) {
      if (oldVar.getDataType() == DataType.STRUCTURE) continue;

      String varName = N3iosp.makeValidNetcdfObjectName(oldVar.getShortName());
      DataType newType = oldVar.getDataType();

      List<Dimension> newDims = new ArrayList<Dimension>();
      newDims.add(recordDim);
      for (Dimension dim : oldVar.getDimensions()) {
        newDims.add(ncfile.addDimension(oldVar.getShortName() + "_strlen", dim.getLength()));
      }

      Variable newVar = ncfile.addVariable(varName, newType, newDims);
      if (debug) System.out.println("add var= " + newVar);

      // attributes
      List<Attribute> attList = oldVar.getAttributes();
      for (Attribute att : attList) {
        String useName = N3iosp.makeValidNetcdfObjectName(att.getName());
        if (att.isArray()) ncfile.addVariableAttribute(varName, useName, att.getValues());
        else if (att.isString())
          ncfile.addVariableAttribute(varName, useName, att.getStringValue());
        else ncfile.addVariableAttribute(varName, useName, att.getNumericValue());
      }
    }

    // int max_seq = countSeq(recordStruct);
    // Dimension seqD = ncfile.addDimension("level", max_seq);

    for (Variable v : recordStruct.getVariables()) {
      if (v.getDataType() != DataType.STRUCTURE) continue;
      String structName = N3iosp.makeValidNetcdfObjectName(v.getShortName());
      int shape[] = v.getShape();

      Dimension structDim = ncfile.addDimension(structName, shape[0]);

      Structure struct = (Structure) v;
      for (Variable seqVar : struct.getVariables()) {
        String varName = N3iosp.makeValidNetcdfObjectName(seqVar.getShortName() + "-" + structName);
        DataType newType = seqVar.getDataType();

        List<Dimension> newDims = new ArrayList<Dimension>();
        newDims.add(recordDim);
        newDims.add(structDim);
        for (Dimension dim : seqVar.getDimensions()) {
          newDims.add(ncfile.addDimension(seqVar.getShortName() + "_strlen", dim.getLength()));
        }

        Variable newVar = ncfile.addVariable(varName, newType, newDims);
        if (debug) System.out.println("add var= " + newVar);

        // attributes
        List<Attribute> attList = seqVar.getAttributes();
        for (Attribute att : attList) {
          String useName = N3iosp.makeValidNetcdfObjectName(att.getName());
          if (att.isArray()) ncfile.addVariableAttribute(varName, useName, att.getValues());
          else if (att.isString())
            ncfile.addVariableAttribute(varName, useName, att.getStringValue());
          else ncfile.addVariableAttribute(varName, useName, att.getNumericValue());
        }
      }
    }

    // create the file
    ncfile.create();
    if (debug) System.out.println("File Out= " + ncfile.toString());

    // boolean ok = (Boolean) ncfile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);

    double total = copyVarData(ncfile, recordStruct);
    ncfile.flush();
    System.out.println("FileWriter done total bytes = " + total);
    ncfile.close();
  }
Пример #7
0
 public String getName() {
   return att.getName();
 }
Пример #8
0
 public Attribute findAttributeIgnoreCase(String name) {
   for (Attribute att : getAttributes()) if (att.getName().equalsIgnoreCase(name)) return att;
   return null;
 }