Пример #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);
            }
          }
        }
      }
    }
Пример #2
0
    static void Main(string[] args)
    {
      //Gets the text file name from the first argument
      string TxtFileName = args[0];
      //Gets the dfs0 file name from the second argument
      string dfs0FileName = args[1];

      //Creates a new dfs0-file with one item
      DFS0 dfsfile = new DFS0(dfs0FileName, 1);

      //Sets the eumitem and unit.
      dfsfile.Items[0].EumItem = eumItem.eumIConcentration;
      dfsfile.Items[0].EumUnit = eumUnit.eumUmilliGramPerL;
      dfsfile.Items[0].Name = "Concentration";
      dfsfile.Items[0].ValueType = DHI.Generic.MikeZero.DFS.DataValueType.Instantaneous; 

      //Opens the text file
      using (StreamReader sr = new StreamReader(TxtFileName))
      {
        //Count the timesteps. From zero.
        int TimeStepCounter = 0;

        //Loop until at the end of file
        while (!sr.EndOfStream)
        {
          //Read the line
          string line = sr.ReadLine();
          //Split on ";"
          string[] splitLine = line.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
          //Convert first text to date
          DateTime date = DateTime.Parse(splitLine[0]);
          //Convert second text to number
          double value = double.Parse(splitLine[1]);

          //Now set time of time step
          dfsfile.TimeSteps[TimeStepCounter] = date;
          //Now set value
          dfsfile.SetData(TimeStepCounter, 1, value);

          //Increment time step counter
          TimeStepCounter++;
        }
      }
      dfsfile.Dispose();
    }
        /// <summary>
    /// Writes a dfs0 with extraction data for each active intake in every plant using the Permits. 
    /// 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 WriteExtractionDFS0Permits(string OutputPath, IEnumerable<PlantViewModel> Plants, int DistributionYear, int StartYear, int Endyear)
    {

      //Create the text file to the well editor.
      StreamWriter Sw = new StreamWriter(Path.Combine(OutputPath, "WellEditorImportPermits.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, "ExtractionPermits.dfs0");
      DFS0 _tso = new DFS0(dfs0FileName, TheIntakes);

      int Pcount = 0;

      //Set time
      _tso.InsertTimeStep(new DateTime(StartYear, 1, 1, 0, 0, 0));
      _tso.InsertTimeStep(new DateTime(Endyear, 12, 31, 0, 0, 0));

      double fractions;
      int itemCount = 0;

      //loop the plants
      foreach (PlantViewModel P in Plants)
      {
        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.ID + "\t");
          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);
          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.
          fractions = 1.0 / P.ActivePumpingIntakes.Count(var => (var.StartNullable ?? DateTime.MinValue).Year <= DistributionYear & (var.EndNullable ?? DateTime.MaxValue).Year >= DistributionYear);

          //Now loop the intakes
          foreach (var PI in P.ActivePumpingIntakes.Where(var => (var.StartNullable ?? DateTime.MinValue).Year <= DistributionYear & (var.EndNullable ?? DateTime.MaxValue).Year >= DistributionYear))
          {
            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;


            //If data and the intake is active
            _tso.SetData(0, itemCount + 1, (P.Permit * fractions));
            _tso.SetData(1, itemCount + 1, (P.Permit * fractions));


            //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);
        }
      }
      _tso.Dispose();
      Sw.Dispose();
      Sw2.Dispose();
      Sw3.Dispose();
    }
    /// <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();
      }
    /// <summary>
    /// Writes the dfs0-files to used for detailed time series
    /// </summary>
    /// <param name="OutputPath"></param>
    /// <param name="Intakes"></param>
    /// <param name="Start"></param>
    /// <param name="End"></param>
    public static void WriteDetailedTimeSeriesDfs0(string OutputPath, IEnumerable<IIntake> Intakes, params Func<TimestampValue, bool>[] filters)
    {
      foreach (IIntake Intake in Intakes)
      {
        var SelectedObs = Intake.HeadObservations.Items.AsEnumerable<TimestampValue>();
        //Select the observations
        foreach (var v in filters)
          SelectedObs = SelectedObs.Where(v);

        if (SelectedObs.Count() > 0)
        {
          using (DFS0 dfs = new DFS0(Path.Combine(OutputPath, Intake.ToString() + ".dfs0"), 1))
          {
            dfs.FirstItem.ValueType = DataValueType.Instantaneous;
            dfs.FirstItem.EumItem = eumItem.eumIElevation;
            dfs.FirstItem.EumUnit = eumUnit.eumUmeter;
            dfs.FirstItem.Name = Intake.ToString();

            DateTime _previousTimeStep = DateTime.MinValue;

            //Select the observations
            int i = 0;

            foreach (var Obs in SelectedObs)
            {
              //Only add the first measurement of the day
              if (Obs.Time != _previousTimeStep)
              {
                dfs.SetData(Obs.Time, 1, Obs.Value);
              }
              i++;
            }
          }
        }
      }
    }
Пример #6
0
    public static void InsertPointValues(XElement OperationData)
    {
      string filename = OperationData.Element("DFSFileName").Value;

      int Item = OperationData.Element("Item") == null ? 1 : int.Parse(OperationData.Element("Item").Value);
      bool ClearValues = OperationData.Element("ClearValues") == null ? true: bool.Parse(OperationData.Element("ClearValues").Value);

      List<Tuple<double, double, int, int, double>> points = new List<Tuple<double, double, int, int, double>>();

      foreach (var p in OperationData.Element("Points").Elements())
      {
        Tuple<double, double, int, int, double> point = new Tuple<double, double, int, int, double>(
          p.Element("X") == null ? -1 : double.Parse(p.Element("X").Value),
          p.Element("Y") == null ? -1 : double.Parse(p.Element("Y").Value),
          p.Element("Z") == null ? 0 : int.Parse(p.Element("Z").Value),
          p.Element("TimeStep") == null ? 0 : int.Parse(p.Element("TimeStep").Value),
          double.Parse(p.Element("Value").Value));
        points.Add(point);
      }

      if (Path.GetExtension(filename).EndsWith("0"))
      {
        using (DFS0 dfs = new DFS0(filename))
        {
          if (ClearValues)
          {
            for (int i = 0; i < dfs.NumberOfTimeSteps; i++)
            {
              dfs.SetData(i, Item, 0);
            }
          }
          foreach (var p in points)
          {
            dfs.SetData(p.Item4, Item, p.Item5);
          }
        }
      }
      else if (Path.GetExtension(filename).EndsWith("2"))
      {
        using (DFS2 dfs = new DFS2(filename))
        {
          if (ClearValues)
          {
            for (int i = 0; i < dfs.NumberOfTimeSteps; i++)
            {
              dfs.SetData(i, Item, new DenseMatrix(dfs.NumberOfRows, dfs.NumberOfColumns));
            }
          }
          foreach (var p in points)
          {
            var data = dfs.GetData(p.Item4, Item);
            int column = dfs.GetColumnIndex(p.Item1);
            int row = dfs.GetRowIndex(p.Item2);

            if (column >= 0 & row >= 0)
              data[row, column] = p.Item5;

            dfs.SetData(p.Item4, Item, data);
          }
        }
      }
      else if (Path.GetExtension(filename).EndsWith("3"))
      {
        using (DFS3 dfs = new DFS3(filename))
        {
          if (ClearValues)
          {
            for (int i = 0; i < dfs.NumberOfTimeSteps; i++)
            {
              dfs.SetData(i, Item, new Matrix3d(dfs.NumberOfRows, dfs.NumberOfColumns, dfs.NumberOfLayers));
            }
          }
          foreach (var p in points)
          {
            var data = dfs.GetData(p.Item4, Item);
            int column = dfs.GetColumnIndex(p.Item1);
            int row = dfs.GetRowIndex(p.Item2);

            if (column >= 0 & row >= 0)
              data[row, column, p.Item3] = p.Item5;

            dfs.SetData(p.Item4, Item, data);
          }
        }
      }
    }
Пример #7
0
    private void MakePlots()
    {
      if (!PlotsMade) //Only do this once
      {

        Model mShe = new Model(SheFileName);
        DFS3 dfs = new DFS3(Dfs3FileName);
        Item dfsI = dfs.Items[ItemNumber - 1];

        List<TimestampSeries> well_Concentration = new List<TimestampSeries>();

        int[] TimeSteps = ParseString(TimeStepsAsString, 0, dfs.NumberOfTimeSteps - 1);
        int[] WellNumbers = ParseString(WellsAsString, 0, mShe.ExtractionWells.Count - 1);

        List<MikeSheWell> wells = new List<MikeSheWell>();
        foreach (int j in WellNumbers)
          wells.Add(mShe.ExtractionWells[j]);

        foreach (int i in TimeSteps)
        {
          int k = 0;
          foreach (var w in wells)
          {
            if (i == TimeSteps[0])
              well_Concentration.Add(new TimestampSeries(w.ID, new Unit(dfsI.EumQuantity.UnitAbbreviation, 1, 0)));
            well_Concentration[k].Items.Add(new TimestampValue(dfs.TimeSteps[i], (dfs.GetData(i, ItemNumber)[w.Row, w.Column, w.Layer])));
            k++;
          }
        }

        //Sets the upper title
        Header.Content = dfsI.Name;

        //Sets the title of the y-axis
        var ytitle = new VerticalAxisTitle();
        ytitle.Content = dfsI.EumQuantity.ItemDescription + " [" + dfsI.EumQuantity.UnitAbbreviation + "]";
        TheChart.Children.Add(ytitle);

        int l = 0;
        //Loop the wells for plotting
        foreach (var w in wells)
        {
          if (g != null)
          {
            TheChart.Children.Remove(g);
            TheChart.FitToView();
          }

          var axis = new Microsoft.Research.DynamicDataDisplay.Charts.HorizontalDateTimeAxis();
          TheChart.MainHorizontalAxis = axis;
          TheChart.MainVerticalAxis = new Microsoft.Research.DynamicDataDisplay.Charts.VerticalAxis();
          //set the data source
          EnumerableDataSource<TimestampValue> ds = new EnumerableDataSource<TimestampValue>(well_Concentration[l].Items);
          ds.SetXMapping(var => axis.ConvertToDouble(var.Time));
          ds.SetYMapping(var => var.Value);
          //create the graph
          g = TheChart.AddLineGraph(ds, new Pen(Brushes.Black, 3), new PenDescription(w.ID));
         //create a filename
          outfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Dfs3FileName), "Well_No" + "_" + WellNumbers[l].ToString() + "_" + dfsI.EumQuantity.ItemDescription);
          //now save to file          
          this.UpdateLayout();

          MainWindow.SaveScreen(this, outfile + ".jpg", (int)ActualWidth, (int)ActualHeight);


          //Now create the dfs0-file
          using (DFS0 dfs0 = new DFS0(outfile + ".dfs0", 1))
          {
            dfs0.FirstItem.Name = dfsI.Name;
            dfs0.FirstItem.EumItem = dfsI.EumItem;
            dfs0.FirstItem.EumUnit = dfsI.EumUnit;
            dfs0.FirstItem.ValueType = dfsI.ValueType;

            int t = 0;
            foreach (var v in well_Concentration[l].Items)
            {
              dfs0.InsertTimeStep(v.Time);
              dfs0.SetData(t, 1, v.Value);
              t++;
            }
          }

          //Now create the text-file
          using (StreamWriter sw = new StreamWriter(outfile + ".txt", false))
          {
            foreach (var v in well_Concentration[l].Items)
            {
              sw.WriteLine(v.Time + "; " + v.Value);
            }
          }
          l++;
        }
        mShe.Dispose();
        dfs.Dispose();
        PlotsMade = true;
      }
    }