public void TestMethod1()
 {
   DFS0 df = new DFS0(@"C:\Users\Jacob\Downloads\gridKlima20148.dfs0");
   var monthly = TSTools.ChangeZoomLevel(df.GetTimeSpanSeries(1), TimeStepUnit.Month, true);
   using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\Users\Jacob\Downloads\Monthly_20148.csv"))
   {
     sw.WriteLine("Year,Month,Precip");
   foreach(var v in monthly.Items)
     sw.WriteLine(v.Time.Year + ","+v.Time.Month+","+v.Value);
   }
 }
Beispiel #2
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);
            }
          }
        }
      }
    }
Beispiel #3
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();
    }
    public static DFSBase OpenFile(string FileName)
    {
      string FileType = Path.GetExtension(FileName).ToLower();
      DFSBase dfs;

      switch (FileType)
      {
        case ".dfs0":
          dfs = new DFS0(FileName);
          break;
        case ".dfs2":
          dfs = new DFS2(FileName);
          break;
        case ".dfs3":
          dfs = new DFS3(FileName);
          break;
        default:
          throw new Exception("Unsupported file format: " + FileType);
      }
      return dfs;
    }
Beispiel #5
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 #6
0
        public static DFSBase CreateFile(string FileName, int NumberOfItems)
        {
            string  FileType = Path.GetExtension(FileName).ToLower();
            DFSBase dfs;

            switch (FileType)
            {
            case ".dfs0":
                dfs = new DFS0(FileName, NumberOfItems);
                break;

            case ".dfs2":
                dfs = new DFS2(FileName, NumberOfItems);
                break;

            case ".dfs3":
                dfs = new DFS3(FileName, NumberOfItems);
                break;

            default:
                throw new Exception("Unsupported file format: " + FileType);
            }
            return(dfs);
        }
Beispiel #7
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();
      }
    /// <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++;
            }
          }
        }
      }
    }
    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();
    }
    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);
          }
        }
      }
    }
    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;
      }
    }
Beispiel #14
0
    static void Main(string[] args)
    {
      string TextFileName = "";
      string dfs0FileName = "";
      if (args.Length == 0)
      {
        OpenFileDialog OFD = new OpenFileDialog();
        OFD.Title = "Select a text file with discharge data";
        if (DialogResult.OK == OFD.ShowDialog())
          TextFileName = OFD.FileName;
        else
          return;

        SaveFileDialog SFD = new SaveFileDialog();
        SFD.Title = "Select a .dfs0 file or give a new name";
        SFD.Filter = "Known file types (*.dfs0)|*.dfs0";
        SFD.OverwritePrompt = false;
        if (DialogResult.OK == SFD.ShowDialog())
          dfs0FileName = SFD.FileName;
        else
          return;
      }
      else
      {
        TextFileName = args[0];
        dfs0FileName = args[1];
      }

      if (args.Length > 2 || !File.Exists(TextFileName))
      {
        if (DialogResult.Cancel ==
            MessageBox.Show("This program needs two file names as input. If the file names contain spaces the filename should be embraced by \"\". \n Are these file names correct:? \n" + TextFileName + "\n" + dfs0FileName, "Two many arguments!", MessageBoxButtons.OKCancel))
          return;
      }


      List<QStation> _stations = new List<QStation>();
      //Loop to read the Q-stations.
      using (StreamReader SR = new StreamReader(TextFileName, Encoding.Default))
      {
        string line;
        while (!SR.EndOfStream)
        {
          line = SR.ReadLine();
          if (line.Equals("*"))
          {
            QStation qs = new QStation();
            qs.ReadEntryFromText(SR);
            _stations.Add(qs);
          }
        }
      }

      DFS0 _data;
      //Append to existing file
      if (File.Exists(dfs0FileName))
      {
        _data = new DFS0(dfs0FileName);
      }
      else
      {
        //Create new .dfs0-file and list of q-stations
        using (StreamWriter SW = new StreamWriter(Path.Combine(Path.GetDirectoryName(dfs0FileName), "DetailedTimeSeriesImport.txt"), false, Encoding.Default))
        {
          int k = 1;
          _data = new DFS0(dfs0FileName, _stations.Count);

          for (int i = 0; i < _stations.Count; i++)
          {
            //Build the TSITEMS

            _data.Items[i].ValueType = DHI.Generic.MikeZero.DFS.DataValueType.Instantaneous;
            _data.Items[i].EumItem = DHI.Generic.MikeZero.eumItem.eumIDischarge;

            //Provide an ITEM name following the convention by Anker
            if (_stations[i].DmuMaalerNr != "")
              _data.Items[i].Name = _stations[i].DmuMaalerNr;
            else
              _data.Items[i].Name = _stations[i].DmuStationsNr.ToString();

            SW.WriteLine(_data.Items[i].Name + "\t" + _stations[i].UTMX + "\t" + _stations[i].UTMY + "\t" + k);
            k++;
          }
        }
      }

      DateTime LastTimeStep;
      if (_data.TimeSteps.Count==0) //We have a new file
        LastTimeStep = DateTime.MinValue;
      else      // 12 hours have been added in dfs0!
        LastTimeStep = _data.TimeSteps.Last().Subtract(new TimeSpan(12, 0, 0));
      int TSCount = _data.NumberOfTimeSteps;

      DateTime CurrentLastTimeStep = LastTimeStep;


      //Loop the stations from the text-file
      foreach (var qs in _stations.Where(var=>var.Discharge.Items.Count>0))
      {
        qs.Discharge.Sort();
        //See if the station has newer data
        if (qs.Discharge.EndTime > LastTimeStep)
        {
          Item I = _data.Items.FirstOrDefault(var => var.Name == qs.DmuMaalerNr);
          if (I == null)
            I = _data.Items.FirstOrDefault(var => var.Name == qs.DmuStationsNr.ToString());
          if (I == null)
            Console.WriteLine("DMU MÅLER Nr: " + qs.DmuMaalerNr + " eller DMU sted nr: " + qs.DmuStationsNr + " blev ikke fundet i dfs0.filen");
          else
          {
            foreach (var TSE in qs.Discharge.ItemsInPeriod(LastTimeStep, qs.Discharge.EndTime))
            {
              _data.SetData(TSE.Time.AddHours(12), I.ItemNumber, TSE.Value);
            }
          }
        }
      }
      _data.Dispose();
    }