示例#1
0
        private void TestQuickSortGen(ILArray <double> input, int dim, bool desc)
        {
            try {
                ILArray <int> A = ILMath.toint32(input);
                try {
                    ILMatFile f1 = new ILMatFile("tempADebugQuickSort.mat");
                    A = (ILArray <int>)f1["DebugQuickSort"];
                } catch (Exception) {}

                ILArray <int> result;
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                result = ILMath.sort(A, dim, desc);
                sw.Stop();
                if (!isSorted(ILMath.todouble(result), dim, desc))
                {
                    //ILMatFile f = new ILMatFile();
                    //A.Name = "DebugQuickSort";
                    //f.Add(A);
                    //System.IO.Stream s = new System.IO.FileStream("tempADebugQuickSort.mat",System.IO.FileMode.CreateNew);
                    //f.Write(s);
                    throw new Exception("invalid values");
                }
                Success(input.Dimensions.ToString() + "(Int32) needed: " + sw.ElapsedMilliseconds + " ms");
            } catch (Exception e) {
                Error(0, e.Message);
            }
        }
示例#2
0
        public void Model(ILArray <double> x, ILArray <double> u, ILMatFile wt, ILMatFile env, double DT, out double Omega, out double Ct, out double Cp)
        {
            // Parameters

            var R   = (double)wt.GetArray <double>("wt_rotor_radius");
            var I   = (double)wt.GetArray <double>("wt_rotor_inertia");
            var Rho = (double)env.GetArray <double>("env_rho");

            // Definitons etc.

            Omega = x.GetValue(0);
            var Ve   = x.GetValue(1);
            var Beta = u.GetValue(0);
            var Tg   = u.GetValue(1);

            // Algorithm

            var Lambda = Omega * R / Ve;

            _eInterpolCp.Interpolate(Beta, Lambda, wt.GetArray <double>("wt_cp_table"), wt.GetArray <double>("wt_cp_beta"), wt.GetArray <double>("wt_cp_tsr"), out Cp);
            _eInterpolCt.Interpolate(Beta, Lambda, wt.GetArray <double>("wt_ct_table"), wt.GetArray <double>("wt_ct_beta"), wt.GetArray <double>("wt_ct_tsr"), out Ct);

            var Tr = 0.5 * Rho * ILMath.pi * Math.Pow(R, 2) * Math.Pow(Ve, 3) * Cp / Omega;

            Omega = Omega + DT * (Tr - Tg) / I; //Integration method: Forward Euler
        }
        public void MeasurePool()
        {
            Info("Measuring memory pool performance");
            Info("---------------------------------");
            ILArray <int>    Lengths = ILMath.toint32(ILMath.vector(1000000, 1000, 1000000));
            ILArray <int>    PoolSizes = ILMath.toint32(ILMath.vector(00, 10, 250));
            ILArray <double> result = ILMath.zeros(Lengths.Length, PoolSizes.Length);
            ILArray <double> dataA = ILMath.ones(1000, 1000);
            ILArray <double> dataB = ILMath.ones(1000, 1000);
            int counter = 1, countAll = Lengths.Length * PoolSizes.Length;

            for (int p = 0; p < PoolSizes.Length; p++)
            {
                for (int s = 0; s < Lengths.Length; s++)
                {
                    result[s, p] = MeasurePoolParameter((int)Lengths[s], (int)PoolSizes[p], 100, dataA, dataB);
                    Console.Out.Write(String.Format("\r... step {0} of {1} completed", counter++, countAll));
                }
            }
            result.Name = "results";
            ILMatFile mf = new ILMatFile();

            mf["results"]   = result;
            mf["lengths"]   = Lengths;
            mf["poolSizes"] = PoolSizes;
            mf.Write(new FileStream("memoryPoolTestPerf.mat", FileMode.Create));
        }
示例#4
0
 private static void load(string windMatFilePath, out ILArray <double> wind)
 {
     using (var WindMatFile = new ILMatFile(windMatFilePath))
     {
         wind = WindMatFile.GetArray <double>("wind");
     }
 }
示例#5
0
 private static void load(string nrel5MWMatFilePath, out EnvMatFileDataStructure env, out WtMatFileDataStructure wt)
 {
     using (var NREL5MWMatFile = new ILMatFile(nrel5MWMatFilePath))
     {
         env = new EnvMatFileDataStructure(NREL5MWMatFile);
         wt  = new WtMatFileDataStructure(NREL5MWMatFile);
     }
 }
示例#6
0
        public void Test_NameRestrictions()
        {
            int errorCode = 0;

            try {
                ILMatFile        ml = new ILMatFile();
                ILArray <double> A  = ILMath.rand(3, 23, 2);
                ml["hallo"] = A;
                ILBaseArray res = ml["hallo"];
                if (!res.Equals(A))
                {
                    throw new Exception("invalid array returned for : 'hallo'");
                }
                try {
                    ml[""] = A + 1;
                    throw new Exception("empty names are not allowed!");
                } catch (ILArgumentException) {
                    Info("empty name signaled correctly");
                }
                try {
                    ml["1fsdf"] = A + 1;
                    throw new Exception("names starting with numbers are not allowed!");
                } catch (ILArgumentException) {
                    Info("names starting with numbers signaled correctly");
                }
                try {
                    ml["invaldi name"] = A + 1;
                    throw new Exception("names with blank space are not allowed!");
                } catch (ILArgumentException) {
                    Info("names with blank space signaled correctly");
                }
                try {
                    ml["a$me"] = A + 1;
                    throw new Exception("names with invalid characters are not allowed!");
                } catch (ILArgumentException e) {
                    Info("names with invalid characters signaled correctly");
                }
                try {
                    A = (ILArray <double>)ml["hallo_"];
                    throw new Exception("key not found expected");
                } catch (ILArgumentException e) {
                    Info("missing key signaled correctly");
                }
                errorCode   = 2;
                ml["hallo"] = null;
                if (ml.Arrays.Length != 0)
                {
                    throw new Exception("unable to remove array from MatFile");
                }
                Success();
            } catch (Exception e) {
                Error(errorCode, e.Message);
            }
        }
示例#7
0
        protected void StoreIgnoreIds(string outDir)
        {
            // store ignore ids
            ILMatFile     ignoreIDs = new ILMatFile();
            ILArray <int> ids       = new ILArray <int>(m_manualIgnoreIds.ToArray(), m_manualIgnoreIds.Count, 1);

            ignoreIDs["ignored"] = ids;
            using (Stream outStream = new FileStream(outDir + Path.DirectorySeparatorChar + "ignored.mat", FileMode.Create, FileAccess.ReadWrite)) {
                ignoreIDs.Write(outStream);
            }
        }
示例#8
0
        //private void wakeCalculation(ILArray<double> Ct, int i, ILCell wind, out ILArray<double> v_nac)
        public static void Calculate(ILArray <double> Ct, int i, ILMatFile wind, out ILArray <double> v_nac)
        {
            //% v_nac = WAKECALCULATION(Ct,i,wind)
            //This function calculates the wake
            //Currently it is a very very simplified wake calculation. It just serves as
            //a placeholder for a correct wake calculation that will come later

            ILArray <double> scaling = ILMath.linspace(0.5, 0.9, Ct.Length);

            v_nac = scaling * wind.GetArray <double>("wind").GetValue(i - 1, 1);
        }
示例#9
0
 protected void LoadIgnoreIds(string path)
 {
     if (File.Exists(path + Path.DirectorySeparatorChar + "ignored.mat"))
     {
         ILMatFile ignoreIds = new ILMatFile(path + Path.DirectorySeparatorChar + "ignored.mat");
         if (ignoreIds["ignored"] != null && ignoreIds["ignored"] is ILArray <int> )
         {
             ILArray <int> ids = (ILArray <int>)ignoreIds["ignored"];
             m_manualIgnoreIds.AddRange(ids.Values);
         }
     }
 }
示例#10
0
        public void Test_ImportMatlab2()
        {
            int errorCode = 0;

            try {
                ILMatFile      matFile           = new ILMatFile(@"C:\inst\TD_evidence_regression.mat");
                ILBaseArray [] arraysFromMatFile = matFile.Arrays;
                matFile           = new ILMatFile(@"C:\inst\test-v6.mat");
                arraysFromMatFile = matFile.Arrays;
                Success("Test_ImportMatlab successfull.");
            } catch (Exception e) {
                Error("Test_ImportMatlab failed on ErrorCode: " + errorCode + "due: " + e.Message);
            }
        }
示例#11
0
 protected void CheckManualOverwrite(int waitAutoContinueMs,
                                     ILMatFile inputs, ILMatFile outputsExt,
                                     int id, int nrInputParams, int nrOutputParams,
                                     int idFailedOutput, ILBaseArray failedOutputILN)
 {
     // give extensive error info
     Console.Out.WriteLine("Failure! ####################################");
     Console.Out.WriteLine("Should extensive error information be displayed? (y/n)");
     if (Console.In.Read() == 1)
     {
         return;
     }
     // waits for n msec for user input
     // skip
     // overwrite
 }
 static void Main(string[] args)
 {
     using (ILScope.Enter()) {
         ILCell data = Helper.DBQuery();
         // data is:
         //Cell [2,2]
         //[0]: <String>           header 1  <Double> [100,200]
         //[1]: <String>           header 2  <Single> [2,3000]
         // store into mat file
         ILMatFile mat  = new ILMatFile();
         var       key1 = (string)data.GetArray <string>(0, 0);
         mat.AddArray(data.GetArray <double>(0, 1), key1);     // stores rand(100,200) as key: "header1"
         // proceed with other columns...
         // write mat file
         mat.Write("filename");
     }
 }
示例#13
0
 public WtMatFileDataStructure(ILMatFile ilMatFile)
 {
     this.cp.table           = ilMatFile.GetArray <double>("wt_cp_table");
     this.cp.beta            = ilMatFile.GetArray <double>("wt_cp_beta");
     this.cp.tsr             = ilMatFile.GetArray <double>("wt_cp_tsr");
     this.ct.table           = ilMatFile.GetArray <double>("wt_ct_table");
     this.ct.beta            = ilMatFile.GetArray <double>("wt_ct_beta");
     this.ct.tsr             = ilMatFile.GetArray <double>("wt_ct_tsr");
     this.gen.effeciency     = (double)(ilMatFile.GetArray <double>("wt_gen_effeciency"));
     this.rotor.radius       = (double)(ilMatFile.GetArray <double>("wt_rotor_radius"));
     this.rotor.inertia      = (double)(ilMatFile.GetArray <double>("wt_rotor_inertia"));
     this.rotor.ratedspeed   = (double)(ilMatFile.GetArray <double>("wt_rotor_ratedspeed"));
     this.ctrl.pitch.Pgain   = (double)(ilMatFile.GetArray <double>("wt_ctrl_pitch_Pgain"));
     this.ctrl.pitch.Igain   = (double)(ilMatFile.GetArray <double>("wt_ctrl_pitch_Igain"));
     this.ctrl.pitch.ratelim = (double)(ilMatFile.GetArray <double>("wt_ctrl_pitch_ratelim"));
     this.ctrl.pitch.ulim    = (double)(ilMatFile.GetArray <double>("wt_ctrl_pitch_ulim"));
     this.ctrl.pitch.llim    = (double)(ilMatFile.GetArray <double>("wt_ctrl_pitch_llim"));
     this.ctrl.torq.ratelim  = (double)(ilMatFile.GetArray <double>("wt_ctrl_torq_ratelim"));
     this.ctrl.p_rated       = (double)(ilMatFile.GetArray <double>("wt_ctrl_p_rated"));
 }
示例#14
0
        public void Test_StreamMatlab(string filename, ILBaseArray arr)
        {
            int errorCode = 0;

            try {
                using (FileStream s = new FileStream(filename, FileMode.Create)) {
                    arr.ToStream(s, "", ILArrayStreamSerializationFlags.Matlab);
                }
                // test -> read back
                ILMatFile inp = new ILMatFile(filename);
                if (inp.Arrays.Length != 1)
                {
                    throw new Exception("invalid number of arrays after read back from matfile!");
                }
                ILBaseArray reread = inp.Arrays[0];
                if (!reread.Equals(arr))
                {
                    throw new Exception("invalid values after re-reading from mat file!");
                }
                string msg = "";
                if (arr.GetType().GetGenericArguments().Length > 0)
                {
                    msg = "<" + arr.GetType().GetGenericArguments()[0].Name + "> " + arr.Dimensions.ToString();
                }
                else if (arr is ILLogicalArray)
                {
                    msg = "<logical> " + arr.Dimensions.ToString();
                }
                else
                {
                    msg = "<???l> " + arr.Dimensions.ToString();
                }
                Success(msg);
            } catch (Exception e) {
                Error(errorCode, e.Message);
            }
        }
示例#15
0
        public void Test_TestMatlab()
        {
            int errorCode = 0;

            try {
                ILMatFile      matFile           = new ILMatFile("test_matfile.mat");
                ILBaseArray [] arraysFromMatFile = matFile.Arrays;
                if (arraysFromMatFile.Length != 2)
                {
                    throw new Exception("Test_ImportMatlab failed: invalid number of arrays returned.");
                }
                if (arraysFromMatFile[0].Dimensions.NumberOfElements != 100)
                {
                    throw new Exception("Test_ImportMatlab failed: invalid size of first array returned.");
                }
                if (arraysFromMatFile[1].Dimensions.NumberOfElements != 12)
                {
                    throw new Exception("Test_ImportMatlab failed: invalid size of 2. array returned.");
                }
                Success("Test_ImportMatlab successfull.");
            } catch (Exception e) {
                Error("Test_ImportMatlab failed on ErrorCode: " + errorCode + "due: " + e.Message);
            }
        }
示例#16
0
 public EnvMatFileDataStructure(ILMatFile ILMatFile)
 {
     this.rho = (double)(ILMatFile.GetArray <double>("env_rho"));
 }
示例#17
0
 public void Test_NameRestrictions () {
     int errorCode = 0; 
     try {
         ILMatFile ml = new ILMatFile();
         ILArray<double> A = ILMath.rand(3,23,2); 
         ml["hallo"] = A; 
         ILBaseArray res = ml["hallo"]; 
         if (!res.Equals(A))
             throw new Exception("invalid array returned for : 'hallo'");
         try {
             ml[""] = A+1;
             throw new Exception("empty names are not allowed!"); 
         } catch (ILArgumentException ) {
             Info("empty name signaled correctly"); 
         }   
         try {
             ml["1fsdf"] = A+1;
             throw new Exception("names starting with numbers are not allowed!"); 
         } catch (ILArgumentException ) {
             Info("names starting with numbers signaled correctly"); 
         }  
         try {
             ml["invaldi name"] = A+1;
             throw new Exception("names with blank space are not allowed!"); 
         } catch (ILArgumentException ) {
             Info("names with blank space signaled correctly"); 
         }  
         try {
             ml["a$me"] = A+1;
             throw new Exception("names with invalid characters are not allowed!"); 
         } catch (ILArgumentException e) {
             Info("names with invalid characters signaled correctly"); 
         }  
         try {
             A = (ILArray<double>)ml["hallo_"];
             throw new Exception("key not found expected"); 
         } catch (ILArgumentException e) {
             Info("missing key signaled correctly"); 
         } 
         errorCode = 2; 
         ml["hallo"] = null; 
         if (ml.Arrays.Length != 0)
             throw new Exception("unable to remove array from MatFile");
         Success(); 
     } catch (Exception e) {
         Error(errorCode,e.Message); 
     }
 }
示例#18
0
 public void Test_StreamMatlab(string filename, ILBaseArray arr) {
     int errorCode = 0;
     try {
         using (FileStream s = new FileStream(filename,FileMode.Create)) {
             arr.ToStream(s,"",ILArrayStreamSerializationFlags.Matlab);    
         }
         // test -> read back 
         ILMatFile inp = new ILMatFile(filename); 
         if (inp.Arrays.Length != 1)
             throw new Exception("invalid number of arrays after read back from matfile!");
         ILBaseArray reread = inp.Arrays[0]; 
         if (!reread.Equals (arr)) 
             throw new Exception("invalid values after re-reading from mat file!");
         string msg = ""; 
         if (arr.GetType().GetGenericArguments().Length > 0)
             msg = "<" + arr.GetType().GetGenericArguments()[0].Name + "> " + arr.Dimensions.ToString(); 
         else if (arr is ILLogicalArray)
             msg = "<logical> " + arr.Dimensions.ToString(); 
         else 
             msg = "<???l> " + arr.Dimensions.ToString(); 
         Success(msg);
     } catch (Exception e) {
         Error(errorCode, e.Message);
     }
 }
示例#19
0
 public void Test_TestMatlab() {
     int errorCode = 0;
     try {
         ILMatFile matFile = new ILMatFile("test_matfile.mat"); 
         ILBaseArray [] arraysFromMatFile =  matFile.Arrays; 
         if (arraysFromMatFile.Length != 2)
             throw new Exception("Test_ImportMatlab failed: invalid number of arrays returned."); 
         if (arraysFromMatFile[0].Dimensions.NumberOfElements != 100)
             throw new Exception("Test_ImportMatlab failed: invalid size of first array returned.");
         if (arraysFromMatFile[1].Dimensions.NumberOfElements != 12)
             throw new Exception("Test_ImportMatlab failed: invalid size of 2. array returned.");
         Success("Test_ImportMatlab successfull.");
     } catch (Exception e) {
         Error("Test_ImportMatlab failed on ErrorCode: " + errorCode + "due: " + e.Message);
     }
 }
示例#20
0
 public void Test_ImportMatlab2() {
     int errorCode = 0;
     try {
         ILMatFile matFile = new ILMatFile(@"C:\inst\TD_evidence_regression.mat"); 
         ILBaseArray [] arraysFromMatFile =  matFile.Arrays; 
         matFile = new ILMatFile(@"C:\inst\test-v6.mat"); 
         arraysFromMatFile =  matFile.Arrays; 
         Success("Test_ImportMatlab successfull.");
     } catch (Exception e) {
         Error("Test_ImportMatlab failed on ErrorCode: " + errorCode + "due: " + e.Message);
     }
 }
        /// <summary>
        /// generate single test case
        /// </summary>
        /// <param name="arrProv">test data provider (ILCell, specific type)</param>
        /// <param name="definition">case definition</param>
        /// <returns>localPostfixedTestCaseName</returns>
        public string AutoCreateTestCase(ILTestArrayProvider arrProv, ILTestCaseDefinition definition)
        {
            StringBuilder ocs = new StringBuilder("clear output*;");
            string        matInputFileName        = INPUT_PARAMETER_PREFIX + ".mat";
            string        matOutputFileName       = OUTPUT_PARAMETER_PREFIX + ".mat";
            string        resultOverridesFileName = OVERRIDES_PARAMETER_PREFIX + ".mat";
            ILCell        inputVars = arrProv.GenerateTestArrays();
            ILMatFile     matFile   = new ILMatFile();
            List <string> inTag     = new List <string>();
            List <string> outTag    = new List <string>();
            string        outTagJoined;
            string        inTagJoined;

            ocs.Append("\n" + String.Format("parameter = load('{0}');", matInputFileName));
            for (int i = 0; i < inputVars.Dimensions[0]; i++)
            {
                inTag.Clear(); outTag.Clear();
                // handle input parameters
                for (int c = 0; c < definition.InputParameterCount; c++)
                {
                    string ident = "_" + i.ToString() + "_" + c.ToString();
                    matFile[INPUT_PARAMETER_PREFIX + ident] = inputVars.GetValue(i, c);
                    inTag.Add("parameter." + INPUT_PARAMETER_PREFIX + ident);
                }
                // handle output parameters
                for (int c = 0; c < definition.OutputParameterCount; c++)
                {
                    string ident = "_" + i.ToString() + "_" + c.ToString();
                    outTag.Add(OUTPUT_PARAMETER_PREFIX + ident);
                }
                //outTagJoined = String.Join(",", outTag.ToArray());
                //inTagJoined = String.Join(",", inTag.ToArray());
                List <object> allTags = new List <object>();
                foreach (string s in inTag)
                {
                    allTags.Add(s);
                }
                foreach (string s in outTag)
                {
                    allTags.Add(s);
                }

                string octaveFuncCall = String.Format(definition.OctaveFunctionDef, allTags.ToArray());
                ocs.Append(String.Format("\ntry {0} catch  {1} = 'Exception'; end",
                                         octaveFuncCall, outTag[0]));
            }
            // the name for the case directory will be postfixed with the arrayprovider types ('double',...)
            string localPostfixedTestCaseName = definition.TestCaseName + "_" + arrProv.GetIdentifierPostfix();
            string TestCaseOutputPath         = Path.Combine(m_baseDirectory, RelativeTestCasePath);

            TestCaseOutputPath = Path.Combine(TestCaseOutputPath, localPostfixedTestCaseName)
                                 + Path.DirectorySeparatorChar;
            if (Directory.Exists(TestCaseOutputPath))
            {
                Directory.Delete(TestCaseOutputPath, true);
            }
            Directory.CreateDirectory(TestCaseOutputPath);
            // save matfile
            using (Stream outStream = new FileStream(TestCaseOutputPath + matInputFileName, FileMode.Create)) {
                matFile.Write(outStream);
            }
            // finish + save creation script
            ocs.Append(String.Format("\n\nsave ('{0}','{1}*','-v6');", matOutputFileName, OUTPUT_PARAMETER_PREFIX));
            File.WriteAllText(TestCaseOutputPath + OCTAVE_CREATION_SCRIPT_NAME, ocs.ToString());
            #region create test class file
            inTag.Clear(); outTag.Clear();
            List <string> inTagR      = new List <string>();
            StringBuilder testRunFunc = new StringBuilder();
            // handles input parameter
            for (int i = 0; i < definition.InputParameterCount; i++)
            {
                testRunFunc.Append(String.Format(@"{1} {2}{0} = ({1})m_inputMatfile[""{2}_""+id.ToString()+""_{0}""];
                {2}{0}.Detach();"
                                                 , i.ToString(), arrProv.GetCSharpTypeDefinition(), INPUT_PARAMETER_PREFIX));
                inTag.Add(INPUT_PARAMETER_PREFIX + i.ToString());
                inTagR.Add(INPUT_PARAMETER_PREFIX + i.ToString() + ".R");
            }
            // handles output parameter
            StringBuilder errorCheckString = new StringBuilder();
            for (int i = 0; i < definition.OutputParameterCount; i++)
            {
                testRunFunc.Append(Environment.NewLine + "\t\t\t\t"
                                   + String.Format(@"ILBaseArray parameter{0} = null;", i));
                outTag.Add("parameter" + i.ToString());
                // error checking
                errorCheckString.Append(String.Format(@"
                if (!(parameter{0}.IsEmpty & m_outputMatfile[""output_""+id.ToString()+""_{0}""].IsEmpty) &&
                     (!TestHelper.TestEqualSloppy(parameter{0},m_outputMatfile[""{1}_""+id.ToString()+""_{0}""]))) {{
                    Error(""result{0} does not match expected value! parameterset: #""+id.ToString()+"",input #0: "" + input0.Dimensions.ToString());
                    return ProcessParameterErrorInfo(id, parameter{0}, {2}, {3}, {0}, m_inputMatfile, m_outputMatfile,{4});
                }}", i.ToString(), OUTPUT_PARAMETER_PREFIX, definition.InputParameterCount, definition.OutputParameterCount, escape(definition.TargetFunctionDef)));
            }
            outTagJoined = String.Join(",", outTag.ToArray());
            inTagJoined  = String.Join(",", inTag.ToArray());
            string inTagRJoined = String.Join(",", inTagR.ToArray());
            inTag.AddRange(outTag);
            inTagR.AddRange(outTag);
            string targetFunction = String.Format(definition.TargetFunctionDef, inTag.ToArray());
            // create dense test
            testRunFunc.Append(Environment.NewLine + "\t\t\t\t" + targetFunction);
            testRunFunc.Append(errorCheckString.ToString());
            // create reference test
            targetFunction = String.Format(definition.TargetFunctionDef, inTagR.ToArray());
            testRunFunc.Append(Environment.NewLine + "\t\t\t\t" + targetFunction);
            testRunFunc.Append(errorCheckString.ToString());
            // finish
            string runtimeRelPath2matFiles = Path.Combine(m_baseDirectoryRelative2EXE, RelativeTestCasePath) + Path.DirectorySeparatorChar
                                             + localPostfixedTestCaseName
                                             + Path.DirectorySeparatorChar;
            string testClass = String.Format(HEADER, localPostfixedTestCaseName,          // 0
                                             runtimeRelPath2matFiles + matInputFileName,
                                             runtimeRelPath2matFiles + matOutputFileName, // 1,2
                                             inputVars.Dimensions[0].ToString(),
                                             testRunFunc.ToString(),
                                             arrProv.GetCSharpTypeDefinition(),
                                             runtimeRelPath2matFiles + resultOverridesFileName);
            File.WriteAllText(TestCaseOutputPath + localPostfixedTestCaseName + ".cs", testClass);
            #endregion
            if (DeleteResultsOnRecreate)
            {
                if (File.Exists(TestCaseOutputPath + matOutputFileName))
                {
                    File.Delete(TestCaseOutputPath + matOutputFileName);
                }
            }
            #region write ResultOverrides
            if (definition.ResultOverrides != null)
            {
                ILMatFile overridesMatFile   = new ILMatFile();
                bool      mustWriteOverrides = false;
                foreach (ILResultOverride overr in definition.ResultOverrides)
                {
                    if (overr.TestArrayProvider == arrProv)
                    {
                        // foreach override find matching parameters in current provider
                        for (int o = 0; o < overr.Inputs.Dimensions[0]; o++)
                        {
                            for (int i = 0; i < inputVars.Dimensions[0]; i++)
                            {
                                if (ILMath.isequalwithequalnans(
                                        overr.Inputs[o, null], inputVars[i, null]))
                                {
                                    // matching override found
                                    System.Diagnostics.Debug.Assert(overr.Outputs.Dimensions[1] == inputVars.Dimensions[1]);
                                    for (int c = 0; c < inputVars.Dimensions[1]; c++)
                                    {
                                        string ident = "_" + i.ToString() + "_" + c.ToString();
                                        overridesMatFile[OUTPUT_PARAMETER_PREFIX + ident] = overr.Outputs[o, c];
                                    }
                                    mustWriteOverrides = true;
                                }
                            }
                        }
                    }
                }
                if (mustWriteOverrides)
                {
                    using (FileStream overridesStream = new FileStream(TestCaseOutputPath + OVERRIDES_PARAMETER_PREFIX + ".mat", FileMode.Create)) {
                        overridesMatFile.Write(overridesStream);
                    }
                }
                else if (File.Exists(TestCaseOutputPath + OVERRIDES_PARAMETER_PREFIX + ".mat"))
                {
                    File.Delete(TestCaseOutputPath + OVERRIDES_PARAMETER_PREFIX + ".mat");
                }
            }
            #endregion

            return(localPostfixedTestCaseName);
        }
示例#22
0
        protected ErrorHandlerProcessMethod ProcessParameterErrorInfo(int id, ILBaseArray parameter0,
                                                                      int nrInputParams, int nrOutputParams, int failedResultNo,
                                                                      ILMatFile inputMatfile, ILMatFile outputMatfile,
                                                                      string functionDefinition)
        {
            // determine how to proceed with the error
            if (m_ignoreAllErrors || m_manualIgnoreIds.Contains(id))
            {
                if (!m_manualIgnoreIds.Contains(id))
                {
                    m_manualIgnoreIds.Add(id);
                }
                return(ErrorHandlerProcessMethod.IgnoreAll);
            }
            Console.ResetColor();
            Console.WriteLine("Press 'i' for extended error information! (will continue in " + m_errorWaitForUserInputSec.ToString() + " sec otherwise)");
            DateTime end = DateTime.Now + TimeSpan.FromSeconds(m_errorWaitForUserInputSec);

            while (!Console.KeyAvailable && DateTime.Now < end)
            {
                System.Threading.Thread.Sleep(100);
            }
            if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.I)
            {
                // function definition
                Console.WriteLine("Function: {0}", functionDefinition);
                // write error infos: input parameters
                for (int i = 0; i < nrInputParams; i++)
                {
                    Console.WriteLine("Input parameter #{0}:\r\n#############################\r\n{1}", i, inputMatfile["input_" + id.ToString() + "_" + i.ToString()].ToString());
                }
                // write error infos: output parameters
                for (int i = 0; i < nrOutputParams; i++)
                {
                    Console.WriteLine("Expected output parameter #{0}:\r\n#############################\r\n{1}", i, outputMatfile["output_" + id.ToString() + "_" + i.ToString()].ToString());
                }
                Console.WriteLine("Result #{0} returned unexpected value: \r\n ############################\r\n{1}", failedResultNo, parameter0.ToString());
                // ask how to proceed
                ConsoleKey pressedKey = ConsoleKey.NoName;
                while (pressedKey != ConsoleKey.A &&
                       pressedKey != ConsoleKey.I &&
                       pressedKey != ConsoleKey.P &&
                       pressedKey != ConsoleKey.L)
                {
                    Console.WriteLine("_A_bort / _I_gnore/ _P_ermanently ignore / Ignore al_L_ ");
                    while (!Console.KeyAvailable)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    pressedKey = Console.ReadKey(false).Key;
                }
                if (pressedKey == ConsoleKey.A)
                {
                    Console.WriteLine("Aborting...");
                    return(ErrorHandlerProcessMethod.Abort);
                }
                else if (pressedKey == ConsoleKey.L)
                {
                    Console.WriteLine("All errors will be ignored in future runs of this test ...");
                    m_manualIgnoreIds.Add(id);
                    m_ignoreAllErrors = true;
                    return(ErrorHandlerProcessMethod.IgnoreAll);
                }
                else if (pressedKey == ConsoleKey.I)
                {
                    Console.WriteLine("The error will be ignored in this test ...");
                    return(ErrorHandlerProcessMethod.IgnoreAll);
                }
                else if (pressedKey == ConsoleKey.P)
                {
                    Console.WriteLine("The error will be permanently ignored in this test ...");
                    m_manualIgnoreIds.Add(id);
                    return(ErrorHandlerProcessMethod.IgnoreAll);
                }
            }
            return(ErrorHandlerProcessMethod.Ignore);
        }
示例#23
0
        //% The main file for running the wind farm controll and wake simulation.
        // It is not completely done yet. Further updates will come
        // Currently there are only 4 turbines, for test purposes. But is should be
        // easily updated to a larger number of turbines.
        // Similarly there is a lot of room for speed optimizations, even though it
        // now runs slowly with only 4 turbines
        // 19/07-13 MS

        public static double[][] Simulation(WakeFarmControlConfig config)
        {
            var parm = new WindTurbineParameters();

            ILMatFile env;
            ILMatFile wt;

            ILArray <int>    idx;
            ILArray <double> ee;

            double           Ki;
            double           Kp;
            int              PC_MaxPit;
            int              PC_MinPit;
            double           VS_CtInSp;
            double           VS_RtGnSp;
            double           VS_Rgn2K;
            double           omega0;
            double           beta0;
            double           power0;
            ILArray <double> x;
            ILArray <double> u0;
            ILArray <double> u;
            ILArray <double> Mg_old;
            ILArray <double> P_ref;
            ILArray <double> Pa;
            ILArray <double> Power;
            ILArray <double> Ct;
            ILArray <double> P_ref_new;
            ILArray <double> v_nac;
            double           alpha;
            double           Mg_max_rate;
            ILArray <double> e;
            ILArray <double> Mg;
            ILArray <double> beta;
            ILArray <double> Cp;
            ILArray <double> Omega;
            ILArray <double> out_;

            if (config.NTurbines == 0)
            {
                return(null);
            }

            // Wind farm properties
            //turbine properties
            env             = wt = new ILMatFile(config.NREL5MW_MatFile);                                             //Load parameters from the NREL 5MW turbine
            parm.N          = config.NTurbines;                                                                       // number of turbines in farm
            parm.rho        = (double)env.GetArray <double>("env_rho");                                               //air density
            parm.radius     = ((double)(wt.GetArray <double>("wt_rotor_radius"))) * ILMath.ones(1, config.NTurbines); // rotor radius (NREL5MW)
            parm.rated      = 5e6 * ILMath.ones(1, config.NTurbines);                                                 //rated power (NREL5MW)
            parm.ratedSpeed = (double)wt.GetArray <double>("wt_rotor_ratedspeed");                                    //rated rotor speed

            idx = ILMath.empty <int>();
            ILMath.max(wt.GetArray <double>("wt_cp_table")[ILMath.full], idx);                                        //Find index for max Cp;
            parm.Cp = ILMath.ones(1, config.NTurbines) * wt.GetArray <double>("wt_cp_table").GetValue(idx.ToArray()); //Set power coefficent to maximum value in the cp table
            parm.Ct = ILMath.ones(1, config.NTurbines) * wt.GetArray <double>("wt_ct_table").GetValue(idx.ToArray()); //Set power coefficent to maximum value in the ct table

            // NOTE: controller parameters should be imported from the wt....struct in
            //Pitch control

            ee = 0;                                 //blade pitch integrator
            Ki = 0.008068634 * 360 / 2 / ILMath.pi; // integral gain (NREL5MW)
            Kp = 0.01882681 * 360 / 2 / ILMath.pi;  // proportional gain (NREL5MW)

            PC_MaxPit = 90;
            PC_MinPit = 0;

            //region control NREL
            VS_CtInSp = 70.16224;
            VS_RtGnSp = 121.6805;
            VS_Rgn2K  = 2.332287;


            // load initial wind data
            var wind = new ILMatFile(config.Wind_MatFile);

            //% Set initial conditions
            omega0 = 1.267; //Rotation speed
            beta0  = 0;     //Pitch

            var timeLine = (int)config.TimeLine();

            power0 = parm.rated.GetValue(0); //Power production
            x      = (omega0 * ILMath.ones(parm.N, 1)).Concat((wind.GetArray <double>("wind").GetValue(0, 1) * ILMath.ones(parm.N, 1)), 1);
            u0     = (beta0 * ILMath.ones(parm.N, 1)).Concat((power0 * ILMath.ones(parm.N, 1)), 1);
            u      = u0.C;
            Mg_old = u[ILMath.full, 1];
            P_ref  = ILMath.zeros(parm.N, (int)config.TimeLine()); //Initialize matrix to save the power production history for each turbine
            Pa     = P_ref.C;                                      //Initialize available power matrix
            Power  = P_ref.C;
            Ct     = parm.Ct.C;                                    //Initialize Ct - is this correct?
            Ct[timeLine - 1, ILMath.full] = Ct[0, ILMath.full];
            P_ref_new = power0 * ILMath.ones(config.NTurbines, 1);

            v_nac = ILMath.zeros(Ct.Size[1], timeLine);
            Mg    = ILMath.zeros(u.Size[0], timeLine);
            beta  = ILMath.zeros(u.Size[0], timeLine);
            Omega = ILMath.zeros(Ct.Size[1], timeLine);
            Cp    = ILMath.zeros(timeLine, parm.Cp.Size[1]);

            var turbineModel = new TurbineDrivetrainModel();

            //% Simulate wind farm operation
            //var timeLine = (int) config.TimeLine();
            for (var i = 2; i <= timeLine; i++) //At each sample time(DT) from Tstart to Tend
            {
                //Calculate the wake using the current Ct values
                {
                    ILArray <double> out_v_nac;
                    WakeCalculation.Calculate((Ct[i - 1 - 1, ILMath.full]), i, wind, out out_v_nac);
                    v_nac[ILMath.full, i - 1] = out_v_nac;
                }
                x[ILMath.full, 1] = v_nac[ILMath.full, i - 1];


                //Farm control
                //Calculate the power distribution references for each turbine
                if (config.EnablePowerDistribution)
                {
                    ILArray <double> out_Pa;
                    PowerDistributionControl.DistributePower(v_nac[ILMath.full, i - 1], config.Pdemand, Power[ILMath.full, i - 1 - 1], parm, out P_ref_new, out out_Pa);
                    Pa[ILMath.full, i - 1] = out_Pa;
                }

                //Hold  the demand for some seconds
                if (ILMath.mod(i, ILMath.round(config.PRefSampleTime / config.DT)) == 2) //???
                {
                    P_ref[ILMath.full, i - 1] = P_ref_new;
                }
                else
                {
                    if (config.PowerRefInterpolation)
                    {
                        alpha = 0.01;
                        P_ref[ILMath.full, i - 1] = (1 - alpha) * P_ref[ILMath.full, i - 1 - 1] + (alpha) * P_ref_new;
                    }
                    else
                    {
                        P_ref[ILMath.full, i - 1] = P_ref_new;
                    }
                }


                //Calculate control for each individual turbine - should be moved to the
                //turbine (drivetrain) model.

                //Torque controller
                for (var j = 1; j <= parm.N; j++)
                {
                    if ((x.GetValue(j - 1, 0) * 97 >= VS_RtGnSp) || (u.GetValue(j - 1, 0) >= 1))   // We are in region 3 - power is constant
                    {
                        u.SetValue(P_ref.GetValue(j - 1, i - 1) / x.GetValue(j - 1, 0), j - 1, 1);
                    }
                    else if (x.GetValue(j - 1, 0) * 97 <= VS_CtInSp)                            //! We are in region 1 - torque is zero
                    {
                        u.SetValue(0.0, j - 1, 1);
                    }
                    else                                                         //! We are in region 2 - optimal torque is proportional to the square of the generator speed
                    {
                        u.SetValue(97 * VS_Rgn2K * x.GetValue(j - 1, 0) * x.GetValue(j - 1, 0) * Math.Pow(97, 2), j - 1, 1);
                    }
                }

                //Rate limit torque change
                //  u(:,2) - Mg_old;
                Mg_max_rate       = 1e6 * config.DT;
                u[ILMath.full, 1] = ILMath.sign(u[ILMath.full, 1] - Mg_old) * ILMath.min(ILMath.abs(u[ILMath.full, 1] - Mg_old), Mg_max_rate) + Mg_old;

                //Pitch controller
                e  = 97 * (omega0 * ILMath.ones(parm.N, 1) - x[ILMath.full, 0]);
                ee = ee - config.DT * e;
                ee = ILMath.min(ILMath.max(ee, PC_MinPit / Ki), PC_MaxPit / Ki);

                u[ILMath.full, 0] = -Kp * config.DT * e + Ki * ee;
                for (var j = 1; j <= parm.N; j++)
                {
                    u.SetValue(Math.Min(Math.Max(u.GetValue(j - 1, 0), PC_MinPit), PC_MaxPit), j - 1, 0);
                }

                if (!config.EnableTurbineDynamics)
                {
                    u = u0;
                }

                Mg[ILMath.full, i - 1] = u[ILMath.full, 1];
                Mg_old = Mg[ILMath.full, i - 1];
                beta[ILMath.full, i - 1] = u[ILMath.full, 0]; //Set pitch


                //Turbine dynamics - can be simplified
                if (config.EnableTurbineDynamics)
                {
                    for (var j = 1; j <= parm.N; j++)
                    {
                        double out_x;
                        double out_Ct;
                        double out_Cp;
                        turbineModel.Model(x[j - 1, ILMath.full], u[j - 1, ILMath.full], wt, env, config.DT, out out_x, out out_Ct, out out_Cp);
                        x.SetValue(out_x, j - 1, 0);
                        Ct.SetValue(out_Ct, i - 1, j - 1);
                        Cp.SetValue(out_Cp, i - 1, j - 1);
                    }
                }
                else
                {
                    Ct[i - 1, ILMath.full] = parm.Ct;
                    Cp[i - 1, ILMath.full] = parm.Cp;
                    x[ILMath.full, 0]      = parm.ratedSpeed;//Rotational speed
                }

                Omega[ILMath.full, i - 1] = x[ILMath.full, 0];
                Power[ILMath.full, i - 1] = Omega[ILMath.full, i - 1] * Mg[ILMath.full, i - 1];
            }

            //% Save output data
            out_ = (config.DT * (ILMath.counter(0, 1, config.TimeLine())));
            out_ = out_.Concat(v_nac.T, 1);
            out_ = out_.Concat(Omega.T, 1);
            out_ = out_.Concat(beta.T, 1);
            out_ = out_.Concat(P_ref.T, 1);
            out_ = out_.Concat(Ct, 1);
            out_ = out_.Concat(Cp, 1);
            out_ = out_.Concat(Pa.T, 1);
            out_ = out_.Concat(Mg.T, 1);
            out_ = out_.Concat(Power.T, 1);

            //Ttotal power demand
            var l = config.NTurbines * 3 + 1;
            var r = l + config.NTurbines - 1;

            out_ = out_.Concat(ILMath.sum(out_[ILMath.full, ILMath.r(l, r)], 1) / 1e6, 1);    // P_ref sum

            l = config.NTurbines * 6 + 1;
            r = l + config.NTurbines - 1;

            out_ = out_.Concat(ILMath.sum(out_[ILMath.full, ILMath.r(l, r)], 1) / 1e6, 1);    // Pa sum. 'Power Demand'
            out_ = out_.Concat(ILMath.sum(Power).T / 1e6, 1);                                 // 'Actual Production'

            //Ttotal power demand
            out_ = out_.Concat(ILMath.sum(P_ref.T, 1), 1);              // 'Demand'
            out_ = out_.Concat(ILMath.sum(Pa.T, 1), 1);                 // 'Available'
            out_ = out_.Concat(ILMath.sum(Mg * Omega).T, 1);            // 'Actual'

            //Total power produced
            out_ = out_.Concat((Mg * Omega).T, 1);

            var out_doubleArray = new double[out_.Size[0]][];

            for (int i = 0; i <= out_doubleArray.GetLength(0) - 1; i++)
            {
                out_doubleArray[i] = new double[out_.Size[1]];
                for (int j = 0; j <= out_doubleArray[i].GetLength(0) - 1; j++)
                {
                    out_doubleArray[i][j] = out_.GetValue(i, j);
                }
            }
            return(out_doubleArray);
        }
示例#24
0
        private void TestQuickSortGen(ILArray<double> input,int dim, bool desc) {
            try {
                ILArray<int> A = ILMath.toint32( input ); 
                try {
                    ILMatFile f1 = new ILMatFile("tempADebugQuickSort.mat");
                    A = (ILArray<int>)f1["DebugQuickSort"]; 
                } catch (Exception) {}

                ILArray<int> result;
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); 
                sw.Start();
                result = ILMath.sort(A,dim,desc); 
                sw.Stop(); 
                if (!isSorted(ILMath.todouble(result),dim,desc)) {
                    //ILMatFile f = new ILMatFile(); 
                    //A.Name = "DebugQuickSort"; 
                    //f.Add(A); 
                    //System.IO.Stream s = new System.IO.FileStream("tempADebugQuickSort.mat",System.IO.FileMode.CreateNew); 
                    //f.Write(s); 
                    throw new Exception("invalid values"); 
                }
                Success(input.Dimensions.ToString() + "(Int32) needed: " + sw.ElapsedMilliseconds + " ms"); 
            } catch (Exception e) {
                Error(0, e.Message); 
            }
        }