Example usage for org.joda.time DateTime getMonthOfYear

List of usage examples for org.joda.time DateTime getMonthOfYear

Introduction

In this page you can find the example usage for org.joda.time DateTime getMonthOfYear.

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.adige.SnowMelting.java

License:Open Source License

@Execute
public void process() throws Exception { // transform the

    if (init2) {//from w ww  . j a  v a2  s.  c  om
        outMeasured = new double[pDimMeas];
        init2 = false;
        if (pDoReadMeas) {
            // outSimulated=new double[pDimMeas+1];
            // outMeasured = new double[pDimMeas];
            int dim = pDimMeas;
            double[] portate = new double[dim];
            int cont_portate = 0;
            // System.out.println("SONOENTRATO");
            // lettura portate//
            try {

                String str = new String();
                str = pPathtoMeas;

                FileInputStream fstream = new FileInputStream(str);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;

                double aa = 0;
                while ((strLine = br.readLine()) != null) {
                    aa = Double.parseDouble(strLine);
                    portate[cont_portate] = aa;
                    // System.out.println(aa);
                    cont_portate += 1;

                }
                in.close();
            } catch (Exception e) {
                // System.err.println("Errore: " + e.getMessage());
            }

            outMeasured = portate;
            pDoReadMeas = false;

        }
    }

    /*
     * The models use only one value of the latitude. So I have decided to
     * set it to the center of the raster. Extract the CRS of the
     * GridCoverage and transform the value of a WGS84 latitude.
     */
    CoordinateReferenceSystem sourceCRS = inDem.getCoordinateReferenceSystem2D();

    int numPointToCompute = 0;

    GridGeometry2D inRainGridGeo = null;

    if (doRaster == false) {
        pointsToComputeId2Coordinates = getCoordinate(numPointToCompute, inStations, fStationsid);
        numPointToCompute = pointsToComputeId2Coordinates.size();

    } else if (doRaster == true) {
        if (inRainGrid != null) {
            inRainGridGeo = inRainGrid.getGridGeometry();
        }
        pointsToComputeId2Coordinates = getCoordinate(inRainGridGeo);
        numPointToCompute = pointsToComputeId2Coordinates.size();
    }
    Set<Integer> pointsToInterpolateIdSet = pointsToComputeId2Coordinates.keySet();
    Iterator<Integer> idIterator = pointsToInterpolateIdSet.iterator();
    int j = 0;
    xStation = new double[numPointToCompute];
    yStation = new double[numPointToCompute];
    idStation = new int[numPointToCompute];
    colnumvetVect = new int[numPointToCompute];
    rownumvetVect = new int[numPointToCompute];
    lambdaVect = new double[numPointToCompute];
    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
    while (idIterator.hasNext()) {
        int id = idIterator.next();
        idStation[j] = id;
        Coordinate coordinate = (Coordinate) pointsToComputeId2Coordinates.get(id);
        xStation[j] = coordinate.x;
        yStation[j] = coordinate.y;

        double srcPts[] = new double[] { (xStation[j]), (yStation[j]) };
        Coordinate source = new Coordinate(srcPts[0], srcPts[1]);

        Point[] so = new Point[] { GeometryUtilities.gf().createPoint(source) };
        CrsUtilities.reproject(sourceCRS, targetCRS, so);
        // the latitude value
        lambdaVect[j] = Math.toRadians(so[0].getY());

        j += 1;

    }
    MathTransform transf = inDem.getGridGeometry().getCRSToGrid2D();
    for (int i = 0; i < xStation.length; i++) {

        DirectPosition point = new DirectPosition2D(sourceCRS, xStation[i], yStation[i]);
        DirectPosition gridPoint = transf.transform(point, null);

        colnumvetVect[i] = (int) gridPoint.getCoordinate()[0];
        rownumvetVect[i] = (int) gridPoint.getCoordinate()[1];
        // System.out.println(idStation[i] + " "
        // + gridPoint.getCoordinate()[0] + " "
        // + gridPoint.getCoordinate()[1]);
    }

    double minimofeb = 0;
    double minimomar = 0;
    double minimoapr = 0;
    double minimomagg = 0;
    double minimogiu = 0;
    double dx = 0;
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").withZone(DateTimeZone.UTC);
    DateTime startcurrentDatetime = formatter.parseDateTime(tStartDate);

    DateTime endcurrentDatetime = formatter.parseDateTime(tEndDate);
    long diff = 0;
    if (doDaily == false) {
        diff = (endcurrentDatetime.getMillis() - startcurrentDatetime.getMillis()) / (1000 * 60 * 60);
    }
    if (doDaily) {
        diff = (endcurrentDatetime.getMillis() - startcurrentDatetime.getMillis()) / (1000 * 60 * 60 * 24);
    }
    DateTime array[] = new DateTime[(int) diff];
    if (doDaily == false) {
        for (int i = 0; i < array.length; i++) {
            array[i] = startcurrentDatetime.plusHours(i);
        }
    }
    if (doDaily) {
        for (int i = 0; i < array.length; i++) {
            array[i] = startcurrentDatetime.plusDays(i);
        }
    }
    if (doOneTime) {
        attribute = CoverageUtilities.getRegionParamsFromGridCoverage(inSkyview);
        dx = attribute.get(CoverageUtilities.XRES);

        double srcPts[] = new double[] { attribute.get(CoverageUtilities.EAST),
                attribute.get(CoverageUtilities.SOUTH) };
        // CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
        Coordinate source = new Coordinate(srcPts[0], srcPts[1]);
        Point[] so = new Point[] { GeometryUtilities.gf().createPoint(source) };
        CrsUtilities.reproject(sourceCRS, targetCRS, so);
        // the latitude value
        lambda = Math.toRadians(so[0].getY());
        CoverageUtilities.getRegionParamsFromGridCoverage(inSkyview);

        if (pMode == 0) {

            RenderedImage insFebTmpRI = inInsFeb.getRenderedImage();
            width = insFebTmpRI.getWidth();
            height = insFebTmpRI.getHeight();
            insFebWR = CoverageUtilities.replaceNovalue(insFebTmpRI, -9999.0);

            RenderedImage insJanTmpRI = inInsJan.getRenderedImage();
            width = insJanTmpRI.getWidth();
            height = insJanTmpRI.getHeight();
            insJanWR = CoverageUtilities.replaceNovalue(insJanTmpRI, -9999.0);

            RenderedImage insMarTmpRI = inInsMar.getRenderedImage();
            insMarWR = CoverageUtilities.replaceNovalue(insMarTmpRI, -9999.0);
            insMarTmpRI = null;

            RenderedImage insAprTmpRI = inInsApr.getRenderedImage();
            insAprWR = CoverageUtilities.replaceNovalue(insAprTmpRI, -9999.0);
            insAprTmpRI = null;

            RenderedImage insMayTmpRI = inInsMay.getRenderedImage();
            insMayWR = CoverageUtilities.replaceNovalue(insMayTmpRI, -9999.0);
            insMayTmpRI = null;

            RenderedImage insJuneTmpRI = inInsJun.getRenderedImage();
            insJunWR = CoverageUtilities.replaceNovalue(insJuneTmpRI, -9999.0);
            insJuneTmpRI = null;
            minimofeb = findminumum(insFebWR, hoursToFeb);
            minimomar = findminumum(insMarWR, hoursToMar);
            minimoapr = findminumum(insAprWR, hoursToApr);
            minimomagg = findminumum(insMayWR, hoursToMay);
            minimogiu = findminumum(insJunWR, hoursToJune);

        }
        RenderedImage drmri = inDem.getRenderedImage();
        demwr = CoverageUtilities.replaceNovalue(drmri, -9999.0);
        drmri = null;
        RenderedImage SkyTmpRI = inSkyview.getRenderedImage();
        skyviewfactorWR = CoverageUtilities.renderedImage2WritableRaster(SkyTmpRI, true);

        inCondIniL = new HashMap<Integer, double[]>();
        inCondIniI = new HashMap<Integer, double[]>();
        outSWEData = new HashMap<Integer, double[]>();
        outFreezingData = new HashMap<Integer, double[]>();

        doOneTime = false;
    }
    folder = null;
    P_listOfFiles = null;
    T_listOfFiles = null;
    if (doRaster == true) {

        folder = new File(pathRainfMaps);
        P_listOfFiles = folder.listFiles();
        for (int i = 0; i < P_listOfFiles.length; i++) {
            System.out.println(P_listOfFiles[i]);
        }
        folder = new File(pathTempMaps);
        T_listOfFiles = folder.listFiles();
        for (int i = 0; i < T_listOfFiles.length; i++) {
            System.out.println(T_listOfFiles[i]);
        }

    }
    OmsTimeSeriesIteratorReader reader_temp = new OmsTimeSeriesIteratorReader();
    OmsTimeSeriesIteratorReader reader_solar = new OmsTimeSeriesIteratorReader();

    OmsTimeSeriesIteratorReader reader_rainf = new OmsTimeSeriesIteratorReader();
    OmsTimeSeriesIteratorWriter writer = new OmsTimeSeriesIteratorWriter();
    OmsTimeSeriesIteratorWriter writer2 = new OmsTimeSeriesIteratorWriter();
    OmsTimeSeriesIteratorWriter writer3 = new OmsTimeSeriesIteratorWriter();
    OmsTimeSeriesIteratorWriter writer4 = new OmsTimeSeriesIteratorWriter();
    OmsTimeSeriesIteratorWriter writer5 = new OmsTimeSeriesIteratorWriter();

    if (doRaster == false) {

        if (!((pathTemp == null))) {
            reader_temp.file = pathTemp;
            reader_temp.idfield = "ID";
            reader_temp.tStart = tStartDate;
            reader_temp.tEnd = tEndDate;
            reader_temp.fileNovalue = "-9999";
            reader_temp.tTimestep = inTimestep;
        }

        if (!((pathToSolarRad == null))) {
            reader_solar.file = pathToSolarRad;
            reader_solar.idfield = "ID";
            reader_solar.tStart = tStartDate;
            reader_solar.tEnd = tEndDate;
            reader_solar.fileNovalue = "-9999";
            reader_solar.tTimestep = inTimestep;
        }

        if (!(pathRainf == null)) {

            reader_rainf.file = pathRainf;
            reader_rainf.idfield = "ID";
            reader_rainf.tStart = tStartDate;
            reader_rainf.tEnd = tEndDate;
            reader_rainf.fileNovalue = "-9999";
            reader_rainf.tTimestep = inTimestep;

        }

        if (pathToMelting != null) {
            writer.file = pathToMelting;
            writer.tStart = tStartDate;
            writer.tTimestep = inTimestep;
        }
        if (pathToSwe != null) {
            writer2.file = pathToSwe;
            writer2.tStart = tStartDate;
            writer2.tTimestep = inTimestep;

        }
        if (pathToFreezing != null) {
            writer3.file = pathToFreezing;
            writer3.tStart = tStartDate;
            writer3.tTimestep = inTimestep;

        }
        if (pathToSolidWater != null) {
            writer4.file = pathToSolidWater;
            writer4.tStart = tStartDate;
            writer4.tTimestep = inTimestep;
        }
        if (pathToLiquidWater != null) {
            writer5.file = pathToLiquidWater;
            writer5.tStart = tStartDate;
            writer5.tTimestep = inTimestep;

        }

        if (numSitesWhereCalibrate != 1) {
            outSWEVECTOR = new double[array.length * numSitesWhereCalibrate];
            outMELTINGVECTOR = new double[array.length * numSitesWhereCalibrate];
        } else {
            outSWEVECTOR = new double[array.length];
            outMELTINGVECTOR = new double[array.length];

        }
        conta = 0;
    }

    outMELTINGVECTOR_forMaps = new double[numPointToCompute];
    outSWEVECTOR_forMaps = new double[numPointToCompute];

    for (int i = 0; i < array.length; i++) {
        outSWE = new HashMap<Integer, double[]>();
        outMeltingData = new HashMap<Integer, double[]>();
        // System.out.println(" data=" + array[i]);
        DateTime currentime = array[i];
        if (doRaster == false) {
            if (!(pathTemp == null)) {
                reader_temp.nextRecord();
                temp_values = reader_temp.outData;
            }

            if (!(pathRainf == null)) {
                reader_rainf.nextRecord();
                rain_values = reader_rainf.outData;
            }
            if (!(pathToSolarRad == null)) {
                reader_solar.nextRecord();
                solar_values = reader_solar.outData;
            }
        }
        int month = currentime.getMonthOfYear();
        switch (month) {

        case 1:
            calcMelting(insJanWR, demwr, dx, currentime, hoursToJan, minimofeb, i);
            break;
        case 10:
            calcMelting(insFebWR, demwr, dx, currentime, hoursToFeb, minimofeb, i);
            break;
        case 11:
            calcMelting(insFebWR, demwr, dx, currentime, hoursToFeb, minimofeb, i);
            break;
        case 12:
            calcMelting(insFebWR, demwr, dx, currentime, hoursToFeb, minimofeb, i);
            break;
        case 2:
            calcMelting(insFebWR, demwr, dx, currentime, hoursToFeb, minimofeb, i);
            break;
        case 3:
            calcMelting(insMarWR, demwr, dx, currentime, hoursToMar, minimomar, i);
            break;
        case 4:
            calcMelting(insAprWR, demwr, dx, currentime, hoursToApr, minimoapr, i);
            break;
        case 5:
            calcMelting(insMayWR, demwr, dx, currentime, hoursToMay, minimomagg, i);
            break;
        case 6:
            calcMelting(insJunWR, demwr, dx, currentime, hoursToJune, minimogiu, i);
            break;
        case 7:
            calcMelting(insJunWR, demwr, dx, currentime, hoursToJune, minimogiu, i);
            break;
        case 8:
            calcMelting(insJunWR, demwr, dx, currentime, hoursToJune, minimogiu, i);
            break;
        case 9:
            calcMelting(insJunWR, demwr, dx, currentime, hoursToJune, minimogiu, i);
            break;
        default:
            break;
        }

        //
        // calcInsolation(lambda, pitWR, gradientWR, insolationWR,
        // staoWR,
        // diffuseWR, dx, currentime);
        if (doRaster == false) {
            if (pathToMelting != null) {
                writer.inData = outMeltingData;

                writer.writeNextLine();
            }
            if (pathToSolidWater != null) {
                writer4.inData = inCondIniI;

                writer4.writeNextLine();
            }
            if (pathToLiquidWater != null) {
                writer5.inData = inCondIniL;

                writer5.writeNextLine();
            }
            if (pathToSwe != null) {
                writer2.inData = outSWEData;
                writer2.writeNextLine();
            }
            if (pathToFreezing != null) {
                writer3.inData = outFreezingData;
                writer3.writeNextLine();
            }
        } else if (doRaster) {

            storeResult(outSWEVECTOR_forMaps, outMELTINGVECTOR_forMaps, pointsToComputeId2Coordinates);
            // }

        }
        // pm.worked(i - startDay);
    }
    if (pathToMelting != null) {
        writer.close();
    }
    if (pathToSwe != null) {
        writer2.close();
    }
    if (pathToFreezing != null) {
        writer3.close();
    }
    if (pathToSolidWater != null) {
        writer4.close();
    }
    if (pathToLiquidWater != null) {
        writer5.close();
    }
    outSwevector = outSWEVECTOR;

}

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.energybalance.OmsEnergyBalance.java

License:Open Source License

@Execute
public void process() throws Exception {
    outPnet = new HashMap<Integer, double[]>();
    outPrain = new HashMap<Integer, double[]>();
    outPsnow = new HashMap<Integer, double[]>();
    outSwe = new HashMap<Integer, double[]>();
    outNetradiation = new HashMap<Integer, double[]>();
    outNetshortradiation = new HashMap<Integer, double[]>();

    if (safePoint == null)
        safePoint = new SafePoint();
    // retrieve number of bands
    num_EI = 0;/*from   www .j  a  v  a2 s .  c  o  m*/
    for (EIEnergy energy : inEnergy) {
        int j = energy.energeticBandId;
        if (j > num_EI) {
            num_EI = j;
        }
    }
    num_EI++;
    num_ES = 0;
    for (EIAreas area : inAreas) {
        int j = area.altimetricBandId;
        if (j > num_ES) {
            num_ES = j;
        }
    }
    num_ES++;

    if (basinid2BasinindexMap == null) {
        // get basin features from feature link
        basinsFeatures = new ArrayList<SimpleFeature>();
        FeatureIterator<SimpleFeature> featureIterator = inBasins.features();

        basinNum = inBasins.size();
        SimpleFeatureType featureType = inBasins.getSchema();

        int basinIdFieldIndex = featureType.indexOf(fBasinid);
        if (basinIdFieldIndex == -1) {
            throw new IllegalArgumentException(
                    "The field of the basin id couldn't be found in the supplied basin data.");
        }
        if (fBasinlandcover != null) {
            usoFieldIndex = featureType.indexOf(fBasinlandcover);
            if (usoFieldIndex == -1) {
                throw new IllegalArgumentException(
                        "The field of the soil type (usofield) couldn't be found in the supplied basin data.");
            }
        }
        basinid2BasinindexMap = new HashMap<Integer, Integer>();
        basinindex2BasinidMap = new HashMap<Integer, Integer>();

        pm.beginTask("Read basins data.", inBasins.size());
        int index = 0;
        Abasin = new double[basinNum];
        while (featureIterator.hasNext()) {
            pm.worked(1);
            SimpleFeature feature = featureIterator.next();
            basinsFeatures.add(feature);
            basinid2BasinindexMap.put(((Number) feature.getAttribute(basinIdFieldIndex)).intValue(), index);
            basinindex2BasinidMap.put(index, ((Number) feature.getAttribute(basinIdFieldIndex)).intValue());
            Geometry basinGeometry = (Geometry) feature.getDefaultGeometry();
            Abasin[index] = basinGeometry.getArea() / 1000000.0; // area in km2 as the input
            // area for energetic and
            // altimetric bands
            index++;

            // read land cover if requested
            if (usoFieldIndex != -1) {
                if (usoList == null) {
                    usoList = new ArrayList<Integer>();
                }
                int uso = ((Number) feature.getAttribute(usoFieldIndex)).intValue();
                usoList.add(uso);
            }

        }
        featureIterator.close();
        pm.done();
    }

    // get rain from scalar link
    double[] rain = new double[basinNum];
    Set<Integer> basinIdSet = inRain.keySet();
    pm.beginTask("Read rain data.", basinIdSet.size());
    for (Integer basinId : basinIdSet) {
        pm.worked(1);
        Integer index = basinid2BasinindexMap.get(basinId);
        if (index == null) {
            continue;
        }
        double[] value = inRain.get(basinId);
        if (!isNovalue(value[0])) {
            rain[index] = value[0];
        } else {
            rain[index] = 0.0;
        }
    }
    pm.done();

    // get energy values from scalar link ([12][num_EI][basinNum]) 12 ==
    // 0,1,2,3,4,5,5,4,3,2,1,0 ones at the beginning of the simulation
    if (EI == null) {
        EI = new double[12][num_EI][basinNum];
        pm.beginTask("Read energy index data.", inEnergy.size());
        for (EIEnergy energy : inEnergy) {
            pm.worked(1);
            int tempId = energy.basinId;
            Integer index = basinid2BasinindexMap.get(tempId);
            if (index == null) {
                // basinid2BasinindexMap.remove(tempId);
                continue;
            }
            int j = energy.energeticBandId;
            int k = energy.virtualMonth;
            int kInverse = 11 - k;

            EI[k][j][index] = energy.energyValue;
            EI[kInverse][j][index] = energy.energyValue;
        }
        pm.done();
    }
    // get area bande fascie from scalar link ([num_ES][num_EI][basinNum]) ones at the
    // beginning of the simulation
    if (A == null) {
        A = new double[num_ES][num_EI][basinNum];

        pm.beginTask("Read area per heigth and band data.", inAreas.size());

        HashMap<Integer, HashMap<Integer, HashMap<Integer, Double>>> idbasinMap = new HashMap<Integer, HashMap<Integer, HashMap<Integer, Double>>>();
        for (EIAreas area : inAreas) {
            int idBasin = area.basinId;
            HashMap<Integer, HashMap<Integer, Double>> idfasceMap = idbasinMap.get(idBasin);
            if (idfasceMap == null) {
                idfasceMap = new HashMap<Integer, HashMap<Integer, Double>>();
                idbasinMap.put(idBasin, idfasceMap);
            }
            int idAltimetricBand = area.altimetricBandId;
            HashMap<Integer, Double> idbandeMap = idfasceMap.get(idAltimetricBand);
            if (idbandeMap == null) {
                idbandeMap = new HashMap<Integer, Double>();
                idfasceMap.put(idAltimetricBand, idbandeMap);
            }
            int idEnergeticBand = area.energyBandId;
            double areaValue = area.areaValue;
            idbandeMap.put(idEnergeticBand, areaValue);
            pm.worked(1);
        }
        pm.done();

        for (int i = 0; i < basinNum; i = i + 1) {
            Integer index = basinindex2BasinidMap.get(i);
            if (index == null) {
                basinid2BasinindexMap.remove(i);
                continue;
            }
            HashMap<Integer, HashMap<Integer, Double>> fasceMap = idbasinMap.get(index);

            for (int j = 0; j < num_ES; j++) {
                HashMap<Integer, Double> bandeMap = fasceMap.get(j);
                for (int k = 0; k < num_EI; k++) {
                    A[j][k][i] = bandeMap.get(k);
                }
            }
        }
    }

    // get T (temperatures per basin per band) from scalar input link at each time step
    double[][] T = null;
    if (inTemp != null) {
        T = new double[basinNum][num_ES];
        pm.beginTask("Read temperature data.", inTemp.size());
        Set<Integer> basinIdsSet = inTemp.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inTemp.get(basinId);
            T[index] = values;
        }
        pm.done();
    }

    // get V (wind speed per basin per band) from scalar link at each time step
    double[][] V = null;
    if (inWind != null) {
        V = new double[basinNum][num_ES];
        pm.beginTask("Read wind speed data.", inWind.size());
        Set<Integer> basinIdsSet = inWind.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inWind.get(basinId);
            V[index] = values;
        }
    }

    // get P (pressure per basin per band) from scalar link at each time step
    double[][] P = null;
    if (inPressure != null) {
        P = new double[basinNum][num_ES];
        pm.beginTask("Read pressure data.", inPressure.size());
        Set<Integer> basinIdsSet = inPressure.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inPressure.get(basinId);
            P[index] = values;
        }
        pm.done();
    }

    // get RH (relative humidity per basin per band) from scalar link at each time step
    double[][] RH = null;
    if (inRh != null) {
        RH = new double[basinNum][num_ES];
        pm.beginTask("Read humidity data.", inRh.size());
        Set<Integer> basinIdsSet = inRh.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inRh.get(basinId);
            RH[index] = values;
        }
        pm.done();
    }

    // get dtday (daily temperature range per basin per band) from scalar link at each time
    // step
    double[][] DTd = null;
    if (inDtday != null) {
        DTd = new double[basinNum][num_ES];
        pm.beginTask("Read dtday data.", inDtday.size());
        Set<Integer> basinIdsSet = inDtday.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inDtday.get(basinId);
            DTd[index] = values;
        }
        pm.done();
    }

    // get dtmonth (monthly temperature range per basin per band) from scalar link at each
    // time step
    double[][] DTm = null;
    if (inDtmonth != null) {
        DTm = new double[basinNum][num_ES];
        pm.beginTask("Read dtday data.", inDtmonth.size());
        Set<Integer> basinIdsSet = inDtmonth.keySet();
        for (Integer basinId : basinIdsSet) {
            pm.worked(1);
            Integer index = basinid2BasinindexMap.get(basinId);
            if (index == null) {
                // data for a basin that is not considered, ignore it
                continue;
            }
            double[] values = inDtmonth.get(basinId);
            DTm[index] = values;
        }
        pm.done();
    }

    /*
     * set the current time: day, month and hour
     */
    DateTime currentDatetime = formatter.parseDateTime(tCurrent);
    int currentMonth = currentDatetime.getMonthOfYear();
    int currentDay = currentDatetime.getDayOfMonth();
    int currentMinute = currentDatetime.getMinuteOfDay();
    double hour = currentMinute / 60.0;
    System.out.println("ora: " + hour);

    if (averageTemperature == null) {
        averageTemperature = new double[2 * basinNum];
    } else {
        Arrays.fill(averageTemperature, 0.0);
    }
    /*
     * these have to be taken from initial values 
     */
    if (safePoint.SWE == null) {
        if (pInitsafepoint != null && new File(pInitsafepoint).exists()) {
            safePoint = getSafePointData();
        } else {
            safePoint.SWE = new double[num_ES][num_EI][basinNum];
            if (pInitswe == -9999.0) {
                pInitswe = 0.0;
            }
            for (int i = 0; i < basinNum; i++) {
                double sweTmp = pInitswe;
                if (usoList != null) {
                    int usoTmp = usoList.get(i);
                    if (usoTmp == pGlacierid) {
                        sweTmp = GLACIER_SWE;
                    }
                }
                for (int k = 0; k < num_ES; k++) {
                    for (int j = 0; j < num_EI; j++) {
                        safePoint.SWE[j][k][i] = sweTmp;
                    }
                }
            }
            safePoint.U = new double[num_ES][num_EI][basinNum];
            safePoint.SnAge = new double[num_ES][num_EI][basinNum];
            safePoint.Ts = new double[num_ES][num_EI][basinNum];
        }
    }

    // this has to be taken from a file, scalarreader
    // TODO add the input canopyLink for the canopy height for each altimetric band
    /*
     * if there is no canopy input matrix for the model create an empty canopy matrix for each elevation band and for each basin
     */
    double[][] canopy = new double[num_ES][basinNum];
    for (int i = 0; i < canopy.length; i++) {
        for (int j = 0; j < canopy[0].length; j++) {
            canopy[i][j] = pCanopyh;
        }
    }
    checkParametersAndRunEnergyBalance(rain, T, V, P, RH, currentMonth, currentDay, hour, Abasin, A, EI, DTd,
            DTm, canopy);

}

From source file:org.jgrasstools.hortonmachine.modules.hydrogeomorphology.etp.OmsPenmanEtp.java

License:Open Source License

@Execute
public void penman() {

    checkNull(inPressure, inTemp, inRh, inWind, inSwe, inVegetation, inShortradiation, inNetradiation);

    outEtp = new HashMap<Integer, double[]>();

    DateTime currentTimestamp = formatter.parseDateTime(tCurrent);
    int monthOfYear = currentTimestamp.getMonthOfYear();

    Set<Entry<Integer, double[]>> elevSet = inTemp.entrySet();
    for (Entry<Integer, double[]> entry : elevSet) {
        Integer basinId = entry.getKey();
        // double elevation = inElevations.get(basinId)[0];
        double tair = entry.getValue()[0];
        double pressure = inPressure.get(basinId)[0];
        double relativeHumidity = inRh.get(basinId)[0];
        double wind = inWind.get(basinId)[0];
        double snowWaterEquivalent = inSwe.get(basinId)[0];
        double shortRadiation = inShortradiation.get(basinId)[0];
        double netRadiation = inNetradiation.get(basinId)[0];

        VegetationLibraryRecord vegetation = inVegetation.get(basinId);
        double displacement = vegetation.getDisplacement(monthOfYear);
        double roughness = vegetation.getRoughness(monthOfYear);
        double rs = vegetation.getMinStomatalResistance();
        double RGL = vegetation.getRgl();
        double lai = vegetation.getLai(monthOfYear);
        double rarc = vegetation.getArchitecturalResistance();

        /*/*from ww w . j  a v  a  2 s .  c o  m*/
         * set the pressure in Pascal instead of in hPa as the input link gives 
         */
        pressure = pressure / 100;
        double vpd = svp(tair) - (relativeHumidity * 100 / svp(tair)); // vpd in KPa
        double ra = calcAerodynamic(displacement, roughness, ZREF, wind, snowWaterEquivalent);

        // CONSIDER THE SOIL RESISTANCE NULL
        // // calculate gsm_inv: soil moisture stress factor
        // double criticalSoilMoisture = 0.33; // fraction of soil moisture content at the
        // critical
        // // point
        // double wiltingPointSoilMoisture = 0.133;
        // double waterContentCriticalPoint = criticalSoilMoisture * maxMoisture;
        // double waterContentWiltingPoint = wiltingPointSoilMoisture * maxMoisture;
        // double gsm_inv; // soil moisture stress factor
        // if (soilMoisture >= waterContentCriticalPoint) {
        // gsm_inv = 1.0;
        // } else if (soilMoisture >= waterContentWiltingPoint) {
        // gsm_inv = (soilMoisture - waterContentWiltingPoint) / (waterContentCriticalPoint -
        // waterContentWiltingPoint);
        // } else {
        // gsm_inv = 0.0;
        // }
        /* calculate the slope of the saturated vapor pressure curve in Pa/K */
        double slope = svp_slope(tair) * 1000.0;

        /* factor for canopy resistance based on photosynthesis */
        double dayFactor;
        /* calculate resistance factors (Wigmosta et al., 1994) */
        double f = 0.0;
        if (rs > 0.) {
            if (RGL < 0) {
                throw new ModelsIllegalargumentException("Invalid value of RGL for the current class.", this);
            } else if (RGL == 0) {
                f = shortRadiation;
            } else {
                f = shortRadiation / RGL;
            }
            dayFactor = (1. + f) / (f + rs / RSMAX);
        } else
            dayFactor = 1.;

        /* factor for canopy resistance based on temperature */
        double tFactor = .08 * tair - 0.0016 * tair * tair;
        tFactor = (tFactor <= 0.0) ? 1e-10 : tFactor;

        /* factor for canopy resistance based on vpd */
        double vpdFactor = 1 - vpd / CLOSURE;
        vpdFactor = (vpdFactor < VPDMINFACTOR) ? VPDMINFACTOR : vpdFactor;

        /* calculate canopy resistance in s/m */
        // double rc = rs / (lai * gsm_inv * tFactor * vpdFactor) * dayFactor;
        double rc = rs / (lai * tFactor * vpdFactor) * dayFactor;
        rc = (rc > RSMAX) ? RSMAX : rc;

        // double h; /* scale height in the atmosphere (m) */
        // /* calculate scale height based on average temperature in the column */
        // h = 287 / 9.81 * ((tair + 273.15) + 0.5 * (double) elevation * LAPSE_PM);
        //
        // /* use hypsometric equation to calculate p_z, assume that virtual temperature is
        // equal
        // air_temp */
        // pz = PS_PM * Math.exp(-(double) elevation / h);

        // instead of calculating the pressure in h.adige it is possible to read the
        // interpolated
        // pressure from input link
        // pz is the surface air pressure

        /* calculate latent heat of vaporization. Eq. 4.2.1 in Handbook of Hydrology, assume Ts is Tair */
        double lv = 2501000 - 2361 * tair;

        /* calculate the psychrometric constant gamma (Pa/C). Eq. 4.2.28. Handbook of Hydrology */
        double gamma = 1628.6 * pressure / lv;

        /* calculate factor to be applied to rc/ra */

        /* calculate the air density (in kg/m3), using eq. 4.2.4 Handbook of Hydrology */
        double r_air = 0.003486 * pressure / (275 + tair);

        /* calculate the Penman-Monteith evaporation in mm/day (by not dividing by 
         * the density of water (~1000 kg/m3)), the result ends up being in mm instead of m */
        double evap = ((slope * netRadiation + r_air * CP_PM * vpd / ra)
                / (lv * (slope + gamma * (1 + (rc + rarc) / ra))) * SEC_PER_DAY) / 24.0;

        if (vpd >= 0.0 && evap < 0.0)
            evap = 0.0;

        outEtp.put(basinId, new double[] { evap });
    }
}

From source file:org.jimcat.gui.histogram.image.DateTakenDimension.java

License:Open Source License

/**
 * get label text for given index/*from   w  ww. j a  va 2  s. com*/
 * 
 * @param index
 * @return the label text for given index
 */
private String getMonthLabel(int index) {
    DateTime date = indexToDate(MONTHS, index);
    int month = date.getMonthOfYear();
    if (month % 3 == 0) {
        return MONTH_LABEL_FORMATTER.print(date);
    }
    return null;
}

From source file:org.jimcat.gui.histogram.image.DateTakenDimension.java

License:Open Source License

/**
 * get mark for index//w  ww  .  jav a  2 s .co m
 * 
 * @see org.jimcat.gui.histogram.image.Dimension#getMarkFor(int, int)
 */
@Override
public ScaleMark getMarkFor(int resolution, int index) {
    ScaleMark result = ScaleMark.SMALL;

    // get corresponding date
    DateTime date = indexToDate(resolution, index);
    if (date == null) {
        // no data available
        return ScaleMark.NONE;
    }

    if (resolution == DAYS) {
        int day = date.getDayOfMonth();
        if (day == 1 || day == 15) {
            result = ScaleMark.LABEL;
        }
    } else if (resolution == WEEKS) {
        int week = date.getWeekOfWeekyear();
        if (week == 1 || week % 10 == 0) {
            result = ScaleMark.LABEL;
        }
    } else if (resolution == MONTHS) {
        int month = date.getMonthOfYear();
        if (month % 3 == 0) {
            result = ScaleMark.LABEL;
        }
    }

    return result;
}

From source file:org.jimcat.services.rename.Renamer.java

License:Open Source License

@SuppressWarnings("null")
private String getNewName(Image image, int n) {
    String newName = configString;
    DateTime date = null;

    switch (useDate) {
    case MODIFICATION:
        date = image.getMetadata().getModificationDate();
        break;// w ww  . j a  va2  s .co m
    case ADDED:
        date = image.getMetadata().getDateAdded();
        break;
    case TAKEN:

        ExifMetadata exifMetadata = image.getExifMetadata();

        if (exifMetadata != null) {
            date = exifMetadata.getDateTaken();
        }
        break;
    }

    String random;

    do {
        random = String.valueOf(Math.random());
    } while (configString.contains(random));

    if (hasParameter(escapeCharacter.charAt(0))) {
        newName = newName.replace(escapeCharacter + escapeCharacter, random);
    }

    if (hasParameter('n')) {
        String number = String.format("%0" + digits + "d", new Integer(n));
        newName = newName.replace(escapeCharacter + "n", number);
    }

    if (hasParameter('w')) {
        newName = newName.replace(escapeCharacter + "w", "" + image.getMetadata().getWidth());
    }

    if (hasParameter('h')) {
        newName = newName.replace(escapeCharacter + "h", "" + image.getMetadata().getHeight());
    }

    if (hasParameter('d')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "d", unknownResultCharacter);
        } else {
            String day = formatNumber(date.getDayOfMonth(), 2);
            newName = newName.replace(escapeCharacter + "d", day);
        }
    }

    if (hasParameter('m')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "m", unknownResultCharacter);
        } else {
            String month = formatNumber(date.getMonthOfYear(), 2);
            newName = newName.replace(escapeCharacter + "m", month);
        }
    }

    if (hasParameter('y')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "y", unknownResultCharacter);
        } else {
            String year = formatNumber(date.getYear(), 4);
            newName = newName.replace(escapeCharacter + "y", year);
        }
    }

    if (hasParameter('H')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "H", unknownResultCharacter);
        } else {
            String hour = formatNumber(date.getHourOfDay(), 2);
            newName = newName.replace(escapeCharacter + "H", hour);
        }
    }

    if (hasParameter('M')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "M", unknownResultCharacter);
        } else {
            String minute = formatNumber(date.getMinuteOfHour(), 2);
            newName = newName.replace(escapeCharacter + "M", minute);
        }
    }

    if (hasParameter('S')) {
        if (date == null) {
            newName = newName.replace(escapeCharacter + "S", unknownResultCharacter);
        } else {
            String seconds = formatNumber(date.getSecondOfMinute(), 2);
            newName = newName.replace(escapeCharacter + "S", seconds);
        }
    }

    if (hasParameter('r')) {
        newName = newName.replace(escapeCharacter + "r", ratingToString(image.getRating()));
    }

    if (hasParameter('f')) {
        if (image.getMetadata() != null && image.getMetadata().getPath() != null) {
            String fileName = removeFileType(image.getMetadata().getPath());
            newName = newName.replace(escapeCharacter + "f", fileName);
        } else {
            newName = newName.replace(escapeCharacter + "f", unknownResultCharacter);
        }
    }

    if (newName.length() == 0) {
        return newName;
    }

    // if the user is just typing dont show the last $
    // but if he wants a $ at the and (by using $$) allow it and even allow
    // $$ at the end

    int escapeCharactersAtEnd = 0;
    int index = newName.length() - 1;

    while (index >= 0 && newName.charAt(index--) == escapeCharacter.charAt(0)) {
        escapeCharactersAtEnd++;
    }

    if (escapeCharactersAtEnd % 2 == 1) {
        newName = newName.substring(0, newName.length() - 1);
    }

    if (hasParameter(escapeCharacter.charAt(0))) {
        newName = newName.replace(random, escapeCharacter);
    }

    // set at the end because the original title could contain evil control
    // sequences
    if (hasParameter('t')) {
        newName = newName.replace(escapeCharacter + "t", image.getTitle());
    }

    return newName;
}

From source file:org.joda.example.time.DateTimePerformance.java

License:Apache License

private void checkJodaGetMonth() {
    int COUNT = COUNT_VERY_FAST;
    DateTime dt = new DateTime(GJChronology.getInstance());
    for (int i = 0; i < AVERAGE; i++) {
        start("Joda", "getMonth");
        for (int j = 0; j < COUNT; j++) {
            int val = dt.getMonthOfYear();
            if (val == 0) {
                System.out.println("Anti optimise");
            }//w  ww.ja  v  a2  s . c om
        }
        end(COUNT);
    }
}

From source file:org.joda.example.time.DateTimePerformance.java

License:Apache License

private void checkJISOGetMonth() {
    int COUNT = COUNT_VERY_FAST;
    DateTime dt = new DateTime();
    for (int i = 0; i < AVERAGE; i++) {
        start("JISO", "getMonth");
        for (int j = 0; j < COUNT; j++) {
            int val = dt.getMonthOfYear();
            if (val == 0) {
                System.out.println("Anti optimise");
            }//from   w  ww  . j  av a 2  s . co m
        }
        end(COUNT);
    }
}

From source file:org.joda.example.time.Examples.java

License:Apache License

private void runDateTime() {
    System.out.println("DateTime");
    System.out.println("=======");
    System.out.println(//w  ww . jav  a2s.c om
            "DateTime stores a the date and time using millisecs from 1970-01-01T00:00:00Z internally");
    System.out.println("DateTime is immutable and thread-safe");
    System.out.println("                      in = new DateTime()");
    DateTime in = new DateTime();
    System.out.println("Millisecond time:     in.getMillis():           " + in.getMillis());
    System.out.println("ISO string version:   in.toString():            " + in.toString());
    System.out.println("ISO chronology:       in.getChronology():       " + in.getChronology());
    System.out.println("Your time zone:       in.getDateTimeZone():     " + in.getZone());
    System.out.println("Change millis:        in.withMillis(0):         " + in.withMillis(0L));
    System.out.println("");
    System.out.println("Get year:             in.getYear():             " + in.getYear());
    System.out.println("Get monthOfYear:      in.getMonthOfYear():      " + in.getMonthOfYear());
    System.out.println("Get dayOfMonth:       in.getDayOfMonth():       " + in.getDayOfMonth());
    System.out.println("...");
    System.out.println("Property access:      in.dayOfWeek().get():                   " + in.dayOfWeek().get());
    System.out.println(
            "Day of week as text:  in.dayOfWeek().getAsText():             " + in.dayOfWeek().getAsText());
    System.out.println(
            "Day as short text:    in.dayOfWeek().getAsShortText():        " + in.dayOfWeek().getAsShortText());
    System.out.println("Day in french:        in.dayOfWeek().getAsText(Locale.FRENCH):"
            + in.dayOfWeek().getAsText(Locale.FRENCH));
    System.out.println("Max allowed value:    in.dayOfWeek().getMaximumValue():       "
            + in.dayOfWeek().getMaximumValue());
    System.out.println("Min allowed value:    in.dayOfWeek().getMinimumValue():       "
            + in.dayOfWeek().getMinimumValue());
    System.out.println(
            "Copy & set to Jan:    in.monthOfYear().setCopy(1):            " + in.monthOfYear().setCopy(1));
    System.out.println(
            "Copy & add 14 months: in.monthOfYear().addCopy(14):           " + in.monthOfYear().addToCopy(14));
    System.out.println("Add 14 mnths in field:in.monthOfYear().addWrapFieldCopy(14):  "
            + in.monthOfYear().addWrapFieldToCopy(14));
    System.out.println("...");
    System.out.println("Convert to Instant:   in.toInstant():           " + in.toInstant());
    System.out.println("Convert to DateTime:  in.toDateTime():          " + in.toDateTime());
    System.out.println("Convert to MutableDT: in.toMutableDateTime():   " + in.toMutableDateTime());
    System.out.println("Convert to Date:      in.toDate():              " + in.toDate());
    System.out.println("Convert to Calendar:  in.toCalendar(Locale.UK): "
            + in.toCalendar(Locale.UK).toString().substring(0, 46));
    System.out.println("Convert to GregCal:   in.toGregorianCalendar(): "
            + in.toGregorianCalendar().toString().substring(0, 46));
    System.out.println("");
    System.out.println("                      in2 = new DateTime(in.getMillis() + 10)");
    DateTime in2 = new DateTime(in.getMillis() + 10);
    System.out.println("Equals ms and chrono: in.equals(in2):           " + in.equals(in2));
    System.out.println("Compare millisecond:  in.compareTo(in2):        " + in.compareTo(in2));
    System.out.println("Compare millisecond:  in.isEqual(in2):          " + in.isEqual(in2));
    System.out.println("Compare millisecond:  in.isAfter(in2):          " + in.isAfter(in2));
    System.out.println("Compare millisecond:  in.isBefore(in2):         " + in.isBefore(in2));
}

From source file:org.jruby.ext.date.RubyDate.java

License:LGPL

@JRubyMethod // Time.local(year, mon, mday)
public RubyTime to_time(ThreadContext context) {
    final Ruby runtime = context.runtime;
    DateTime dt = this.dt;

    dt = new DateTime(adjustJodaYear(dt.getYear()), dt.getMonthOfYear(), dt.getDayOfMonth(), 0, 0, 0,
            RubyTime.getLocalTimeZone(runtime));
    return new RubyTime(runtime, runtime.getTime(), dt);
}