Example #1
0
    static void Main(string[] args)
    {
      //Extract the filenames from the arguments
      string dfs0FileName = args.First(var => Path.GetExtension(var).ToLower() == ".dfs0");
      string AsciiFileName = args.First(var => Path.GetExtension(var).ToLower() != ".dfs0");

      //Create a DFS0-object
      using (DFS0 _dfs0 = new DFS0(dfs0FileName)) //"Using" will make sure the object is correctly disposed 
      {
        //Creates a streamreader object
        using (StreamReader sr = new StreamReader(AsciiFileName))
        {
          //Not used but need to advance to next line
          string headline = sr.ReadLine();

          //Loop until end of stream
          while (!sr.EndOfStream)
          {
            //Reads next line
            string line = sr.ReadLine();

            //Splits on tabs into an array of strings
            string[] lineArray = line.Split('\t');

            //Gets the ItemName from the first column
            string ItemName =lineArray[0];

            //Gets the Item number as the second column
            int ItemNumber = int.Parse(lineArray[1]);

            //Gets the Multiplication factor as the third column
            double MultiplyFactor = double.Parse(lineArray[2]);

            //Try to find the item based on the item name
            Item I = _dfs0.Items.FirstOrDefault(var => var.Name == ItemName);

            //I will be zero if it was not found
            if (I != null)
              ItemNumber = I.ItemNumber; //Now sets the item number to the correct number

            //Loop all the timesteps in the dfs0
            for (int i = 0; i < _dfs0.NumberOfTimeSteps; i++)
            {
              //Get the original value
              double val = _dfs0.GetData(i, ItemNumber);
              //Calculate new value
              double newval = val * MultiplyFactor;
              //Set the new value
              _dfs0.SetData(i, ItemNumber, newval);
            }
          }
        }
      }
    }
    /// <summary>
    /// Writes a dfs0 with extraction data for each active intake in every plant. 
    /// Also writes the textfile that can be imported by the well editor.
    /// </summary>
    /// <param name="OutputPath"></param>
    /// <param name="Plants"></param>
    /// <param name="Start"></param>
    /// <param name="End"></param>
    public static void WriteExtractionDFS0(string OutputPath, IEnumerable<PlantViewModel> Plants, DateTime Start, DateTime End)
      {

        //Create the text file to the well editor.
        StreamWriter Sw = new StreamWriter(Path.Combine(OutputPath, "WellEditorImport.txt"), false, Encoding.Default);
        StreamWriter Sw2 = new StreamWriter(Path.Combine(OutputPath, "WellsWithMissingInfo.txt"), false, Encoding.Default);
        StreamWriter Sw3 = new StreamWriter(Path.Combine(OutputPath, "PlantWithoutWells.txt"), false, Encoding.Default);


        var TheIntakes = Plants.Sum(var => var.ActivePumpingIntakes.Count());

        //Create the DFS0 Object
        string dfs0FileName = Path.Combine(OutputPath, "Extraction.dfs0");
        DFS0 _tso = new DFS0(dfs0FileName, TheIntakes);

        DFS0 _tsoStat = new DFS0(Path.Combine(OutputPath, "ExtractionStat.dfs0"), 4);
        Dictionary<int, double> Sum = new Dictionary<int, double>();
        Dictionary<int, double> SumSurfaceWater = new Dictionary<int, double>();
        Dictionary<int, double> SumNotUsed = new Dictionary<int, double>();

        int Pcount = 0;

        int NumberOfYears = End.Year - Start.Year + 1;

        //Dummy year because of mean step accumulated
        _tso.InsertTimeStep( new DateTime(Start.Year, 1, 1, 0, 0, 0));

        for (int i = 0; i < NumberOfYears; i++)
        {
          _tso.InsertTimeStep(new DateTime(Start.Year + i, 12, 31, 12, 0, 0));
          _tsoStat.InsertTimeStep(new DateTime(Start.Year + i, 12, 31, 12, 0, 0));
          Sum.Add(i, 0);
          SumSurfaceWater.Add(i, 0);
          SumNotUsed.Add(i, 0);
        }

        double[] fractions = new double[NumberOfYears];
        int itemCount = 0;

        //loop the plants
        foreach (PlantViewModel P in Plants)
        {
          double val;
          //Add to summed extraction, surface water and not assigned
          for (int i = 0; i < NumberOfYears; i++)
          {
            if (P.plant.SurfaceWaterExtrations.TryGetValue(Start.AddYears(i), out val))
              SumSurfaceWater[i] += val;
            //Create statistics for plants without active intakes
            if (P.ActivePumpingIntakes.Count() == 0)
              if (P.plant.Extractions.TryGetValue(Start.AddYears(i), out val))
                SumNotUsed[i] += val;

            if (P.plant.Extractions.TryGetValue(Start.AddYears(i), out val))
              Sum[i] += val;
          }
          Pcount++;

          //Used for extraction but has missing data
          foreach (var NotUsedWell in P.PumpingIntakes.Where(var => var.Intake.well.UsedForExtraction & (var.Intake.well.HasMissingData() | var.Intake.HasMissingdData())))
          {
            StringBuilder Line = new StringBuilder();
            Line.Append(NotUsedWell.Intake.well.X + "\t");
            Line.Append(NotUsedWell.Intake.well.Y + "\t");
            Line.Append(NotUsedWell.Intake.well.Terrain + "\t");
            Line.Append("0\t");
            Line.Append(P.ID + "\t");
            Sw2.WriteLine(Line);
          }

          //Only go in here if the plant has active intakes
          if (P.ActivePumpingIntakes.Count() > 0)
          {
            //Calculate the fractions based on how many intakes are active for a particular year.
            for (int i = 0; i < NumberOfYears; i++)
            {
              fractions[i] = 1.0 / P.ActivePumpingIntakes.Count(var => (var.StartNullable ?? DateTime.MinValue).Year <= Start.Year + i & (var.EndNullable ?? DateTime.MaxValue).Year >= Start.Year + i);
            }

            //Now loop the intakes
            foreach (var PI in P.ActivePumpingIntakes)
            {
              IIntake I = PI.Intake;
              //Build novanaid
              string NovanaID = P.ID.ToString() + "_" + I.well.ID.Replace(" ", "") + "_" + I.IDNumber;

              _tso.Items[itemCount].ValueType = DataValueType.MeanStepBackward;
              _tso.Items[itemCount].EumItem = eumItem.eumIPumpingRate;
              _tso.Items[itemCount].EumUnit = eumUnit.eumUm3PerYear;
              _tso.Items[itemCount].Name = NovanaID;

              //Loop the years
              for (int i = 0; i < NumberOfYears; i++)
              {
                //Extractions are not necessarily sorted and the time series may have missing data
                var k = P.plant.Extractions.Items.FirstOrDefault(var => var.StartTime.Year == Start.Year + i);

                //If data and the intake is active
                if (k != null & (PI.StartNullable ?? DateTime.MinValue).Year <= Start.Year + i & (PI.EndNullable ?? DateTime.MaxValue).Year >= Start.Year + i)
                  _tso.SetData(i + 1, itemCount + 1, (k.Value * fractions[i]));
                else
                  _tso.SetData(i + 1, itemCount + 1, 0); //Prints 0 if no data available

                //First year should be printed twice
                if (i == 0)
                  _tso.SetData(i, itemCount + 1, _tso.GetData(i + 1, itemCount + 1));
              }

              //Now add line to text file.
              StringBuilder Line = new StringBuilder();
              Line.Append(NovanaID + "\t");
              Line.Append(I.well.X + "\t");
              Line.Append(I.well.Y + "\t");
              Line.Append(I.well.Terrain + "\t");
              Line.Append("0\t");
              Line.Append(P.ID + "\t");
              Line.Append(I.Screens.Max(var => var.TopAsKote) + "\t");
              Line.Append(I.Screens.Min(var => var.BottomAsKote) + "\t");
              Line.Append(1 + "\t");
              Line.Append(Path.GetFileNameWithoutExtension(dfs0FileName) + "\t");
              Line.Append(itemCount+1);
              Sw.WriteLine(Line.ToString());

              itemCount++;
            }
          }
          else //Plants with no wells
          {
            Sw3.WriteLine(P.DisplayName + "\t" + P.ID);
          }
        }


        foreach(var Item in _tsoStat.Items)
        {
          Item.EumItem = eumItem.eumIPumpingRate;
          Item.EumUnit = eumUnit.eumUm3PerSec;
          Item.ValueType = DataValueType.MeanStepBackward;
        }
        
        _tsoStat.Items[0].Name="Sum";
        _tsoStat.Items[1].Name = "Mean";
        _tsoStat.Items[2].Name = "SumNotUsed";
        _tsoStat.Items[3].Name = "SumSurfaceWater";

        for (int i = 0; i < NumberOfYears; i++)
        {
          _tsoStat.SetData(i, 1, Sum[i]);
          _tsoStat.SetData(i, 2, Sum[i]/((double)Pcount));
          _tsoStat.SetData(i, 3, SumNotUsed[i]);
          _tsoStat.SetData(i, 4, SumSurfaceWater[i]);
        }

        _tsoStat.Dispose(); 
        _tso.Dispose();
        Sw.Dispose();
        Sw2.Dispose();
        Sw3.Dispose();
      }
    public void PercentileTest()
    {
      DFSBase target = DfsFileFactory.OpenFile(TestPath + @"novomr4_indv_dfs0_ud1.dfs0");
      double[] Percentiles = new double[] { 0.1, 0.5, 0.9 };
      DFSBase outf = DfsFileFactory.CreateFile(TestPath + @"novomr4_indv_dfs0_ud1_percentiles.dfs0", Percentiles.Count());

      outf.CopyFromTemplate(target);
      int Item = 1; // TODO: Initialize to an appropriate value

      int k = 0;
      //Create the items
      foreach (double j in Percentiles)
      {
        outf.Items[k].EumItem = target.Items[Item-1].EumItem;
        outf.Items[k].EumUnit = target.Items[Item-1].EumUnit;
        outf.Items[k].Name = j.ToString() + " Percentile";
        k++;
      }

      int[] TSteps = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

      target.Percentile(Item, TSteps, outf, Percentiles);
      outf.Dispose();
      target.Dispose();

      DFS0 df = new DFS0(TestPath + @"novomr4_indv_dfs0_ud1_percentiles.dfs0");

      Assert.AreEqual(25952,df.GetData(0,1),0.5);
      Assert.AreEqual(27294, df.GetData(0, 2),0.5);
      Assert.AreEqual(33422, df.GetData(0, 3), 0.5);

      df.Dispose();
    }