Beispiel #1
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();
    }
Beispiel #2
0
    private void InitializeDetailedM11()
    {
      mike11Observations = new List<DetailedMike11>();

      DFS0 simdata = new DFS0(mshe.Files.DetailedTimeSeriesM11);
      Dictionary<string, DFS0> ObsCache= new Dictionary<string,DFS0>();


      foreach (var obs in mshe.Input.MIKESHE_FLOWMODEL.StoringOfResults.DetailedM11TimeseriesOutput.Item_1s)
      {
        var m = new DetailedMike11() { Chainage = obs.Chainage, Name = obs.Name };

        m.Branch = mshe.River.network.GetBranch(obs.BranchName, obs.Chainage);

        if (m.Branch != null)
        {
          m.Location = m.Branch.GetPointAtChainage(obs.Chainage);
          var item = simdata.Items.FirstOrDefault(i => i.Name == m.Name);

          if (item != null)
            m.Simulation = simdata.GetTimeSpanSeries(item.ItemNumber);


          if (obs.InclObserved == 1)
          {
            DFS0 obsdata;
            if (!ObsCache.TryGetValue(obs.TIME_SERIES_FILE.FILE_NAME, out obsdata))
            {
              obsdata = new DFS0(obs.TIME_SERIES_FILE.FILE_NAME);
              ObsCache.Add(obs.TIME_SERIES_FILE.FILE_NAME, obsdata);
            }
              m.Observation = obsdata.GetTimeSpanSeries(obs.TIME_SERIES_FILE.ITEM_NUMBERS);
          }
          mike11Observations.Add(m);
        }
      }
      simdata.Dispose();
      foreach (var obsdata in ObsCache.Values)
        obsdata.Dispose();
    }
Beispiel #3
0
    public void SaveToMike11(string m11name)
    {
      NWK11File nwk = new NWK11File();

      double x0 = double.MaxValue;
      double x1 = double.MinValue;
      double y0 = double.MaxValue;
      double y1 = double.MinValue;

      int pointcount =1;

      //This is necessary because it fails if DHI.CrossSection.Dll tries to load UFS.dll
      DFS0 d = new DFS0(@"v");
      d.Dispose();



      CrossSectionCollection csc = new CrossSectionCollection();
      csc.Connection.FilePath = Path.ChangeExtension(m11name, ".xns11");
      csc.Connection.Bridge = csc.Connection.AvailableBridges[0];


      foreach (var b in Branches)
      {
        var newbranch = nwk.MIKE_11_Network_editor.BRANCHES.AddBranch();
        newbranch.definitions.Par1 = b.Name;

        double lastchainage = 0;
        for (int i = 0; i < b.Links.Count; i++)
        {
          var bp = nwk.MIKE_11_Network_editor.POINTS.AddPoint();
          bp.Par1 = pointcount;
          bp.Par2 = b.Links[i].UpstreamNode.Location.X;
          bp.Par3 = b.Links[i].UpstreamNode.Location.Y;

          x0 = Math.Min(b.Links[i].UpstreamNode.Location.X, x0);
          x1 = Math.Max(b.Links[i].UpstreamNode.Location.X, x1);
          y0 = Math.Min(b.Links[i].UpstreamNode.Location.Y, y0);
          y1 = Math.Max(b.Links[i].UpstreamNode.Location.Y, y1);

          if (i == 0)
          {
            bp.Par4 = 1;
          }
          else
          {
            bp.Par4 = 0;
            lastchainage += b.Links[i - 1].Length;
          }
          bp.Par5 = lastchainage;
          newbranch.points.AddValue(pointcount);


          //CrossSections

          CrossSection cs = new CrossSection(new DHI.Generic.RouteLocation(b.Name, "Topo-id", lastchainage, b.Links[i].pfslink.Par5));
          if (b.Links[i].Xsec != null && b.Links[i].Xsec.TypeNo == 4)
          {
            double bottom = double.MaxValue;
            int bottomindex = 0;
            int index = 0;
            foreach (var dat in b.Links[i].Xsec.Datas)
            {
              var z = dat.GetValue(1);
              if (z < bottom)
              {
                bottom = z;
                bottomindex = index;
              }
              cs.Points.AddPoint(new CrossSectionPoint(dat.GetValue(0), z));
              index++;
            }

            if (bottom == 0)
              cs.Datum = b.Links[i].UpstreamNode.pfsnode.InvertLevel;

            cs.Points.SetMarkerAt(1, 0);
            cs.Points.SetMarkerAt(3, b.Links[i].Xsec.Datas.Count - 1);
            cs.Points.SetMarkerAt(2, bottomindex);
            csc.Add(cs);
          }
          else if (b.Links[i].pfslink.Par4 == 1) //Assume circular
          {
            cs.Geometry = DHI.Mike1D.CrossSections.Geometry.ClosedCircular;
            cs.SetDiameter(b.Links[i].pfslink.Par7);
            cs.Datum = b.Links[i].UpstreamNode.pfsnode.InvertLevel;
            csc.Add(cs);
          }

          if (i == b.Links.Count - 1)
          {
            lastchainage += b.Links[i].Length;

            var connectionlink = b.Links[i].DownstreamNode.Links.FirstOrDefault(l => l.UpstreamNode == b.Links[i].DownstreamNode);
            if (connectionlink != null) //Create a connection
            {
              var branch = Branches.Single(br => br.Links.Contains(connectionlink));
              newbranch.connections.Par3 = branch.Name;
              newbranch.connections.Par4 = branch.GetChainage(connectionlink);
            }
            pointcount++;
            var bpn = nwk.MIKE_11_Network_editor.POINTS.AddPoint();
            bpn.Par1 = pointcount;
            bpn.Par2 = b.Links[i].DownstreamNode.Location.X;
            bpn.Par3 = b.Links[i].DownstreamNode.Location.Y;
            bpn.Par4 = 0;
            bpn.Par5 = lastchainage;
            newbranch.points.AddValue(pointcount);
          }
          pointcount++;
        }
        newbranch.definitions.Par3 = 0;
        newbranch.definitions.Par4 = (int) lastchainage;
        newbranch.definitions.Par6 = 1000;
        newbranch.definitions.Par7 = 3;
      }

      nwk.MIKE_11_Network_editor.DATA_AREA.x0 =(int) (x0- 0.1* (x1-x0));
      nwk.MIKE_11_Network_editor.DATA_AREA.x1 = (int)(x1 + 0.1 * (x1 - x0));
      nwk.MIKE_11_Network_editor.DATA_AREA.y0 = (int)(y0 - 0.1 * (y1 - y0));
      nwk.MIKE_11_Network_editor.DATA_AREA.y1 = (int)(y1 + 0.1 * (y1 - y0));

      nwk.FileName = m11name;
      nwk.Save();
      csc.Connection.Save();


    }
        /// <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();
      }
    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();
    }