Пример #1
0
        private void AddResult(MathArgs args, MathResult result)
        {
            if (m_args2entry.ContainsKey(args))
            {
                return;
            }
            while (m_id2args.Count >= m_capacity)
            {
                SortedDictionary <long, MathArgs> .Enumerator it = m_id2args.GetEnumerator();
                it.MoveNext();
                m_args2entry.Remove(it.Current.Value);
                m_id2args.Remove(it.Current.Key);
            }
            ++m_lastUsedID;
            Entry entry = new Entry(result, m_lastUsedID);

            m_args2entry.Add(args, entry);
            try
            {
                m_id2args.Add(m_lastUsedID, args);
            }
            catch (System.Exception)
            {
                m_args2entry.Remove(args);
                throw;
            }
        }
Пример #2
0
        public static Interval CalculateConfidenceInterval(double[] data, double confidenceLevel)
        {
            if ((confidenceLevel <= 0) || (confidenceLevel >= 1))
            {
                string st = string.Format("Confidence level = {0}, but must be more than 0 and less than 1", confidenceLevel);
                throw new ArgumentException(st);
            }
            double average;
            double s2 = CalculateSampleVarianceAndAverage(data, out average);

            MathArgs args = new MathArgs();

            args.Add("$level", confidenceLevel);
            args.Add("$freedom", data.Length - 1);

            MathResult answer = s_confidenceIntervalCache.LookFor(args);

            if (null == answer)
            {
                answer = MathematicaKernel.Execute(s_confidenceInterval, args);
                s_confidenceIntervalCache.Add(args, answer);
            }
            double deviation = (double)answer["deviation"];
            double k         = Math.Sqrt(s2 / data.Length);

            deviation *= k;
            double minimum = average - deviation;
            double maximum = average + deviation;

            return(new Interval(minimum, maximum));
        }
Пример #3
0
        public MainViewModel()
        {
            items = new ObservableCollection <ItemMainMenu> {
                new ItemMainMenu("./img/rect.png", false, DisplayBuildingPage),
                new ItemMainMenu("./img/people.png", false, DisplayPeoplePage),
                new ItemMainMenu("./img/star.png", false, DisplayCriterionPage),
                new ItemMainMenu("./img/note.png", false, DisplayAlternativePage),
                new ItemMainMenu("./img/checkmark.png", false, DisplayPeoplePage),
            };



            homePage        = new HomePage();
            buildingPage    = new BuildingHierarchyPage();
            peoplePage      = new PeopleAssessmentsPage();
            criterionPage   = new CriterionAssessmentsPage();
            alternativePage = new AlternativeAssessmentsPage();

            buildingVM = new BuildingViewModel();
            buildingPage.DataContext = buildingVM;
            buildingVM.Notify       += GetFullInfo;

            mathResult = new MathResult();

            EnabledMenu       = false;
            SelectedIndexMenu = -1;
            CurrentPage       = homePage;
        }
Пример #4
0
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return(1);
            }
            MathResult other = (MathResult)obj;

            return(this.Result.CompareTo(other.Result));
        }
Пример #5
0
        private static void  MathResultOrderTester()
        {
            var results = MathResult.GetResults();

            foreach (var r in results)
            {
                System.Console.WriteLine(r.Result);
            }
            results.Sort();
            foreach (var r in results)
            {
                System.Console.WriteLine(r.Result);
            }
        }
Пример #6
0
 public void Add(MathArgs args, MathResult result)
 {
     if (null == args)
     {
         throw new NullReferenceException("args cannot be null");
     }
     if (null == result)
     {
         throw new NullReferenceException("result cannot be null");
     }
     lock (m_synchronizer)
     {
         AddResult(args, result);
     }
 }
        /// <summary>
        /// This method check and compare captcha text and user entered text.
        /// </summary>
        /// <param name="checkText">User's entered text.</param>
        /// <returns>Returns the result of control and comparison.</returns>
        public bool CheckCorrect(string checkText)
        {
            bool result = false;

            switch (CaptchaStyle)
            {
            case CaptchaStyles.Normal:
                result = checkText == Text ? true : false;
                break;

            case CaptchaStyles.Math:
                result = checkText == MathResult.ToString() ? true : false;
                break;
            }

            return(result);
        }
Пример #8
0
        void ParseResults()
        {
            m_result = new MathResult();
            List <string> output = new List <string>();

            foreach (var element in m_math.PrintOutput)
            {
                string powers = string.Empty;
                string values = Reformat(element, out powers);
                Match  match  = m_pattern.Match(values);
                if (!match.Success)
                {
                    continue;
                }
                string name = match.Groups[1].Value;
                ParseData(name, powers, values);
            }
        }
        public GraphElement CreateNode(MathNode mathNode)
        {
            if (mathNode is MathOperator)
            {
                MathOperator add = mathNode as MathOperator;

                return(CreateMathNode(mathNode, mathNode.name, add.m_Position, 2, 1));
            }
            else if (mathNode is MathStackNode)
            {
                MathStackNode mathStackNode = mathNode as MathStackNode;

                return(CreateStackNode(mathStackNode, mathStackNode.m_Position));
            }
            else if (mathNode is MathFunction)
            {
                MathFunction fn = mathNode as MathFunction;

                Debug.Assert(fn.parameterCount == fn.parameterNames.Length);

                Node nodeUI = CreateMathNode(mathNode, mathNode.name, mathNode.m_Position, fn.parameterNames.Length, 1);

                for (int i = 0; i < fn.parameterNames.Length; ++i)
                {
                    (nodeUI.inputContainer.ElementAt(i) as Port).portName = fn.parameterNames[i];
                }

                return(nodeUI);
            }
            else if (mathNode is IMathBookFieldNode)
            {
                IMathBookFieldNode mathBookFieldNode = mathNode as IMathBookFieldNode;
                SimpleTokenNode    tokenNode         = new SimpleTokenNode(mathBookFieldNode);

                tokenNode.SetPosition(new Rect(mathNode.m_Position, Vector2.zero));
                tokenNode.RefreshPorts();
                tokenNode.visible = true;

                return(tokenNode);
            }
            else if (mathNode is MathConstant)
            {
                MathConstant mathConstant = mathNode as MathConstant;

                Node nodeUI = CreateMathNode(
                    mathNode,
                    mathConstant.name,
                    mathConstant.m_Position, 0, 1);

                var field = new DoubleField()
                {
                    value = mathConstant.m_Value
                };
                field.SetEnabled(!(mathConstant is PIConstant));
                field.RegisterValueChangedCallback(evt => mathConstant.m_Value = (float)evt.newValue);
                nodeUI.inputContainer.Add(field);
                nodeUI.RefreshExpandedState();
                return(nodeUI);
            }
            else if (mathNode is MathResult)
            {
                MathResult mathResult = mathNode as MathResult;

                Node nodeUI = CreateMathNode(
                    mathNode,
                    "Result",
                    mathResult.m_Position, 1, 0);

                nodeUI.inputContainer.Add(new Button(() => Debug.Log(mathResult.Evaluate()))
                {
                    text = "Print result"
                });

                return(nodeUI);
            }
            else if (mathNode is MathGroupNode)
            {
                MathGroupNode mathGroupNode = mathNode as MathGroupNode;

                if (mathGroupNode.m_IsScope)
                {
                    return(CreateScope(mathGroupNode,
                                       mathGroupNode.m_Position));
                }
                else
                {
                    return(CreateGroupNode(mathGroupNode,
                                           mathGroupNode.m_Title,
                                           mathGroupNode.m_Position));
                }
            }

            return(null);
        }
 //Add a MathResult to the list
 public void Add(MathResult result)
 {
     mathResultList.Add(result);
 }
        public void Reload(IEnumerable <MathNode> nodesToReload, IEnumerable <MathPlacemat> placemats, IEnumerable <MathStickyNote> stickies, Dictionary <string, string> oldToNewIdMapping = null)
        {
            string oldId;
            var    nodes          = new Dictionary <MathNode, GraphElement>();
            var    oldIdToNewNode = new Dictionary <string, ISelectable>();

            var newToOldIdMapping = new Dictionary <string, string>();

            if (oldToNewIdMapping != null)
            {
                foreach (var oldIdKV in oldToNewIdMapping)
                {
                    newToOldIdMapping[oldIdKV.Value] = oldIdKV.Key;
                }
            }

            // Create the nodes.
            foreach (MathNode mathNode in nodesToReload)
            {
                GraphElement node = m_SimpleGraphViewWindow.CreateNode(mathNode);

                if (node is Group)
                {
                    node.name = "SimpleGroup";
                }
                else if (node is Scope)
                {
                    node.name = "SimpleScope";
                }
                else
                {
                    node.name = "SimpleNode";
                }

                if (node == null)
                {
                    Debug.LogError("Could not create node " + mathNode);
                    continue;
                }

                nodes[mathNode] = node;

                if (mathNode.groupNode == null)
                {
                    if (newToOldIdMapping.TryGetValue(mathNode.nodeID.ToString(), out oldId))
                    {
                        oldIdToNewNode.Add(oldId, node);
                    }
                }

                AddElement(node);
            }

            // Assign scopes
            foreach (MathNode mathNode in nodesToReload)
            {
                if (mathNode.groupNode == null)
                {
                    continue;
                }

                Scope graphScope = nodes[mathNode.groupNode] as Scope;

                graphScope.AddElement(nodes[mathNode]);
            }

            // Add to stacks
            foreach (MathNode mathNode in nodesToReload)
            {
                MathStackNode stack = mathNode as MathStackNode;

                if (stack == null)
                {
                    continue;
                }

                StackNode graphStackNode = nodes[stack] as StackNode;

                for (int i = 0; i < stack.nodeCount; ++i)
                {
                    MathNode stackMember = stack.GetNode(i);
                    if (stackMember == null)
                    {
                        Debug.LogWarning("null stack member! Item " + i + " of stack " + stack.name + " is null. Possibly a leftover from bad previous manips.");
                    }

                    graphStackNode.AddElement(nodes[stackMember]);
                }
            }

            // Connect the presenters.
            foreach (var mathNode in nodesToReload)
            {
                if (mathNode is MathOperator)
                {
                    MathOperator mathOperator = mathNode as MathOperator;

                    if (!nodes.ContainsKey(mathNode))
                    {
                        Debug.LogError("No element found for " + mathNode);
                        continue;
                    }

                    var graphNode = nodes[mathNode] as Node;

                    if (mathOperator.left != null && nodes.ContainsKey(mathOperator.left))
                    {
                        var outputPort = (nodes[mathOperator.left] as Node).outputContainer[0] as Port;
                        var inputPort  = graphNode.inputContainer[0] as Port;

                        Edge edge = inputPort.ConnectTo(outputPort);
                        edge.viewDataKey = mathOperator.left.nodeID + "_edge";
                        AddElement(edge);
                    }
                    else if (mathOperator.left != null)
                    {
                        //add.m_Left = null;
                        Debug.LogWarning("Invalid left operand for operator " + mathOperator + " , " + mathOperator.left);
                    }

                    if (mathOperator.right != null && nodes.ContainsKey(mathOperator.right))
                    {
                        var outputPort = (nodes[mathOperator.right] as Node).outputContainer[0] as Port;
                        var inputPort  = graphNode.inputContainer[1] as Port;

                        Edge edge = inputPort.ConnectTo(outputPort);
                        edge.viewDataKey = mathOperator.right.nodeID + "_edge";
                        AddElement(edge);
                    }
                    else if (mathOperator.right != null)
                    {
                        Debug.LogWarning("Invalid right operand for operator " + mathOperator + " , " + mathOperator.right);
                    }
                }
                else if (mathNode is MathFunction)
                {
                    MathFunction mathFunction = mathNode as MathFunction;

                    if (!nodes.ContainsKey(mathNode))
                    {
                        Debug.LogError("No element found for " + mathNode);
                        continue;
                    }

                    var graphNode = nodes[mathNode] as Node;

                    for (int i = 0; i < mathFunction.parameterCount; ++i)
                    {
                        MathNode param = mathFunction.GetParameter(i);

                        if (param != null && nodes.ContainsKey(param))
                        {
                            var outputPort = (nodes[param] as Node).outputContainer[0] as Port;
                            var inputPort  = graphNode.inputContainer[i] as Port;

                            Edge edge = inputPort.ConnectTo(outputPort);
                            edge.viewDataKey = param.nodeID + "_edge";
                            AddElement(edge);
                        }
                        else if (param != null)
                        {
                            Debug.LogWarning("Invalid parameter for function" + mathFunction + " , " +
                                             param);
                        }
                    }
                }
                else if (mathNode is MathResult)
                {
                    MathResult mathResult = mathNode as MathResult;
                    var        graphNode  = nodes[mathNode] as Node;

                    if (mathResult.root != null)
                    {
                        var outputPort = (nodes[mathResult.root] as Node).outputContainer[0] as Port;
                        var inputPort  = graphNode.inputContainer[0] as Port;

                        Edge edge = inputPort.ConnectTo(outputPort);
                        edge.viewDataKey = mathResult.root.nodeID + "_edge";
                        AddElement(edge);
                    }
                }
            }

            foreach (var matModel in placemats.OrderBy(p => p.zOrder))
            {
                var newPlacemat = placematContainer.CreatePlacemat <SimplePlacemat>(matModel.position, matModel.zOrder, matModel.title);
                newPlacemat.userData    = matModel;
                newPlacemat.viewDataKey = matModel.identification;
                newPlacemat.Model       = matModel;

                if (newToOldIdMapping.TryGetValue(matModel.identification, out oldId))
                {
                    oldIdToNewNode.Add(oldId, newPlacemat);
                }
            }

            if (stickies != null)
            {
                var existingStickies = this.Query <SimpleStickyNote>().ToList();

                foreach (var sticky in existingStickies.Where(t => !stickies.Contains(t.model)))
                {
                    RemoveElement(sticky);
                }

                foreach (var stickyModel in stickies.Except(existingStickies.Select(t => t.model)))
                {
                    var newSticky = new SimpleStickyNote();
                    newSticky.model    = stickyModel;
                    newSticky.userData = stickyModel;
                    AddElement(newSticky);

                    if (newToOldIdMapping.TryGetValue(stickyModel.id, out oldId))
                    {
                        oldIdToNewNode.Add(oldId, newSticky);
                    }
                }
            }

            // Now that all graph elements have been created, init the collapsed elements of each placemat.
            foreach (var p in this.Query <SimplePlacemat>().ToList())
            {
                p.InitCollapsedElementsFromModel();
            }

            // Make sure collapsed edges are hidden.
            placematContainer.HideCollapsedEdges();

            UpdateSelection(oldIdToNewNode);

            RebuildBlackboard();
        }
Пример #12
0
 public Entry(MathResult result, long id)
 {
     Result = result;
     ID     = id;
 }
Пример #13
0
        private static bool CalculateLinearMarginBalanceInternal(Portfolio portfolio, bool[] zeros, double[,] sigma, double[] profit, double[] margin, PortfolioInput input, Vector[] balance)
        {
            int count = 0;
            Dictionary <int, int> map = new Dictionary <int, int>();

            for (int index = 0; index < zeros.Length; ++index)
            {
                bool status = zeros[index];
                if (!status)
                {
                    map[map.Count] = index;
                    ++count;
                }
            }
            if (0 == count)
            {
                return(true);               // nothing to do
            }
            // create sub-matrix
            double[,] _sigma = new double[count, count];
            double[] _profit = new double[count];
            double[] _margin = new double[count];

            for (int row = 0; row < count; ++row)
            {
                int r = map[row];
                _profit[row] = profit[r];
                _margin[row] = margin[r];
                for (int column = 0; column < count; ++column)
                {
                    int c = map[column];
                    _sigma[row, column] = sigma[r, c];
                }
            }


            double[,] _balance = new double[balance.Length, count];
            for (int row = 0; row < balance.Length; ++row)
            {
                int r = row;
                for (int column = 0; column < count; ++column)
                {
                    int c = map[column];
                    _balance[row, column] = balance[row][c];
                }
            }


            // calculate factor and check it
            double factor = NumericalMethods.Sqrt(_sigma.Maximum());

            if (factor <= 0)
            {
                string st = string.Format("Runtime error: invalid factor = {0}", factor);
                throw new InvalidOperationException(st);
            }
            // normalize data
            NumericalMethods.Multiply(_sigma, 1 / factor / factor);
            NumericalMethods.Multiply(_profit, 1 / factor);
            // execute mathematica script
            MathArgs args = new MathArgs();

            args.Add("$profit", _profit);
            args.Add("$reliability", input.Reliability);
            args.Add("$covariance", _sigma);
            args.Add("$loss", input.MaximumLoss / factor);
            args.Add("$profit", _profit);
            args.Add("$balance", _balance);
            args.Add("$margin", _margin);


            //args.Add("$margin", m);

            double marginThreshold = (input.InitialDeposit - input.MaximumLoss) / input.MarginLevelThreshold;

            args.Add("$marginThreshold", marginThreshold);

            MathResult output = MathematicaKernel.Execute(s_portfolioMarginBalance, args);

            double[] coefficients = (double[])output["result"];
            double   p            = (double)output["profit"];

            if (0 == p)
            {
                return(true);
            }
            // check results
            bool result = FastPositiveMinimalThreshold(zeros, input.MinimumCoefficientValue, count, map, coefficients);

            if (!result)
            {
                return(result);
            }
            // prepare results
            for (int index = 0; index < count; ++index)
            {
                portfolio.Coefficients[map[index]] = coefficients[index];
            }
            portfolio.Profit = (double)output["profit"] * factor;
            portfolio.When   = (double)output["when"];
            return(result);
        }