public void PreProcessTest()
 {
   Model m = new Model(@"..\..\..\..\TestData\TestModel.she");
   m.Run(false,true);
   Console.WriteLine("simulation finished");
   Thread.Sleep(2000);
 }
Ejemplo n.º 2
0
    public void GetIndexTest()
    {
      Model mshe = new Model(@"..\..\..\TestData\TestModelDemo.she");

      int Column;
      int Row;

      Assert.IsTrue(mshe.GridInfo.TryGetIndex(11,11,out Column, out Row));
      Assert.AreEqual(1, Column);
      Assert.AreEqual(1, Row);

      Assert.IsTrue(mshe.GridInfo.TryGetIndex(19, 19, out Column, out Row));
      Assert.AreEqual(1, Column);
      Assert.AreEqual(1, Row);

      mshe.Dispose();

      DFS3 heads = new DFS3(@"..\..\..\TestData\TestModelDemo.she - Result Files\TestModelDemo_3DSZ.dfs3");

      Assert.AreEqual(1, heads.GetColumnIndex(11));

      Assert.AreEqual(2, heads.GetColumnIndex(19));

      heads.Dispose();
      

    }
Ejemplo n.º 3
0
    static void Main(string[] args)
    {
      Model M = new Model(args[0]);

      List<double> MingroundWaterLevels = new List<double>();
      for (int i = 1; i < args.Count(); i++)
        MingroundWaterLevels.Add(double.Parse(args[i]));

      DFS2 CustomPhreaticHead = new DFS2(Path.Combine(M.Files.ResultsDirectory, "CustomPhreaticHeads.dfs2"), MingroundWaterLevels.Count);
      CustomPhreaticHead.NumberOfRows = M.GridInfo.NumberOfRows;
      CustomPhreaticHead.NumberOfColumns = M.GridInfo.NumberOfColumns;
      CustomPhreaticHead.XOrigin = M.GridInfo.XOrigin;
      CustomPhreaticHead.YOrigin = M.GridInfo.YOrigin;
      CustomPhreaticHead.GridSize = M.GridInfo.GridSize;
      CustomPhreaticHead.TimeOfFirstTimestep = M.Results.Heads.TimeSteps.First();
      CustomPhreaticHead.TimeStep = M.Results.Heads.TimeSteps[1].Subtract(M.Results.Heads.TimeSteps[0]);
      CustomPhreaticHead.DeleteValue = M.Results.DeleteValue;


      for (int l = 0; l < MingroundWaterLevels.Count; l++)
      {
        CustomPhreaticHead.Items[l].Name = MingroundWaterLevels[l].ToString();
        CustomPhreaticHead.Items[l].EumItem = DHI.Generic.MikeZero.eumItem.eumIHeadElevation;
        CustomPhreaticHead.Items[l].EumUnit = DHI.Generic.MikeZero.eumUnit.eumUmeter;
      }

      var LowerLevel = M.GridInfo.LowerLevelOfComputationalLayers.Data;

      //Time loop
      for (int t = 0; t < M.Results.Heads.TimeSteps.Count; t++)
      {
        var heads = M.Results.Heads.TimeData(t);

        for (int l = 0; l < MingroundWaterLevels.Count; l++)
        {
          DenseMatrix phreatichead = (DenseMatrix) heads[0].Clone();

          for (int i = 0; i < CustomPhreaticHead.NumberOfRows; i++)
            for (int j = 0; j < CustomPhreaticHead.NumberOfColumns; j++)
            {
              if (heads[0][i, j] != CustomPhreaticHead.DeleteValue)
              {
                for (int k = M.GridInfo.NumberOfLayers - 1; k >= 0; k--)
                {
                  if (heads[k][i, j] >= LowerLevel[k][i, j] + MingroundWaterLevels[l])
                  {
                    phreatichead[i, j] = heads[k][i, j];
                    break;
                  }
                }
              }
            }

          CustomPhreaticHead.SetData(t, l + 1, phreatichead);
        }
      }
      CustomPhreaticHead.Dispose();
      M.Dispose();
    }
Ejemplo n.º 4
0
 private void RunNext(Model mshe)
 {
   if (ParameterSets.Count > 0)
   {
     ParameterSets.Pop();
     mshe.Run(true, true);
   }
 }
Ejemplo n.º 5
0
    public void DetailedM11Test()
    {
      var _karup = new Model(TestPath + @"Karup_Example_DemoMode1.she").Results;

      var m11obs = _karup.Mike11Observations;
      Assert.AreEqual(1, m11obs.Count);

      var scaled = TSTools.ChangeZoomLevel(m11obs.First().Simulation, TimeStepUnit.Month, true);

    }
Ejemplo n.º 6
0
    public void TestMethod1()
    {

      Model mshe = new Model(@"D:\Work\HydroNumerics\MikeSheTools\TestData\Karup_Example_DemoMode.SHE");

      



    }
Ejemplo n.º 7
0
 public void BigTest()
 {
   var _karup = new Model(@"E:\dhi\data\dkm\dk2\result\DK2_v3_gvf_PT_100p_24hr.she").Results;
   Stopwatch sw = new Stopwatch();
   sw.Start();
   var m11obs = _karup.Mike11Observations;
   sw.Stop();
   Assert.AreEqual(201, m11obs.Count);
   Assert.AreEqual(200, m11obs.Where(sim=>sim.Simulation!=null).Count());
   _karup.Dispose();
 }
Ejemplo n.º 8
0
    public void PostProcess()
    {
      Runner = new Process();
      Runner.StartInfo.FileName = PostProcessBatFile;
      Runner.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(file.FileName);
      Runner.Start();
      Runner.WaitForExit();
      
      Model mshe = new Model(MsheFileName);
      Status = OutputGenerator.KSTResults(mshe);
      mshe.Dispose();

    }
     public void Initialize(IArgument[] properties)
    {
      MsheOrg.Initialize(properties);

      string mshefilename = System.IO.Path.Combine(properties.First(a => a.Key == "SetupPath").Value, properties.First(a => a.Key == "SetupFileName").Value);

      Model mshe = new Model(mshefilename);

      List<double> InnerXValues= new List<double>();
      List<double> InnerYValues = new List<double>();

      int k=0;
        for(int j=0;j<mshe.GridInfo.NumberOfColumns;j++)
          for (int i = 0; i < mshe.GridInfo.NumberOfRows; i++)
          {
          if (mshe.GridInfo.ModelDomainAndGrid.Data[i, j] == 1)
          {
            InnerXValues.Add(mshe.GridInfo.GetXCenter(j));
            InnerYValues.Add(mshe.GridInfo.GetYCenter(i));
            InnerIdeces.Add(k);
            k++;
          }
          else if (mshe.GridInfo.ModelDomainAndGrid.Data[i, j] == 2)
            k++;
        }


        DHI.OpenMI.MikeShe.BaseGridElementSet NewBaseGrid = new DHI.OpenMI.MikeShe.BaseGridElementSet(new DHI.MikeShe.Engine.BaseGrid(InnerXValues.Count, InnerXValues.ToArray(), InnerYValues.ToArray(), mshe.GridInfo.GridSize,0));

      mshe.Dispose();
      for (int i = 0; i < MsheOrg.OutputExchangeItemCount; i++)
      {
        var org = MsheOrg.GetOutputExchangeItem(i);

        if (org.ElementSet.ID == "BaseGrid")
        {
          OutputExchangeItem onew = new OutputExchangeItem();
          onew.Quantity = org.Quantity;
          onew.ElementSet = NewBaseGrid;
          for (int j = 0; j < org.DataOperationCount; j++)
          {
            onew.AddDataOperation(org.GetDataOperation(j));
          }
          OutputExchangeItems.Add(onew);
        }
        else
        {
          OutputExchangeItems.Add(org);
        }
      }
    }
Ejemplo n.º 10
0
      /// <summary>
      /// Reads in the wells defined in detailed timeseries input section
      /// </summary>
      /// <param name="Mshe"></param>
      public static IEnumerable<IWell> ReadInDetailedTimeSeries(Model Mshe)
      {
        MikeSheWell CurrentWell;
        IIntake CurrentIntake;
        TSObject _tso = null;

        foreach (var dt in Mshe.Input.MIKESHE_FLOWMODEL.StoringOfResults.DetailedTimeseriesOutput.Item_1s)
        {
          CurrentWell = new MikeSheWell(dt.Name);
          CurrentWell.X = dt.X;
          CurrentWell.Y = dt.Y;
          CurrentWell.UsedForExtraction = false;
          CurrentIntake = CurrentWell.AddNewIntake(1);
          Screen sc = new Screen(CurrentIntake);
          sc.DepthToTop = dt.Z;
          sc.DepthToBottom = dt.Z;

          CurrentWell.Row = Mshe.GridInfo.GetRowIndex(CurrentWell.X);
          CurrentWell.Column = Mshe.GridInfo.GetColumnIndex(CurrentWell.Y);

          CurrentWell.Terrain = Mshe.GridInfo.SurfaceTopography.Data[CurrentWell.Row, CurrentWell.Column];

          //Read in observations if they are included
          if (dt.InclObserved == 1)
          {
            if (_tso == null || _tso.Connection.FilePath != dt.TIME_SERIES_FILE.FILE_NAME)
            {
              _tso = new TSObjectClass();
              _tso.Connection.FilePath = dt.TIME_SERIES_FILE.FILE_NAME;
              _tso.Connection.Open();
            }

            //Loop the observations and add
            for (int i = 1; i <= _tso.Time.NrTimeSteps; i++)
            {
              CurrentIntake.HeadObservations.Items.Add(new TimestampValue((DateTime)_tso.Time.GetTimeForTimeStepNr(i), (float)_tso.Item(dt.TIME_SERIES_FILE.ITEM_NUMBERS).GetDataForTimeStepNr(i)));
            }
          }
          yield return CurrentWell;
        }
      }
Ejemplo n.º 11
0
    private JupiterViewModel jvm; //Necessary to change between well list


    public MikeSheViewModel(Model Mshe, JupiterViewModel JVM)
    {
      jvm = JVM;
      mshe = Mshe;
      Layers = new ObservableCollection<MikeSheLayerViewModel>();
      ScreensToMove = new ObservableCollection<MoveToChalkViewModel>();
      ScreensAboveTerrain = new ObservableCollection<MoveToChalkViewModel>();
      ScreensBelowBottom = new ObservableCollection<MoveToChalkViewModel>();

      for (int i = 0; i < mshe.GridInfo.NumberOfLayers; i++)
      {
        
        MikeSheLayerViewModel msvm = new MikeSheLayerViewModel(i, mshe.GridInfo.NumberOfLayers);
//        if(mshe.Input.MIKESHE_FLOWMODEL.SaturatedZone.TypeOfVerDiscr==2)
          msvm.DisplayName = mshe.Input.MIKESHE_FLOWMODEL.SaturatedZone.CompLayersSZ.Layer_2s[mshe.GridInfo.NumberOfLayers - 1 - i].Name;
  //      else 
    //      msvm.DisplayName = "Computational layer 
        Layers.Add(msvm);
      }
      Layers.First().IsChalkLayer = true;

      Chalks = new SortedDictionary<string, string>();
      Clays = new SortedDictionary<string, string>();
      string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
      var doc = XDocument.Load(Path.Combine(dir,"LithologyGroups.xml")).Element("LithologyGroups");

      foreach (var el in doc.Element("Chalks").Elements())
        Chalks.Add(el.Value, "");

      foreach (var el in doc.Element("Clays").Elements())
        Clays.Add(el.Value, "");
 
      foreach(var msvm in Layers)
        msvm.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(msvm_PropertyChanged);


      RaisePropertyChanged("Layers");

      ShowExtractionWells = true;
    }
Ejemplo n.º 12
0
    public ExtractData(string FileName, string Dfs3FileName)
    {
      mShe = new Model(FileName);

      DFS3 dfs = new DFS3(Dfs3FileName);

      List<List<double>> wells = new List<List<double>>();

      foreach (var W in mShe.ExtractionWells)
      {
        wells.Add(new List<double>());
      }

      for (int i = 0; i < dfs.NumberOfTimeSteps; i++ )
      {
        for (int j = 0; j < mShe.ExtractionWells.Count; j++)
        {
          var w = mShe.ExtractionWells[j];

          wells[j].Add(dfs.GetData(i, 1)[w.Row, w.Column, w.Layer]);
        }
      }
    }
Ejemplo n.º 13
0
    public void Mike11ObservationsTest()
    {
      Model Mshe = new Model(@"D:\DK_information\M11_omr4-7\XY_M11_detailed\Mike11\DK5_2013_inv.she");
      List<DetailedMike11> actual;
      actual = Mshe.Results.Mike11Observations;

      System.Data.DataTable dt = new System.Data.DataTable();

      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Branch", typeof(string));
      dt.Columns.Add("Chainage", typeof(double));

      using (HydroNumerics.Geometry.Shapes.ShapeWriter sw = new Geometry.Shapes.ShapeWriter(@"d:\temp\detailedm11Points_DK5.shp"))
      {
        foreach (var m11 in actual)
        {
          var data = dt.NewRow();
          data[0]= m11.Name;
          data[1] = m11.Branch;
          data[2]=m11.Chainage;
          sw.Write(new Geometry.GeoRefData() { Geometry = m11.Location, Data = data });
        }
      }
    }
Ejemplo n.º 14
0
		public static void Main(string[] args)
		{
      DFS.DFS3.MaxEntriesInBuffer =10;
      bool stay = true;

      while (stay)
      {
        stay = false;
        foreach (var v in System.Diagnostics.Process.GetProcesses())
        {
          if (v.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
          {
            if (v.ProcessName.ToLower().StartsWith("ls.exe"))
            {
              if (v.UserProcessorTime > TimeSpan.FromSeconds(0.2))
              {
                stay = true;
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30));
                break;
              }
            }
          }
        }
      }

      MikeSheGridInfo _grid = null;
      Results _res = null;
      try
      {
        string ObsFileName;

        //Input is a -she-file and an observation file
        if (args.Length == 2)
        {
          Model MS = new Model(args[0]);
          _grid = MS.GridInfo;
          _res = MS.Results;
          ObsFileName = args[1];
        }
        //Input is an .xml-file
        else if (args.Length == 1)
        {
          Configuration cf = Configuration.ConfigurationFactory(args[0]);

          _grid = new MikeSheGridInfo(cf.PreProcessedDFS3, cf.PreProcessedDFS2);

          if (cf.HeadItemText != null)
            _res = new Results(cf.ResultFile, _grid, cf.HeadItemText);
          else
            _res = new Results(cf.ResultFile, _grid);

          if (_res.Heads == null)
            throw new Exception("Heads could not be found. Check that item: \"" + _res.HeadElevationString + "\" exists in + " + cf.ResultFile);

          if (_grid.NumberOfLayers != _res.Heads.TimeData(0).LayerCount)
            throw new Exception("Number of layers in preprocessed files do not match number of layers in resultfile: " + cf.ResultFile);

          ObsFileName = cf.ObservationFile;
        }
        else
        {
          OpenFileDialog Ofd = new OpenFileDialog();

          Ofd.Filter = "Known file types (*.she)|*.she";
          Ofd.ShowReadOnly = true;
          Ofd.Title = "Select a MikeShe setup file";


          if (DialogResult.OK == Ofd.ShowDialog())
          {
            Model MS = new Model(Ofd.FileName);
            _grid = MS.GridInfo;
            _res = MS.Results;
            Ofd.Filter = "Known file types (*.txt)|*.txt";
            Ofd.ShowReadOnly = true;
            Ofd.Title = "Select a LayerStatistics setup file";

            if (DialogResult.OK == Ofd.ShowDialog())
              ObsFileName = Ofd.FileName;
            else
              return;
          }
          else
            return;
        }

        InputOutput IO = new InputOutput(_grid.NumberOfLayers);

        string _baseOutPutFileName;
        string path = Path.GetDirectoryName(ObsFileName);
        string FileName = Path.GetFileNameWithoutExtension(ObsFileName);
        _baseOutPutFileName = Path.Combine(path, FileName);


        //Read in the wells
        Dictionary<string, MikeSheWell> Wells = IO.ReadFromLSText(ObsFileName);

        int NLay = _grid.NumberOfLayers;
        double[] ME = new double[NLay];
        double[] RMSE = new double[NLay];
        int[] ObsUsed = new int[NLay];
        int[] ObsTotal = new int[NLay];

        //Initialiserer
        for (int i = 0; i < NLay; i++)
        {
          ME[i] = 0;
          RMSE[i] = 0;
          ObsUsed[i] = 0;
          ObsTotal[i] = 0;
        }

        //Only operate on wells within the mikeshe area
        var SelectedWells = _grid.SelectByMikeSheModelArea(Wells.Values);


        StreamWriter sw = new StreamWriter(_baseOutPutFileName + "_observations.txt");
        StreamWriter swell = new StreamWriter(_baseOutPutFileName + "_wells.txt");

        sw.WriteLine("OBS_ID\tX\tY\tDepth\tLAYER\tOBS_VALUE\tDATO\tSIM_VALUE_INTP\tSIM_VALUE_CELL\tME\tME^2\t#DRY_CELLS\t#BOUNDARY_CELLS\tCOLUMN\tROW\tCOMMENT\t#OBSInWell");
        swell.WriteLine("OBS_ID\tX\tY\tDepth\tLAYER\tME\tME^2");


        //Loops the wells that are within the model area and set the layer or depth
        foreach (MikeSheWell W in SelectedWells)
        {
          //Get layer or depth
          if (W.Layer == -3)
            W.Layer = _grid.GetLayerFromDepth(W.Column, W.Row, W.Depth.Value);
          else
            W.Depth = _grid.SurfaceTopography.Data[W.Row, W.Column] - (_grid.LowerLevelOfComputationalLayers.Data[W.Row, W.Column, W.Layer] + 0.5 * _grid.ThicknessOfComputationalLayers.Data[W.Row, W.Column, W.Layer]);
        }

        System.Diagnostics.Stopwatch swm = new System.Diagnostics.Stopwatch();

        swm.Start();


        foreach (Observation TSE in SelectedWells.Where(var => var.Layer >= 0).SelectMany(var2 => var2.Intakes).SelectMany(var3 => ((LsIntake)var3).Observations).OrderBy(var4 => var4.Time))
        {
          var M = _res.PhreaticHead.TimeData(TSE.Time)[TSE.Well.Layer];
          TSE.SimulatedValueCell= M[TSE.Well.Row, TSE.Well.Column];
          int DryCells = 0;
          int BoundaryCells = 0;

          //Interpolates in the matrix
          TSE.InterpolatedValue = _grid.Interpolate(TSE.Well.X, TSE.Well.Y, TSE.Well.Layer, M, out DryCells, out BoundaryCells);

          TSE.DryCells = DryCells;
          TSE.BoundaryCells = BoundaryCells;
        }
        swm.Stop();


        //Loops the wells that are within the model area
        foreach (MikeSheWell W in SelectedWells)
        {
          double MEWell = 0;
          double RMSWell = 0;
          int UsedObsInWells = 0;

          //Calculate results
          foreach (LsIntake I in W.Intakes)
          {
            foreach (Observation TSE in I.Observations.OrderBy(var=>var.Time))
            {
              StringBuilder ObsString = new StringBuilder();
              string Comment = "";
              double? MECell = null;
              double? RMSCell = null;

              if (W.Layer < 0)
                Comment = "Depth is above the surface or below bottom of the model domain";
              else
              {

                MECell = TSE.Value - TSE.InterpolatedValue;
                RMSCell = Math.Pow(MECell.Value, 2);

                if (TSE.SimulatedValueCell == _res.DeleteValue)
                {
                  Comment = "Cell is dry";
                }
                else
                {
                  UsedObsInWells++;
                  MEWell += MECell.Value;
                  RMSWell += RMSCell.Value;
                }
              }
              ObsString.Append(W.ID + "\t");
              ObsString.Append(W.X + "\t");
              ObsString.Append(W.Y + "\t");
              ObsString.Append(W.Depth + "\t");

              if (W.Layer >= 0)
                ObsString.Append((_grid.NumberOfLayers - W.Layer) + "\t");
              else
                ObsString.Append((W.Layer) + "\t");
              ObsString.Append(TSE.Value + "\t");
              ObsString.Append(TSE.Time.ToString("dd-MM-yyyy") + "\t");
              ObsString.Append(TSE.InterpolatedValue + "\t");
              ObsString.Append(TSE.SimulatedValueCell + "\t");
              ObsString.Append(MECell + "\t");
              ObsString.Append(RMSCell + "\t");
              ObsString.Append(TSE.DryCells + "\t");
              ObsString.Append(TSE.BoundaryCells + "\t");
              ObsString.Append(W.Column + "\t");
              ObsString.Append(W.Row + "\t");
              ObsString.Append(Comment + "\t");
              ObsString.Append(I.Observations.Count);
              sw.WriteLine(ObsString.ToString());
            }
          }

          if (UsedObsInWells > 0)
          {
            MEWell /= UsedObsInWells;
            RMSWell /= UsedObsInWells;
            ME[W.Layer] += MEWell;
            RMSE[W.Layer] += RMSWell;
            ObsUsed[W.Layer]++;
          }

          if (W.Layer>=0)
            ObsTotal[W.Layer]++;

          //Write for each well
          StringBuilder WellString = new StringBuilder();
          WellString.Append(W.ID + "\t");
          WellString.Append(W.X + "\t");
          WellString.Append(W.Y + "\t");
          WellString.Append(W.Depth + "\t");
          if (W.Layer >= 0)
          {
            WellString.Append((_grid.NumberOfLayers - W.Layer) + "\t");
            WellString.Append(MEWell + "\t");
            WellString.Append(RMSWell+ "\t");
          }
          else
            WellString.Append((W.Layer) + "\t" + "\t" + "\t");
          swell.WriteLine(WellString.ToString());
        }
        sw.Dispose();

        swell.Dispose();



        //Divide with the number of observations.
        for (int i = 0; i < NLay; i++)
        {
          ME[i] = ME[i] / ObsUsed[i];
          RMSE[i] = Math.Pow(RMSE[i] / ObsUsed[i], 0.5);
        }

        //Write output
        IO.WriteLayers(ME, RMSE, ObsUsed, ObsTotal);

      }

      catch (Exception e)
      {
        MessageBox.Show("An error has occurred in LayerStatistics  " + e.Message);
      }

      finally
      {
        //Dispose MikeShe
        _grid.Dispose();
        _res.Dispose();
      }
		}
Ejemplo n.º 15
0
    public void DetailedM11Test()
    {
      var actual = new Model(@"F:\dhi\data\dkm\dk1\result\DK1_R201401_m11_produktion.she");

      var obs = actual.Results.Mike11Observations.Where(m11 => m11.Observation != null);

      using (HydroNumerics.Geometry.Shapes.ShapeWriter sw = new Geometry.Shapes.ShapeWriter(@"d:\temp\obs.shp"))
      {
        foreach (var item in obs)
        {

          sw.WritePointShape(item.Location.X, item.Location.Y);
        }
      }
    }
Ejemplo n.º 16
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];
        string BaseFileName = System.IO.Path.ChangeExtension(Dfs3FileName, "");

        int[] TimeSteps = Dfs3plotdfs0.MainWindow.ParseString(TimeStepsAsString, 0, dfs.NumberOfTimeSteps - 1);
        int[] Layers = Dfs3plotdfs0.MainWindow.ParseString(LayersAsString, 0, dfs.NumberOfLayers - 1);

        //Set graph headers
        Header.Content = dfsI.Name;
        Unit.Content = dfsI.EumQuantity.UnitAbbreviation;

        //Give plot the same scale as the dfs grid
        plotter.Width = plotter.Height * ((double)dfs.NumberOfColumns) / (double)dfs.NumberOfRows;

        //Plot the extraction wells
        EnumerableDataSource<MikeSheWell> ds = new EnumerableDataSource<MikeSheWell>(mShe.ExtractionWells);
        ds.SetXMapping(var => var.X);
        ds.SetYMapping(var => var.Y);
        var point = new Microsoft.Research.DynamicDataDisplay.PointMarkers.CirclePointMarker();
        point.Size = 10;
        point.Pen = new Pen(Brushes.Black, 3);
        plotter.AddLineGraph(ds, null, point, null);

        //Now loop, first on time steps then on layers
        foreach (int T in TimeSteps)
        {
          foreach (int L in Layers)
          {
            Header2.Content = "Time: " + dfs.TimeSteps[T].ToShortDateString() + ", Layer: " + L; 
            var M = dfs.GetData(T, ItemNumber)[L];
            NaiveColorMap nc = new NaiveColorMap();
            M.Transpose(); //Need to transpose
            nc.Data = M.ToArray();
            M.Transpose(); //Transpose back as this is a reference to data held in the buffer
            nc.Palette = Microsoft.Research.DynamicDataDisplay.Common.Palettes.UniformLinearPalettes.RedGreenBluePalette;
            var bmp = nc.BuildImage();
            image.Source = bmp;

            //Set the color scale
            paletteControl.Palette = nc.Palette;
            paletteControl.Range = nc.Data.GetMinMax();
            
            //Set the size
            var visible = new Microsoft.Research.DynamicDataDisplay.DataRect(dfs.XOrigin, dfs.YOrigin, dfs.GridSize*dfs.NumberOfColumns, dfs.GridSize * dfs.NumberOfRows);            
            ViewportPanel.SetViewportBounds(image, visible);
            plotter.Visible = visible;

            //Write the bitmap
            this.UpdateLayout();
            string fname = BaseFileName + "TimeStep_" +T + "_Layer_" + L;
            Dfs3plotdfs0.MainWindow.SaveScreen(this, fname + ".jpg", (int)ActualWidth, (int)ActualHeight);

            //Now write the ascii grid
            using (StreamWriter sw = new StreamWriter(fname + ".asc"))
            {
              sw.Write(dfs.GetASCIIGrid(T, ItemNumber, L)); 
            }
          }
        }
      }
    }
Ejemplo n.º 17
0
    static void Main(string[] args)
    {
      string DFS3FileName = args.FirstOrDefault(var => Path.GetExtension(var).Equals(".dfs3"));
      var SheFiles = args.Where(var => Path.GetExtension(var).Equals(".she"));

      if (DFS3FileName == null)
      {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Known file types (*.dfs3)|*.dfs3"; //Only open .dfs2-files
        ofd.Title = "Select a .dfs2-file with grid codes marking the areas where timeseries should be aggregated";
        if (ofd.ShowDialog() == DialogResult.OK)
          DFS3FileName = ofd.FileName;
        else
          return;
      }
      if (SheFiles.Count() == 0)
      {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Known file types (*.she)|*.she"; //Only open .asc-files
        ofd.Title = "Select the she-files with the scenarios";
        ofd.Multiselect = true;
        if (ofd.ShowDialog() == DialogResult.OK)
          SheFiles = ofd.FileNames;
        else
          return;
      }

      DFS3 GridFile = new DFS3(DFS3FileName);

      foreach (var file in SheFiles)
      {
        Model M = new Model(file);
        ITSObject timeseries = new TSObjectClass();
        timeseries.Time.AddTimeSteps(M.Results.PhreaticHead.TimeSteps.Count());

        
        for (int t = 0; t < M.Results.PhreaticHead.TimeSteps.Count(); t++)
        {
              for (int k=0;k<GridFile.NumberOfLayers;k++)
              {
        Dictionary<int,List<double>> AggregatedValues = new Dictionary<int,List<double>>();
          for (int i =0;i< GridFile.NumberOfRows;i++)
          {
            for (int j=0;j<GridFile.NumberOfColumns;j++)
            {
              int gridcode = (int)GridFile.GetData(0,1)[i,j,k];
              List<double> Values;
              if(!AggregatedValues.TryGetValue(gridcode, out Values))
              {
                Values = new List<double>();
                AggregatedValues.Add(gridcode,Values);
              }

              Values.Add(M.Results.PhreaticHead.TimeData(t)[i,j,k]);
              }
            }
                foreach(var kvp in AggregatedValues)
                {

                }
          }



          timeseries.Time.SetTimeForTimeStepNr(t,M.Results.PhreaticHead.TimeSteps[t]);
          timeseries.Item(0).SetDataForTimeStepNr(t,

        }
        



      }
    }
Ejemplo n.º 18
0
 /// <summary>
 /// Use this when the filenames object and the GridInfo object have already been constructed
 /// </summary>
 /// <param name="fileNames"></param>
 /// <param name="Grid"></param>
 internal Results(Model Mshe)
 {
   mshe = Mshe;
   _grid = mshe.GridInfo;
   if (System.IO.File.Exists(Mshe.Files.SZ3DFileName))
   {
     Initialize3DSZ(mshe.Files.SZ3DFileName);
     Initialize3DSZFlow(mshe.Files.SZ3DFlowFileName);
   }
 }
Ejemplo n.º 19
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;
      }
    }
Ejemplo n.º 20
0
    public void FileBySachin()
    {

      Model m = new Model(@"..\..\..\testdata\sachin\PRES_ECHAM-ICTP.she");


    }
Ejemplo n.º 21
0
 public static void MyClassInitialize(TestContext testContext)
 {
   mshe = new Model(@"..\..\..\..\TestData\Karup_Example_DemoMode.SHE");
 }
Ejemplo n.º 22
0
    public Controller(Configuration Config)
    {
      _config = Config;
      _she = new Model(_config.SheFile);

    }
Ejemplo n.º 23
0
    public static string KSTResults(Model mshe)
    {

      string returnstring="";
      double[] percentiles = new double[] { 0.1, 0.5, 0.9, 0.95 };

      if (!File.Exists(Path.GetFullPath(mshe.Files.SZ3DFileName)))
      {
        returnstring += "Could not find:" + Path.GetFullPath(mshe.Files.SZ3DFileName); 
      }
      else
      {
        var dfs = DfsFileFactory.OpenFile(mshe.Files.SZ3DFileName);

        //Find first time step to use by skipping the firstyear
        int firsttimestep = 0;

        while (dfs.TimeOfFirstTimestep.Year+5 == dfs.TimeSteps[firsttimestep].Year)
          firsttimestep++;

        List<int> timesteps= new List<int>();
        for (int j = firsttimestep; j < dfs.NumberOfTimeSteps; j++)
          timesteps.Add(j);


        string filename = Path.Combine(mshe.Files.ResultsDirectory, "SZ3D_percentiles.dfs3");
        var dfsout = DfsFileFactory.CreateFile(filename, percentiles.Count());
        dfsout.CopyFromTemplate(dfs);
        dfs.Percentile(1, timesteps.ToArray(), dfsout, percentiles, 400);
        dfsout.Dispose();

        for (int i = 1; i <= 12; i++)
        {
          //Get the timesteps
          timesteps.Clear();

          for (int j = firsttimestep; j < dfs.TimeSteps.Count; j++)
            if (dfs.TimeSteps[j].Month == i)
              timesteps.Add(j);

          if (timesteps.Count > 3)
          {
            string filename2 = Path.Combine(mshe.Files.ResultsDirectory, "SZ3D_percentiles_Month_" + i + ".dfs3");
            var dfsoutm = DfsFileFactory.CreateFile(filename2, percentiles.Count());
            dfsoutm.CopyFromTemplate(dfs);
            dfs.Percentile(1, timesteps.ToArray(), dfsoutm, percentiles, 400);
            dfsoutm.Dispose();
          }
        }
        dfs.Dispose();
      }

      if (!File.Exists(Path.GetFullPath(mshe.Files.SZ2DFileName)))
      {
        returnstring += "\n Could not find:" + Path.GetFullPath(mshe.Files.SZ2DFileName); 
      }
      else
      {
        var dfs = DfsFileFactory.OpenFile(mshe.Files.SZ2DFileName);

        //Find first time step to use by skipping the firstyear
        int firsttimestep = 0;

        while (dfs.TimeOfFirstTimestep.Year + 5 == dfs.TimeSteps[firsttimestep].Year)
          firsttimestep++;

        List<int> timesteps = new List<int>();
        for (int j = firsttimestep; j < dfs.NumberOfTimeSteps; j++)
          timesteps.Add(j);


        var filename = Path.Combine(mshe.Files.ResultsDirectory, "Phreatic_percentiles.dfs2");
        var dfsout = DfsFileFactory.CreateFile(filename, percentiles.Count());
        dfsout.CopyFromTemplate(dfs);
        dfs.Percentile(1, timesteps.ToArray(), dfsout, percentiles, 400);
        dfsout.Dispose();

        for (int i = 1; i <= 12; i++)
        {
          //Get the timesteps
          timesteps.Clear();

          for (int j = firsttimestep; j < dfs.TimeSteps.Count; j++)
            if (dfs.TimeSteps[j].Month == i)
              timesteps.Add(j);

          if (timesteps.Count > 3)
          {
            string filename2 = Path.Combine(mshe.Files.ResultsDirectory, "Phreatic_percentiles_Month_" + i + ".dfs2");
            var dfsoutm = DfsFileFactory.CreateFile(filename2, percentiles.Count());
            dfsoutm.CopyFromTemplate(dfs);
            dfs.Percentile(1, timesteps.ToArray(), dfsoutm, percentiles, 400);
            dfsoutm.Dispose();
          }
        }
        dfs.Dispose();
      }
      return returnstring;
    }
Ejemplo n.º 24
0
 public void KSTResultsTest()
 {
   Model mshe = new Model(@"C:\Jacob\Work\HydroNumerics\MikeSheTools\TestData\Karup_Example_DemoMode.SHE");
   OutputGenerator.KSTResults(mshe);
 }