Example usage for java.lang Float NaN

List of usage examples for java.lang Float NaN

Introduction

In this page you can find the example usage for java.lang Float NaN.

Prototype

float NaN

To view the source code for java.lang Float NaN.

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type float .

Usage

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowPerformances.java

@Override
public void run(CommandLine line) throws Exception {
    Path outputCsvFile = Paths.get(line.getOptionValue("csv-file"));
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    List<String> workflowsIds = new ArrayList<String>();
    if (line.hasOption("workflow"))
        workflowsIds.add(line.getOptionValue("workflow"));
    else if (line.hasOption("workflows"))
        workflowsIds = Arrays.asList(line.getOptionValue("workflows").split(","));
    else if (line.hasOption("basecase")) {
        DateTime basecaseDate = DateTime.parse(line.getOptionValue("basecase"));
        workflowsIds = onlinedb.listWorkflows(basecaseDate).stream().map(OnlineWorkflowDetails::getWorkflowId)
                .collect(Collectors.toList());
    } else if (line.hasOption("basecases-interval")) {
        Interval basecasesInterval = Interval.parse(line.getOptionValue("basecases-interval"));
        workflowsIds = onlinedb.listWorkflows(basecasesInterval).stream()
                .map(OnlineWorkflowDetails::getWorkflowId).collect(Collectors.toList());
    } else {//  w w w  .j a va2s .com
        System.out.println("You must specify workflow(s) or basecase(s)");
        return;
    }
    Collections.sort(workflowsIds, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    System.out.println("Printing performances of workflows " + workflowsIds);
    CsvWriter cvsWriter = null;
    try (FileWriter content = new FileWriter(outputCsvFile.toFile())) {
        cvsWriter = new CsvWriter(content, ',');
        String[] headers = new String[25];
        int i = 0;
        headers[i++] = "workflow_id";
        headers[i++] = "basecase";
        headers[i++] = "secure_contingencies";
        headers[i++] = "unsecure_contingencies";
        headers[i++] = "unsecure_contingencies_ratio";
        headers[i++] = "secure_contingencies_ratio";
        headers[i++] = "unsecure_secure_contingencies_ratio";
        headers[i++] = "wca_missed_alarms";
        headers[i++] = "wca_missed_alarms_lst";
        headers[i++] = "wca_false_alarms";
        headers[i++] = "wca_false_alarms_lst";
        headers[i++] = "wca_accuracy";
        headers[i++] = "wca_efficiency";
        headers[i++] = "mcla_missed_alarms";
        headers[i++] = "mcla_missed_alarms_lst";
        headers[i++] = "mcla_false_alarms";
        headers[i++] = "mcla_false_alarms_lst";
        headers[i++] = "mcla_accuracy";
        headers[i++] = "mcla_efficiency";
        headers[i++] = "wf_missed_alarms";
        headers[i++] = "wf_missed_alarms_lst";
        headers[i++] = "wf_false_alarms";
        headers[i++] = "wf_false_alarms_lst";
        headers[i++] = "wf_accuracy";
        headers[i++] = "wf_efficiency";
        cvsWriter.writeRecord(headers);
        // cycle over the workflows
        for (String workflowId : workflowsIds) {
            try {
                System.out.println("\nPrinting performances of workflow " + workflowId);
                OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId);
                if (parameters != null && parameters.validation()) {
                    OnlineWorkflowResults wfResults = onlinedb.getResults(workflowId);
                    Map<String, Boolean> contigencySecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyWCASecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyMCLASecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyWfSecure = new HashMap<String, Boolean>();
                    Map<String, Map<SecurityIndexType, Boolean>> contigencyPhenomenaSecure = new HashMap<String, Map<SecurityIndexType, Boolean>>();
                    Map<String, Map<SecurityIndexType, Boolean>> contigencyPhenomenaMCLASecure = new HashMap<String, Map<SecurityIndexType, Boolean>>();
                    int unsecureContingencies = 0;
                    int secureContingencies = 0;
                    int wcaFalseAlarms = 0;
                    List<String> wcaFalseAlarmsList = new ArrayList<String>();
                    int wcaMissedAlarms = 0;
                    List<String> wcaMissedAlarmsList = new ArrayList<String>();
                    int mclaFalseAlarms = 0;
                    List<String> mclaFalseAlarmsList = new ArrayList<String>();
                    int mclaMissedAlarms = 0;
                    List<String> mclaMissedAlarmsList = new ArrayList<String>();
                    int wfFalseAlarms = 0;
                    List<String> wfFalseAlarmsList = new ArrayList<String>();
                    int wfMissedAlarms = 0;
                    List<String> wfMissedAlarmsList = new ArrayList<String>();
                    if (wfResults != null) {
                        if (!wfResults.getUnsafeContingencies().isEmpty()) {
                            Network basecase = onlinedb.getState(workflowId, 0);
                            String basecaseId = basecase.getId();
                            OnlineWorkflowWcaResults wfWcaResults = onlinedb.getWcaResults(workflowId);
                            OnlineWorkflowRulesResults wfRulesResults = onlinedb.getRulesResults(workflowId);
                            SecurityIndexType[] securityIndexTypes = parameters.getSecurityIndexes() == null
                                    ? SecurityIndexType.values()
                                    : parameters.getSecurityIndexes().toArray(
                                            new SecurityIndexType[parameters.getSecurityIndexes().size()]);
                            for (String contingencyId : wfResults.getUnsafeContingencies()) {
                                // initialize values
                                contigencySecure.put(contingencyId, true);
                                if (wfWcaResults.getClusterIndex(contingencyId) == 1)
                                    contigencyWCASecure.put(contingencyId, true);
                                else
                                    contigencyWCASecure.put(contingencyId, false);
                                contigencyMCLASecure.put(contingencyId, true);
                                Map<SecurityIndexType, Boolean> phenomenaSecure = new HashMap<SecurityIndexType, Boolean>();
                                Map<SecurityIndexType, Boolean> phenomenaMCLASecure = new HashMap<SecurityIndexType, Boolean>();
                                for (SecurityIndexType securityIndexType : securityIndexTypes) {
                                    phenomenaSecure.put(securityIndexType, true);
                                    phenomenaMCLASecure.put(securityIndexType, true);
                                }
                                contigencyPhenomenaSecure.put(contingencyId, phenomenaSecure);
                                contigencyPhenomenaMCLASecure.put(contingencyId, phenomenaMCLASecure);
                                // compute values
                                for (Integer stateId : wfResults.getUnstableStates(contingencyId)) {
                                    Map<String, Boolean> securityIndexes = wfResults
                                            .getIndexesData(contingencyId, stateId);
                                    Map<String, Boolean> securityRules = wfRulesResults
                                            .getStateResults(contingencyId, stateId);
                                    for (SecurityIndexType securityIndexType : securityIndexTypes) {
                                        if (securityIndexes.containsKey(securityIndexType.getLabel())
                                                && !securityIndexes.get(securityIndexType.getLabel())) {
                                            contigencySecure.put(contingencyId, false);
                                            contigencyPhenomenaSecure.get(contingencyId).put(securityIndexType,
                                                    false);
                                        }
                                        if (securityRules.containsKey(securityIndexType.getLabel())
                                                && !securityRules.get(securityIndexType.getLabel())) {
                                            contigencyMCLASecure.put(contingencyId, false);
                                            contigencyPhenomenaMCLASecure.get(contingencyId)
                                                    .put(securityIndexType, false);
                                        }
                                    }
                                }
                                if (contigencyWCASecure.get(contingencyId)
                                        || (!contigencyWCASecure.get(contingencyId)
                                                && contigencyMCLASecure.get(contingencyId)))
                                    contigencyWfSecure.put(contingencyId, true);
                                else
                                    contigencyWfSecure.put(contingencyId, false);
                                // compute data for performances
                                if (contigencySecure.get(contingencyId))
                                    secureContingencies++;
                                else
                                    unsecureContingencies++;
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyWCASecure.get(contingencyId)) {
                                    wcaMissedAlarms++;
                                    wcaMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyWCASecure.get(contingencyId)) {
                                    wcaFalseAlarms++;
                                    wcaFalseAlarmsList.add(contingencyId);
                                }
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyMCLASecure.get(contingencyId)) {
                                    mclaMissedAlarms++;
                                    mclaMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyMCLASecure.get(contingencyId)) {
                                    mclaFalseAlarms++;
                                    mclaFalseAlarmsList.add(contingencyId);
                                }
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyWfSecure.get(contingencyId)) {
                                    wfMissedAlarms++;
                                    wfMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyWfSecure.get(contingencyId)) {
                                    wfFalseAlarms++;
                                    wfFalseAlarmsList.add(contingencyId);
                                }
                            }
                            // compute performances
                            float wcaAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) wcaMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float wcaEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) wcaFalseAlarms / (float) secureContingencies)) * 100f;
                            float mclaAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) mclaMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float mclaEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) mclaFalseAlarms / (float) secureContingencies)) * 100f;
                            float wfAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) wfMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float wfEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) wfFalseAlarms / (float) secureContingencies)) * 100f;
                            float unsecureRatio = (float) unsecureContingencies
                                    / (float) (secureContingencies + unsecureContingencies);
                            float secureRatio = (float) secureContingencies
                                    / (float) (secureContingencies + unsecureContingencies);
                            float secureUnsecureRatio = (secureContingencies == 0) ? Float.NaN
                                    : (float) unsecureContingencies / (float) secureContingencies;
                            //                     System.out.println("contigencySecure: " + contigencySecure);
                            //                     System.out.println("contigencyWCASecure: " + contigencyWCASecure);
                            //                     System.out.println("contigencyMCLASecure: " + contigencyMCLASecure);
                            //                     System.out.println("contigencyWfSecure: " + contigencyWfSecure);
                            //                     System.out.println("contigencyPhenomenaSecure: " + contigencyPhenomenaSecure);
                            //                     System.out.println("contigencyPhenomenaMCLASecure: " + contigencyPhenomenaMCLASecure);
                            // print performances
                            String[] values = new String[25];
                            i = 0;
                            values[i++] = workflowId;
                            values[i++] = basecaseId;
                            values[i++] = Integer.toString(secureContingencies);
                            values[i++] = Integer.toString(unsecureContingencies);
                            values[i++] = Float.toString(unsecureRatio);
                            values[i++] = Float.toString(secureRatio);
                            values[i++] = Float.toString(secureUnsecureRatio);
                            values[i++] = Integer.toString(wcaMissedAlarms);
                            values[i++] = wcaMissedAlarmsList.toString();
                            values[i++] = Integer.toString(wcaFalseAlarms);
                            values[i++] = wcaFalseAlarmsList.toString();
                            values[i++] = Float.toString(wcaAccuracy);
                            values[i++] = Float.toString(wcaEfficiency);
                            values[i++] = Integer.toString(mclaMissedAlarms);
                            values[i++] = mclaMissedAlarmsList.toString();
                            values[i++] = Integer.toString(mclaFalseAlarms);
                            values[i++] = mclaFalseAlarmsList.toString();
                            values[i++] = Float.toString(mclaAccuracy);
                            values[i++] = Float.toString(mclaEfficiency);
                            values[i++] = Integer.toString(wfMissedAlarms);
                            values[i++] = wfMissedAlarmsList.toString();
                            values[i++] = Integer.toString(wfFalseAlarms);
                            values[i++] = wfFalseAlarmsList.toString();
                            values[i++] = Float.toString(wfAccuracy);
                            values[i++] = Float.toString(wfEfficiency);
                            cvsWriter.writeRecord(values);
                            cvsWriter.flush();
                        } else
                            System.out.println("No data for benchmark: skipping wf " + workflowId);
                    } else {
                        System.out.println("No results: skipping wf " + workflowId);
                    }
                } else
                    System.out.println("No data for validation: skipping wf " + workflowId);
            } catch (IOException e1) {
            }
        }
    } finally {
        if (cvsWriter != null)
            cvsWriter.close();
        onlinedb.close();
    }
}

From source file:org.bitpipeline.lib.owm.WeatherData.java

public float getTemp() {
    if (hasMain() && this.main.hasTemp())
        return this.main.getTemp();
    return Float.NaN;
}

From source file:org.bitpipeline.lib.owm.WeatherData.java

public float getHumidity() {
    if (hasMain() && this.main.hasHumidity())
        return this.main.getHumidity();
    return Float.NaN;
}

From source file:org.bitpipeline.lib.owm.WeatherData.java

public float getPressure() {
    if (hasMain() && this.main.hasPressure())
        return this.main.getPressure();
    return Float.NaN;
}

From source file:org.esa.snap.core.gpf.common.BandMathsOpTest.java

@Test
public void testDivisionByZero() throws Exception {
    Map<String, Object> parameters = new HashMap<>();
    BandMathsOp.BandDescriptor[] bandDescriptors = new BandMathsOp.BandDescriptor[1];
    bandDescriptors[0] = createBandDescription("aBandName", "band1/0.0", ProductData.TYPESTRING_FLOAT32,
            "bigUnits");
    parameters.put("targetBands", bandDescriptors);
    Product sourceProduct = createTestProduct(4, 4);
    Product targetProduct = GPF.createProduct("BandMaths", parameters, sourceProduct);

    assertNotNull(targetProduct);/*from   w ww  .  j  a  v  a 2 s . c  om*/
    Band band = targetProduct.getBand("aBandName");
    assertNotNull(band);
    assertEquals("aDescription", band.getDescription());
    assertEquals("bigUnits", band.getUnit());
    assertEquals(ProductData.TYPE_FLOAT32, band.getDataType());

    float[] floatValues = new float[16];
    band.readPixels(0, 0, 4, 4, floatValues, ProgressMonitor.NULL);
    float[] expectedValues = new float[16];
    Arrays.fill(expectedValues, Float.NaN);
    assertTrue(Arrays.equals(expectedValues, floatValues));
}

From source file:byps.test.TestSerializePrimitiveTypes.java

@Test
public void testSerializeFloat() throws BException {
    log.info("testSerializeFloat(");
    internalTestSerializeFloat(Float.NaN);
    internalTestSerializeFloat(Float.NEGATIVE_INFINITY);
    internalTestSerializeFloat(Float.POSITIVE_INFINITY);
    internalTestSerializeFloat(0.0f);/*  w ww . jav a  2  s  .  c om*/
    internalTestSerializeFloat(1.0f);
    internalTestSerializeFloat(-1.0f);
    internalTestSerializeFloat(1.0e7f);
    internalTestSerializeFloat(1.0e-7f);
    internalTestSerializeFloat(2.0E5f);
    log.info(")testSerializeFloat");
}

From source file:com.taobao.weex.dom.WXAttr.java

public float getElevation(int viewPortW) {
    Object obj = get(Constants.Name.ELEVATION);
    float ret = Float.NaN;
    if (obj != null) {
        String number = obj.toString();
        if (!TextUtils.isEmpty(number)) {
            ret = WXViewUtils.getRealSubPxByWidth(WXUtils.getFloat(number), viewPortW);
        } else {//  w w w  . j  a  v  a 2 s  . c  o  m
            ret = 0;
        }
    }
    return ret;
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

private static float xmlStringToFloat(String value) {
    if ("NaN".equals(value)) {
        return Float.NaN;
    } else if ("INF".equals(value)) {
        return Float.POSITIVE_INFINITY;
    } else if ("-INF".equals(value)) {
        return Float.NEGATIVE_INFINITY;
    } else {//from   ww w  .j ava 2s.co  m
        return Float.parseFloat(value);
    }
}

From source file:nu.nethome.tools.protocol_analyzer.RawMessageDistributionWindow.java

/**
 * Mark pulses within the specified pulse length interval in the signal graph and indicate the interval
 * in the pulse distribution graph.// www  .j av  a 2 s.  com
 * @param minLength low end of the pulse length interval
 * @param maxLength high end of the pulse length interval
 * @param isMark true if we shall indicate mark pulses, false for space pulses
 */
protected void markPulseInterval(double minLength, double maxLength, boolean isMark) {
    Iterator<Integer> samples = m_Message.m_Samples.iterator();
    Iterator<Integer> pulses = m_Message.m_PulseList.iterator();

    double x = 0.0;
    double lastX = 0;
    int lastFlank = 0;
    boolean level = false;
    int sampleNumber = 0;
    int nextPulse = pulses.hasNext() ? pulses.next() : 0;

    // Remove the selection data series from the view to speed up handling
    m_SignalSeriesCollection.removeSeries(m_SelectedPulseSeries);
    m_DistributionData.removeSeries(m_SelectedIntervalSeries);

    // Clear them
    m_SelectedPulseSeries.clear();
    m_SelectedIntervalSeries.clear();

    // Mark the selected region in the pulse distribution graph
    m_SelectedIntervalSeries.add(((int) (minLength / 10)) * 10, 0);
    m_SelectedIntervalSeries.add(((int) (maxLength / 10)) * 10 + 10, 0);
    m_SelectedIntervalSeries.add(Float.NaN, Float.NaN);

    // Add the selection series to the graph again
    m_DistributionData.addSeries(m_SelectedIntervalSeries);

    // Check what kind of data we have, if it is only pulses, generate from them
    // and if we have samples, then generate from the samples
    if (m_Message.m_Samples.size() == 0) {
        // Generate from pulse series
        for (double pulse : m_Message.m_PulseLengths) {
            x += pulse;
            // Check if the pulse matches our interval
            if ((pulse >= (minLength - 0.5)) && (pulse <= (maxLength + 0.5)) && (isMark == level)) {
                // If it does, plot the pulse
                //m_SelectedPulseSeries.add(Double.NaN, Double.NaN);
                m_SelectedPulseSeries.add(lastX, SELECTION_MARK);
                m_SelectedPulseSeries.add(x, SELECTION_MARK);
                m_SelectedPulseSeries.add(Double.NaN, Double.NaN);
            }
            lastX = x;
            level = !level;
        }
    } else {
        // Loop through the samples and pulses and plot the pulses matching the length interval
        while (samples.hasNext()) {
            samples.next();

            // Check if we have reached a pulse flank
            if (sampleNumber == nextPulse) {
                nextPulse = pulses.hasNext() ? pulses.next() : 0;

                // calculate the pulse length
                double length = (sampleNumber - lastFlank) * 1000000.0 / m_Message.m_SampleFrequency;

                // Check if the pulse matches our interval
                if ((length >= (minLength - 0.5)) && (length <= (maxLength + 0.5)) && (isMark == level)) {
                    // If it does, plot the pulse
                    //m_SelectedPulseSeries.add(Double.NaN, Double.NaN);
                    m_SelectedPulseSeries.add(lastX, SELECTION_MARK);
                    m_SelectedPulseSeries.add(x, SELECTION_MARK);
                    m_SelectedPulseSeries.add(Double.NaN, Double.NaN);
                }
                lastFlank = sampleNumber;
                lastX = x;
                level = !level;
            }
            x += 1000.0 / m_Message.m_SampleFrequency;
            sampleNumber++;
        }
    }

    // Add the selection series to the graph again
    m_SignalSeriesCollection.addSeries(m_SelectedPulseSeries);
}

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException {
    File wktDir = new File(filePath);
    wktDir.mkdirs();//from  w  ww. j  a v a  2  s. c om

    int[] wktMap = null;

    //track values for the SLD
    ArrayList<Integer> maxValues = new ArrayList<Integer>();
    ArrayList<String> labels = new ArrayList<String>();

    HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>();
    Properties p = new Properties();
    p.load(new FileReader(filePath + ".txt"));

    boolean mergeProperties = false;

    Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>();
    Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>();
    Map<String, Integer> translateValues = new HashMap<String, Integer>();
    ArrayList<Integer> keys = new ArrayList<Integer>();
    for (String key : p.stringPropertyNames()) {
        try {
            int k = Integer.parseInt(key);
            keys.add(k);

            //grouping of property file keys by value
            String value = p.getProperty(key);
            Set<Integer> klist = groupedKeys.get(value);
            if (klist == null)
                klist = new HashSet<Integer>();
            else
                mergeProperties = true;
            klist.add(k);
            groupedKeys.put(value, klist);

            if (!translateValues.containsKey(value))
                translateValues.put(value, translateValues.size() + 1);
            translateKeys.put(k, translateValues.get(value));

        } catch (NumberFormatException e) {
            logger.info("Excluding shape key '" + key + "'");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    java.util.Collections.sort(keys);

    Grid g = new Grid(filePath);
    boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE;

    if (mergeProperties) {
        g.replaceValues(translateKeys);

        if (!new File(filePath + ".txt.old").exists())
            FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old"));

        StringBuilder sb = new StringBuilder();
        for (String value : translateValues.keySet()) {
            sb.append(translateValues.get(value)).append("=").append(value).append('\n');
        }
        FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString());

        return buildFromGrid(filePath);
    }

    if (generateWkt) {
        for (String name : groupedKeys.keySet()) {
            try {
                Set<Integer> klist = groupedKeys.get(name);

                String key = klist.iterator().next().toString();
                int k = Integer.parseInt(key);

                GridClass gc = new GridClass();
                gc.setName(name);
                gc.setId(k);

                if (klist.size() == 1)
                    klist = null;

                logger.info("getting wkt for " + filePath + " > " + key);

                Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed(
                        filePath + "," + key + "," + key, klist, wktMap);

                //write class wkt
                File zipFile = new File(filePath + File.separator + key + ".wkt.zip");
                ZipOutputStream zos = null;
                try {
                    zos = new ZipOutputStream(new FileOutputStream(zipFile));
                    zos.putNextEntry(new ZipEntry(key + ".wkt"));
                    zos.write(((String) wktIndexed.get("wkt")).getBytes());
                    zos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (zos != null) {
                        try {
                            zos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                BufferedOutputStream bos = null;
                try {
                    bos = new BufferedOutputStream(
                            new FileOutputStream(filePath + File.separator + key + ".wkt"));
                    bos.write(((String) wktIndexed.get("wkt")).getBytes());
                    bos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (bos != null) {
                        try {
                            bos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                logger.info("wkt written to file");
                gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0);

                //store map
                wktMap = (int[]) wktIndexed.get("map");

                //write wkt index
                FileWriter fw = null;
                try {
                    fw = new FileWriter(filePath + File.separator + key + ".wkt.index");
                    fw.append((String) wktIndexed.get("index"));
                    fw.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (fw != null) {
                        try {
                            fw.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km)
                int minPolygonNumber = 0;
                int maxPolygonNumber = 0;

                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw");

                    String[] index = ((String) wktIndexed.get("index")).split("\n");

                    for (int i = 0; i < index.length; i++) {
                        if (index[i].length() > 1) {
                            String[] cells = index[i].split(",");
                            int polygonNumber = Integer.parseInt(cells[0]);
                            raf.writeInt(polygonNumber); //polygon number
                            int polygonStart = Integer.parseInt(cells[1]);
                            raf.writeInt(polygonStart); //character offset

                            if (i == 0) {
                                minPolygonNumber = polygonNumber;
                            } else if (i == index.length - 1) {
                                maxPolygonNumber = polygonNumber;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }

                //for SLD
                maxValues.add(gc.getMaxShapeIdx());
                labels.add(name.replace("\"", "'"));
                gc.setMinShapeIdx(minPolygonNumber);
                gc.setMaxShapeIdx(maxPolygonNumber);

                logger.info("getting multipolygon for " + filePath + " > " + key);
                MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key);
                gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ","));

                classes.put(k, gc);

                try {
                    //write class kml
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".kml.zip"));

                        zos.putNextEntry(new ZipEntry(key + ".kml"));
                        Encoder encoder = new Encoder(new KMLConfiguration());
                        encoder.setIndenting(true);
                        encoder.encode(mp, KML.Geometry, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("kml written to file");

                    final SimpleFeatureType TYPE = DataUtilities.createType("class",
                            "the_geom:MultiPolygon,id:Integer,name:String");
                    FeatureJSON fjson = new FeatureJSON();
                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
                    SimpleFeature sf = featureBuilder.buildFeature(null);

                    //write class geojson
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".geojson.zip"));
                        zos.putNextEntry(new ZipEntry(key + ".geojson"));
                        featureBuilder.add(mp);
                        featureBuilder.add(k);
                        featureBuilder.add(name);

                        fjson.writeFeature(sf, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("geojson written to file");

                    //write class shape file
                    File newFile = new File(filePath + File.separator + key + ".shp");
                    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
                    Map<String, Serializable> params = new HashMap<String, Serializable>();
                    params.put("url", newFile.toURI().toURL());
                    params.put("create spatial index", Boolean.FALSE);
                    ShapefileDataStore newDataStore = null;
                    try {
                        newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
                        newDataStore.createSchema(TYPE);
                        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
                        Transaction transaction = new DefaultTransaction("create");
                        String typeName = newDataStore.getTypeNames()[0];
                        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
                        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
                        featureStore.setTransaction(transaction);
                        List<SimpleFeature> features = new ArrayList<SimpleFeature>();

                        DefaultFeatureCollection collection = new DefaultFeatureCollection();
                        collection.addAll(features);
                        featureStore.setTransaction(transaction);

                        features.add(sf);
                        featureStore.addFeatures(collection);
                        transaction.commit();
                        transaction.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (newDataStore != null) {
                            try {
                                newDataStore.dispose();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }

                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".shp.zip"));
                        //add .dbf .shp .shx .prj
                        String[] exts = { ".dbf", ".shp", ".shx", ".prj" };
                        for (String ext : exts) {
                            zos.putNextEntry(new ZipEntry(key + ext));
                            FileInputStream fis = null;
                            try {
                                fis = new FileInputStream(filePath + File.separator + key + ext);
                                byte[] buffer = new byte[1024];
                                int size;
                                while ((size = fis.read(buffer)) > 0) {
                                    zos.write(buffer, 0, size);
                                }
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            } finally {
                                if (fis != null) {
                                    try {
                                        fis.close();
                                    } catch (Exception e) {
                                        logger.error(e.getMessage(), e);
                                    }
                                }
                            }
                            //remove unzipped files
                            new File(filePath + File.separator + key + ext).delete();
                        }
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("shape file written to zip");
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        //write polygon mapping
        g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres,
                g.yres, g.nrows, g.ncols);

        //copy the header file to get it exactly the same, but change the data type
        copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd");
    } else {
        //build classes without generating polygons
        Map<Float, float[]> info = new HashMap<Float, float[]>();
        for (int j = 0; j < keys.size(); j++) {
            info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN });
        }

        g.getClassInfo(info);

        for (int j = 0; j < keys.size(); j++) {
            int k = keys.get(j);
            String key = String.valueOf(k);

            String name = p.getProperty(key);

            GridClass gc = new GridClass();
            gc.setName(name);
            gc.setId(k);

            //for SLD
            maxValues.add(Integer.valueOf(key));
            labels.add(name.replace("\"", "'"));
            gc.setMinShapeIdx(Integer.valueOf(key));
            gc.setMaxShapeIdx(Integer.valueOf(key));

            float[] stats = info.get(keys.get(j).floatValue());

            //only include if area > 0
            if (stats[0] > 0) {
                gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + ","
                        + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " "
                        + stats[2] + "))");

                gc.setArea_km((double) stats[0]);
                classes.put(k, gc);
            }
        }
    }

    //write sld
    exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues,
            labels);

    writeProjectionFile(filePath + File.separator + "polygons.prj");

    //write .classes.json
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File(filePath + ".classes.json"), classes);

    return classes;
}