public static void AppendDefaulTrajectory(string onetrajectory_filename, string reduced_filename, int index_increment)
        {
            ScenarioTree onetrajectory_st = ScenarioTree.AMPL_Import(onetrajectory_filename);
            ScenarioTree reduced          = ScenarioTree.AMPL_Import(onetrajectory_filename);

            AppendDefaulTrajectory(onetrajectory_st, reduced, reduced_filename, index_increment);
        }
        public static ScenarioTree AMPL_Import(string file_name)
        {
            ScenarioTree St      = new ScenarioTree();
            StreamReader freader = File.OpenText(file_name);

            string first_line = freader.ReadLine();

            do
            {
                string   line  = freader.ReadLine();
                string[] parts = line.Split('\t');

                if (parts[parts.Length - 1] == string.Empty)
                {
                    parts = Reshape(parts, 0, parts.Length - 1);
                }

                if (parts.Length > 6)
                {
                    TreeNode Tn = new TreeNode();

                    Tn.Id          = int.Parse(parts[0]);
                    Tn.Probability = double.Parse(parts[1]);
                    Tn.Period      = int.Parse(parts[2]);

                    if (parts[3] != string.Empty)
                    {
                        Tn.PredecessorId = int.Parse(parts[3]);
                    }
                    else
                    {
                        Tn.PredecessorId = -1;
                    }

                    Tn.Value = new float[parts.Length - 4];
                    for (int c = 0; c < parts.Length - 4; c++)
                    {
                        Tn.Value[c] = float.Parse(parts[4 + c]);
                    }

                    St.Add(Tn);
                }
            }while (!freader.EndOfStream);

            St.ConvertPredecessorIdsToReferences();

            // Create a deltaT vector.
            St.deltaT = new double[St.T];
            for (int i = 0; i < St.deltaT.Length; i++)
            {
                St.deltaT[i] = 1;
            }

            freader.Close();
            return(St);
        }
        public ScenarioTree Clone()
        {
            ScenarioTree cloned = new ScenarioTree();

            for (int z = 0; z < Count; z++)
            {
                cloned.Add(this[z]);
                if (this[z].Predecessor != null)
                {
                    cloned[z].Predecessor = cloned[this.FindPredecessorIndex(z)];
                }
            }

            cloned.deltaT = (double[])deltaT.Clone();
            return(cloned);
        }
        /// <summary>
        /// Builds a new scenario tree by merging two scenarios.
        /// </summary>
        /// <param name="St1"></param>
        /// <param name="St2"></param>
        /// <returns></returns>
        public static ScenarioTree Merge(ScenarioTree St1, ScenarioTree St2)
        {
            ScenarioTree St = new ScenarioTree();

            St.deltaT = St1.deltaT;

            //get the maximum period index...
            int T = St1.T;

            for (int t = 0; t <= T; t++)
            {
                if (t == 0)
                {
                    TreeNode root1 = St1.Root;
                    TreeNode root2 = St2.Root;
                    TreeNode root  = new TreeNode(t, null, 1.0);
                    MergeValues(root1, root2, ref root);
                    root.ComesFrom(root1, root2);

                    St.Add(root);
                }
                else
                {
                    List <TreeNode> L1 = St1.NodesAt(t);
                    List <TreeNode> L2 = St2.NodesAt(t);

                    List <TreeNode> Previous = St.NodesAt(t - 1);
                    foreach (TreeNode n1 in L1)
                    {
                        foreach (TreeNode n2 in L2)
                        {
                            TreeNode n = new TreeNode();
                            n.Period      = t;
                            n.Probability = n1.Probability * n2.Probability;
                            MergeValues(n1, n2, ref n);

                            n.Predecessor = ScenarioTree.ComeFromListSearch(Previous, n1.Predecessor, n2.Predecessor);

                            St.Add(n);
                            n.ComesFrom(n1, n2);
                        }
                    }
                }
            }

            return(St);
        }
Пример #5
0
        //old generation routine
        static ScenarioTree GenerateOld()
        {
            int p_Periods = 11;

            ScenarioTree XST = new XTree(1);

            XST.Generate();


            ScenarioTree WST = new WTree(p_Periods);

            WST.Generate();

            ScenarioTree ST = ScenarioTree.Merge(XST, WST);

            return(ST);
        }
        //index_increment when in memory indices start from 0 so must be incremented
        public static void AppendDefaulTrajectory(ScenarioTree onetrajectory_scenario_tree, ScenarioTree reduced, string reduced_filename, int index_increment)
        {
            // Now find the nodes belonging to the first in the second.
            int T = onetrajectory_scenario_tree.Count;

            int[] default_trajectory = new int[T];

            for (int i = 0; i < T; i++)
            {
                bool     found = false;
                TreeNode N_i   = onetrajectory_scenario_tree[i];
                for (int j = 0; j < reduced.Count; j++)
                {
                    TreeNode N_j = reduced[j];
                    if (N_i.Period == N_j.Period)
                    {
                        if (N_j.HaveEqualValues(N_j))
                        {
                            // The two nodes reference the same realization of the underlying.
                            default_trajectory[i] = N_j.Id;
                            found = true;
                            break;
                        }
                    }
                }

                if (!found)
                {
                    Console.WriteLine("Cannot match node");
                    return;
                }
            }

            // Now write in the output the information about the default trajectory.
            StreamWriter sw = File.AppendText(reduced_filename);

            sw.WriteLine("param DefaultTrj:=");
            for (int i = 0; i < T; i++)
            {
                int period = onetrajectory_scenario_tree[i].Period + index_increment;
                sw.WriteLine(period.ToString() + "\t" + default_trajectory[i].ToString());
            }

            sw.WriteLine(";");
            sw.Close();
        }
Пример #7
0
        public ScenarioReduction(ScenarioTree scenarioTree)
        {
            this.inputScenarioTree = scenarioTree;
            this.deltaT            = scenarioTree.deltaT;

            this.trajectories = (float[][][])scenarioTree.Scenarios;
            this.p            = (double[])scenarioTree.ScenariosProbabilities.Clone();

            // Standardize the scenario variables.
            Standardize(VarianceStandardizationType);

            this.nodesTrajectories = scenarioTree.ScenariosNodes;

            this.distanceWithw0 = new double[this.nodesTrajectories.Length];
            for (int z = 0; z < this.distanceWithw0.Length; z++)
            {
                this.distanceWithw0[z] = -1;
            }
        }
Пример #8
0
        static void Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
            DateTime t0 = DateTime.Now;

            string mode = "A";// only AMPL

            if (args.Length < 2)
            {
                Console.WriteLine("ScenarioReduction V1.2.2\n");
                Console.WriteLine("Usage: ScenarioReduction infilename  action [out_scenarios]  [outputmode default=A] [Options]");

                Console.WriteLine("action can be: rnd:reduce  or N: no operation (displays in output the original scenario) ");
                Console.WriteLine("output mode: C complete (descriptive statistics), A only AMPL output");
                Console.WriteLine("options can be:");
                Console.WriteLine("[Sn] standardize n=0,1 (use time specific std),2 (use avg std)");
                Console.WriteLine("[Mn] metric n=0: L2 ,n=1: fortet mourer (L2)");

                Console.WriteLine("Args count=", args.Length.ToString());
                return;
            }

            string infilename = args[0];

            string action = args[1].ToUpper();

            int out_scenenarios      = -1;
            int optional_param_count = 0;

            if (action == "rnd")
            {
                out_scenenarios = int.Parse(args[2]);
                optional_param_count++;
            }
            if (args.Length > 2 + optional_param_count)
            {
                mode = args[2 + optional_param_count].ToUpper();
            }

            if (2 + optional_param_count < args.Length - 1)
            {
                Console.WriteLine("Options:");
                do
                {
                    optional_param_count++;
                    string op  = args[2 + optional_param_count];
                    int    val = int.Parse(op.Substring(1));
                    switch (op[0])
                    {
                    case 'S':    //standardize
                        ScenarioReduction.VarianceStandardizationType = val;
                        if (mode == "C")
                        {
                            Console.WriteLine("Standardize=" + val);
                        }
                        break;

                    case 'M':    // metric
                        ScenarioReduction.DistanceType = val;
                        if (mode == "C")
                        {
                            Console.WriteLine("Metric =" + val);
                        }
                        break;
                    }
                }while (2 + optional_param_count < args.Length - 1);
            }
            ScenarioReduction SRA = null;

            ScenarioTree ST = ScenarioTree.FromFile(infilename);


            if (mode == "C")
            {
                Console.WriteLine("Original Tree Descriptive Statistics:");
                ST.DescriptiveStatistics(Console.Out);
            }

            ScenarioTree reduced_tree = null;

            if (action == "rnd")
            {
                SRA = new BackwardReduction(ST);
                SRA.Reduce(out_scenenarios);
                reduced_tree = SRA.ReducedScenarioTree;
            }
            else
            {
                reduced_tree = ST;
            }

            if (mode == "C")
            {
                Console.WriteLine("Reduced Tree descriptive Statistics:");
                reduced_tree.DescriptiveStatistics(Console.Out);

                Console.WriteLine("Reduced Tree:");
                Console.WriteLine(reduced_tree.ToString());
            }

            Console.Write(reduced_tree.AMPL_Export("", "N_", null));


            DateTime t1 = DateTime.Now;
        }
        /// <summary>
        /// Read a text file with the following structure
        ///
        /// Node:
        /// Id:= x1
        /// p := x1
        /// t := x1
        /// v := x1 x2 xn
        /// ParentId := c1
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static ScenarioTree FromFile(string file)
        {
            StreamReader sr = File.OpenText(file);
            string       line;

            ScenarioTree tree = new ScenarioTree();
            TreeNode     tn   = null;

            do
            {
                line = sr.ReadLine();

                if (line.Contains("Node:"))
                {
                    // Add the previous.
                    if (tn != null)
                    {
                        tree.Add(tn);
                    }

                    tn = new TreeNode();
                }
                else if (line.Contains("ParentId"))
                {
                    line = CutIdentifier(line);
                    int predessor_id = int.Parse(line);
                    if (predessor_id > 0)
                    {
                        tn.Predecessor = tree[predessor_id - 1];
                    }
                }
                else if (line.Contains("Id"))
                {
                    line  = CutIdentifier(line);
                    tn.Id = int.Parse(line);
                }
                else if (line.Contains("p"))
                {
                    line           = CutIdentifier(line);
                    tn.Probability = double.Parse(line);
                }
                else if (line.Contains("t"))
                {
                    line      = CutIdentifier(line);
                    tn.Period = int.Parse(line);
                }
                else if (line.Contains("v"))
                {
                    line = CutIdentifier(line);
                    string[] values = line.Split('\t');
                    tn.Value = new float[values.Length - 1];
                    for (int i = 0; i < values.Length - 1; i++)
                    {
                        tn.Value[i] = float.Parse(values[i]);
                    }
                }
            }while (!sr.EndOfStream);

            // Aadd the last one.
            if (tn != null)
            {
                tree.Add(tn);
            }

            int min_period = 1;

            // Check for the format of periods.
            for (int z = 0; z < tree.Count; z++)
            {
                if (tree[z].Period < min_period)
                {
                    min_period = tree[z].Period;
                }
            }

            if (min_period == 1)
            {
                tree.OneBasedPeriods = 1;

                for (int z = 0; z < tree.Count; z++)
                {
                    tree[z].Period--;
                }
            }
            else
            {
                tree.OneBasedPeriods = 0;
            }

            int Periods = tree.T + 1;

            tree.deltaT = new double[Periods];
            for (int t = 0; t < Periods; t++)
            {
                tree.deltaT[t] = 1;
            }

            return(tree);
        }
        /// <summary>
        /// Return a scenario tree formed by only the component selected...
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public ScenarioTree GetComponent(int d)
        {
            ScenarioTree ST = new ScenarioTree();

            return(null);
        }
Пример #11
0
        public void Export(ScenarioTree tree)
        {
            // Number of scenarios.
            int L = tree.Leafs.Count;

            // Number of stages.
            int S = 1 + tree.T;

            // Prints a string like: stage: [1 2 2 3 3 3 3 4 4 4 4 4 4 4 4].
            Console.Write("stage: [");
            for (int n = 0; n < tree.Count; n++)
            {
                Console.Write(tree[n].Period + 1 + "\t");
            }

            Console.WriteLine("]");

            // Number of stages.
            Console.WriteLine("numTime: " + S);

            // Number of scenarios.
            Console.WriteLine("numScenario: " + tree.Leafs.Count);
            Console.WriteLine("numNode: " + tree.Count);

            int idx = -1;

            for (int z = 0; z < tree.Count; z++)
            {
                // Periods starts form zero.
                if (tree[z].Period == S - 2)
                {
                    idx = z;
                }
            }

            // Index of last node of the second last stage.
            Console.WriteLine("secondlaststagenode: " + (idx + 1));

            // Checks if it's correct!
            if (tree[idx + 1].Period != S - 1)
            {
                throw new Exception("Failed to calculate secondlaststagenode");
            }

            // Scenario node variable.
            TreeNode[][] sn = tree.ScenariosNodes;
            Console.Write("ScenarioNode: [");
            for (int l = 0; l < L; l++)
            {
                for (int s = 0; s < S; s++)
                {
                    Console.Write(sn[l][s].Id + "\t");
                }
                if (l < L - 1)
                {
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("]");
                }
            }

            // ***************************
            // Generate Probability: stages by row
            // Probability: [1 0.5 0.5].
            Console.Write("Probability: [");
            for (int s = 0; s < S; s++)
            {
                List <TreeNode> nodes = tree.NodesAt(s);
                foreach (TreeNode n in nodes)
                {
                    Console.Write(n.Probability + "\t");
                }

                if (s < S - 1)
                {
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("]");
                }
            }

            // Descendant...Matrix
            // for every node (rows) it calculates the start and the end of the
            // descendant nodes for every subsequent period.
            Console.WriteLine("successor: [");
            for (int n = 0; n < tree.Count; n++)
            {
                if (tree[n].Period < S - 1)
                {
                    for (int s = 1; s < S; s++)
                    {
                        List <TreeNode> successors = tree.GetSuccessors(tree[n], s);
                        if (successors.Count > 0)
                        {
                            Console.Write(successors[0].Id + "\t" +
                                          successors[successors.Count - 1].Id + "\t");
                        }
                        else
                        {
                            Console.Write("0\t0\t");
                        }
                    }

                    Console.WriteLine();
                }
            }

            Console.WriteLine("]");

            // Merge component names that contain _P _B in the name.
            List <int[]> indices = new List <int[]>();

            // Already taken.
            bool[] taken = new bool[tree.componentNames.Count];

            // Iterate for every component.
            for (int d = 0; d < tree.componentNames.Count; d++)
            {
                if (!taken[d])
                {
                    List <int> sub = new List <int>();
                    sub.Add(d);
                    taken[d] = true;
                    if (tree.componentNames[d].Contains("_B"))
                    {
                        string name = tree.componentNames[d].Replace("_B", "_P");
                        for (int d1 = d + 1; d1 < tree.componentNames.Count; d1++)
                        {
                            if (name.Equals(tree.componentNames[d1],
                                            StringComparison.InvariantCultureIgnoreCase))
                            {
                                sub.Add(d1);
                                taken[d1] = true;
                                break;
                            }
                        }
                    }

                    indices.Add(sub.ToArray());
                }
            }

            // Value Variables.
            for (int z = 0; z < indices.Count; z++)
            {
                int[]  sub  = indices[z];
                int    d    = sub[0];
                string name = "Component" + (z + 1);
                if (tree.componentNames != null)
                {
                    if (d < tree.componentNames.Count)
                    {
                        name = tree.componentNames[d];
                        if (sub.Length > 1)
                        {
                            name = name.Replace("_B", string.Empty);
                        }
                    }
                }

                Console.Write(name + ": [");
                for (int s = 0; s < S; s++)
                {
                    List <TreeNode> nodes = tree.NodesAt(s);
                    foreach (TreeNode n in nodes)
                    {
                        for (int z1 = 0; z1 < sub.Length; z1++)
                        {
                            Console.Write(n.Value[sub[z1]] + "\t");
                        }
                    }

                    if (s < S - 1)
                    {
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine("]");
                    }
                }
            }

            return;
        }
 public int DecoratedPeriod(ScenarioTree tree)
 {
     return(this.Period + tree.OneBasedPeriods);
 }
Пример #13
0
 public BackwardReduction(ScenarioTree p_st)
     : base(p_st)
 {
     LogReset();
 }
 public SimultaneousBackwardReduction(ScenarioTree scenarioTree)
     : base(scenarioTree)
 {
 }