Beispiel #1
0
        public void RunMain()
        {
            Proposition expr;
            string      result;

            //string s = "( p -> ( q & r ) ) <-> y";
            //string s = "(A ->( B -> C )) <-> ( C -> D ) & ( D -> E) ";
            //string s = "p<->p";
            //string s = "p <-> a & b";
            //string s = "((p | q) & (~p | r)) -> (q | r)";
            //string s = "(P|(S&T))|R";
            //string s = "(A&B)|(~A)|(~B)";
            //string s = "(~p)<->(p->F)";
            //string s = "(~((a&b)|c)&d)|(((a&b)|c)&(~d))";
            string      s           = "(a&b)|(c&d)|(e&f)";
            ParseEngine parseEngine = new ParseEngine();

            parseEngine.TryParse(out expr, out result, s);

            LogicEngine logicEng = new LogicEngine();
            Proposition nnfExpr  = logicEng.ConvertToNNF(expr);

            Proposition cnfExpr = logicEng.ConvertToCNF(nnfExpr);
            bool        b       = logicEng.IsTautology(cnfExpr);

            WriteFile(cnfExpr.ToString());
        }
Beispiel #2
0
        public void Constructor_CreateDoubleNegationOfLiteral_LeftChildCreatedWithNegationRemoved()
        {
            // Arrange
            Negation negation       = (Negation)PropositionGenerator.CreateUnaryConnectiveWithRandomSymbol(Negation.SYMBOL);
            Negation doubleNegation = new Negation();

            doubleNegation.LeftSuccessor = negation;

            HashSet <Proposition> propositions = new HashSet <Proposition>()
            {
                doubleNegation
            };

            // Act
            SemanticTableauxElement semanticTableauxElement = new SemanticTableauxElement(propositions);
            HashSet <Proposition>   propositionSetOfChild   = semanticTableauxElement.LeftChild.Propositions;

            int actualNumberOfPropositionsInSet   = propositionSetOfChild.Count;
            int expectedNumberOfPropositionsInSet = 1;

            Proposition expectedPropositionInSet = negation.LeftSuccessor;

            // Assert
            actualNumberOfPropositionsInSet.Should().Be(expectedNumberOfPropositionsInSet, "Because after removing the negation of one proposition we are left with one proposition");

            foreach (Proposition p in propositionSetOfChild)
            {
                p.Should().Be(expectedPropositionInSet, "Because the inner most child will be left over after removing it's encapsulating negations");
            }
        }
Beispiel #3
0
        public void Save()
        {
            IPropositionDAO pdao = new MSSQLPropositionDAO();
            Proposition     prop = new Proposition();

            prop.dateOfSubmission = DateOfSubmission;
            prop.proposing        = Proposing.Id;
            prop.replacementFor   = Replacing.Id;


            try
            {
                int prop_id = pdao.SaveProposition(prop);
                IPropositionsCoursesDAO pcdao = new MSSQLPropositionsCoursesDAO();

                foreach (CourseModel cm in Replacements)
                {
                    pcdao.SavePropositionCourse(new PropositionCourse(prop_id, cm.Id));
                }
            }
            catch (NoDatasourceConnectionException e)
            {
                Debug.Write(e.Message);
                throw new DataServiceException();
            }
        }
Beispiel #4
0
 public ActionResult NewProposition(string id, [FromBody] Offre offre)
 {
     try
     {
         var proposition = new Proposition
         {
             Id    = offre.Id,
             Offre = offre
         };
         var entrepriseCollection = new EntrepriseCollection();
         var entreprise           = entrepriseCollection.GetItems(e => e.Id == id).FirstOrDefault();
         if (entreprise == null)
         {
             return(StatusCode(500, "Internal Server Error: Entreprise not found"));
         }
         if (entreprise.Propositions == null)
         {
             entreprise.Propositions = new List <Offre>();
         }
         ((List <Offre>)(entreprise.Propositions)).Add(offre);
         entrepriseCollection.UpdateItem(entreprise.Id, entreprise);
         var propositionCollection = new PropositionCollection();
         propositionCollection.NewItems(proposition);
         return(Ok("Propositions posté avec success"));
     }
     catch (Exception e)
     {
         return(StatusCode(500, e.Message));
     }
 }
Beispiel #5
0
        public void IsClosed_ContradictionByConjunction_AfterCreatingChildElementContainsContradictionClosedShouldReturnTrue()
        {
            // Arrange
            Conjunction contradiction = new Conjunction();

            Proposition child = new Proposition('Z');

            contradiction.LeftSuccessor = child;

            Negation negatedChild = new Negation();

            negatedChild.LeftSuccessor   = child;
            contradiction.RightSuccessor = negatedChild;

            Proposition p = new Proposition('G');

            HashSet <Proposition> propositionSet = new HashSet <Proposition>()
            {
                contradiction,
                p
            };

            // Act
            SemanticTableauxElement alphaRuleElement = new SemanticTableauxElement(propositionSet);
            bool alphaRuleClosedByChild = alphaRuleElement.IsClosed();

            // Assert
            alphaRuleClosedByChild.Should().BeTrue("Because the child alpha rule element should close the branch by contradiction.");
        }
Beispiel #6
0
        public void GetVariablesTest()
        {
            string      input = "=(&(~(b), a),|(=(c,d),>(e,f)))";
            Proposition check = new Proposition(input);

            Assert.AreEqual(6, check.GetVariables().Count());
        }
Beispiel #7
0
    /// <summary>enumerates the state transitions of the process</summary>
    public TransitionSystem BuildTransitionSystem(string[] variables, int initialNode, int finalNode, out int[] intialStates, out int[] finalStates, out IProposition[] propositions)
    {
        // crawl
        var numVariables = variables.Length;
        var steps        = new List <Step>();
        var initialState = new State(numVariables);
        var initialStep  = Crawl(initialNode, initialState, steps);

        // create transition system and proposition
        var transitionSystem = new TransitionSystem(steps.Count);
        var props            = new Proposition[numVariables];

        for (int i = 0; i < numVariables; i++)
        {
            props[i] = new Proposition(transitionSystem.numStates, variables[i]);
        }

        // convert steps to state transitions
        var addedSteps = new List <Step>();

        BuildTransitionSystem(transitionSystem, props, initialStep, addedSteps);

        // export initial and final states
        intialStates = new[] { initialStep.id };
        finalStates  = steps.Where(p => p.node == finalNode).Select(p => p.id).ToArray();
        propositions = props;

        return(transitionSystem);
    }
Beispiel #8
0
        public void Single_flag()
        {
            Proposition temp = new Proposition();

            temp.setA(0);
            Assert.AreEqual(temp.Single, true);
        }
Beispiel #9
0
        public void testOperations()
        {
            Proposition tempAnd = new Proposition(2, Operations.Conjunction, 3);

            Assert.AreEqual(Operations.Conjunction, tempAnd.Operation, "AND Error");

            Proposition tempOr = new Proposition(2, Operations.Disjunction, 3);

            Assert.AreEqual(Operations.Disjunction, tempOr.Operation, "OR Error");

//          Proposition tempNot = new Proposition("!", 3);
//          Assert.AreEqual(Operations.Negation, tempNot.getO(), "NOT Error");

            Proposition tempImp = new Proposition(2, Operations.Implication, 3);

            Assert.AreEqual(Operations.Implication, tempImp.Operation, "Implication Error");

            Proposition tempBic = new Proposition(2, Operations.Biconditional, 3);

            Assert.AreEqual(Operations.Biconditional, tempBic.Operation, "Biconditional Error");

            Proposition tempNS = new Proposition();

            Assert.AreEqual(Operations.NotSet, tempNS.Operation, "Not Set Error");
        }
Beispiel #10
0
        /// <summary>
        /// Get the binary tree of DNF
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        private Proposition GetDNFRecursively(List <Row> rows)
        {
            Proposition root = null;

            //if there is 1 row, return the DNF of it
            if (rows.Count == 1)
            {
                root = rows[0].GetDNF();
            }

            //if there is more than 1 row, return a binary tree with root 'Or'
            else if (rows.Count > 1)
            {
                root          = new Or();
                root.LeftNode = rows[0].GetDNF();
                rows.RemoveAt(0);

                //if there is 1 row in the right, return the right node
                if (rows.Count == 1)
                {
                    root.RightNode = rows[0].GetDNF();
                }
                //if there is more than 1 row, create the right sub-tree
                else
                {
                    root.RightNode = GetDNFRecursively(rows);
                }
            }

            return(root);
        }
Beispiel #11
0
 /// <summary>
 /// A rule that states that the head is justified by the body
 /// </summary>
 /// <param name="head">proposition that can be concluded from the body</param>
 /// <param name="body">Literal or conjunction that would justify the head</param>
 public Rule(Proposition head, Expression body)
 {
     Head            = head;
     Head.IsRuleHead = true;
     Body            = body;
     Body.MarkAntecedent();
 }
Beispiel #12
0
        public void doesItConsumePropsCorrectlyTest()
        {
            Proposition proposition          = new Proposition("|(=(>(d,B),>(s,B)),=(>(c,B),>(s,g)))");
            string      expected_proposition = "|(=(>(d,B),>(s,B)),=(>(c,B),>(s,g)))";

            Assert.AreEqual(expected_proposition, proposition.getPropositionASCIIFormat());
        }
Beispiel #13
0
        public void doesItConsumePropsCorrectlyWithNOTSecondTest()
        {
            Proposition proposition          = new Proposition("~(|(~(>(a,b)),=(c,f)))");
            string      expected_proposition = "~(|(~(>(a,b)),=(c,f)))";

            Assert.AreEqual(expected_proposition, proposition.getPropositionASCIIFormat());
        }
Beispiel #14
0
        private bool IsInDnf(Proposition dnfRoot)
        {
            bool dnf = true;

            Stack <Proposition> propositionStack = new Stack <Proposition>();

            propositionStack.Push(dnfRoot);

            Proposition currentProposition = dnfRoot;

            while (propositionStack.Count > 0)
            {
                if (currentProposition.GetType() == typeof(Conjunction))
                {
                    Conjunction conjunction = (Conjunction)currentProposition;
                    dnf = checkIfNotFollowedByDisjunction(conjunction);

                    if (!dnf) // If it fails anywhere in the syntax tree we can early exit.
                    {
                        return(dnf);
                    }
                }
                else
                {
                    AddChildrenToStack(ref propositionStack, currentProposition);
                }

                currentProposition = propositionStack.Pop();
            }

            return(dnf);
        }
Beispiel #15
0
        /// <summary>Evaluate with given data</summary>
        /// <param name="data">Data to evaulate</param>
        /// <returns>Evaluation result</returns>
        public static bool Eval(this Proposition expr, Dictionary <string, bool> data)
        {
            bool value; string error;

            calcEngine.TryEvaluate(out value, out error, expr, data);
            return(value);
        }
        public async Task <IActionResult> Create([Bind("Title, Content, UserId, CityId, Date")] Proposition proposition)
        {
            var cities = await _context.Cities.ToListAsync();

            ViewData["Cities"] = cities;

            var user = GetUser();

            try
            {
                if (ModelState.IsValid)
                {
                    proposition.UserId = user.Id;
                    proposition.Date   = DateTime.Now;
                    _context.Add(proposition);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index", "Proposition"));
                }
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(proposition));
        }
        /// <summary>
        /// Generate a text file to print the tree through GraphViz
        /// </summary>
        /// <param name="p"></param>
        /// <param name="filename"></param>
        public void GenerateTextFile(Proposition p, string filename)//Generate a text file to print the tree through GraphViz
        {
            FileStream   fs = null;
            StreamWriter sw = null;

            fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
            sw = new StreamWriter(fs);
            try
            {
                sw.WriteLine("graph logic {");
                sw.WriteLine("   node [ fontname = \"Arial\" ]");
                WriteFormulaToTextFile(p, sw);
                sw.WriteLine("}");
            }
            catch (IOException i)
            {
                MessageBox.Show(i.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
        }
Beispiel #18
0
        public void doesItCalculatePropsCorrectlyTest()
        {
            Proposition proposition     = new Proposition("|(=(>(1,1),>(1,1)),=(>(1,1),>(1,1)))");
            bool        expected_result = true;

            Assert.AreEqual(expected_result, proposition.calculate());
        }
Beispiel #19
0
        public void doesItConsumePropsCorrectlySecondTest()
        {
            Proposition proposition          = new Proposition(">(d,B)");
            string      expected_proposition = ">(d,B)";

            Assert.AreEqual(expected_proposition, proposition.getPropositionASCIIFormat());
        }
        public Proposition GetProposition(object owner, IContextLookup globalVars, IDictionary <string, RandomVariable> randomVariables)
        {
            switch (PropositionType)
            {
            case PropositionType.RandomVariable:
            case PropositionType.Assignment:
                RandomVariable randomVar;
                if (!randomVariables.TryGetValue(RandomVariable, out randomVar))
                {
                    throw new ApplicationException("Missing variable " + RandomVariable);
                }
                switch (PropositionType)
                {
                case PropositionType.RandomVariable:
                    return((Proposition)randomVar);

                case PropositionType.Assignment:
                    var objValue = Value.EvaluateTyped(owner, globalVars);
                    return(new AssignmentProposition(randomVar, objValue));

                default:
                    throw new ArgumentOutOfRangeException();
                }

            case PropositionType.Dysjunctive:
            case PropositionType.Conjunctive:
                if (Children.Count > 0)
                {
                    Proposition newPropositionInfo = null;
                    foreach (PropositionInfo assignmentPropositionInfo in Children)
                    {
                        var objAssignment = assignmentPropositionInfo.GetProposition(owner, globalVars, randomVariables);
                        if (newPropositionInfo == null)
                        {
                            newPropositionInfo = objAssignment;
                        }
                        else
                        {
                            if (PropositionType == PropositionType.Conjunctive)
                            {
                                newPropositionInfo = new ConjunctiveProposition(newPropositionInfo, objAssignment);
                            }
                            else
                            {
                                newPropositionInfo = new DisjunctiveProposition(newPropositionInfo, objAssignment);
                            }
                        }
                    }
                    return(newPropositionInfo);
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #21
0
        public void PropositionTestNormalProposition()
        {
            string      input  = "=(A,|(C,B))";
            string      output = "(A=(C|B))";
            Proposition check  = new Proposition(input);

            Assert.AreEqual(output, check.ToString());
        }
Beispiel #22
0
 /// <summary>Convert to NNF proposition</summary>
 /// <exception cref="InvaildPropositionException"></exception>
 /// <returns>NNF proposition</returns>
 public static Proposition ToNNF(this Proposition expr)
 {
     if (expr.IsNNF())
     {
         return(expr);
     }
     return(logEngine.ConvertToNNF(expr));
 }
        public void CreateBinaryConnectiveWithRandomSymbols_ValidBinaryConnectiveSymbolGiven_ExpectedBinaryConnectiveReturned(char connectiveSymbol, Type type)
        {
            // Arrange // Act
            Proposition binaryConnective = PropositionGenerator.CreateBinaryConnectiveWithRandomSymbols(connectiveSymbol);

            // Assert
            binaryConnective.GetType().Should().Be(type, "Because that is the type we requested a unary connective from");
        }
        public void GenerateRandomConstant_IntegerForConstantGiven_ExpectedTrueOrFalseReturned(int coinFlip, Type type)
        {
            // Arrange // Act
            Proposition generatedProposition = PropositionGenerator.GenerateRandomConstant(coinFlip);

            // Assert
            generatedProposition.GetType().Should().Be(type, "Because based on that integer either True or False is returned.");
        }
        public void GetRandomPropositionSymbol_CallToGetRandomPropositionSymbol_ExpectedRandomPropositionReturned()
        {
            // Arrange // Act
            Proposition randomProposition = PropositionGenerator.GetRandomPropositionSymbol();

            // Assert
            randomProposition.Should().BeOfType <Proposition>("Because a proposition with a random variable letter is generated");
        }
Beispiel #26
0
        public void PropositionTestErrorWhenWrongOperator()
        {
            string      input  = "+(A,B)";
            string      output = "Ups, you did something wrong!";
            Proposition check  = new Proposition(input);

            Assert.AreEqual(output, check.ToString());
        }
Beispiel #27
0
        public void PropositionTestWithSpaces()
        {
            string      input  = "=( | (A ,B), &(C ,D))";
            string      output = "((A|B)=(C&D))";
            Proposition check  = new Proposition(input);

            Assert.AreEqual(output, check.ToString());
        }
Beispiel #28
0
        public void PropositionTestBiimplication()
        {
            string      input  = "=(A,B)";
            string      output = "(A=B)";
            Proposition check  = new Proposition(input);

            Assert.AreEqual(output, check.ToString());
        }
Beispiel #29
0
        public void PropositionTestBigProposition()
        {
            string      input  = "=(&(~(B), A),|(=(C,D),>(E,F)))";
            string      output = "((~(B)&A)=((C=D)|(E>F)))";
            Proposition check  = new Proposition(input);

            Assert.AreEqual(output, check.ToString());
        }
Beispiel #30
0
        public ActionResult DeleteConfirmed(int id)
        {
            Proposition proposition = db.Propositions.Find(id);

            db.Propositions.Remove(proposition);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #31
0
 public void Set(Proposition proposition, bool value)
 {
     if (state.ContainsKey (proposition)) {
         state [proposition] = value;
     } else {
         state.Add (proposition, value);
     }
 }
        public void Selection()
        {
            var criteria = (Expression<Func<int, bool>>)(x => x > 0);
            var negatedSpec = new Proposition<int>(criteria);

            Assert.That(negatedSpec.IsSatisfiedBy(1), Is.True);
            Assert.That(negatedSpec.IsSatisfiedBy(0), Is.False);
            Assert.That(negatedSpec.IsSatisfiedBy(-1), Is.False);
        }
Beispiel #33
0
        public void BindTo( Proposition prop, IList<UInt16> prices, IList<UInt16> baseJpRewards, IList<UInt16> baseGilRewards )
        {
            if (ourContext != FFTPatch.Context)
            {
                ourContext = FFTPatch.Context;
                RegenerateContextSensitiveData();
            }

            if (this.prices == null || !Utilities.CompareArrays( prices, this.prices ) ||
                this.jpRewards == null || !Utilities.CompareArrays(baseJpRewards, this.jpRewards) ||
                this.gilRewards == null || !Utilities.CompareArrays(baseGilRewards, this.gilRewards) )
            {
                NotifyNewPrices( prices, baseJpRewards, baseGilRewards );
            }

            ignoreChanges = true;

            preferredStatsComboBox.SetIndexAndDefault( (int)prop.BraveFaith, (int)prop.Default.BraveFaith );
            maxDaysSpinner.SetValueAndDefault( prop.MaxDays, prop.Default.MaxDays );
            minDaysSpinner.SetValueAndDefault( prop.MinDays, prop.Default.MinDays );
            prereqByteSpinner.SetValueAndDefault( prop.PrereqByte, prop.Default.PrereqByte );
            completeJobComboBox.SetIndexAndDefault( (int)prop.PrereqProp, (int)prop.Default.PrereqProp );
            prereqTypeComboBox.SetIndexAndDefault( (int)prop.PrereqType, (int)prop.Default.PrereqType );
            certainDateComboBox.SetIndexAndDefault( (int)prop.PrereqZodiac, (int)prop.Default.PrereqZodiac );
            price1ComboBox.SetIndexAndDefault( prop.PriceIndex1 - 1, prop.Default.PriceIndex1 - 1 );
            price2ComboBox.SetIndexAndDefault( prop.PriceIndex2 - 1, prop.Default.PriceIndex2 - 1 );
            baseJpRewardComboBox.SetIndexAndDefault( (int)prop.BaseSmallReward, (int)prop.Default.BaseSmallReward );
            baseGilRewardComboBox.SetIndexAndDefault( (int)prop.BaseLargeReward, (int)prop.Default.BaseLargeReward );
            rewardComboBox.SetIndexAndDefault( (int)prop.Reward+1, (int)prop.Default.Reward +1);
            townComboBox.SetIndexAndDefault( (int)prop.Town, (int)prop.Default.Town );
            jobTypeComboBox.SetIndexAndDefault( (int)prop.Type, (int)prop.Default.Type );
            randomSuccessClassComboBox.SetIndexAndDefault( (int)prop.RandomSuccessClass, (int)prop.Default.RandomSuccessClass );

            //unknown0x09Spinner.SetValueAndDefault( prop.Unknown0x09, prop.Default.Unknown0x09 );
            //unknown0x0BSpinner.SetValueAndDefault( prop.Unknown0x0B, prop.Default.Unknown0x0B );
            //unknown0x0CSpinner.SetValueAndDefault( prop.Unknown0x0C, prop.Default.Unknown0x0C );
            unknown0x0FSpinner.SetValueAndDefault( prop.Unknown0x0F, prop.Default.Unknown0x0F );
            //unknown0x14Spinner.SetValueAndDefault( prop.Unknown0x14, prop.Default.Unknown0x14 );
            unlockedComboBox.SetValueAndDefault( prop.WhenUnlocked, prop.Default.WhenUnlocked );

            rawByteLabel.Enabled = prop.PrereqType != PrereqType.None;
            completeJobLabel.Enabled = prop.PrereqType == PrereqType.FinishedJob;
            certainDateLabel.Enabled = prop.PrereqType == PrereqType.CertainMonth;
            dateRangeLabel.Enabled = prop.PrereqType == PrereqType.CertainMonth;

            proposition = prop;
            ignoreChanges = false;

            //FireDataChanged();
        }
        public void Criteria()
        {
            var spec = new IntegerPredicate(i => i == 0);
            var criteria = spec.Criteria;

            var proposition = new Proposition<int>(criteria);
            var proposedCriteria = proposition.Criteria;

            Assert.That(proposedCriteria.Body, Is.AssignableTo<BinaryExpression>());

            var binary = (BinaryExpression)proposedCriteria.Body;

            Assert.That(binary.NodeType, Is.EqualTo(ExpressionType.Equal));
            Assert.That(binary.Method, Is.Null);
            Assert.That(binary.IsLifted, Is.False);
            Assert.That(binary.IsLiftedToNull, Is.False);
            Assert.That(binary.Conversion, Is.Null);
            Assert.That(binary.Left, Is.AssignableTo<ParameterExpression>());
            Assert.That(binary.Right, Is.TypeOf<ConstantExpression>().With.Property("Value").EqualTo(0));

            ExpressionWriter.Write(proposedCriteria);
        }
 private void copyAll(object sender, EventArgs args)
 {
     copiedEntry = listBox1.SelectedItem as Proposition;
 }
Beispiel #36
0
 public double Satisfy (State s, Proposition proposition)
 {
     if (s.ValidPropositions.Contains (proposition)) {
         return 1;
     } else {
         return 0; 
     }
 }