상속: Npc
예제 #1
0
        public void MakeStep(out int iter, out double residual)
        {
            if (!init)
            {
                throw new InvalidOperationException("Решатель не инициализирован, выполнение операции невозможно");
            }
            currentIter++;
            iter = currentIter;

            Az            = A.Multiply(z);
            coefficient   = dotproduct_rr / Az.DotProduct(z);
            x             = x.Add(z, coefficient);
            r             = r.Add(Az, -coefficient);
            coefficient   = dotproduct_rr;
            dotproduct_rr = r.DotProduct(r);
            coefficient   = dotproduct_rr / coefficient;
            z             = r.Add(z, coefficient);

            if (Double.IsInfinity(coefficient) || Double.IsNaN(coefficient))
            {
                residual = -1;
                return;
            }
            residual = Math.Sqrt(dotproduct_rr) / norm_b;
        }
예제 #2
0
        public Vector Solve(Slae <ProfileMatrix> SLAE, Vector Initial, int maxiter, double eps)
        {
            int    iterNum;
            double pr, pr1, alpha, betta, residual;
            Vector Az;

            Vector r = new Vector(SLAE.RightPart.Differ(SLAE.Matrix.Multiply(Initial)));

            Vector result = new Vector(Initial);

            residual = r.Norm() / SLAE.RightPart.Norm();
            Vector z = new Vector(r);
            Vector s = new Vector(r);
            Vector p = new Vector(r);

            pr1 = p.Scalar(r);
            for (iterNum = 0; iterNum < maxiter && residual >= eps; iterNum++)
            {
                Az       = SLAE.Matrix.Multiply(z);
                alpha    = pr1 / Az.Scalar(s);
                result   = result.Sum(z.Mult(alpha));
                r        = r.Differ(Az.Mult(alpha));
                p        = p.Differ(SLAE.Matrix.TMultiply(s).Mult(alpha));
                pr       = p.Scalar(r);
                betta    = pr / pr1;
                pr1      = pr;
                z        = r.Sum(z.Mult(betta));
                s        = p.Sum(s.Mult(betta));
                residual = r.Norm() / SLAE.RightPart.Norm();
                if (!autotest)
                {
                    if (!InputOutput.OutputIterationToForm(iterNum, residual, maxiter, false))
                    {
                        MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                    }
                }
            }
            if (!autotest)
            {
                if (!InputOutput.OutputIterationToForm(iterNum - 1, residual, maxiter, true))
                {
                    MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                }
            }
            return(result);
        }
예제 #3
0
        public void TestBad2()
        {
            var o = new Az {
                S = "zzz", B = new Bz {
                    S = new Cz {
                        S = 100
                    }
                }, Z = "qxx"
            };

            byte[] data = serializer.Serialize(o);
            var    oo   = serializer.Deserialize <A>(data);

            Assert.AreEqual("zzz", oo.S);
            Assert.AreEqual(null, oo.B.S);
            Assert.AreEqual("qxx", oo.Z);
        }
예제 #4
0
파일: CGM.cs 프로젝트: alandre/SLAE-solver
        public void MakeStep(out int iter, out double residual)
        {
            if (!init)
            {
                throw new InvalidOperationException("Решатель не инициализирован, выполнение операции невозможно");
            }

            currentIter++;
            iter = currentIter;

            if (Factorizer != null)
            {
                Az = Factorizer.UTransposeSolve(At.Multiply(Factorizer.LTransposeSolve(Factorizer.LSolve(A.Multiply(Factorizer.USolve(z))))));;
            }
            else
            {
                Az = At.Multiply(A.Multiply(z));
            }

            coefficient = dotproduct_rr / Az.DotProduct(z);

            if (Double.IsInfinity(coefficient) || Double.IsNaN(coefficient))
            {
                residual = -1;
                return;
            }

            xk            = xk.Add(z, coefficient);
            r             = r.Add(Az, -coefficient);
            coefficient   = dotproduct_rr;
            dotproduct_rr = r.DotProduct(r);
            coefficient   = dotproduct_rr / coefficient;

            if (Double.IsInfinity(coefficient) || Double.IsNaN(coefficient))
            {
                residual = -1;
                return;
            }

            z        = r.Add(z, coefficient);
            residual = Math.Sqrt(dotproduct_rr) / norm_b;
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string T;
            string Az;
            string Pitch;
            string Roll, t1, t2;
            double AzD = 0, RollD = 0;
            // int AzI = 0;

            string bufStr;

            //label5.Invoke(new MethodInvoker(delegate() { label5.Text = Convert.ToString(key); }));
            if (serialPort1.IsOpen)
            {
                Thread.Sleep(40);
            }
            while (key != true)
            {
                try
                {
                    T  = serialPort1.ReadTo("|");
                    Az = serialPort1.ReadTo("|");
                    //  t1 = serialPort1.ReadTo("|");
                    Pitch          = serialPort1.ReadTo("|");
                    Roll           = serialPort1.ReadTo("|");
                    driveRotKeyNow = Convert.ToInt32(serialPort1.ReadLine());

                    //t2 = serialPort1.ReadLine();
                    //Roll = "76.6";
                    //Az = "346.4";
                    if (Az == "nan")
                    {
                        Az = "0.1";
                    }
                    bufStr = Az.Replace(".", ","); // заменяем точку на запятую для double

                    AzD = Convert.ToDouble(bufStr);
                    if (AzD < 2 || AzD > 358)
                    {
                        angle = (float)AzD;
                        KalmanFiltrMag(AzD);
                        xMagOpt = AzD;
                    }
                    else
                    {
                        KalmanFiltrMag(AzD);
                        angle = (float)xMagOpt;   // значение угла на картинке
                    }


                    bufStr = Roll.Replace(".", ","); // заменяем точку на запятую для double
                    RollD  = Convert.ToDouble(bufStr);


                    // xAcelOpt = (float)RollD;
                    KalmanFiltr(RollD);
                    pitch = -(float)xAcelOpt;// значение угла на картинке
                    pictureBox1.Invoke(new MethodInvoker(delegate() { pictureBox1.Invalidate(); }));
                    pictureBox2.Invoke(new MethodInvoker(delegate() { pictureBox2.Invalidate(); }));
                    label10.Invoke(new MethodInvoker(delegate() { label10.Text = T + "°C"; }));
                    label9.Invoke(new MethodInvoker(delegate() { label9.Text = Az; }));
                    label8.Invoke(new MethodInvoker(delegate() { label8.Text = Roll; }));
                    //label7.Invoke(new MethodInvoker(delegate() { label7.Text = Pitch; }));
                    label15.Invoke(new MethodInvoker(delegate() { label15.Text = Convert.ToString(Math.Round(xAcelOpt, 2)) + "°"; }));
                    label18.Invoke(new MethodInvoker(delegate() { label18.Text = Convert.ToString(Math.Round(xMagOpt, 2)) + "°"; }));
                    //label25.Invoke(new MethodInvoker(delegate() { label25.Text = Convert.ToString(driveRotKey); }));
                    //if (orientChan == true)
                    //{
                    //    // calibrKey = true;
                    //    rotatFunc(az, el, xMagOpt, xAcelOpt);
                    //}
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message);     //если ком порт не открылся, показываем почему.
                }

                //Thread.Sleep(40);
            }
            if (!serialPort1.IsOpen)
            {
                textBox1.Invoke(new MethodInvoker(delegate() { textBox1.Text = "Disconnect"; }));
            }
            // label5.Invoke(new MethodInvoker(delegate() { label5.Text = Convert.ToString(key); }));
        }
예제 #6
0
        public Vector Solve(Slae <ProfileMatrix> SLAE, Vector Initial, int maxiter, double eps)
        {
            int    iterNum;
            double iner_r, iner_mr, alpha, betta, residual;
            Vector Az, Mr;

            Vector r = new Vector(SLAE.RightPart.Differ(SLAE.Matrix.Multiply(Initial)));

            Vector result = new Vector(Initial);

            residual = r.Norm() / SLAE.RightPart.Norm();
            if (Data.preconditioner == 0)//нет предобуславливания
            {
                Vector z = new Vector(r);
                for (iterNum = 0; iterNum < maxiter && residual >= eps; iterNum++)
                {
                    iner_r = r.Scalar(r);
                    Az     = SLAE.Matrix.Multiply(z);
                    alpha  = r.Scalar(r) / Az.Scalar(z);
                    result = result.Sum(z.Mult(alpha));
                    r      = r.Differ(Az.Mult(alpha));
                    betta  = r.Scalar(r) / iner_r;
                    z      = r.Sum(z.Mult(betta));

                    residual = r.Norm() / SLAE.RightPart.Norm();
                    if (!autotest)
                    {
                        if (!InputOutput.OutputIterationToForm(iterNum, residual, maxiter, false))
                        {
                            MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                        }
                    }
                }
                if (!autotest)
                {
                    if (!InputOutput.OutputIterationToForm(iterNum - 1, residual, maxiter, true))
                    {
                        MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                    }
                }
            }
            else
            if (Data.preconditioner == 1 || Data.preconditioner == 2 || Data.preconditioner == 3 || Data.preconditioner == 4)    //диагональное предобуславливание или Неполное разложение Холесского
            {
                Vector z = new Vector(SLAE.PMatrix.ReverseProgress(SLAE.PMatrix.DirectProgress(r)));
                for (iterNum = 0; iterNum < maxiter && residual >= eps; iterNum++)
                {
                    Mr      = SLAE.PMatrix.ReverseProgress(SLAE.PMatrix.DirectProgress(r)); //M^-1*r(k-1)
                    Az      = SLAE.Matrix.Multiply(z);                                      //A*z(k-1)
                    alpha   = Mr.Scalar(r) / Az.Scalar(z);
                    result  = result.Sum(z.Mult(alpha));
                    iner_mr = Mr.Scalar(r);    //(M^-1*r(k-1),r(k-1))
                    r       = r.Differ(Az.Mult(alpha));
                    Mr      = SLAE.PMatrix.ReverseProgress(SLAE.PMatrix.DirectProgress(r));
                    betta   = Mr.Scalar(r) / iner_mr;
                    z       = Mr.Sum(z.Mult(betta));

                    residual = r.Norm() / SLAE.RightPart.Norm();
                    if (!autotest)
                    {
                        if (!InputOutput.OutputIterationToForm(iterNum, residual, maxiter, false))
                        {
                            MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                        }
                    }
                }
                if (!autotest)
                {
                    if (!InputOutput.OutputIterationToForm(iterNum - 1, residual, maxiter, true))
                    {
                        MessageBox.Show("Ошибка при выводе данных на форму.", "Опаньки...", MessageBoxButtons.OK);
                    }
                }
            }
            return(result);
        }
예제 #7
0
        public void TestMethod1()
        {
            Angle Az, Ha, Dec;
            Angle LST = WiseSite.Instance.LocalSiderealTime;

            Ha  = LST;
            Dec = Angle.FromDegrees(65, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));

            Ha  = LST;
            Dec = Angle.FromDegrees(25, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));

            Ha  = LST;
            Dec = Angle.FromDegrees(-15, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));

            Ha  = LST;
            Dec = Angle.FromDegrees(0, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));


            Ha  = LST + Angle.FromHours(4);
            Dec = Angle.FromRadians(0, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));

            Ha  = Angle.FromHours(-3.25);
            Dec = Angle.FromRadians(0, Angle.Type.Dec);
            Az  = domeSlaveDriver.CalculateDomeAzimuth(Ha, Dec);
            Console.WriteLine(string.Format("{0}, {1} => {2}", Ha.ToString(), Dec.ToString(), Az.ToNiceString()));
        }
예제 #8
0
        public void MakeStep(out int iter, out double residual)
        {
            if (!init)
            {
                throw new InvalidOperationException("Решатель не инициализирован, выполнение операции невозможно");
            }

            currentIter++;
            iter = currentIter;

            if (Factorizer != null)
            {
                if (currentIter % 5 == 0)
                {
                    r_prev             = Factorizer.LSolve(b.Add(A.Multiply(xk), -1));
                    r0                 = r_prev.Clone();
                    z                  = Factorizer.USolve(r_prev.Clone());
                    dotproduct_rr      = r_prev.DotProduct(r_prev);
                    dotproduct_rprevr0 = dotproduct_rr;
                }

                LAUz = Factorizer.LSolve(A.Multiply(Factorizer.USolve(z)));
                var alpha = dotproduct_rprevr0 / (LAUz.DotProduct(r0));

                p = r_prev.Add(LAUz, -alpha);

                LAUp = Factorizer.LSolve(A.Multiply(Factorizer.USolve(p)));
                var gamma = (LAUp.DotProduct(p)) / (LAUp.DotProduct(LAUp));

                xk = xk.Add(z, alpha).Add(p, gamma);
                r  = p.Add(LAUp, -gamma);

                dotproduct_rkr0 = r.DotProduct(r0);
                var beta = alpha * dotproduct_rkr0 / (gamma * dotproduct_rprevr0);
                z = r.Add(z, beta).Add(LAUz, -beta * gamma);

                dotproduct_rprevr0 = dotproduct_rkr0;
                r_prev             = r;


                if (Double.IsNaN(beta) || Double.IsInfinity(beta))
                {
                    residual = -1;
                    return;
                }
            }
            else
            {
                if (currentIter % 5 == 0)
                {
                    r_prev             = b.Add(A.Multiply(xk), -1);
                    r0                 = r_prev.Clone();
                    z                  = r_prev.Clone();
                    dotproduct_rr      = r_prev.DotProduct(r_prev);
                    dotproduct_rprevr0 = dotproduct_rr;
                }

                Az = A.Multiply(z);
                var alpha = dotproduct_rprevr0 / (Az.DotProduct(r0));

                p = r_prev.Add(Az, -alpha);

                Ap = A.Multiply(p);
                var gamma = (Ap.DotProduct(p)) / (Ap.DotProduct(Ap));

                xk = xk.Add(z, alpha).Add(p, gamma);
                r  = p.Add(Ap, -gamma);

                dotproduct_rkr0 = r.DotProduct(r0);
                var beta = alpha * dotproduct_rkr0 / (gamma * dotproduct_rprevr0);
                z = r.Add(z, beta).Add(Az, -beta * gamma);

                dotproduct_rprevr0 = dotproduct_rkr0;
                r_prev             = r;

                if (Double.IsNaN(beta) || Double.IsInfinity(beta))
                {
                    residual = -1;
                    return;
                }
            }

            dotproduct_rr = r.DotProduct(r);
            residual      = Math.Sqrt(dotproduct_rr) / norm_b;
        }
예제 #9
0
        /// <summary>
        /// Решение СЛАУ методом сопряженных градиентов
        /// </summary>
        /// <param name="A">Матрица СЛАУ</param>
        /// <param name="b">Ветор правой части</param>
        /// <param name="Initial">Ветор начального приближения</param>
        /// <param name="Precision">Точность</param>
        /// <param name="Maxiter">Максимальное число итераций</param>
        /// <returns>Вектор x - решение СЛАУ Ax=b с заданной точностью</returns>
        public IVector Solve(IPreconditioner Preconditioner, IMatrix A, IVector b, IVector Initial, double Precision, int Maxiter, ILogger Logger)
        {
            Logger.WriteNameSolution("MSG", Preconditioner.getName());
            string start = DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss:fff");

            Logger.setMaxIter(Maxiter);
            IVector x = Preconditioner.MultU(Initial);

            double scalAzZ, scalRR, alpha, beta = 1.0;

            IVector r = b.Add(A.Mult(Initial), 1, -1);

            r = Preconditioner.T.SolveL(Preconditioner.SolveL(r));
            IVector Az, Atz, z = A.Transpose.Mult(r);

            z = Preconditioner.T.SolveU(z);

            r      = z.Clone() as IVector;
            scalRR = r.ScalarMult(r);
            double normR = Math.Sqrt(scalRR) / b.Norm;

            for (int iter = 0; iter < Maxiter && normR > Precision && beta > 0; iter++)
            {
                Az = Preconditioner.SolveU(z);

                Atz = A.Mult(Az);
                Atz = Preconditioner.T.SolveL(Preconditioner.SolveL(Atz));
                Az  = A.Transpose.Mult(Atz);
                Az  = Preconditioner.T.SolveU(Az);

                scalAzZ = Az.ScalarMult(z);

                if (scalAzZ == 0)
                {
                    Logger.WriteSolution(x, Maxiter, b.Add(A.Mult(x), -1, 1).Norm);
                    Logger.WriteTime(start, DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss:fff"));
                    throw new DivideByZeroException("Division by 0");
                }

                alpha = scalRR / scalAzZ;

                x.Add(z, 1, alpha, true);
                r.Add(Az, 1, -alpha, true);

                beta = scalRR;
                if (scalRR == 0)
                {
                    Logger.WriteSolution(x, Maxiter, b.Add(A.Mult(x), -1, 1).Norm);
                    Logger.WriteTime(start, DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss:fff"));
                    throw new DivideByZeroException("Division by 0");
                }
                scalRR = r.ScalarMult(r);
                beta   = scalRR / beta;

                z     = r.Add(z, 1, beta);
                normR = Math.Sqrt(scalRR) / b.Norm;
                Factory.Residual.Add(normR);
                Logger.WriteIteration(iter, normR);

                if (double.IsNaN(normR) || double.IsInfinity(normR))
                {
                    x = Preconditioner.SolveU(x);
                    Logger.WriteSolution(x, Maxiter, b.Add(A.Mult(x), -1, 1).Norm);
                    Logger.WriteTime(start, DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss:fff"));
                    throw new CantSolveException();
                }
            }
            ;
            x = Preconditioner.SolveU(x);
            Logger.WriteSolution(x, Maxiter, b.Add(A.Mult(x), -1, 1).Norm);
            Logger.WriteTime(start, DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss:fff"));
            return(x);
        }
예제 #10
0
파일: Program.cs 프로젝트: tessin/cloud-pad
        // LINQPad script entry point
        // when deployed as an Azure Function this method is not used
        public static async Task <int> MainAsync(object userQuery, string[] args)
        {
            var hasConsoleInput = false;

            if ("LPRun.exe".Equals(Process.GetCurrentProcess().MainModule.ModuleName, StringComparison.OrdinalIgnoreCase))
            {
                hasConsoleInput = Environment.UserInteractive;

                // pipe trace to console
                Trace.Listeners.Add(new ConsoleTraceListener());
            }

            if (userQuery == null)
            {
                throw new ArgumentNullException("User query cannot be null. You should pass 'this' here.", nameof(userQuery));
            }
            var userQueryTypeInfo = new UserQueryTypeInfo(userQuery);

            var currentQuery = Util.CurrentQuery;

            if (currentQuery == null)
            {
                throw new InvalidOperationException("This script must be run from wthin a LINQPad context (either via LINQPad or LPRun).");
            }
            var currentQueryInfo = new QueryInfo(currentQuery);

            var currentQueryPath = Util.CurrentQueryPath;

            if (currentQueryPath == null)
            {
                throw new InvalidOperationException("A file name is required (save your LINQPad query to disk). Without it, we cannot establish a context for your functions.");
            }
            var currentQueryPathInfo = new QueryPathInfo(currentQueryPath);

            // ========

            args = args ?? new string[0]; // note: `args` can be null
            if (args.Length == 0)
            {
                if (FirstRun.ShouldPrompt())
                {
                    FirstRun.Prompt();
                }

                // ================================

                var workingDirectory = Path.Combine(Env.GetLocalAppDataDirectory(), currentQueryPathInfo.InstanceId);
                Debug.WriteLine($"workingDirectory: {workingDirectory}");
                FunctionApp.Deploy(workingDirectory);

                // ================================

                Compiler.Compile(new UserQueryTypeInfo(userQuery), currentQueryInfo, new CompilationOptions(currentQueryPath)
                {
                    OutDir = workingDirectory,
                }, currentQueryInfo);

                // ================================

                StorageEmulator.StartOrInstall();

                // todo: if AzureWebJobsStorage or AzureWebJobsDashboard is set elsewhere, like app.config we shouldn't override them like this

                if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AzureWebJobsStorage")))
                {
                    Environment.SetEnvironmentVariable("AzureWebJobsStorage", "UseDevelopmentStorage=true");
                }

                if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AzureWebJobsDashboard")))
                {
                    Environment.SetEnvironmentVariable("AzureWebJobsDashboard", "UseDevelopmentStorage=true");
                }

                // ================================

                var lastWriteTime = File.GetLastWriteTimeUtc(currentQueryPathInfo.QueryPath);

                using (var fs = new FileSystemWatcher(currentQueryPathInfo.QueryDirectoryName, currentQueryPathInfo.QueryFileName))
                {
                    var stream = new BlockingCollection <int>();

                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        foreach (var x in stream.GetConsumingEnumerable())
                        {
                            Thread.Sleep(250); // hold, for just a moment...

                            var lastWriteTime2 = File.GetLastWriteTimeUtc(currentQueryPathInfo.QueryPath);
                            if (lastWriteTime < lastWriteTime2)
                            {
                                Debug.WriteLine("Recompiling...");

                                Util.RunAndWait(currentQueryPathInfo.QueryPath, new[] { "-compile", "-out-dir", workingDirectory });

                                Debug.WriteLine("Recompiled!");

                                lastWriteTime = lastWriteTime2;
                            }
                        }
                    });

                    fs.Changed += (sender, e) => stream.Add(0);

                    fs.EnableRaisingEvents = true;

                    await JobHost.LaunchAsync(workingDirectory);

                    stream.CompleteAdding();
                }

                // ================================

                return(0);
            }
            else
            {
                try
                {
                    var options = CommandLine.Parse(args, new Options {
                    });
                    if (options.compile)
                    {
                        var compilationOptions = new CompilationOptions(currentQueryPath);
                        compilationOptions.OutDir = options.out_dir == null?Path.Combine(compilationOptions.QueryDirectoryName, compilationOptions.QueryName + "_" + userQueryTypeInfo.Id) : Path.GetFullPath(options.out_dir);

                        Compiler.Compile(userQueryTypeInfo, currentQueryInfo, compilationOptions, currentQueryInfo);
                        Trace.WriteLine($"Done. Output written to '{compilationOptions.OutDir}'");
                        return(0);
                    }
                    else if (options.publish)
                    {
                        var compilationOptions = new CompilationOptions(currentQueryPath);
                        compilationOptions.OutDir = Path.Combine(compilationOptions.QueryDirectoryName, compilationOptions.QueryName + "_" + userQueryTypeInfo.Id + "_" + Environment.TickCount);
                        try
                        {
                            Compiler.Compile(userQueryTypeInfo, currentQueryInfo, compilationOptions, currentQueryInfo);

                            var publishSettingsFileNames = FileUtil.ResolveSearchPatternUpDirectoryTree(compilationOptions.QueryDirectoryName, "*.PublishSettings").ToList();
                            if (1 != publishSettingsFileNames.Count)
                            {
                                if (1 < publishSettingsFileNames.Count)
                                {
                                    throw new InvalidOperationException($"Aborted. Found two or more '*.PublishSettings' files. " + string.Join(", ", publishSettingsFileNames));
                                }
                                else
                                {
                                    throw new InvalidOperationException($"Aborted. Cannot find a '*.PublishSettings' file in '{compilationOptions.QueryDirectoryName}' or any of it's parents");
                                }
                            }

                            var kudu = KuduClient.FromPublishProfile(publishSettingsFileNames[0]);

                            var appSettings = kudu.GetSettings();
                            if (appSettings.TryGetValue("WEBSITE_SITE_NAME", out var siteName) && appSettings.TryGetValue("WEBSITE_SLOT_NAME", out var slotName))
                            {
                                Trace.WriteLine($"Publishing to '{siteName}' ({slotName})...");
                            }
                            else
                            {
                                Trace.WriteLine($"Site '{kudu.Host}' metadata is missing");
                            }

                            // this setting needs to be changed using the az command line
                            // https://docs.microsoft.com/en-us/azure/azure-functions/set-runtime-version#view-and-update-the-runtime-version-using-azure-cli
                            // using the Kudu settings API doesn't update the application app settings

                            if (appSettings.TryGetValue("FUNCTIONS_EXTENSION_VERSION", out var functionsExtensionVersion))
                            {
                                if (functionsExtensionVersion != "~1")
                                {
                                    var text    = "The Azure Functions runtime version 1.x is required. Would you like to change the FUNCTIONS_EXTENSION_VERSION setting to ~1?";
                                    var caption = "Azure Functions Runtime";

                                    if (MessageBox.ShowYesNoQuestion(text, caption))
                                    {
                                        var result = await Az.RunAsunc("functionapp", "list", "--query", $"[?name=='{siteName}']");

                                        if (result.Output.Count() != 1)
                                        {
                                            throw new InvalidOperationException($"Aborted. Cannot find Azure Function App '{siteName}'");
                                        }

                                        var functionApp = result.Output[0];

                                        var g = (string)functionApp["resourceGroup"];

                                        var result2 = await Az.RunAsunc("functionapp", "config", "appsettings", "set", "-g", g, "-n", siteName, "--settings", "FUNCTIONS_EXTENSION_VERSION=~1");

                                        if (result2.ExitCode != 0)
                                        {
                                            throw new InvalidOperationException($"Aborted. Cannot configure Azure Function App '{siteName}'");
                                        }
                                    }
                                    else
                                    {
                                        throw new InvalidOperationException("Aborted. Azure Functions runtime version 1.x is required");
                                    }
                                }
                            }

                            // need to check for cloud pad function app runtime
                            // if not found, offer to deploy it

                            if (!kudu.VfsExists("site/wwwroot/bin/CloudPad.FunctionApp.dll"))
                            {
                                if (hasConsoleInput)
                                {
                                    var text    = "It looks like the CloudPad.FunctionApp (runtime) has not been deployed yet. Would you like to deploy this now (you only do this once per Azure Function App)?";
                                    var caption = "Deployment";

                                    if (MessageBox.ShowYesNoQuestion(text, caption))
                                    {
                                        Trace.WriteLine($"Deploying runtime... (this will just take a minute)");
                                        kudu.ZipDeployPackage(FunctionApp.PackageUri);
                                    }
                                }
                                else
                                {
                                    Trace.WriteLine($"Oh no. You have to deploy the CloudPad.FunctionApp runtime first");
                                    return(1);
                                }
                            }

                            Trace.WriteLine($"Deploying script '{currentQueryPathInfo.QueryFileNameWithoutExtension}' ({userQueryTypeInfo.AssemblyName})...");

                            kudu.ZipUpload(compilationOptions.OutDir);
                        }
                        finally
                        {
                            if (Directory.Exists(compilationOptions.OutDir))
                            {
                                Directory.Delete(compilationOptions.OutDir, true);
                            }
                        }
                        Trace.WriteLine("Done.");
                        if (options.interactive)
                        {
                            if (hasConsoleInput)
                            {
                                Console.WriteLine("Press any key to continue...");
                                Console.ReadKey();
                            }
                        }
                        return(0);
                    }
                    else if (options.pack)
                    {
                        var compilationOptions = new CompilationOptions(currentQueryPath);
                        compilationOptions.OutDir = options.out_dir == null?Path.Combine(compilationOptions.QueryDirectoryName, compilationOptions.QueryName + "_publish") : Path.GetFullPath(options.out_dir);

                        FunctionApp.Deploy(compilationOptions.OutDir);
                        Compiler.Compile(userQueryTypeInfo, currentQueryInfo, compilationOptions, currentQueryInfo);
                        Trace.WriteLine($"Done. Output written to '{compilationOptions.OutDir}'");
                        return(0);
                    }
                    else if (options.install)
                    {
                        FirstRun.Install();
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);

                    if (hasConsoleInput)
                    {
                        Console.WriteLine("Press any key to continue...");
                        Console.ReadKey();
                    }

                    throw;
                }
                return(1);
            }
        }