示例#1
0
        public static void WriteHydAndQual(
            BinaryWriter outStream,
            HydraulicSim hydraulicSim,
            QualitySim qualitySim,
            long step,
            long time)
        {
            QualityNode[] qNodes = qualitySim != null ? qualitySim.NNodes : null;
            QualityLink[] qLinks = qualitySim != null ? qualitySim.NLinks : null;
            var           nodes  = hydraulicSim.Nodes;
            var           links  = hydraulicSim.Links;

            // int nNodes = nodes.Count;
            // int nLinks = links.Count;
            // int baSize = (nNodes * 3 + nLinks * 3) * sizeof(double) + sizeof(long) * 2;

            int count = 0;

            foreach (SimulationNode node  in  nodes)
            {
                outStream.Write((double)node.SimDemand);
                outStream.Write((double)node.SimHead);
                outStream.Write((double)(qualitySim != null ? qNodes[count++].Quality : 0.0));
            }

            count = 0;
            foreach (SimulationLink link  in  links)
            {
                outStream.Write((double)(link.SimStatus <= StatType.CLOSED ? 0d : link.SimFlow));
                outStream.Write((double)(link.First.SimHead - link.Second.SimHead));
                outStream.Write((double)(qualitySim != null ? qLinks[count++].GetAverageQuality(null) : 0));
            }

            outStream.Write((long)step);
            outStream.Write((long)time);
        }
示例#2
0
        public static void main(string[] args)
        {
            TraceSource log = new TraceSource(typeof(EPATool).FullName, SourceLevels.All);

            string hydFile  = null;
            string qualFile = null;
            var    net      = new EpanetNetwork();

            List <NodeVariableType> nodesVariables = new List <NodeVariableType>();
            List <LinkVariableType> linksVariables = new List <LinkVariableType>();

            string        inFile      = "";
            List <long>   targetTimes = new List <long>();
            List <string> targetNodes = new List <string>();
            List <string> targetLinks = new List <string>();

            int parseMode = 0;

            foreach (string arg in args)
            {
                if (arg.EndsWith(".inp", StringComparison.OrdinalIgnoreCase))
                {
                    parseMode = 0;
                    inFile    = arg;
                    if (!File.Exists(inFile))
                    {
                        ConsoleLog("END_RUN_ERR");
                        Console.Error.WriteLine("File not found !");
                        return;
                    }
                    continue;
                }

                switch (arg)
                {
                case "-T":
                case "-t":
                    parseMode = 1;
                    continue;

                case "-N":
                case "-n":
                    parseMode = 2;
                    continue;

                case "-L":
                case "-l":
                    parseMode = 3;
                    continue;
                }

                switch (parseMode)
                {
                case 1:
                    targetTimes.Add((long)(Utilities.GetHour(arg) * 3600));
                    break;

                case 2:
                    targetNodes.Add(arg);
                    break;

                case 3:
                    targetLinks.Add(arg);
                    break;
                }
            }

            try {
                InputParser parserInp = InputParser.Create(FileType.INP_FILE);
                net = parserInp.Parse(new EpanetNetwork(), inFile);


                if (targetTimes.Count > 0)
                {
                    foreach (long time  in  targetTimes)
                    {
                        string epanetTime = time.GetClockTime();
                        if (time < net.RStart)
                        {
                            throw new Exception("Target time \"" + epanetTime + "\" smaller than simulation start time");
                        }

                        if (time > net.Duration)
                        {
                            throw new Exception("Target time \"" + epanetTime + "\" bigger than simulation duration");
                        }

                        if ((time - net.RStart) % net.RStep != 0)
                        {
                            throw new Exception("Target time \"" + epanetTime + "\" not found");
                        }
                    }
                }

                foreach (string nodeName  in  targetNodes)
                {
                    if (net.GetNode(nodeName) == null)
                    {
                        throw new Exception("Node \"" + nodeName + "\" not found");
                    }
                }

                foreach (string linkName  in  targetLinks)
                {
                    if (net.GetLink(linkName) == null)
                    {
                        throw new Exception("Link \"" + linkName + "\" not found");
                    }
                }

                nodesVariables.Add(NodeVariableType.ELEVATION);
                nodesVariables.Add(NodeVariableType.BASEDEMAND);

                if (net.QualFlag != QualType.NONE)
                {
                    nodesVariables.Add(NodeVariableType.INITQUALITY);
                }

                nodesVariables.Add(NodeVariableType.PRESSURE);
                nodesVariables.Add(NodeVariableType.HEAD);
                nodesVariables.Add(NodeVariableType.DEMAND);

                if (net.QualFlag != (QualType.NONE))
                {
                    nodesVariables.Add(NodeVariableType.QUALITY);
                }

                linksVariables.Add(LinkVariableType.LENGHT);
                linksVariables.Add(LinkVariableType.DIAMETER);
                linksVariables.Add(LinkVariableType.ROUGHNESS);
                linksVariables.Add(LinkVariableType.FLOW);
                linksVariables.Add(LinkVariableType.VELOCITY);
                linksVariables.Add(LinkVariableType.UNITHEADLOSS);
                linksVariables.Add(LinkVariableType.FRICTIONFACTOR);

                if (net.QualFlag != QualType.NONE)
                {
                    linksVariables.Add(LinkVariableType.QUALITY);
                }

                hydFile = Path.GetTempFileName(); // "hydSim.bin"

                ConsoleLog("START_RUNNING");

                HydraulicSim hydSim = new HydraulicSim(net, log);
                hydSim.Simulate(hydFile);


                if (net.QualFlag != QualType.NONE)
                {
                    qualFile = Path.GetTempFileName(); // "qualSim.bin"

                    QualitySim q = new QualitySim(net, log);
                    q.Simulate(hydFile, qualFile);
                }


                HydraulicReader hydReader = new HydraulicReader(new BinaryReader(File.OpenRead(hydFile)));

                StreamWriter nodesTextWriter = null;
                StreamWriter linksTextWriter = null;
                string       nodesOutputFile = null;

                if (targetNodes.Count == 0 && targetLinks.Count == 0 || targetNodes.Count > 0)
                {
                    nodesOutputFile = Path.GetFullPath(inFile) + ".nodes.out";
                    nodesTextWriter = new StreamWriter(nodesOutputFile, false, Encoding.UTF8);

                    nodesTextWriter.Write('\t');
                    foreach (NodeVariableType nodeVar  in  nodesVariables)
                    {
                        nodesTextWriter.Write('\t');
                        nodesTextWriter.Write(nodeVar.ToString());
                    }
                    nodesTextWriter.Write("\n\t");

                    foreach (NodeVariableType nodeVar  in  nodesVariables)
                    {
                        nodesTextWriter.Write('\t');
                        nodesTextWriter.Write(net.FieldsMap.GetField(ToFieldType(nodeVar)).Units);
                    }
                    nodesTextWriter.Write('\n');
                }


                if (targetNodes.Count == 0 && targetLinks.Count == 0 || targetLinks.Count > 0)
                {
                    string linksOutputFile = Path.GetFullPath(inFile) + ".links.out";
                    linksTextWriter = new StreamWriter(linksOutputFile, false, Encoding.UTF8);

                    linksTextWriter.Write('\t');
                    foreach (LinkVariableType linkVar  in  linksVariables)
                    {
                        linksTextWriter.Write('\t');
                        linksTextWriter.Write(linkVar.ToString());
                    }
                    linksTextWriter.Write("\n\t");

                    foreach (LinkVariableType linkVar  in  linksVariables)
                    {
                        linksTextWriter.Write('\t');
                        if (linkVar < 0)
                        {
                            continue;
                        }
                        linksTextWriter.Write(net.FieldsMap.GetField((FieldType)linkVar).Units);
                    }
                    linksTextWriter.Write('\n');
                }


                for (long time = net.RStart; time <= net.Duration; time += net.RStep)
                {
                    AwareStep step = hydReader.GetStep((int)time);

                    int i = 0;

                    if (targetTimes.Count > 0 && !targetTimes.Contains(time))
                    {
                        continue;
                    }

                    if (nodesTextWriter != null)
                    {
                        foreach (Node node  in  net.Nodes)
                        {
                            if (targetNodes.Count > 0 && !targetNodes.Contains(node.Name))
                            {
                                continue;
                            }

                            nodesTextWriter.Write(node.Name);

                            nodesTextWriter.Write('\t');
                            nodesTextWriter.Write(time.GetClockTime());

                            foreach (NodeVariableType nodeVar  in  nodesVariables)
                            {
                                nodesTextWriter.Write('\t');
                                double val = GetNodeValue(nodeVar, net.FieldsMap, step, node, i);
                                nodesTextWriter.Write(ConvertToScientifcNotation(val, 1000, 0.01, 2));
                            }

                            nodesTextWriter.Write('\n');

                            i++;
                        }
                    }

                    i = 0;

                    if (linksTextWriter != null)
                    {
                        foreach (Link link  in  net.Links)
                        {
                            if (targetLinks.Count > 0 && !targetLinks.Contains(link.Name))
                            {
                                continue;
                            }

                            linksTextWriter.Write(link.Name);

                            linksTextWriter.Write('\t');
                            linksTextWriter.Write(time.GetClockTime());

                            foreach (LinkVariableType linkVar  in  linksVariables)
                            {
                                linksTextWriter.Write('\t');
                                double val = GetLinkValue(
                                    linkVar,
                                    net.FormFlag,
                                    net.FieldsMap,
                                    step,
                                    link,
                                    i);
                                linksTextWriter.Write(ConvertToScientifcNotation(val, 1000, 0.01, 2));
                            }

                            linksTextWriter.Write('\n');

                            i++;
                        }
                    }
                }

                if (nodesTextWriter != null)
                {
                    nodesTextWriter.Close();
                    ConsoleLog("NODES FILE \"" + nodesOutputFile + "\"");
                }

                if (linksTextWriter != null)
                {
                    linksTextWriter.Close();
                    ConsoleLog("LINKS FILES \"" + nodesOutputFile + "\"");
                }

                ConsoleLog("END_RUN_OK");
            }
            catch (ENException e) {
                ConsoleLog("END_RUN_ERR");
                Debug.Print(e.ToString());
            }
            catch (IOException e) {
                ConsoleLog("END_RUN_ERR");
                Debug.Print(e.ToString());
            }
            catch (Exception e) {
                ConsoleLog("END_RUN_ERR");
                Debug.Print(e.ToString());
            }

            if (!string.IsNullOrEmpty(hydFile))
            {
                File.Delete(hydFile);
            }

            if (!string.IsNullOrEmpty(qualFile))
            {
                File.Delete(qualFile);
            }
        }
示例#3
0
        private void RunSimulation(string fileName)
        {
            TraceListener simHandler = null;

            Simulated         = true;
            _canselSimulation = false;

            progressBar.Value   = 0;
            progressBar.Maximum = 100;
            progressBar.Minimum = 0;

            try {
                if (showHydraulicSolverEventsCheckBox.Checked)
                {
                    string logFile = Path.Combine(Path.GetDirectoryName(fileName) ?? string.Empty, "hydEvents.log");

                    try {
                        simHandler = new EpanetTraceListener(logFile, false);
                        simHandler.TraceOutputOptions &= ~TraceOptions.DateTime;
                        log.Listeners.Add(simHandler);
                    }
                    catch (IOException ex) {
                        log.Error(ex);
                    }
                }

                int reportPeriod    = ((TimeStep)reportPeriodBox.SelectedItem).Time;
                int reportStartTime = (int)(Utilities.GetHour(textReportStart.Text) * 3600);
                int hydTStep        = ((TimeStep)hydComboBox.SelectedItem).Time;
                int qualTStep       = ((TimeStep)qualComboBox.SelectedItem).Time;
                int durationTime    = (int)(Utilities.GetHour(textSimulationDuration.Text) * 3600);

                _net.RStart   = reportStartTime;
                _net.RStep    = reportPeriod;
                _net.HStep    = hydTStep;
                _net.Duration = durationTime;
                _net.QStep    = qualTStep;

                statusLabel.Text = "Simulating hydraulics";

                try {
                    _hydSim = new HydraulicSim(_net, log);

                    RunThread(
                        () => _hydSim.Simulate("hydFile.bin"),
                        10,
                        30,
                        () => _hydSim.Htime,
                        () => _hydSim.Htime / (double)_net.Duration);
                }
                catch (ENException ex) {
                    if (ex.Code == ErrorCode.Err1000)
                    {
                        throw new ThreadInterruptedException();
                    }

                    MessageBox.Show(
                        ex.Message + "\nCheck epanet.log for detailed error description",
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);

                    return;
                }

                if (_canselSimulation)
                {
                    return;
                }

                if (_fileMsx != null && qualityMSXCheckBox.Checked)
                {
                    statusLabel.Text = "Simulating MSX";

                    try {
                        // reload MSX
                        _netMsx = new EpanetMSX(_epanetTk);
                        _netMsx.Load(_fileMsx);

                        _netMsx.Network.Rstep  = reportPeriod;
                        _netMsx.Network.Qstep  = qualTStep;
                        _netMsx.Network.Rstart = reportStartTime;
                        _netMsx.Network.Dur    = durationTime;

                        _epanetTk.Open("hydFile.bin");

                        RunThread(
                            () => _netMsx.Run("msxFile.bin"),
                            30,
                            50,
                            () => _netMsx.QTime,
                            () => _netMsx.QTime / (double)_net.Duration);
                    }
                    catch (IOException) {}
                    catch (ENException) {
                        throw new ThreadInterruptedException();
                    }
                    finally {
                        _epanetTk.Close();
                    }

                    // netMSX.getReport().MSXrpt_write(new "msxFile.bin");
                }

                if (_canselSimulation)
                {
                    return;
                }

                if (qualityCheckBox.Checked)
                {
                    try {
                        QualitySim qSim = new QualitySim(_net, log);
                        statusLabel.Text = "Simulating Quality";

                        RunThread(
                            () => qSim.Simulate("hydFile.bin", "qualFile.bin"),
                            30,
                            50,
                            () => qSim.Qtime,
                            () => qSim.Qtime / (double)_net.Duration);
                    }
                    catch (ENException ex) {
                        MessageBox.Show(
                            ex.Message + "\nCheck epanet.log for detailed error description",
                            "Error",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                    catch (IOException e1) {
                        Debug.Print(e1.ToString());
                    }
                }

                if (_canselSimulation)
                {
                    return;
                }

                progressBar.Value = 50;
                statusLabel.Text  = "Writting report";

                _gen = new ReportGenerator(fileName);

                //log

                log.Information("Starting report write");
                if (showSummaryCheckBox.Checked)
                {
                    _gen.WriteSummary(_fileInp, _net, _fileMsx, _netMsx);
                }

                if (_canselSimulation)
                {
                    return;
                }

                if (transposeResultsCheckBox.Checked)
                {
                    _gen.TransposedMode = true;
                }

                if (hydraulicsCheckBox.Checked)
                {
                    // Write hydraulic spreadsheets
                    bool[] values = new bool[ReportGenerator.HydVariable.Values.Length];
                    for (int i = 0; i < ReportGenerator.HydVariable.Values.Length; i++)
                    {
                        values[i] = hydVariables.GetItemChecked(i);
                    }

                    statusLabel.Text = "Writing hydraulic report";

                    RunThread(
                        () => _gen.CreateHydReport("hydFile.bin", _net, values),
                        50,
                        60,
                        () => _gen.Rtime,
                        () => (_gen.Rtime - _net.RStart) / (double)_net.Duration);
                }

                if (_canselSimulation)
                {
                    return;
                }

                if (qualityCheckBox.Checked)
                {
                    statusLabel.Text = "Writing quality report";

                    bool nodes = qualityVariables.GetItemChecked(0);
                    bool links = qualityVariables.GetItemChecked(1);

                    RunThread(
                        () => _gen.CreateQualReport("qualFile.bin", _net, nodes, links),
                        60,
                        70,
                        () => _gen.Rtime,
                        () => (_gen.Rtime - _net.RStart) / (double)_net.Duration);
                }

                if (_canselSimulation)
                {
                    return;
                }

                // Write MSX quality spreadsheets
                if (_fileMsx != null && qualityMSXCheckBox.Checked)
                {
                    bool[] valuesMsx = new bool[speciesCheckList.Items.Count];
                    for (int i = 0; i < speciesCheckList.Items.Count; i++)
                    {
                        valuesMsx[i] = speciesCheckList.GetItemChecked(i);
                    }

                    _gen.CreateMsxReport(
                        "msxFile.bin",
                        _net,
                        _netMsx,
                        _epanetTk,
                        valuesMsx);

                    RunThread(
                        () =>
                        _gen.CreateMsxReport(
                            "msxFile.bin",
                            _net,
                            _netMsx,
                            _epanetTk,
                            valuesMsx),
                        70,
                        80,
                        () => _netMsx.QTime,
                        () => (_gen.Rtime - _net.RStart) / (double)_net.Duration);
                }

                if (_canselSimulation)
                {
                    return;
                }

                statusLabel.Text = "Writing workbook";
                _gen.WriteWorksheet();
                log.Information("Ending report write");
            }
            catch (ThreadInterruptedException) {
                log.Warning(0, "Simulation aborted!");
            }
            finally {
                if (simHandler != null)
                {
                    log.Listeners.Remove(simHandler);
                    simHandler.Close();
                }

                Simulated = false;
            }
        }