Input:
This converts UDUnits to UCUM .
 UDUnits : http : // www . unidata . ucar . edu / software / udunits / udunits - 1 / etc / udunits . dat http : // www . unidata . ucar . edu / software / udunits / udunits - 2 / udunits2 . html I worked with v 2 . 1 . 9
 UCUM : http : // unitsofmeasure . org / ucum . html I worked with Version : 1 . 8 $Revision : 28894 $

 UDUnits supports lots of aliases ( short and long ) and plurals ( usually by adding s ) . These all get reduced to UCUM s short and canonical - only units .

 Notes :

 This method is a strictly case sensitive . The only UDUnits that should be capitalized ( other than acronyms ) are Btu Gregorian ... Julian ... PI .
 The only UDUnits that may be capitalized are Celsius Fahrenheit Kelvin Rankine .
 For 10 to the UCUM allows 10 * or 10^ . This method uses 10^ .
 NTU becomes { ntu } .
 PSU or psu becomes { psu } .

 return the UDUnits converted to UCUM . null returns null . returns . throws Exception if trouble . [CODESPLIT] public static String udunitsToUcum ( String udunits ) { if ( udunits == null ) { return null ; } //is it a point in time? e.g., seconds since 1970-01-01T00:00:00T int sincePo = udunits . indexOf ( " since " ) ; if ( sincePo > 0 ) { try { //test if really appropriate double baf [ ] = ErddapCalendar2 . getTimeBaseAndFactor ( udunits ) ; //throws exception if trouble //use 'factor', since it is more forgiving than udunitsToUcum converter String u ; if ( Misc . nearlyEquals ( baf [ 1 ] , 0.001 , 1e-6 ) ) { // Can't simply do "baf[1] == 0.001". u = "ms" ; } else if ( baf [ 1 ] == 1 ) { u = "s" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_MINUTE ) { u = "min" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_HOUR ) { u = "h" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_DAY ) { u = "d" ; } else if ( baf [ 1 ] == 30 * ErddapCalendar2 . SECONDS_PER_DAY ) { // mo_j ? u = "mo" ; } else if ( baf [ 1 ] == 360 * ErddapCalendar2 . SECONDS_PER_DAY ) { // a_j ? u = "a" ; } else { u = udunitsToUcum ( udunits . substring ( 0 , sincePo ) ) ; //shouldn't happen, but weeks? microsec? } //make "s{since 1970-01-01T00:00:00T} return u + "{" + udunits . substring ( sincePo + 1 ) + "}" ; } catch ( Exception e ) { } } //parse udunits and build ucum, till done StringBuilder ucum = new StringBuilder ( ) ; int udLength = udunits . length ( ) ; int po = 0 ; //po is next position to be read while ( po < udLength ) { char ch = udunits . charAt ( po ) ; //letter   if ( isUdunitsLetter ( ch ) ) { //includes 'µ' and '°' //find contiguous letters|_|digit (no '-')  int po2 = po + 1 ; while ( po2 < udLength && ( isUdunitsLetter ( udunits . charAt ( po2 ) ) || udunits . charAt ( po2 ) == ' ' || ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) ) { po2 ++ ; } String tUdunits = udunits . substring ( po , po2 ) ; po = po2 ; //some udunits have internal digits, but none end in digits  //if it ends in digits, treat as exponent //find contiguous digits at end int firstDigit = tUdunits . length ( ) ; while ( firstDigit >= 1 && ErddapString2 . isDigit ( tUdunits . charAt ( firstDigit - 1 ) ) ) { firstDigit -- ; } String exponent = tUdunits . substring ( firstDigit ) ; tUdunits = tUdunits . substring ( 0 , firstDigit ) ; String tUcum = oneUdunitsToUcum ( tUdunits ) ; //deal with PER -> /  if ( tUcum . equals ( "/" ) ) { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //2 '/' cancel out } else if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { ucum . append ( ' ' ) ; } } else { ucum . append ( tUcum ) ; } //add the exponent ucum . append ( exponent ) ; //catch -exponent as a number below continue ; } //number if ( ch == ' ' || ErddapString2 . isDigit ( ch ) ) { //find contiguous digits int po2 = po + 1 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } //decimal place + digit (not just .=multiplication) boolean hasDot = false ; if ( po2 < udLength - 1 && udunits . charAt ( po2 ) == ' ' && ErddapString2 . isDigit ( udunits . charAt ( po2 + 1 ) ) ) { hasDot = true ; po2 += 2 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } } //exponent?     e-  or e{digit} boolean hasE = false ; if ( po2 < udLength - 1 && Character . toLowerCase ( udunits . charAt ( po2 ) ) == ' ' && ( udunits . charAt ( po2 + 1 ) == ' ' || ErddapString2 . isDigit ( udunits . charAt ( po2 + 1 ) ) ) ) { hasE = true ; po2 += 2 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } } String num = udunits . substring ( po , po2 ) ; po = po2 ; //convert floating point to rational number if ( hasDot || hasE ) { int rational [ ] = ErddapString2 . toRational ( ErddapString2 . parseDouble ( num ) ) ; if ( rational [ 1 ] == Integer . MAX_VALUE ) { ucum . append ( num ) ; //ignore the trouble !!! ??? } else if ( rational [ 1 ] == 0 ) //includes {0, 0} { ucum . append ( rational [ 0 ] ) ; } else { ucum . append ( rational [ 0 ] ) . append ( ".10^" ) . append ( rational [ 1 ] ) ; } } else { //just copy num ucum . append ( num ) ; } continue ; } //space or . or · (183) (multiplication) if ( ch == ' ' || ch == ' ' || ch == 183 ) { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' || lastUcum == ' ' ) { //if last token was / or .,  do nothing } else { ucum . append ( ' ' ) ; } po ++ ; continue ; } // *  (multiplication * or exponent **) if ( ch == ' ' ) { po ++ ; if ( po < udLength && udunits . charAt ( po ) == ' ' ) { ucum . append ( ' ' ) ; // exponent: ** -> ^ po ++ ; } else { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' || lastUcum == ' ' ) { //if last token was / or .,  do nothing } else { ucum . append ( ' ' ) ; } } continue ; } // / if ( ch == ' ' ) { po ++ ; char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  2 '/' cancel out } else if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { ucum . append ( ' ' ) ; } continue ; } // " if ( ch == ' ' ) { po ++ ; ucum . append ( "''" ) ; continue ; } //otherwise, punctuation.   copy it ucum . append ( ch ) ; po ++ ; } return ucum . toString ( ) ; }


Input: This converts one udunits term ( perhaps with metric prefix ( es )) to the corresponding ucum string . If udunits is just metric prefix ( es ) this returns the prefix acronym ( s ) with { count } as suffix ( e . g . dkilo returns dk { count } ) . If this can t completely convert udunits it returns the original udunits ( e . g . kiloBobs remains kiloBobs ( to avoid exact becoming ect ) . [CODESPLIT] private static String oneUdunitsToUcum ( String udunits ) { //repeatedly pull off start of udunits and build ucum, till done String oldUdunits = udunits ; StringBuilder ucum = new StringBuilder ( ) ; MAIN : while ( true ) { //try to find udunits in hashMap String tUcum = udHashMap . get ( udunits ) ; if ( tUcum != null ) { //success! done! ucum . append ( tUcum ) ; return ucum . toString ( ) ; } //try to separate out a metricName prefix (e.g., "kilo") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( udunits . startsWith ( metricName [ p ] ) ) { udunits = udunits . substring ( metricName [ p ] . length ( ) ) ; ucum . append ( metricAcronym [ p ] ) ; if ( udunits . length ( ) == 0 ) { ucum . append ( "{count}" ) ; return ucum . toString ( ) ; } continue MAIN ; } } //try to separate out a metricAcronym prefix (e.g., "k") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( udunits . startsWith ( metricAcronym [ p ] ) ) { udunits = udunits . substring ( metricAcronym [ p ] . length ( ) ) ; ucum . append ( metricAcronym [ p ] ) ; if ( udunits . length ( ) == 0 ) { ucum . append ( "{count}" ) ; return ucum . toString ( ) ; } continue MAIN ; } } return oldUdunits ; } }


Input:
This converts UCUM to UDUnits .
 UDUnits : http : // www . unidata . ucar . edu / software / udunits / udunits - 1 / etc / udunits . dat http : // www . unidata . ucar . edu / software / udunits / udunits - 2 / udunits2 . html
 UCUM : http : // unitsofmeasure . org / ucum . html

 UCUM tends to be short canonical - only and strict . Many UCUM units are the same in UDUnits .

 UDUnits supports lots of aliases ( short and long ) and plurals ( usually by adding s ) . This tries to convert UCUM to a short common UDUNIT units .

 Problems :

 UCUM has only deg no concept of degree_east|north|true|true .

 Notes :

 This method is a strictly case sensitive .
 For 10 to the UCUM allows 10 * or 10^ . This method uses 10^ .
 { ntu } becomes NTU .
 { psu } becomes PSU .

 return the UCUM converted to UDUNITS . null returns null . returns . [CODESPLIT] public static String ucumToUdunits ( String ucum ) { if ( ucum == null ) { return null ; } StringBuilder udunits = new StringBuilder ( ) ; int ucLength = ucum . length ( ) ; if ( ucLength == 0 ) { return "" ; } //is it a time point?  e.g., s{since 1970-01-01T00:00:00T} if ( ucum . charAt ( ucLength - 1 ) == ' ' && //quick reject ucum . indexOf ( ' ' ) == ucLength - 1 ) { //reasonably quick reject int sincePo = ucum . indexOf ( "{since " ) ; if ( sincePo > 0 ) { //is first part an atomic ucum unit? String tUdunits = ucHashMap . get ( ucum . substring ( 0 , sincePo ) ) ; if ( tUdunits != null ) { return tUdunits + " " + ucum . substring ( sincePo + 1 , ucLength - 1 ) ; } } } //parse ucum and build udunits, till done         int po = 0 ; //po is next position to be read while ( po < ucLength ) { char ch = ucum . charAt ( po ) ; //letter   if ( isUcumLetter ( ch ) ) { //includes [, ], {, }, 'µ' and "'" //find contiguous letters|_|digit (no '-')  int po2 = po + 1 ; while ( po2 < ucLength && ( isUcumLetter ( ucum . charAt ( po2 ) ) || ucum . charAt ( po2 ) == ' ' || ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) ) { po2 ++ ; } String tUcum = ucum . substring ( po , po2 ) ; po = po2 ; //some ucum have internal digits, but none end in digits  //if it ends in digits, treat as exponent //find contiguous digits at end int firstDigit = tUcum . length ( ) ; while ( firstDigit >= 1 && ErddapString2 . isDigit ( tUcum . charAt ( firstDigit - 1 ) ) ) { firstDigit -- ; } String exponent = tUcum . substring ( firstDigit ) ; tUcum = tUcum . substring ( 0 , firstDigit ) ; String tUdunits = oneUcumToUdunits ( tUcum ) ; //deal with PER -> /  if ( tUdunits . equals ( "/" ) ) { char lastUdunits = udunits . length ( ) == 0 ? ' ' : udunits . charAt ( udunits . length ( ) - 1 ) ; if ( lastUdunits == ' ' ) { udunits . setCharAt ( udunits . length ( ) - 1 , ' ' ) ; //2 '/' cancel out } else if ( lastUdunits == ' ' ) { udunits . setCharAt ( udunits . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { udunits . append ( ' ' ) ; } } else { udunits . append ( tUdunits ) ; } //add the exponent udunits . append ( exponent ) ; //catch -exponent as a number below continue ; } //number if ( ch == ' ' || ErddapString2 . isDigit ( ch ) ) { //find contiguous digits int po2 = po + 1 ; while ( po2 < ucLength && ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) { po2 ++ ; } // ^-  or ^{digit} if ( po2 < ucLength - 1 && Character . toLowerCase ( ucum . charAt ( po2 ) ) == ' ' && ( ucum . charAt ( po2 + 1 ) == ' ' || ErddapString2 . isDigit ( ucum . charAt ( po2 + 1 ) ) ) ) { po2 += 2 ; while ( po2 < ucLength && ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) { po2 ++ ; } } String num = ucum . substring ( po , po2 ) ; po = po2 ; udunits . append ( num ) ; continue ; } // . if ( ch == ' ' ) { po ++ ; udunits . append ( ' ' ) ; // ' ' is more common than '.' in udunits continue ; } // * if ( ch == ' ' ) { po ++ ; udunits . append ( ' ' ) ; continue ; } // '  '' if ( ch == ' ' ) { po ++ ; if ( po < ucLength && ucum . charAt ( po ) == ' ' ) { udunits . append ( "arc_second" ) ; po ++ ; } else { udunits . append ( "arc_minute" ) ; } continue ; } //otherwise, punctuation.   copy it //  / (division), " doesn't occur, udunits . append ( ch ) ; po ++ ; } return udunits . toString ( ) ; }


Input: This converts one ucum term ( perhaps with metric prefix ( es )) ( to the corresponding udunits string . If ucum is just metric prefix ( es ) this returns the metric prefix acronym ( s ) with { count } as suffix ( e . g . dkilo returns dk { count } ) . If this can t completely convert ucum it returns the original ucum ( e . g . kiloBobs remains kiloBobs ( to avoid exact becoming ect ) . [CODESPLIT] private static String oneUcumToUdunits ( String ucum ) { //repeatedly pull off start of ucum and build udunits, till done String oldUcum = ucum ; StringBuilder udunits = new StringBuilder ( ) ; MAIN : while ( true ) { //try to find ucum in hashMap String tUdunits = ucHashMap . get ( ucum ) ; if ( tUdunits != null ) { //success! done! udunits . append ( tUdunits ) ; return udunits . toString ( ) ; } //try to separate out a metricAcronym prefix (e.g., "k") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( ucum . startsWith ( metricAcronym [ p ] ) ) { ucum = ucum . substring ( metricAcronym [ p ] . length ( ) ) ; udunits . append ( metricAcronym [ p ] ) ; if ( ucum . length ( ) == 0 ) { udunits . append ( "{count}" ) ; return udunits . toString ( ) ; } continue MAIN ; } } //try to separate out a twoAcronym prefix (e.g., "Ki") for ( int p = 0 ; p < nTwo ; p ++ ) { if ( ucum . startsWith ( twoAcronym [ p ] ) ) { ucum = ucum . substring ( twoAcronym [ p ] . length ( ) ) ; char udch = udunits . length ( ) > 0 ? udunits . charAt ( udunits . length ( ) - 1 ) : ' ' ; if ( udch != ' ' && udch != ' ' && udch != ' ' ) { udunits . append ( ' ' ) ; } if ( ucum . length ( ) == 0 ) { udunits . append ( "{count}" ) ; return udunits . toString ( ) ; } udunits . append ( twoValue [ p ] ) . append ( "." ) ; continue MAIN ; } } //ends in comment?  try to just convert the beginning int po1 = oldUcum . lastIndexOf ( ' ' ) ; if ( po1 > 0 && oldUcum . endsWith ( "}" ) ) { return oneUcumToUdunits ( oldUcum . substring ( 0 , po1 ) ) + oldUcum . substring ( po1 ) ; } return oldUcum ; } }


Input: Reads the contents of { @code inputStream } into a HashMap . Each key - value pair in the input will result in an entry in the map . <p / > The specified stream remains open after this method returns . [CODESPLIT] public static HashMap < String , String > getHashMapStringString ( InputStream inputStream , String charset ) throws IOException { HashMap < String , String > ht = new HashMap <> ( ) ; ErddapStringArray sa = ErddapStringArray . fromInputStream ( inputStream , charset ) ; int n = sa . size ( ) ; int i = 0 ; while ( i < n ) { String s = sa . get ( i ++ ) ; if ( s . startsWith ( "#" ) ) { continue ; } while ( i < n && s . endsWith ( "\\" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) + sa . get ( i ++ ) ; } int po = s . indexOf ( ' ' ) ; if ( po < 0 ) { continue ; } //new String: so not linked to big source file's text ht . put ( s . substring ( 0 , po ) . trim ( ) , s . substring ( po + 1 ) . trim ( ) ) ; } return ht ; }


Input: Center name from table C - 1 or C - 11 [CODESPLIT] public static String getCenterName ( int center_id , int edition ) { String result = ( edition == 1 ) ? getTableValue ( 1 , center_id ) : getTableValue ( 11 , center_id ) ; if ( result != null ) return result ; if ( center_id == 0 ) return "WMO standard table" ; return "Unknown center=" + center_id ; }


Input: Center name from table C - 1 or C - 11 [CODESPLIT] public static String getCenterNameBufr ( int center_id , int edition ) { String result = ( edition < 4 ) ? getTableValue ( 1 , center_id ) : getTableValue ( 11 , center_id ) ; if ( result != null ) return result ; if ( center_id == 0 ) return "WMO standard table" ; return "Unknown center=" + center_id ; }


Input: Not supported by SimpleCatalogBuilder . [CODESPLIT] public InvCatalogImpl generateProxyDsResolverCatalog ( CrawlableDataset catalogCrDs , ProxyDatasetHandler pdh ) throws IOException { throw new java . lang . UnsupportedOperationException ( "This method not supported by SimpleCatalogBuilder." ) ; }


Input: Extract the lat / lon / alt bounding boxes from the dataset . [CODESPLIT] static public ThreddsMetadata . GeospatialCoverage extractGeospatial ( InvDatasetImpl threddsDataset ) throws IOException { ThreddsDataFactory . Result result = null ; try { result = new ThreddsDataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ; if ( result . fatalError ) { System . out . println ( " openDatatype errs=" + result . errLog ) ; return null ; } if ( result . featureType == FeatureType . GRID ) { System . out . println ( " GRID=" + result . location ) ; GridDataset gridDataset = ( GridDataset ) result . featureDataset ; return extractGeospatial ( gridDataset ) ; } else if ( result . featureType == FeatureType . POINT ) { PointObsDataset pobsDataset = ( PointObsDataset ) result . featureDataset ; LatLonRect llbb = pobsDataset . getBoundingBox ( ) ; if ( null != llbb ) { ThreddsMetadata . GeospatialCoverage gc = new ThreddsMetadata . GeospatialCoverage ( ) ; gc . setBoundingBox ( llbb ) ; return gc ; } } else if ( result . featureType == FeatureType . STATION ) { StationObsDataset sobsDataset = ( StationObsDataset ) result . featureDataset ; LatLonRect llbb = sobsDataset . getBoundingBox ( ) ; if ( null != llbb ) { ThreddsMetadata . GeospatialCoverage gc = new ThreddsMetadata . GeospatialCoverage ( ) ; gc . setBoundingBox ( llbb ) ; return gc ; } } } finally { try { if ( ( result != null ) && ( result . featureDataset != null ) ) result . featureDataset . close ( ) ; } catch ( IOException ioe ) { logger . error ( "Closing dataset " + result . featureDataset , ioe ) ; } } return null ; }


Input: Extract a list of data variables ( and their canonical names if possible ) from the dataset . [CODESPLIT] static public ThreddsMetadata . Variables extractVariables ( InvDatasetImpl threddsDataset ) throws IOException { ThreddsDataFactory . Result result = null ; try { result = new ThreddsDataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ; if ( result . fatalError ) { System . out . println ( " openDatatype errs=" + result . errLog ) ; return null ; } if ( result . featureType == FeatureType . GRID ) { // System.out.println(" extractVariables GRID=" + result.location); GridDataset gridDataset = ( GridDataset ) result . featureDataset ; return extractVariables ( threddsDataset , gridDataset ) ; } else if ( ( result . featureType == FeatureType . STATION ) || ( result . featureType == FeatureType . POINT ) ) { PointObsDataset pobsDataset = ( PointObsDataset ) result . featureDataset ; ThreddsMetadata . Variables vars = new ThreddsMetadata . Variables ( "CF-1.0" ) ; for ( VariableSimpleIF vs : pobsDataset . getDataVariables ( ) ) { ThreddsMetadata . Variable v = new ThreddsMetadata . Variable ( ) ; vars . addVariable ( v ) ; v . setName ( vs . getShortName ( ) ) ; v . setDescription ( vs . getDescription ( ) ) ; v . setUnits ( vs . getUnitsString ( ) ) ; ucar . nc2 . Attribute att = vs . findAttributeIgnoreCase ( "standard_name" ) ; if ( att != null ) v . setVocabularyName ( att . getStringValue ( ) ) ; } vars . sort ( ) ; return vars ; } } finally { try { if ( ( result != null ) && ( result . featureDataset != null ) ) result . featureDataset . close ( ) ; } catch ( IOException ioe ) { logger . error ( "Closing dataset " + result . featureDataset , ioe ) ; } } return null ; }


Input: ///////////////////////////////////////////////////////////////////////////// [CODESPLIT] static public ThreddsMetadata . Variables extractVariables ( FeatureDatasetPoint fd ) { ThreddsMetadata . Variables vars = new ThreddsMetadata . Variables ( "CF-1.5" ) ; List < VariableSimpleIF > dataVars = fd . getDataVariables ( ) ; if ( dataVars == null ) return vars ; for ( VariableSimpleIF v : dataVars ) { ThreddsMetadata . Variable tv = new ThreddsMetadata . Variable ( ) ; vars . addVariable ( tv ) ; tv . setName ( v . getShortName ( ) ) ; tv . setDescription ( v . getDescription ( ) ) ; tv . setUnits ( v . getUnitsString ( ) ) ; ucar . nc2 . Attribute att = v . findAttributeIgnoreCase ( "standard_name" ) ; if ( att != null ) tv . setVocabularyName ( att . getStringValue ( ) ) ; } vars . sort ( ) ; return vars ; }


Input: Create a CalendarDateUnit from a calendar name and a udunit string = unit since calendarDate [CODESPLIT] static public CalendarDateUnit of ( String calendarName , String udunitString ) { Calendar calt = Calendar . get ( calendarName ) ; if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }


Input: Create a CalendarDateUnit from a calendar and a udunit string = unit since calendarDate [CODESPLIT] static public CalendarDateUnit withCalendar ( Calendar calt , String udunitString ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }


Input: Create a CalendarDateUnit from a calendar a CalendarPeriod . Field and a base date [CODESPLIT] static public CalendarDateUnit of ( Calendar calt , CalendarPeriod . Field periodField , CalendarDate baseDate ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , periodField , baseDate ) ; }


Input: inverse of makeCalendarDate [CODESPLIT] public double makeOffsetFromRefDate ( CalendarDate date ) { if ( isCalendarField ) { if ( date . equals ( baseDate ) ) return 0.0 ; return date . getDifference ( baseDate , periodField ) ; } else { long msecs = date . getDifferenceInMsecs ( baseDate ) ; return msecs / period . getValueInMillisecs ( ) ; } }


Input:
inverse of makeOffsetFromRefDate [CODESPLIT] public CalendarDate makeCalendarDate ( double value ) { if ( isCalendarField ) return baseDate . add ( CalendarPeriod . of ( ( int ) value , periodField ) ) ; // LOOK int vs double
 else return baseDate . add ( value , periodField ) ; }


Input: ////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static void main ( String [ ] args ) { CalendarDateUnit cdu ; String s = "calendar Month since 2012-01-19T18:00:00.000Z" ; cdu = CalendarDateUnit . of ( null , s ) ; System . out . printf ( "%s == %s%n" , s , cdu ) ; }


Input: / * public java . io . File chooseFile () { if ( !readOk ) return null ; w . show () ; [CODESPLIT] public String chooseFilenameToSave ( String defaultFilename ) { chooser . setDialogType ( JFileChooser . SAVE_DIALOG ) ; String result = ( defaultFilename == null ) ? chooseFilename ( ) : chooseFilename ( defaultFilename ) ; chooser . setDialogType ( JFileChooser . OPEN_DIALOG ) ; return result ; }


Input:
Allow user to select file then return the filename in canonical form always using / never \ [CODESPLIT] public String chooseFilename ( ) { if ( ! readOk ) return null ; selectedFile = false ; //selectedURL = false;
 w . setVisible ( true ) ; // modal, so blocks; listener calls hide(), which unblocks.
 if ( selectedFile ) { File file = chooser . getSelectedFile ( ) ; if ( file == null ) return null ; try { return file . getCanonicalPath ( ) . replace ( ' ' , ' ' ) ; } catch ( IOException ioe ) { } // return null
 } /* if (selectedURL) {
      return (String) urlComboBox.getSelectedItem();
    }  */ return null ; }


Input: Returns the corresponding quantity dimension . [CODESPLIT] public QuantityDimension getQuantityDimension ( ) { Factor [ ] factors = getFactors ( ) ; for ( int i = factors . length ; -- i >= 0 ; ) { Factor factor = factors [ i ] ; factors [ i ] = new Factor ( ( ( BaseUnit ) factor . getBase ( ) ) . getBaseQuantity ( ) , factor . getExponent ( ) ) ; } return new QuantityDimension ( factors ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { System . out . println ( "new UnitDimension() = \"" + new UnitDimension ( ) + ' ' ) ; UnitDimension timeDimension = new UnitDimension ( BaseUnit . getOrCreate ( UnitName . newUnitName ( "second" , null , "s" ) , BaseQuantity . TIME ) ) ; System . out . println ( "timeDimension = \"" + timeDimension + ' ' ) ; UnitDimension lengthDimension = new UnitDimension ( BaseUnit . getOrCreate ( UnitName . newUnitName ( "meter" , null , "m" ) , BaseQuantity . LENGTH ) ) ; System . out . println ( "lengthDimension = \"" + lengthDimension + ' ' ) ; System . out . println ( "lengthDimension.isReciprocalOf(timeDimension) = \"" + lengthDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; UnitDimension hertzDimension = timeDimension . raiseTo ( - 1 ) ; System . out . println ( "hertzDimension = \"" + hertzDimension + ' ' ) ; System . out . println ( "hertzDimension.isReciprocalOf(timeDimension) = \"" + hertzDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; System . out . println ( "lengthDimension.divideBy(timeDimension) = \"" + lengthDimension . divideBy ( timeDimension ) + ' ' ) ; System . out . println ( "lengthDimension.divideBy(timeDimension).raiseTo(2) = \"" + lengthDimension . divideBy ( timeDimension ) . raiseTo ( 2 ) + ' ' ) ; }


Input:
Check if this is a valid SIGMET - IRIS file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) { try { raf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // The first struct in the file is the product_hdr, which will have the
 // standard structure_header, followed by other embedded structures.
 // Each of these structures also have a structure header. To validate
 // the file we check for a product_hdr (by looking for type 27 in the
 // structure_header), then a product_configuration structure (by looking
 // for type 26 in its structure_header), then checking that that
 // the product_configuration does indicate a type of RAW data (type 15)
 raf . seek ( 0 ) ; short [ ] data = new short [ 13 ] ; raf . readShort ( data , 0 , 13 ) ; return ( data [ 0 ] == ( short ) 27 && data [ 6 ] == ( short ) 26 && data [ 12 ] == ( short ) 15 ) ; } catch ( IOException ioe ) { System . out . println ( "In isValidFile(): " + ioe . toString ( ) ) ; return false ; } }


Input:
Open existing file and populate ncfile with it . [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws java . io . IOException { super . open ( raf , ncfile , cancelTask ) ; //java.util.Map<String, Number> recHdr=new java.util.HashMap<String, Number>();
 java . util . Map < String , String > hdrNames = new java . util . HashMap < String , String > ( ) ; volScan = new SigmetVolumeScan ( raf , ncfile , varList ) ; this . varList = init ( raf , ncfile , hdrNames ) ; // doData(raf, ncfile, varList);
 // raf.close();
 // this.ncfile.close();
 }


Input:
Read some global data from SIGMET file . The SIGMET file consists of records with fixed length = 6144 bytes . [CODESPLIT] static public java . util . Map < String , Number > readRecordsHdr ( ucar . unidata . io . RandomAccessFile raf ) { java . util . Map < String , Number > recHdr1 = new java . util . HashMap < String , Number > ( ) ; try { int nparams = 0 ; //      -- Read from <product_end> of the 1st record -- 12+320+120
 //      -- Calculate Nyquist velocity --------------------
 raf . seek ( 452 ) ; int prf = raf . readInt ( ) ; raf . seek ( 480 ) ; int wave = raf . readInt ( ) ; float vNyq = calcNyquist ( prf , wave ) ; recHdr1 . put ( "vNyq" , vNyq ) ; //      -- Read from the 2nd record----------- 6144+12(strucr_hdr)+168(from ingest_config)
 raf . seek ( 6324 ) ; int radar_lat = raf . readInt ( ) ; int radar_lon = raf . readInt ( ) ; //6328
 short ground_height = raf . readShort ( ) ; //6332
 short radar_height = raf . readShort ( ) ; //6334
 raf . skipBytes ( 4 ) ; short num_rays = raf . readShort ( ) ; // 6340
 raf . skipBytes ( 2 ) ; int radar_alt = raf . readInt ( ) ; //6344
 raf . seek ( 6648 ) ; int time_beg = raf . readInt ( ) ; raf . seek ( 6652 ) ; int time_end = raf . readInt ( ) ; raf . seek ( 6772 ) ; int data_mask = raf . readInt ( ) ; for ( int j = 0 ; j < 32 ; j ++ ) { nparams += ( ( data_mask >> j ) & ( 0x1 ) ) ; } raf . seek ( 6912 ) ; short multiprf = raf . readShort ( ) ; raf . seek ( 7408 ) ; int range_first = raf . readInt ( ) ; //  cm    7408
 int range_last = raf . readInt ( ) ; //  cm  7412
 raf . skipBytes ( 2 ) ; short bins = raf . readShort ( ) ; //7418
 if ( bins % 2 != 0 ) bins = ( short ) ( bins + 1 ) ; raf . skipBytes ( 4 ) ; int step = raf . readInt ( ) ; //  cm    7424
 raf . seek ( 7574 ) ; short number_sweeps = raf . readShort ( ) ; // 7574
 raf . seek ( 12312 ) ; int base_time = raf . readInt ( ) ; //<ingest_data_header> 3d rec
 raf . skipBytes ( 2 ) ; short year = raf . readShort ( ) ; short month = raf . readShort ( ) ; short day = raf . readShort ( ) ; recHdr1 . put ( "radar_lat" , calcAngle ( radar_lat ) ) ; recHdr1 . put ( "radar_lon" , calcAngle ( radar_lon ) ) ; recHdr1 . put ( "range_first" , range_first ) ; recHdr1 . put ( "range_last" , range_last ) ; recHdr1 . put ( "ground_height" , ground_height ) ; recHdr1 . put ( "radar_height" , radar_height ) ; recHdr1 . put ( "radar_alt" , radar_alt ) ; recHdr1 . put ( "step" , step ) ; recHdr1 . put ( "bins" , bins ) ; //System.out.println("  bins="+bins);
 recHdr1 . put ( "num_rays" , num_rays ) ; //System.out.println("  rays="+num_rays);
 recHdr1 . put ( "nparams" , nparams ) ; //System.out.println("  nparams="+nparams);
 recHdr1 . put ( "multiprf" , multiprf ) ; recHdr1 . put ( "number_sweeps" , number_sweeps ) ; //System.out.println("IN HDR:  number_sweeps="+number_sweeps);
 recHdr1 . put ( "year" , year ) ; recHdr1 . put ( "month" , month ) ; recHdr1 . put ( "day" , day ) ; recHdr1 . put ( "base_time" , base_time ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } return recHdr1 ; }


Input:
Read StationName strings [CODESPLIT] public java . util . Map < String , String > readStnNames ( ucar . unidata . io . RandomAccessFile raf ) { java . util . Map < String , String > hdrNames = new java . util . HashMap < String , String > ( ) ; try { raf . seek ( 6288 ) ; String stnName = raf . readString ( 16 ) ; //System.out.println(" stnName="+stnName.trim());
 raf . seek ( 6306 ) ; String stnName_util = raf . readString ( 16 ) ; hdrNames . put ( "StationName" , stnName . trim ( ) ) ; hdrNames . put ( "StationName_SetupUtility" , stnName_util . trim ( ) ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } return hdrNames ; }


Input:
Define Dimensions Variables Attributes in ncfile [CODESPLIT] public ArrayList < Variable > init ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , java . util . Map < String , String > hdrNames ) throws java . io . IOException { // prepare attribute values
 String [ ] data_name = { " " , "TotalPower" , "Reflectivity" , "Velocity" , "Width" , "Differential_Reflectivity" } ; String [ ] unit = { " " , "dbZ" , "dbZ" , "m/sec" , "m/sec" , "dB" } ; int [ ] type = { 1 , 2 , 3 , 4 , 5 } ; String def_datafile = "SIGMET-IRIS" ; String tim = "" ; int ngates = 0 ; recHdr = readRecordsHdr ( raf ) ; hdrNames = readStnNames ( raf ) ; String stnName = hdrNames . get ( "StationName" ) ; String stnName_util = hdrNames . get ( "StationName_SetupUtility" ) ; float radar_lat = recHdr . get ( "radar_lat" ) . floatValue ( ) ; //System.out.println("rad_lat="+radar_lat);
 float radar_lon = recHdr . get ( "radar_lon" ) . floatValue ( ) ; //System.out.println("rad_lon="+radar_lon);
 short ground_height = recHdr . get ( "ground_height" ) . shortValue ( ) ; //System.out.println("ground_H="+ground_height);
 short radar_height = recHdr . get ( "radar_height" ) . shortValue ( ) ; //System.out.println("radar_H="+radar_height);
 int radar_alt = ( recHdr . get ( "radar_alt" ) . intValue ( ) ) / 100 ; //System.out.println("rad_alt="+radar_alt);
 short num_rays = recHdr . get ( "num_rays" ) . shortValue ( ) ; //System.out.println("num_rays="+num_rays);
 short bins = recHdr . get ( "bins" ) . shortValue ( ) ; //System.out.println("bins="+bins);
 float range_first = ( recHdr . get ( "range_first" ) . intValue ( ) ) * 0.01f ; //System.out.println("range_1st="+range_first);
 float range_last = ( recHdr . get ( "range_last" ) . intValue ( ) ) * 0.01f ; //System.out.println("step="+step);
 short number_sweeps = recHdr . get ( "number_sweeps" ) . shortValue ( ) ; //System.out.println("number_sweeps="+number_sweeps);
 int nparams = ( recHdr . get ( "nparams" ) . intValue ( ) ) ; //System.out.println("nparams="+nparams);
 short year = recHdr . get ( "year" ) . shortValue ( ) ; //System.out.println("year="+year);
 short month = recHdr . get ( "month" ) . shortValue ( ) ; short day = recHdr . get ( "day" ) . shortValue ( ) ; int base_time = ( recHdr . get ( "base_time" ) . intValue ( ) ) ; // define number of gates for every sweep
 sweep_bins = new int [ nparams * number_sweeps ] ; if ( number_sweeps > 1 ) { sweep_bins = volScan . getNumberGates ( ) ; } else { for ( int kk = 0 ; kk < nparams ; kk ++ ) { sweep_bins [ kk ] = bins ; } } // add Dimensions
 Dimension scanR = new Dimension ( "scanR" , number_sweeps , true ) ; Dimension radial = new Dimension ( "radial" , num_rays , true ) ; Dimension [ ] gateR = new Dimension [ number_sweeps ] ; String dim_name = "gateR" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { if ( number_sweeps > 1 ) { dim_name = "gateR_sweep_" + ( j + 1 ) ; } gateR [ j ] = new Dimension ( dim_name , sweep_bins [ j ] , true ) ; } ncfile . addDimension ( null , scanR ) ; ncfile . addDimension ( null , radial ) ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { ncfile . addDimension ( null , gateR [ j ] ) ; } ArrayList < Dimension > dims0 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims1 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims2 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims3 = new ArrayList < Dimension > ( ) ; ArrayList < Variable > varList = new ArrayList < Variable > ( ) ; Variable [ ] [ ] v = new Variable [ nparams ] [ number_sweeps ] ; String var_name = "" ; for ( int j = 0 ; j < nparams ; j ++ ) { int tp = type [ j ] ; var_name = data_name [ tp ] ; for ( int jj = 0 ; jj < number_sweeps ; jj ++ ) { if ( number_sweeps > 1 ) { var_name = data_name [ tp ] + "_sweep_" + ( jj + 1 ) ; } v [ j ] [ jj ] = new Variable ( ncfile , null , null , var_name ) ; v [ j ] [ jj ] . setDataType ( DataType . FLOAT ) ; dims2 . add ( radial ) ; dims2 . add ( gateR [ jj ] ) ; v [ j ] [ jj ] . setDimensions ( dims2 ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . LONG_NAME , var_name ) ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . UNITS , unit [ tp ] ) ) ; String coordinates = "time elevationR azimuthR distanceR" ; v [ j ] [ jj ] . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , v [ j ] [ jj ] ) ; varList . add ( v [ j ] [ jj ] ) ; dims2 . clear ( ) ; } } tsu_sec = new int [ number_sweeps ] ; String [ ] tsu = new String [ number_sweeps ] ; String [ ] time_units = new String [ number_sweeps ] ; tsu_sec = volScan . getStartSweep ( ) ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { String st1 = Short . toString ( month ) ; if ( st1 . length ( ) < 2 ) st1 = "0" + st1 ; String st2 = Short . toString ( day ) ; if ( st2 . length ( ) < 2 ) st2 = "0" + st2 ; date0 = String . valueOf ( year ) + "-" + st1 + "-" + st2 ; tsu [ i ] = date0 + "T" + calcTime ( tsu_sec [ i ] , 0 ) + "Z" ; } for ( int j = 0 ; j < number_sweeps ; j ++ ) { time_units [ j ] = "secs since " + tsu [ j ] ; } dims0 . add ( radial ) ; // add "time" variable
 Variable [ ] time = new Variable [ number_sweeps ] ; String tm = "time" ; String tm_name = "" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { tm_name = tm ; if ( number_sweeps > 1 ) { tm_name = tm + "_sweep_" + ( j + 1 ) ; } time [ j ] = new Variable ( ncfile , null , null , tm_name ) ; time [ j ] . setDataType ( DataType . INT ) ; time [ j ] . setDimensions ( dims0 ) ; time [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , "time from start of sweep" ) ) ; time [ j ] . addAttribute ( new Attribute ( CDM . UNITS , time_units [ j ] ) ) ; time [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; time [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 99 ) ) ; ncfile . addVariable ( null , time [ j ] ) ; varList . add ( time [ j ] ) ; } // add "elevationR" variable
 Variable [ ] elevationR = new Variable [ number_sweeps ] ; String ele = "elevationR" ; String ele_name = "" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { ele_name = ele ; if ( number_sweeps > 1 ) { ele_name = ele + "_sweep_" + ( j + 1 ) ; } elevationR [ j ] = new Variable ( ncfile , null , null , ele_name ) ; elevationR [ j ] . setDataType ( DataType . FLOAT ) ; elevationR [ j ] . setDimensions ( dims0 ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , "elevation angle" ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , "degrees" ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialElevation . toString ( ) ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , elevationR [ j ] ) ; varList . add ( elevationR [ j ] ) ; } // add "azimuthR" variable
 Variable [ ] azimuthR = new Variable [ number_sweeps ] ; String azim = "azimuthR" ; String azim_name = "" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { azim_name = azim ; if ( number_sweeps > 1 ) { azim_name = azim + "_sweep_" + ( j + 1 ) ; } azimuthR [ j ] = new Variable ( ncfile , null , null , azim_name ) ; azimuthR [ j ] . setDataType ( DataType . FLOAT ) ; azimuthR [ j ] . setDimensions ( dims0 ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , "azimuth angle" ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , "degrees" ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialAzimuth . toString ( ) ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , azimuthR [ j ] ) ; varList . add ( azimuthR [ j ] ) ; } // add "distanceR" variable
 Variable [ ] distanceR = new Variable [ number_sweeps ] ; String dName = "distanceR" ; String dist_name = "" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { dist_name = dName ; if ( number_sweeps > 1 ) { dist_name = dName + "_sweep_" + ( j + 1 ) ; } distanceR [ j ] = new Variable ( ncfile , null , null , dist_name ) ; distanceR [ j ] . setDataType ( DataType . FLOAT ) ; dims1 . add ( gateR [ j ] ) ; distanceR [ j ] . setDimensions ( dims1 ) ; distanceR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , "radial distance" ) ) ; distanceR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , "m" ) ) ; distanceR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialDistance . toString ( ) ) ) ; ncfile . addVariable ( null , distanceR [ j ] ) ; varList . add ( distanceR [ j ] ) ; dims1 . clear ( ) ; } // add "numGates" variable
 dims3 . add ( scanR ) ; Variable numGates = new Variable ( ncfile , null , null , "numGates" ) ; numGates . setDataType ( DataType . INT ) ; numGates . setDimensions ( dims3 ) ; numGates . addAttribute ( new Attribute ( CDM . LONG_NAME , "number of gates in the sweep" ) ) ; ncfile . addVariable ( null , numGates ) ; varList . add ( numGates ) ; // add global attributes
 ncfile . addAttribute ( null , new Attribute ( "definition" , "SIGMET-IRIS RAW" ) ) ; ncfile . addAttribute ( null , new Attribute ( "description" , "SIGMET-IRIS data are reading by Netcdf IOSP" ) ) ; ncfile . addAttribute ( null , new Attribute ( "StationName" , stnName ) ) ; ncfile . addAttribute ( null , new Attribute ( "StationName_SetupUtility" , stnName_util ) ) ; ncfile . addAttribute ( null , new Attribute ( "radar_lat" , radar_lat ) ) ; ncfile . addAttribute ( null , new Attribute ( "radar_lon" , radar_lon ) ) ; ncfile . addAttribute ( null , new Attribute ( "ground_height" , ground_height ) ) ; ncfile . addAttribute ( null , new Attribute ( "radar_height" , radar_height ) ) ; ncfile . addAttribute ( null , new Attribute ( "radar_alt" , radar_alt ) ) ; ncfile . addAttribute ( null , new Attribute ( "num_data_types" , nparams ) ) ; ncfile . addAttribute ( null , new Attribute ( "number_sweeps" , number_sweeps ) ) ; String sn = "start_sweep" ; String snn = "" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { snn = sn ; if ( number_sweeps > 1 ) { snn = sn + "_" + ( j + 1 ) ; } ncfile . addAttribute ( null , new Attribute ( snn , tsu [ j ] ) ) ; } ncfile . addAttribute ( null , new Attribute ( "num_rays" , num_rays ) ) ; ncfile . addAttribute ( null , new Attribute ( "max_number_gates" , bins ) ) ; ncfile . addAttribute ( null , new Attribute ( "range_first" , range_first ) ) ; ncfile . addAttribute ( null , new Attribute ( "range_last" , range_last ) ) ; ncfile . addAttribute ( null , new Attribute ( "DataType" , "Radial" ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , _Coordinate . Convention ) ) ; // --------- fill all of values in the ncfile ------
 doNetcdfFileCoordinate ( ncfile , volScan . base_time , volScan . year , volScan . month , volScan . day , varList , recHdr ) ; ncfile . finish ( ) ; return varList ; }


Input:
Fill all of the variables / attributes in the ncfile [CODESPLIT] public void doNetcdfFileCoordinate ( ucar . nc2 . NetcdfFile ncfile , int [ ] bst , short [ ] yr , short [ ] m , short [ ] dda , ArrayList < Variable > varList , java . util . Map < String , Number > recHdr ) { // prepare attribute values
 String [ ] unit = { " " , "dbZ" , "dbZ" , "m/sec" , "m/sec" , "dB" } ; String def_datafile = "SIGMET-IRIS" ; Short header_length = 80 ; Short ray_header_length = 6 ; int ngates = 0 ; float radar_lat = recHdr . get ( "radar_lat" ) . floatValue ( ) ; //System.out.println("rad_lat="+radar_lat);
 float radar_lon = recHdr . get ( "radar_lon" ) . floatValue ( ) ; //System.out.println("rad_lon="+radar_lon);
 short ground_height = recHdr . get ( "ground_height" ) . shortValue ( ) ; //System.out.println("ground_H="+ground_height);
 short radar_height = recHdr . get ( "radar_height" ) . shortValue ( ) ; //System.out.println("radar_H="+radar_height);
 int radar_alt = ( recHdr . get ( "radar_alt" ) . intValue ( ) ) / 100 ; //System.out.println("rad_alt="+radar_alt);
 short num_rays = recHdr . get ( "num_rays" ) . shortValue ( ) ; //System.out.println("HERE!! num_rays="+num_rays);
 float range_first = ( recHdr . get ( "range_first" ) . intValue ( ) ) * 0.01f ; //System.out.println("range_1st="+range_first);
 float range_last = ( recHdr . get ( "range_last" ) . intValue ( ) ) * 0.01f ; //System.out.println("step="+step);
 short number_sweeps = recHdr . get ( "number_sweeps" ) . shortValue ( ) ; int nparams = ( recHdr . get ( "nparams" ) . intValue ( ) ) ; //System.out.println("nparams="+nparams);
 // define date/time
 //int last_t=(int)(ray[nparams*number_sweeps-1][num_rays-1].getTime());
 int last_t = volScan . lastRay . getTime ( ) ; String sss1 = Short . toString ( m [ 0 ] ) ; if ( sss1 . length ( ) < 2 ) sss1 = "0" + sss1 ; String sss2 = Short . toString ( dda [ 0 ] ) ; if ( sss2 . length ( ) < 2 ) sss2 = "0" + sss2 ; String base_date0 = String . valueOf ( yr [ 0 ] ) + "-" + sss1 + "-" + sss2 ; String sss11 = Short . toString ( m [ number_sweeps - 1 ] ) ; if ( sss11 . length ( ) < 2 ) sss11 = "0" + sss11 ; String sss22 = Short . toString ( dda [ number_sweeps - 1 ] ) ; if ( sss22 . length ( ) < 2 ) sss22 = "0" + sss22 ; String base_date1 = String . valueOf ( yr [ number_sweeps - 1 ] ) + "-" + sss11 + "-" + sss22 ; String start_time = base_date0 + "T" + calcTime ( bst [ 0 ] , 0 ) + "Z" ; String end_time = base_date1 + "T" + calcTime ( bst [ number_sweeps - 1 ] , last_t ) + "Z" ; ncfile . addAttribute ( null , new Attribute ( "time_coverage_start" , start_time ) ) ; ncfile . addAttribute ( null , new Attribute ( "time_coverage_end" , end_time ) ) ; // set all of Variables
 try { int sz = varList . size ( ) ; ArrayFloat . D2 [ ] dataArr = new ArrayFloat . D2 [ nparams * number_sweeps ] ; Index [ ] dataIndex = new Index [ nparams * number_sweeps ] ; Ray [ ] rtemp = new Ray [ ( int ) num_rays ] ; // NCdump.printArray(dataArr[0], "Total_Power", System.out, null);
 Variable [ ] distanceR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] distArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] distIndex = new Index [ number_sweeps ] ; String distName = "distanceR" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { distName = "distanceR_sweep_" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( distName . trim ( ) ) ) { distanceR [ i ] = aVarList ; break ; } } distArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , distanceR [ i ] . getShape ( ) ) ; distIndex [ i ] = distArr [ i ] . getIndex ( ) ; // for (int jj=0; jj<num_rays; jj++) { rtemp[jj]=ray[i][jj]; }
 ngates = sweep_bins [ i ] ; float stp = calcStep ( range_first , range_last , ( short ) ngates ) ; for ( int ii = 0 ; ii < ngates ; ii ++ ) { distArr [ i ] . setFloat ( distIndex [ i ] . set ( ii ) , ( range_first + ii * stp ) ) ; } } // NCdump.printArray(distArr[0], "distanceR", System.out, null);
 List rgp = volScan . getTotalPowerGroups ( ) ; if ( rgp . size ( ) == 0 ) rgp = volScan . getReflectivityGroups ( ) ; List [ ] sgp = new ArrayList [ number_sweeps ] ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { sgp [ i ] = ( List ) rgp . get ( ( short ) i ) ; } Variable [ ] time = new Variable [ number_sweeps ] ; ArrayInt . D1 [ ] timeArr = new ArrayInt . D1 [ number_sweeps ] ; Index [ ] timeIndex = new Index [ number_sweeps ] ; String t_n = "time" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { t_n = "time_sweep_" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( t_n . trim ( ) ) ) { time [ i ] = aVarList ; break ; } } //                if (time[i].getShape().length == 0) {
 //                    continue;
 //                }
 timeArr [ i ] = ( ArrayInt . D1 ) Array . factory ( DataType . INT , time [ i ] . getShape ( ) ) ; timeIndex [ i ] = timeArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }
 for ( int jj = 0 ; jj < num_rays ; jj ++ ) { timeArr [ i ] . setInt ( timeIndex [ i ] . set ( jj ) , rtemp [ jj ] . getTime ( ) ) ; } } // NCdump.printArray(timeArr[0], "time", System.out, null);
 Variable [ ] azimuthR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] azimArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] azimIndex = new Index [ number_sweeps ] ; String azimName = "azimuthR" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { azimName = "azimuthR_sweep_" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( azimName . trim ( ) ) ) { azimuthR [ i ] = aVarList ; break ; } } azimArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , azimuthR [ i ] . getShape ( ) ) ; azimIndex [ i ] = azimArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }
 for ( int jj = 0 ; jj < num_rays ; jj ++ ) { azimArr [ i ] . setFloat ( azimIndex [ i ] . set ( jj ) , rtemp [ jj ] . getAz ( ) ) ; } } //NCdump.printArray(azimArr[0], "azimuthR", System.out, null);
 Variable [ ] elevationR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] elevArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] elevIndex = new Index [ number_sweeps ] ; String elevName = "elevationR" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { elevName = "elevationR_sweep_" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( elevName . trim ( ) ) ) { elevationR [ i ] = aVarList ; break ; } } elevArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , elevationR [ i ] . getShape ( ) ) ; elevIndex [ i ] = elevArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }
 for ( int jj = 0 ; jj < num_rays ; jj ++ ) { elevArr [ i ] . setFloat ( elevIndex [ i ] . set ( jj ) , rtemp [ jj ] . getElev ( ) ) ; } } // NCdump.printArray(elevArr[0], "elevationR", System.out, null);
 Variable numGates = null ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( "numGates" ) ) { numGates = aVarList ; break ; } } } ArrayInt . D1 gatesArr = ( ArrayInt . D1 ) Array . factory ( DataType . INT , numGates . getShape ( ) ) ; Index gatesIndex = gatesArr . getIndex ( ) ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }
 ngates = rtemp [ 0 ] . getBins ( ) ; gatesArr . setInt ( gatesIndex . set ( i ) , ngates ) ; } for ( int i = 0 ; i < number_sweeps ; i ++ ) { distanceR [ i ] . setCachedData ( distArr [ i ] , false ) ; time [ i ] . setCachedData ( timeArr [ i ] , false ) ; azimuthR [ i ] . setCachedData ( azimArr [ i ] , false ) ; elevationR [ i ] . setCachedData ( elevArr [ i ] , false ) ; } numGates . setCachedData ( gatesArr , false ) ; // startSweep.setCachedData(sweepArr, false);
 //          -------------------------------------------------
 // int b=(int)ray[0][0].getBins();
 // -- Test of readData() and readToByteChannel() -----------------
 /*
Range r1=new Range(356, 359);
Range r2=new Range(0, 15);
java.util.List arlist=new ArrayList();
arlist.add(r1);
arlist.add(r2);
Array testArr=readData(v[0], new Section(arlist));
NCdump.printArray(testArr, "Total_Power_sweep_1", System.out, null);
WritableByteChannel channel=new FileOutputStream(new File("C:\\netcdf\\tt.dat")).getChannel();
long ikk=readToByteChannel(v[0], new Section(arlist), channel);
System.out.println("IKK="+ikk);
channel.close();
      */ //---------------------------------------------------
 } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } }


Input:
Read data from a top level Variable and return a memory resident Array . [CODESPLIT] public Array readData1 ( ucar . nc2 . Variable v2 , Section section ) throws IOException , InvalidRangeException { //doData(raf, ncfile, varList);
 int [ ] sh = section . getShape ( ) ; Array temp = Array . factory ( v2 . getDataType ( ) , sh ) ; long pos0 = 0 ; // Suppose that the data has LayoutRegular
 LayoutRegular index = new LayoutRegular ( pos0 , v2 . getElementSize ( ) , v2 . getShape ( ) , section ) ; if ( v2 . getShortName ( ) . startsWith ( "time" ) | v2 . getShortName ( ) . startsWith ( "numGates" ) ) { temp = readIntData ( index , v2 ) ; } else { temp = readFloatData ( index , v2 ) ; } return temp ; }


Input: Read data from a top level Variable of INTEGER data type and return a memory resident Array . [CODESPLIT] public Array readIntData ( LayoutRegular index , Variable v2 ) throws IOException { int [ ] var = ( int [ ] ) ( v2 . read ( ) . get1DJavaArray ( v2 . getDataType ( ) ) ) ; int [ ] data = new int [ ( int ) index . getTotalNelems ( ) ] ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; System . arraycopy ( var , ( int ) chunk . getSrcPos ( ) / 4 , data , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return Array . factory ( v2 . getDataType ( ) , new int [ ] { ( int ) index . getTotalNelems ( ) } , data ) ; }


Input:
Read data from a top level Variable and send data to a WritableByteChannel . [CODESPLIT] public long readToByteChannel11 ( ucar . nc2 . Variable v2 , Section section , WritableByteChannel channel ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { Array data = readData ( v2 , section ) ; float [ ] ftdata = new float [ ( int ) data . getSize ( ) ] ; byte [ ] bytedata = new byte [ ( int ) data . getSize ( ) * 4 ] ; IndexIterator iter = data . getIndexIterator ( ) ; int i = 0 ; ByteBuffer buffer = ByteBuffer . allocateDirect ( bytedata . length ) ; while ( iter . hasNext ( ) ) { ftdata [ i ] = iter . getFloatNext ( ) ; bytedata [ i ] = new Float ( ftdata [ i ] ) . byteValue ( ) ; buffer . put ( bytedata [ i ] ) ; i ++ ; } buffer = ByteBuffer . wrap ( bytedata ) ; // write the bytes to the channel
 int count = channel . write ( buffer ) ; System . out . println ( "COUNT=" + count ) ; // check if all bytes where written
 if ( buffer . hasRemaining ( ) ) { // if not all bytes were written, move the unwritten bytes to the beginning and
 // set position just after the last unwritten byte
 buffer . compact ( ) ; } else { buffer . clear ( ) ; } return ( long ) count ; }


Input: Calculate radial elevation of each ray [CODESPLIT] static float calcElev ( short angle ) { final double maxval = 65536.0 ; double ang = ( double ) angle ; if ( angle < 0 ) ang = ( ~ angle ) + 1 ; double temp = ( ang / maxval ) * 360.0 ; BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }


Input: Calculate distance between sequential bins in a ray [CODESPLIT] static float calcStep ( float range_first , float range_last , short num_bins ) { float step = ( range_last - range_first ) / ( num_bins - 1 ) ; BigDecimal bd = new BigDecimal ( step ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }


Input:
Calculate azimuth of a ray [CODESPLIT] static float calcAz ( short az0 , short az1 ) { // output in deg
 float azim0 = calcAngle ( az0 ) ; float azim1 = calcAngle ( az1 ) ; float d = 0.0f ; d = Math . abs ( azim0 - azim1 ) ; if ( ( az0 < 0 ) & ( az1 > 0 ) ) { d = Math . abs ( 360.0f - azim0 ) + Math . abs ( azim1 ) ; } double temp = azim0 + d * 0.5 ; if ( temp > 360.0 ) { temp -= 360.0 ; } BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }


Input:
Calculate data values from raw ingest data [CODESPLIT] static float calcData ( Map < String , Number > recHdr , short dty , byte data ) { short [ ] coef = { 1 , 2 , 3 , 4 } ; // MultiPRF modes
 short multiprf = recHdr . get ( "multiprf" ) . shortValue ( ) ; float vNyq = recHdr . get ( "vNyq" ) . floatValue ( ) ; double temp = - 999.99 ; switch ( dty ) { default : // dty=1,2 -total_power, reflectivity (dBZ)
 if ( data != 0 ) { temp = ( ( ( int ) data & 0xFF ) - 64 ) * 0.5 ; } break ; case 3 : // dty=3 - mean velocity (m/sec)
 if ( data != 0 ) { temp = ( ( ( ( int ) data & 0xFF ) - 128 ) / 127.0 ) * vNyq * coef [ multiprf ] ; } break ; case 4 : // dty=4 - spectrum width (m/sec)
 if ( data != 0 ) { double v = ( ( ( ( int ) data & 0xFF ) - 128 ) / 127.0 ) * vNyq * coef [ multiprf ] ; temp = ( ( ( int ) data & 0xFF ) / 256.0 ) * v ; } break ; case 5 : // dty=5 - differential reflectivity (dB)
 if ( data != 0 ) { temp = ( ( ( ( int ) data & 0xFF ) - 128 ) / 16.0 ) ; } break ; } BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }


Input:
Calculate time as hh : mm : ss [CODESPLIT] static String calcTime ( int t , int t0 ) { StringBuilder tim = new StringBuilder ( ) ; int [ ] tt = new int [ 3 ] ; int mmh = ( t + t0 ) / 60 ; tt [ 2 ] = ( t + t0 ) % 60 ; // Define SEC
 tt [ 0 ] = mmh / 60 ; // Define HOUR
 tt [ 1 ] = mmh % 60 ; // Define MIN
 for ( int i = 0 ; i < 3 ; i ++ ) { String s = Integer . toString ( tt [ i ] ) ; int len = s . length ( ) ; if ( len < 2 ) { s = "0" + tt [ i ] ; } if ( i != 2 ) s += ":" ; tim . append ( s ) ; } return tim . toString ( ) ; }


Input:
Calculate of Nyquist velocity [CODESPLIT] static float calcNyquist ( int prf , int wave ) { double tmp = ( prf * wave * 0.01 ) * 0.25 ; tmp = tmp * 0.01 ; //Make it m/sec
 BigDecimal bd = new BigDecimal ( tmp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }


Input: Use the builder to make the Vertical Transform function [CODESPLIT] public VerticalTransform makeVerticalTransform ( NetcdfDataset ds , Dimension timeDim ) { return builder . makeMathTransform ( ds , timeDim , this ) ; }


Input: partitions can be removed ( ! ) [CODESPLIT] public void removePartition ( MCollection partition ) { for ( MFile mfile : partIndexFiles ) { if ( mfile . getName ( ) . equalsIgnoreCase ( partition . getCollectionName ( ) ) ) { List < MFile > part = new ArrayList <> ( partIndexFiles ) ; part . remove ( mfile ) ; partIndexFiles = part ; return ; } } }


Input:
Write equivilent uncompressed version of the file . [CODESPLIT] private RandomAccessFile uncompress ( RandomAccessFile raf2 , String ufilename , boolean debug ) throws IOException { raf2 . seek ( 0 ) ; byte [ ] header = new byte [ Cinrad2Record . FILE_HEADER_SIZE ] ; int bytesRead = raf2 . read ( header ) ; if ( bytesRead != header . length ) { throw new IOException ( "Error reading CINRAD header -- got " + bytesRead + " rather than" + header . length ) ; } RandomAccessFile dout2 = new RandomAccessFile ( ufilename , "rw" ) ; boolean eof = false ; int numCompBytes ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; try { dout2 . write ( header ) ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; while ( ! eof ) { try { numCompBytes = raf2 . readInt ( ) ; if ( numCompBytes == - 1 ) { if ( debug ) log . debug ( "  done: numCompBytes=-1 " ) ; break ; } } catch ( EOFException ee ) { if ( debug ) log . debug ( "  got EOFException " ) ; break ; // assume this is ok } if ( debug ) { log . debug ( "reading compressed bytes " + numCompBytes + " input starts at " + raf2 . getFilePointer ( ) + "; output starts at " + dout2 . getFilePointer ( ) ) ; } /*
        * For some stupid reason, the last block seems to
        * have the number of bytes negated.  So, we just
        * assume that any negative number (other than -1)
        * is the last block and go on our merry little way.
        */ if ( numCompBytes < 0 ) { if ( debug ) log . debug ( "last block?" + numCompBytes ) ; numCompBytes = - numCompBytes ; eof = true ; } byte [ ] buf = new byte [ numCompBytes ] ; raf2 . readFully ( buf ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( buf , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; /*
        while ((nread = cbzip2.read(ubuff)) != -1) {
          dout2.write(ubuff, 0, nread);
          total += nread;
        }
        */ try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) dout2 . write ( obuff , 0 , total ) ; } catch ( BZip2ReadException ioe ) { log . debug ( "Cinrad2IOSP.uncompress " , ioe ) ; } float nrecords = ( float ) ( total / 2432.0 ) ; if ( debug ) log . debug ( "  unpacked " + total + " num bytes " + nrecords + " records; ouput ends at " + dout2 . getFilePointer ( ) ) ; } dout2 . flush ( ) ; } catch ( EOFException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { dout2 . close ( ) ; throw e ; } return dout2 ; }


Input: Set the debug flags [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugOpen = debugFlag . isSet ( "Grid/open" ) ; debugMissing = debugFlag . isSet ( "Grid/missing" ) ; debugMissingDetails = debugFlag . isSet ( "Grid/missingDetails" ) ; debugProj = debugFlag . isSet ( "Grid/projection" ) ; debugVert = debugFlag . isSet ( "Grid/vertical" ) ; debugTiming = debugFlag . isSet ( "Grid/timing" ) ; }


Input: Set how indexes are used for both open and sync [CODESPLIT] static public void setExtendIndex ( boolean b ) { indexFileModeOnOpen = b ? IndexExtendMode . extendwrite : IndexExtendMode . readonly ; indexFileModeOnSync = b ? IndexExtendMode . extendwrite : IndexExtendMode . readonly ; }


Input: Open the service provider for reading . [CODESPLIT] @ Override public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; }


Input: Read the data for the variable [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { long start = System . currentTimeMillis ( ) ; Array dataArray = Array . factory ( DataType . FLOAT , section . getShape ( ) ) ; GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; // Canonical ordering is ens, time, level, lat, lon int rangeIdx = 0 ; Range ensRange = pv . hasEnsemble ( ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range timeRange = ( section . getRank ( ) > 2 ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range levRange = pv . hasVert ( ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range yRange = section . getRange ( rangeIdx ++ ) ; Range xRange = section . getRange ( rangeIdx ) ; IndexIterator ii = dataArray . getIndexIterator ( ) ; for ( int ensIdx : ensRange ) { for ( int timeIdx : timeRange ) { for ( int levelIdx : levRange ) { readXY ( v2 , ensIdx , timeIdx , levelIdx , yRange , xRange , ii ) ; } } } if ( debugTiming ) { long took = System . currentTimeMillis ( ) - start ; System . out . println ( "  read data took=" + took + " msec " ) ; } return dataArray ; }


Input: read one YX array [CODESPLIT] private void readXY ( Variable v2 , int ensIdx , int timeIdx , int levIdx , Range yRange , Range xRange , IndexIterator ii ) throws IOException , InvalidRangeException { GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; GridHorizCoordSys hsys = pv . getHorizCoordSys ( ) ; int nx = hsys . getNx ( ) ; GridRecord record = pv . findRecord ( ensIdx , timeIdx , levIdx ) ; if ( record == null ) { Attribute att = v2 . findAttribute ( "missing_value" ) ; float missing_value = ( att == null ) ? - 9999.0f : att . getNumericValue ( ) . floatValue ( ) ; int xyCount = yRange . length ( ) * xRange . length ( ) ; for ( int j = 0 ; j < xyCount ; j ++ ) { ii . setFloatNext ( missing_value ) ; } return ; } // otherwise read it float [ ] data = _readData ( record ) ; if ( data == null ) { _readData ( record ) ; // debug return ; } // LOOK can improve with System.copy ?? for ( int y : yRange ) { for ( int x : xRange ) { int index = y * nx + x ; ii . setFloatNext ( data [ index ] ) ; } } }


Input: Is this XY level missing? [CODESPLIT] public boolean isMissingXY ( Variable v2 , int timeIdx , int ensIdx , int levIdx ) throws InvalidRangeException { GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; if ( ( timeIdx < 0 ) || ( timeIdx >= pv . getNTimes ( ) ) ) { throw new InvalidRangeException ( "timeIdx=" + timeIdx ) ; } if ( ( levIdx < 0 ) || ( levIdx >= pv . getVertNlevels ( ) ) ) { throw new InvalidRangeException ( "levIdx=" + levIdx ) ; } if ( ( ensIdx < 0 ) || ( ensIdx >= pv . getNEnsembles ( ) ) ) { throw new InvalidRangeException ( "ensIdx=" + ensIdx ) ; } return ( null == pv . findRecord ( ensIdx , timeIdx , levIdx ) ) ; }


Input: The goal of parse () is to extract info from the underlying HttpRequest and cache it in this object . <p > In particular the incoming URL needs to be decomposed into multiple pieces . Certain assumptions are made : 1 . every incoming url is of the form ( a ) http ( s ) : // host : port / d4ts / or ( b ) http ( s ) : // host : port / d4ts / <datasetpath > ?query Case a indicates that the front page is to be returned . Case b indicates a request for a dataset ( or dsr ) and its value is determined by its extensions . The query may be absent . We want to extract the following pieces . 1 . ( In URI parlance ) The scheme plus the authority : http : // host : port 3 . The return type : depending on the last extension ( e . g . . txt ) . 4 . The requested value : depending on the next to last extension ( e . g . . dap ) . 5 . The suffix path specifying the actual dataset : datasetpath with return and request type extensions removed . 6 . The url path = servletpath + datasetpath . 7 . The query part . [CODESPLIT] protected void parse ( ) throws IOException { this . url = request . getRequestURL ( ) . toString ( ) ; // does not include query // The mock servlet code does not construct a query string, // so if we are doing testing, construct from parametermap. if ( DapController . TESTING ) { this . querystring = makeQueryString ( this . request ) ; } else { this . querystring = request . getQueryString ( ) ; // raw (undecoded) } XURI xuri ; try { xuri = new XURI ( this . url ) . parseQuery ( this . querystring ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } // Now, construct various items StringBuilder buf = new StringBuilder ( ) ; buf . append ( request . getScheme ( ) ) ; buf . append ( "://" ) ; buf . append ( request . getServerName ( ) ) ; int port = request . getServerPort ( ) ; if ( port > 0 ) { buf . append ( ":" ) ; buf . append ( port ) ; } this . server = buf . toString ( ) ; // There appears to be some inconsistency in how the url path is divided up // depending on if this is a spring controller vs a raw servlet. // Try to canonicalize so that context path always ends with id // and servletpath does not start with it. String id = controller . getServletID ( ) ; String sp = DapUtil . canonicalpath ( request . getServletPath ( ) ) ; String cp = DapUtil . canonicalpath ( request . getContextPath ( ) ) ; if ( ! cp . endsWith ( id ) ) // probably spring ; contextpath does not ends with id cp = cp + "/" + id ; buf . append ( cp ) ; this . controllerpath = buf . toString ( ) ; sp = HTTPUtil . relpath ( sp ) ; if ( sp . startsWith ( id ) ) // probably spring also sp = sp . substring ( id . length ( ) ) ; this . datasetpath = HTTPUtil . relpath ( sp ) ; this . datasetpath = DapUtil . nullify ( this . datasetpath ) ; this . mode = null ; if ( this . datasetpath == null ) { // Presume mode is a capabilities request this . mode = RequestMode . CAPABILITIES ; this . format = ResponseFormat . HTML ; } else { // Decompose path by '.' String [ ] pieces = this . datasetpath . split ( "[.]" ) ; // Search backward looking for the mode (dmr or dap) // meanwhile capturing the format extension int modepos = 0 ; for ( int i = pieces . length - 1 ; i >= 1 ; i -- ) { //ignore first piece String ext = pieces [ i ] ; // We assume that the set of response formats does not interset the set of request modes RequestMode mode = RequestMode . modeFor ( ext ) ; ResponseFormat format = ResponseFormat . formatFor ( ext ) ; if ( mode != null ) { // Stop here this . mode = mode ; modepos = i ; break ; } else if ( format != null ) { if ( this . format != null ) throw new DapException ( "Multiple response formats specified: " + ext ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; this . format = format ; } } // Set the datasetpath to the entire path before the mode defining extension. if ( modepos > 0 ) this . datasetpath = DapUtil . join ( pieces , "." , 0 , modepos ) ; } if ( this . mode == null ) this . mode = RequestMode . DSR ; if ( this . format == null ) this . format = ResponseFormat . NONE ; // Parse the query string into a Map if ( querystring != null && querystring . length ( ) > 0 ) this . queries = xuri . getQueryFields ( ) ; // For testing purposes, get the desired endianness to use with replies String p = queryLookup ( Dap4Util . DAP4ENDIANTAG ) ; if ( p != null ) { Integer oz = DapUtil . stringToInteger ( p ) ; if ( oz == null ) this . order = ByteOrder . LITTLE_ENDIAN ; else this . order = ( oz != 0 ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; } // Ditto for no checksum p = queryLookup ( Dap4Util . DAP4CSUMTAG ) ; if ( p != null ) { this . checksummode = ChecksumMode . modeFor ( p ) ; } if ( this . checksummode == null ) this . checksummode = DEFAULTCSUM ; if ( DEBUG ) { DapLog . debug ( "DapRequest: controllerpath =" + this . controllerpath ) ; DapLog . debug ( "DapRequest: extension=" + ( this . mode == null ? "null" : this . mode . extension ( ) ) ) ; DapLog . debug ( "DapRequest: datasetpath=" + this . datasetpath ) ; } }


Input:
Get the x y bounding box in projection coordinates . [CODESPLIT] public ProjectionRect getBoundingBox ( ) { if ( mapArea == null ) { CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( ( horizXaxis == null ) || ! horizXaxis . isNumeric ( ) || ( horizYaxis == null ) || ! horizYaxis . isNumeric ( ) ) return null ; // impossible // x,y may be 2D if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { // could try to optimize this - just get corners or something CoordinateAxis2D xaxis2 = ( CoordinateAxis2D ) horizXaxis ; CoordinateAxis2D yaxis2 = ( CoordinateAxis2D ) horizYaxis ; mapArea = null ; // getBBfromCorners(xaxis2, yaxis2);  LOOK LOOK // mapArea = new ProjectionRect(horizXaxis.getMinValue(), horizYaxis.getMinValue(), //         horizXaxis.getMaxValue(), horizYaxis.getMaxValue()); } else { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) horizXaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) horizYaxis ; /* add one percent on each side if its a projection. WHY?
        double dx = 0.0, dy = 0.0;
        if (!isLatLon()) {
          dx = .01 * (xaxis1.getCoordEdge((int) xaxis1.getSize()) - xaxis1.getCoordEdge(0));
          dy = .01 * (yaxis1.getCoordEdge((int) yaxis1.getSize()) - yaxis1.getCoordEdge(0));
        }

        mapArea = new ProjectionRect(xaxis1.getCoordEdge(0) - dx, yaxis1.getCoordEdge(0) - dy,
            xaxis1.getCoordEdge((int) xaxis1.getSize()) + dx,
            yaxis1.getCoordEdge((int) yaxis1.getSize()) + dy); */ mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) , yaxis1 . getCoordEdge ( 0 ) , xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) , yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) ) ; } } return mapArea ; }


Input: Get the Lat / Lon coordinates of the midpoint of a grid cell using the x y indices [CODESPLIT] public LatLonPoint getLatLon ( int xindex , int yindex ) { double x , y ; CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( horizXaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizXaxis ; x = horiz1D . getCoordValue ( xindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizXaxis ; x = horiz2D . getCoordValue ( yindex , xindex ) ; } if ( horizYaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizYaxis ; y = horiz1D . getCoordValue ( yindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizYaxis ; y = horiz2D . getCoordValue ( yindex , xindex ) ; } return isLatLon ( ) ? new LatLonPointImpl ( y , x ) : getLatLon ( x , y ) ; }


Input:
Get horizontal bounding box in lat lon coordinates . [CODESPLIT] public LatLonRect getLatLonBoundingBox ( ) { if ( llbb == null ) { if ( ( getXHorizAxis ( ) instanceof CoordinateAxis2D ) && ( getYHorizAxis ( ) instanceof CoordinateAxis2D ) ) { return null ; } CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( isLatLon ( ) ) { double startLat = horizYaxis . getMinValue ( ) ; double startLon = horizXaxis . getMinValue ( ) ; double deltaLat = horizYaxis . getMaxValue ( ) - startLat ; double deltaLon = horizXaxis . getMaxValue ( ) - startLon ; LatLonPoint llpt = new LatLonPointImpl ( startLat , startLon ) ; llbb = new LatLonRect ( llpt , deltaLat , deltaLon ) ; } else { ProjectionImpl dataProjection = getProjection ( ) ; ProjectionRect bb = getBoundingBox ( ) ; if ( bb != null ) llbb = dataProjection . projToLatLonBB ( bb ) ; } } return llbb ; /*  // look at all 4 corners of the bounding box
        LatLonPointImpl llpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerLeftPoint(), new LatLonPointImpl());
        LatLonPointImpl lrpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerRightPoint(), new LatLonPointImpl());
        LatLonPointImpl urpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperRightPoint(), new LatLonPointImpl());
        LatLonPointImpl ulpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperLeftPoint(), new LatLonPointImpl());

        // Check if grid contains poles.
        boolean includesNorthPole = false;
        int[] resultNP;
        resultNP = findXYindexFromLatLon(90.0, 0, null);
        if (resultNP[0] != -1 && resultNP[1] != -1)
          includesNorthPole = true;
        boolean includesSouthPole = false;
        int[] resultSP;
        resultSP = findXYindexFromLatLon(-90.0, 0, null);
        if (resultSP[0] != -1 && resultSP[1] != -1)
          includesSouthPole = true;

        if (includesNorthPole && !includesSouthPole) {
          llbb = new LatLonRect(llpt, new LatLonPointImpl(90.0, 0.0)); // ??? lon=???
          llbb.extend(lrpt);
          llbb.extend(urpt);
          llbb.extend(ulpt);
          // OR
          //llbb.extend( new LatLonRect( llpt, lrpt ));
          //llbb.extend( new LatLonRect( lrpt, urpt ) );
          //llbb.extend( new LatLonRect( urpt, ulpt ) );
          //llbb.extend( new LatLonRect( ulpt, llpt ) );
        } else if (includesSouthPole && !includesNorthPole) {
          llbb = new LatLonRect(llpt, new LatLonPointImpl(-90.0, -180.0)); // ??? lon=???
          llbb.extend(lrpt);
          llbb.extend(urpt);
          llbb.extend(ulpt);
        } else {
          double latMin = Math.min(llpt.getLatitude(), lrpt.getLatitude());
          double latMax = Math.max(ulpt.getLatitude(), urpt.getLatitude());

          // longitude is a bit tricky as usual
          double lonMin = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true);
          double lonMax = getMinOrMaxLon(lrpt.getLongitude(), urpt.getLongitude(), false);

          llpt.set(latMin, lonMin);
          urpt.set(latMax, lonMax);

          llbb = new LatLonRect(llpt, urpt);
        }
      }
    }  */ }


Input: This reports how well different compression schemes would work on the specific data . Should be renamed [CODESPLIT] public static void calcScaleOffset ( GribData . Bean bean1 , Formatter f ) { float [ ] data ; try { data = bean1 . readData ( ) ; } catch ( IOException e ) { f . format ( "IOException %s" , e . getMessage ( ) ) ; return ; } int npoints = data . length ; // we always use unsigned packed // "If the packed values are intended to be interpreted as signed/unsigned integers" // http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html int nbits = bean1 . getNBits ( ) ; int width = ( 2 << nbits - 1 ) - 2 ; // unsigned int missing_value = ( 2 << nbits - 1 ) - 1 ; // all ones - reserved for missing value // int width2 = (2 << (nbits-1)) - 1;  // signed f . format ( " nbits = %d%n" , nbits ) ; f . format ( " npoints = %d%n" , npoints ) ; f . format ( " width = %d (0x%s) %n" , width , Long . toHexString ( width ) ) ; f . format ( " scale = %g %n" , bean1 . getScale ( ) ) ; f . format ( " resolution = %g %n" , bean1 . getScale ( ) / 2 ) ; f . format ( " range = %f %n%n" , bean1 . getMaximum ( ) - bean1 . getMinimum ( ) ) ; float dataMin = Float . MAX_VALUE ; float dataMax = - Float . MAX_VALUE ; for ( float fd : data ) { if ( Float . isNaN ( fd ) ) continue ; dataMin = Math . min ( dataMin , fd ) ; dataMax = Math . max ( dataMax , fd ) ; } f . format ( "           actual    computed%n" ) ; f . format ( " dataMin = %8f %8f%n" , dataMin , bean1 . getMinimum ( ) ) ; f . format ( " dataMax = %8f %8f%n" , dataMax , bean1 . getMaximum ( ) ) ; f . format ( " actual range = %f%n" , ( dataMax - dataMin ) ) ; // scale_factor =(dataMax - dataMin) / (2^n - 1) // add_offset = dataMin + 2^(n-1) * scale_factor double scale_factor = ( dataMax - dataMin ) / width ; // float add_offset = dataMin + width2 * scale_factor / 2; // signed double add_offset = dataMin ; // unsigned f . format ( " scale_factor = %g%n" , scale_factor ) ; f . format ( " add_offset = %g%n" , add_offset ) ; // unpacked_data_value = packed_data_value * scale_factor + add_offset // packed_data_value = nint((unpacked_data_value - add_offset) / scale_factor) ByteBuffer bb = ByteBuffer . allocate ( 4 * npoints ) ; IntBuffer intBuffer = bb . asIntBuffer ( ) ; double diffMax = - Double . MAX_VALUE ; double diffTotal = 0 ; double diffTotal2 = 0 ; for ( float fd : data ) { if ( Float . isNaN ( fd ) ) { intBuffer . put ( missing_value ) ; continue ; } // otherwise pack it int packed_data = ( int ) Math . round ( ( fd - add_offset ) / scale_factor ) ; // nint((unpacked_data_value - add_offset) / scale_factor) double unpacked_data = packed_data * scale_factor + add_offset ; double diff = Math . abs ( fd - unpacked_data ) ; if ( diff > scale_factor / 2 ) f . format ( "***   org=%g, packed_data=%d unpacked=%g diff = %g%n" , fd , packed_data , unpacked_data , diff ) ; diffMax = Math . max ( diffMax , diff ) ; diffTotal += diff ; diffTotal2 += diff * diff ; intBuffer . put ( packed_data ) ; } f . format ( "%n max_diff = %g%n" , diffMax ) ; f . format ( " avg_diff = %g%n" , diffTotal / data . length ) ; // Math.sqrt( sumsq/n - avg * avg) double mean = diffTotal / npoints ; double var = ( diffTotal2 / npoints - mean * mean ) ; f . format ( " std_diff = %g%n" , Math . sqrt ( var ) ) ; f . format ( "%nCompression%n" ) ; f . format ( " number of values = %d%n" , npoints ) ; f . format ( " uncompressed as floats = %d%n" , npoints * 4 ) ; int packedBitsLen = npoints * nbits / 8 ; f . format ( " uncompressed packed bits = %d%n" , packedBitsLen ) ; f . format ( " grib data length = %d%n" , bean1 . getDataLength ( ) ) ; f . format ( " grib msg length = %d%n" , bean1 . getMsgLength ( ) ) ; byte [ ] bdata = convertToBytes ( data ) ; byte [ ] scaledData = bb . array ( ) ; //////////////////////////////////////////// f . format ( "%ndeflate (float)%n" ) ; Deflater deflater = new Deflater ( ) ; deflater . setInput ( bdata ) ; deflater . finish ( ) ; int compressedSize = deflater . deflate ( new byte [ 10 * npoints ] ) ; deflater . end ( ) ; f . format ( " compressedSize = %d%n" , compressedSize ) ; f . format ( " ratio floats / size = %f%n" , ( float ) ( npoints * 4 ) / compressedSize ) ; f . format ( " ratio packed bits / size = %f%n" , ( float ) packedBitsLen / compressedSize ) ; f . format ( " ratio size / grib = %f%n" , ( float ) compressedSize / bean1 . getMsgLength ( ) ) ; ///////////////////////////////////////////////////////// f . format ( "%ndeflate (scaled ints)%n" ) ; deflater = new Deflater ( ) ; deflater . setInput ( scaledData ) ; deflater . finish ( ) ; compressedSize = deflater . deflate ( new byte [ 10 * npoints ] ) ; deflater . end ( ) ; f . format ( " compressedSize = %d%n" , compressedSize ) ; f . format ( " ratio floats / size = %f%n" , ( float ) ( npoints * 4 ) / compressedSize ) ; f . format ( " ratio packed bits / size = %f%n" , ( float ) packedBitsLen / compressedSize ) ; f . format ( " ratio size / grib = %f%n" , ( float ) compressedSize / bean1 . getMsgLength ( ) ) ; }


Input: Call this when you have set all the sequence lengths . [CODESPLIT] public void finish ( ) { sequenceOffset = new int [ nelems ] ; total = 0 ; for ( int i = 0 ; i < nelems ; i ++ ) { sequenceOffset [ i ] = total ; total += sequenceLen [ i ] ; } sdata = new StructureData [ nelems ] ; for ( int i = 0 ; i < nelems ; i ++ ) sdata [ i ] = new StructureDataA ( this , sequenceOffset [ i ] ) ; // make the member arrays for ( StructureMembers . Member m : members . getMembers ( ) ) { int [ ] mShape = m . getShape ( ) ; int [ ] shape = new int [ mShape . length + 1 ] ; shape [ 0 ] = total ; System . arraycopy ( mShape , 0 , shape , 1 , mShape . length ) ; // LOOK not doing nested structures Array data = Array . factory ( m . getDataType ( ) , shape ) ; m . setDataArray ( data ) ; } }


Input: Flatten the Structures into a 1D array of Structures of length getTotalNumberOfStructures () . [CODESPLIT] public ArrayStructure flatten ( ) { ArrayStructureW aw = new ArrayStructureW ( getStructureMembers ( ) , new int [ ] { total } ) ; for ( int i = 0 ; i < total ; i ++ ) { StructureData sdata = new StructureDataA ( this , i ) ; aw . setStructureData ( sdata , i ) ; } return aw ; }


Input: Blank fill sbuff with blanks until position tabStop . [CODESPLIT] public static void tab ( StringBuffer sbuff , int tabStop , boolean alwaysOne ) { int len = sbuff . length ( ) ; if ( tabStop > len ) { sbuff . setLength ( tabStop ) ; for ( int i = len ; i < tabStop ; i ++ ) { sbuff . setCharAt ( i , ' ' ) ; } } else if ( alwaysOne ) { sbuff . setLength ( len + 1 ) ; sbuff . setCharAt ( len , ' ' ) ; } }


Input: Create a new string by padding the existing one with blanks to specified width . Do nothing if length is already greater or equal to width . [CODESPLIT] public static String pad ( String s , int width , boolean rightJustify ) { if ( s . length ( ) >= width ) { return s ; } StringBuilder sbuff = new StringBuilder ( width ) ; int need = width - s . length ( ) ; sbuff . setLength ( need ) ; for ( int i = 0 ; i < need ; i ++ ) { sbuff . setCharAt ( i , ' ' ) ; } if ( rightJustify ) { sbuff . append ( s ) ; } else { sbuff . insert ( 0 , s ) ; } return sbuff . toString ( ) ; }


Input: Format an integer value . [CODESPLIT] public static String i ( int v , int width ) { return pad ( Integer . toString ( v ) , width , true ) ; }


Input: Format a long value . [CODESPLIT] public static String l ( long v , int width ) { return pad ( Long . toString ( v ) , width , true ) ; }


Input: Double value formatting with minimum number of significant figures in a specified width . This will try to do a reasonable job of getting a representation that has min_sigfig significant figures in the specified width . Right now all it does is call d ( double d int min_sigfig ) and left pad out to width chars . [CODESPLIT] public static String d ( double d , int min_sigfig , int width ) { String s = Format . d ( d , min_sigfig ) ; return pad ( s , width , true ) ; }


Input: Nicely formatted representation of bytes eg turn 5 . 636E7 into [CODESPLIT] public static String formatByteSize ( double size ) { String unit = null ; if ( size > 1.0e15 ) { unit = "Pbytes" ; size *= 1.0e-15 ; } else if ( size > 1.0e12 ) { unit = "Tbytes" ; size *= 1.0e-12 ; } else if ( size > 1.0e9 ) { unit = "Gbytes" ; size *= 1.0e-9 ; } else if ( size > 1.0e6 ) { unit = "Mbytes" ; size *= 1.0e-6 ; } else if ( size > 1.0e3 ) { unit = "Kbytes" ; size *= 1.0e-3 ; } else { unit = "bytes" ; } return Format . d ( size , 4 ) + " " + unit ; }


Input: Show the value of a double to the significant figures [CODESPLIT] private static void show ( double d , int sigfig ) { System . out . println ( "Format.d(" + d + "," + sigfig + ") == " + Format . d ( d , sigfig ) ) ; }


Input: Show the value of a double with specified number of decimal places [CODESPLIT] private static void show2 ( double d , int dec_places ) { System . out . println ( "Format.dfrac(" + d + "," + dec_places + ") == " + Format . dfrac ( d , dec_places ) ) ; }


Input: Write the information as an XML document [CODESPLIT] public String writeXML ( Document doc ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( doc ) ; }


Input: Write the information as an XML document [CODESPLIT] public void writeXML ( Document doc , OutputStream os ) throws IOException { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; fmt . output ( doc , os ) ; }


Input:
Create the Dataset Description XML document from this GridDataset [CODESPLIT] public Document makeDatasetDescription ( ) { Element rootElem = new Element ( "gridDataset" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( "location" , gds . getLocation ( ) ) ; if ( null != path ) rootElem . setAttribute ( "path" , path ) ; /* dimensions
    List dims = getDimensions(gds);
    for (int j = 0; j < dims.size(); j++) {
      Dimension dim = (Dimension) dims.get(j);
      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeDimension(dim, null));
    } */ // coordinate axes
 for ( CoordinateAxis axis : getCoordAxes ( gds ) ) { rootElem . addContent ( writeAxis ( axis ) ) ; } /* grids
    List grids = gds.getGrids();
    Collections.sort(grids, new GridComparator());
    for (int i = 0; i < grids.size(); i++) {
      GeoGrid grid = (GeoGrid) grids.get(i);
      rootElem.addContent(writeGrid(grid));
    } */ /* coordinate systems
    List gridSets = gds.getGridsets();
    for (int i = 0; i < gridSets.size(); i++) {
      GridDataset.Gridset gridset = (GridDataset.Gridset) gridSets.get(i);
      rootElem.addContent(writeCoordSys(gridset.getGeoCoordSystem()));
    } */ // gridSets
 List < GridDataset . Gridset > gridSets = gds . getGridsets ( ) ; Collections . sort ( gridSets , new GridSetComparator ( ) ) ; for ( GridDataset . Gridset gridset : gridSets ) { rootElem . addContent ( writeGridSet ( gridset ) ) ; } // coordinate transforms
 for ( CoordinateTransform ct : getCoordTransforms ( gds ) ) { rootElem . addContent ( writeCoordTransform ( ct ) ) ; } /* global attributes
    Iterator atts = gds.getGlobalAttributes().iterator();
    while (atts.hasNext()) {
      ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();
      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, "attribute", null));
    } */ // add lat/lon bounding box
 LatLonRect bb = gds . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range
 CalendarDate start = gds . getCalendarDateStart ( ) ; CalendarDate end = gds . getCalendarDateEnd ( ) ; if ( ( start != null ) && ( end != null ) ) { Element dateRange = new Element ( "TimeSpan" ) ; dateRange . addContent ( new Element ( "begin" ) . addContent ( start . toString ( ) ) ) ; dateRange . addContent ( new Element ( "end" ) . addContent ( end . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list
 addAcceptList ( rootElem ) ; //    elem.addContent(new Element("accept").addContent("xml"));
 //    elem.addContent(new Element("accept").addContent("csv"));
 //    elem.addContent(new Element("accept").addContent("netcdf"));
 return doc ; }


Input:
Create the Grid Form XML document from this GridDataset . Used to create the Grid HTML form cause I dont know XSLT [CODESPLIT] public Document makeGridForm ( ) { Element rootElem = new Element ( "gridForm" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( "location" , gds . getLocation ( ) ) ; if ( null != path ) rootElem . setAttribute ( "path" , path ) ; // its all about grids
 List < GridDatatype > grids = gds . getGrids ( ) ; Collections . sort ( grids , new GridComparator ( ) ) ; // sort by time axis, vert axis, grid name
 CoordinateAxis currentTime = null ; CoordinateAxis currentVert = null ; Element timeElem = null ; Element vertElem = null ; boolean newTime ; for ( int i = 0 ; i < grids . size ( ) ; i ++ ) { GeoGrid grid = ( GeoGrid ) grids . get ( i ) ; GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; CoordinateAxis time = gcs . getTimeAxis ( ) ; CoordinateAxis vert = gcs . getVerticalAxis ( ) ; /* System.out.println(" grid "+grid.getName()
              +" time="+(time == null ? " null" : time.hashCode())
              +" vert="+(vert == null ? " null" : vert.hashCode())); */ //Assuming all variables in dataset has ensemble dim if one has
 if ( i == 0 ) { CoordinateAxis1D ens = gcs . getEnsembleAxis ( ) ; if ( ens != null ) { Element ensAxisEl = writeAxis2 ( ens , "ensemble" ) ; rootElem . addContent ( ensAxisEl ) ; } } if ( ( i == 0 ) || ! compareAxis ( time , currentTime ) ) { timeElem = new Element ( "timeSet" ) ; rootElem . addContent ( timeElem ) ; Element timeAxisElement = writeAxis2 ( time , "time" ) ; if ( timeAxisElement != null ) timeElem . addContent ( timeAxisElement ) ; currentTime = time ; newTime = true ; } else { newTime = false ; } if ( newTime || ! compareAxis ( vert , currentVert ) ) { vertElem = new Element ( "vertSet" ) ; timeElem . addContent ( vertElem ) ; Element vertAxisElement = writeAxis2 ( vert , "vert" ) ; if ( vertAxisElement != null ) vertElem . addContent ( vertAxisElement ) ; currentVert = vert ; } vertElem . addContent ( writeGrid ( grid ) ) ; } // add lat/lon bounding box
 LatLonRect bb = gds . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add projected bounding box
 //--> Asuming all gridSets have the same coordinates and bbox
 ProjectionRect rect = grids . get ( 0 ) . getCoordinateSystem ( ) . getBoundingBox ( ) ; Element projBBOX = new Element ( "projectionBox" ) ; Element minx = new Element ( "minx" ) ; minx . addContent ( Double . valueOf ( rect . getMinX ( ) ) . toString ( ) ) ; projBBOX . addContent ( minx ) ; Element maxx = new Element ( "maxx" ) ; maxx . addContent ( Double . valueOf ( rect . getMaxX ( ) ) . toString ( ) ) ; projBBOX . addContent ( maxx ) ; Element miny = new Element ( "miny" ) ; miny . addContent ( Double . valueOf ( rect . getMinY ( ) ) . toString ( ) ) ; projBBOX . addContent ( miny ) ; Element maxy = new Element ( "maxy" ) ; maxy . addContent ( Double . valueOf ( rect . getMaxY ( ) ) . toString ( ) ) ; projBBOX . addContent ( maxy ) ; rootElem . addContent ( projBBOX ) ; // add date range
 CalendarDate start = gds . getCalendarDateStart ( ) ; CalendarDate end = gds . getCalendarDateEnd ( ) ; if ( ( start != null ) && ( end != null ) ) { Element dateRange = new Element ( "TimeSpan" ) ; dateRange . addContent ( new Element ( "begin" ) . addContent ( start . toString ( ) ) ) ; dateRange . addContent ( new Element ( "end" ) . addContent ( end . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list
 addAcceptList ( rootElem ) ; //    Element elem = new Element("AcceptList");
 //    elem.addContent(new Element("accept").addContent("xml"));
 //    elem.addContent(new Element("accept").addContent("csv"));
 //    elem.addContent(new Element("accept").addContent("netcdf"));
 //    rootElem.addContent(elem);
 return doc ; }


Input:
/ * private List getDimensions ( ucar . nc2 . dt . GridDataset gds ) { HashSet dimHash = new HashSet () ; List grids = gds . getGrids () ; for ( int i = 0 ; i < grids . size () ; i ++ ) { GeoGrid grid = ( GeoGrid ) grids . get ( i ) ; List dims = grid . getDimensions () ; for ( int j = 0 ; j < dims . size () ; j ++ ) { Dimension dim = ( Dimension ) dims . get ( j ) ; dimHash . add ( dim ) ; } } List list = Arrays . asList ( dimHash . toArray () ) ; Collections . sort ( list ) ; return list ; } [CODESPLIT] private Element writeAxis ( CoordinateAxis axis ) { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element varElem = new Element ( "axis" ) ; varElem . setAttribute ( "name" , axis . getFullName ( ) ) ; varElem . setAttribute ( "shape" , getShapeString ( axis . getShape ( ) ) ) ; // axis.getDimensionsString());
 DataType dt = axis . getDataType ( ) ; varElem . setAttribute ( "type" , dt . toString ( ) ) ; AxisType axisType = axis . getAxisType ( ) ; if ( null != axisType ) varElem . setAttribute ( "axisType" , axisType . toString ( ) ) ; // attributes
 for ( Attribute att : axis . getAttributes ( ) ) { varElem . addContent ( ncmlWriter . makeAttributeElement ( att ) ) ; } if ( axis . getRank ( ) == 1 ) { try { Element values = ncmlWriter . makeValuesElement ( axis , true ) ; varElem . addContent ( values ) ; } catch ( IOException e ) { String message = String . format ( "Couldn't read values for %s. Omitting <values> element." , axis . getFullName ( ) ) ; logger . warn ( message , e ) ; } } return varElem ; }


Input: display name plus the dimensions [CODESPLIT] private String getShapeString ( int [ ] shape ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < shape . length ; i ++ ) { if ( i != 0 ) buf . append ( " " ) ; buf . append ( shape [ i ] ) ; } return buf . toString ( ) ; }


Input: / * private Element writeCoordSys ( GridCoordSystem cs ) { Element csElem = new Element ( coordSys ) ; csElem . setAttribute ( name cs . getName () ) ; List axes = cs . getCoordinateAxes () ; for ( int i = 0 ; i < axes . size () ; i ++ ) { CoordinateAxis axis = ( CoordinateAxis ) axes . get ( i ) ; Element axisElem = new Element ( axisRef ) ; axisElem . setAttribute ( name axis . getName () ) ; csElem . addContent ( axisElem ) ; } List cts = cs . getCoordinateTransforms () ; for ( int j = 0 ; j < cts . size () ; j ++ ) { CoordinateTransform ct = ( CoordinateTransform ) cts . get ( j ) ; Element elem = new Element ( coordTransRef ) ; elem . setAttribute ( name ct . getName () ) ; csElem . addContent ( elem ) ; } return csElem ; } [CODESPLIT] private Element writeCoordTransform ( CoordinateTransform ct ) { Element ctElem = new Element ( "coordTransform" ) ; ctElem . setAttribute ( "name" , ct . getName ( ) ) ; ctElem . setAttribute ( "transformType" , ct . getTransformType ( ) . toString ( ) ) ; for ( Parameter param : ct . getParameters ( ) ) { Element pElem = new Element ( "parameter" ) ; pElem . setAttribute ( "name" , param . getName ( ) ) ; pElem . setAttribute ( "value" , param . getStringValue ( ) ) ; ctElem . addContent ( pElem ) ; } return ctElem ; }


Input: debug [CODESPLIT] public static void main ( String args [ ] ) throws IOException { String url = "cdmremote:http://localhost:8080/thredds/cdmremote/grib/NCDC/CFSR/NCDC-CFSR/PGB-LatLon0p5" ; GridDataset ncd = ucar . nc2 . dt . grid . GridDataset . open ( url ) ; GridDatasetInfo info = new GridDatasetInfo ( ncd , null ) ; FileOutputStream fos2 = new FileOutputStream ( "C:/tmp2/gridInfo.xml" ) ; info . writeXML ( info . makeGridForm ( ) , fos2 ) ; fos2 . close ( ) ; String infoString = info . writeXML ( info . makeGridForm ( ) ) ; System . out . println ( infoString ) ; }


Input: Perform sanity checks on a slice and repair where possible . [CODESPLIT] public Slice finish ( ) throws DapException { // Attempt to repair undefined values if ( this . first == UNDEFINED ) this . first = 0 ; // default if ( this . stride == UNDEFINED ) this . stride = 1 ; // default if ( this . stop == UNDEFINED && this . maxsize != UNDEFINED ) this . stop = this . maxsize ; if ( this . stop == UNDEFINED && this . maxsize == UNDEFINED ) this . stop = this . first + 1 ; if ( this . maxsize == UNDEFINED && this . stop != UNDEFINED ) this . maxsize = this . stop ; // else (this.stop != UNDEFINED && this.maxsize != UNDEFINED) assert ( this . first != UNDEFINED ) ; assert ( this . stride != UNDEFINED ) ; assert ( this . stop != UNDEFINED ) ; // sanity checks if ( this . first > this . maxsize ) throw new DapException ( "Slice: first index > max size" ) ; if ( this . stop > ( this . maxsize + 1 ) ) throw new DapException ( "Slice: stop > max size" ) ; if ( this . first < 0 ) throw new DapException ( "Slice: first index < 0" ) ; if ( this . stop < 0 ) throw new DapException ( "Slice: stop index < 0" ) ; if ( this . stride <= 0 ) throw new DapException ( "Slice: stride index <= 0" ) ; if ( this . first > this . stop ) throw new DapException ( "Slice: first index > last" ) ; return this ; // fluent interface }


Input: Compute the number of elements in the slice . Note that this is different from getStop () because stride is taken into account . [CODESPLIT] public long getCount ( ) { assert this . first != UNDEFINED && this . stride != UNDEFINED && this . stop != UNDEFINED ; long count = ( this . stop ) - this . first ; count = ( count + this . stride - 1 ) ; count /= this . stride ; return count ; }


Input: Convert this slice to a string suitable for use in a constraint [CODESPLIT] public String toConstraintString ( ) throws DapException { assert this . first != UNDEFINED && this . stride != UNDEFINED && this . stop != UNDEFINED ; if ( ( this . stop - this . first ) == 0 ) { return String . format ( "[0]" ) ; } else if ( this . stride == 1 ) { if ( ( this . stop - this . first ) == 1 ) return String . format ( "[%d]" , this . first ) ; else return String . format ( "[%d:%d]" , this . first , this . stop - 1 ) ; } else return String . format ( "[%d:%d:%d]" , this . first , this . stride , this . stop - 1 ) ; }


Input: Take two slices and compose src wrt target Assume neither argument is null . This code should match ucar . ma2 . Section in thredds and dceconstraint . c in the netcdf - c library . [CODESPLIT] static public Slice compose ( Slice target , Slice src ) throws DapException { long sr_stride = target . getStride ( ) * src . getStride ( ) ; long sr_first = MAP ( target , src . getFirst ( ) ) ; long lastx = MAP ( target , src . getLast ( ) ) ; long sr_last = ( target . getLast ( ) < lastx ? target . getLast ( ) : lastx ) ; //min(last(),lastx) return new Slice ( sr_first , sr_last + 1 , sr_stride , sr_last + 1 ) . finish ( ) ; }


Input: Map ith element of one range wrt a target range [CODESPLIT] static long MAP ( Slice target , long i ) throws DapException { if ( i < 0 ) throw new DapException ( "Slice.compose: i must be >= 0" ) ; if ( i > target . getStop ( ) ) throw new DapException ( "i must be < stop" ) ; return target . getFirst ( ) + i * target . getStride ( ) ; }


Input: Provide a simple dump of binary data [CODESPLIT] static public void dumpbytes ( ByteBuffer buf0 , boolean skipdmr ) { int savepos = buf0 . position ( ) ; int limit0 = buf0 . limit ( ) ; int skipcount = 0 ; if ( limit0 > MAXLIMIT ) limit0 = MAXLIMIT ; if ( limit0 >= buf0 . limit ( ) ) limit0 = buf0 . limit ( ) ; if ( skipdmr ) { ByteOrder saveorder = buf0 . order ( ) ; buf0 . order ( ByteOrder . BIG_ENDIAN ) ; // must read in network order skipcount = buf0 . getInt ( ) ; //dmr count buf0 . order ( saveorder ) ; skipcount &= 0xFFFFFF ; // mask off the flags to get true count skipcount += 4 ; // skip the count also } byte [ ] bytes = new byte [ ( limit0 + 8 ) - skipcount ] ; Arrays . fill ( bytes , ( byte ) 0 ) ; buf0 . position ( savepos + skipcount ) ; buf0 . get ( bytes , 0 , limit0 - skipcount ) ; buf0 . position ( savepos ) ; System . err . println ( "order=" + buf0 . order ( ) ) ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) . order ( buf0 . order ( ) ) ; dumpbytes ( buf ) ; }