private static void NormalizeInference(Inference inference)
        {
            if (inference.ValueCase == Inference.ValueOneofCase.None)
            {
                // Note: This will terminate the RPC call. This is okay because the inferencing engine has broken the
                // RPC contract.
                throw new RpcException(
                          new Status(
                              StatusCode.InvalidArgument,
                              $"Inference has no value case set. Inference type: {inference.Type} Inference subtype: {inference.Subtype}"));
            }

            // If the type is auto, this will overwrite it to the correct type.
            // If the type is correctly set, this will be a no-op.
            var inferenceType = inference.ValueCase switch
            {
                Inference.ValueOneofCase.Classification => Inference.Types.InferenceType.Classification,
                Inference.ValueOneofCase.Motion => Inference.Types.InferenceType.Motion,
                Inference.ValueOneofCase.Entity => Inference.Types.InferenceType.Entity,
                Inference.ValueOneofCase.Text => Inference.Types.InferenceType.Text,
                Inference.ValueOneofCase.Event => Inference.Types.InferenceType.Event,
                Inference.ValueOneofCase.Other => Inference.Types.InferenceType.Other,

                _ => throw new ArgumentException($"Inference has unrecognized value case {inference.ValueCase}"),
            };

            inference.Type = inferenceType;
        }
Exemplo n.º 2
0
            public List <DataModel> lstShortDataModel; //需补充的数据list

            public OutputInfo()
            {
                oTriggeringEvent  = new TriggeringEvent();
                oInference        = new Inference();
                oExplanation      = new Explanation();
                lstShortDataModel = new List <DataModel>();
            }
Exemplo n.º 3
0
        private static void AddingFormulas(Inference inference, HashSet <Formula> formulas, Formula target)
        {
            var form = new HashSet <Formula>();

            while (true)
            {
                foreach (var f in form)
                {
                    if (f.Equals(target) == false)
                    {
                        lock (inference)
                        {
                            if (inference.Contains(target))
                            {
                                return;
                            }
                            inference.Push(f);
                        }
                    }
                }

                lock (formulas)
                {
                    form.UnionWith(formulas);
                }
            }
        }
Exemplo n.º 4
0
        public ActionResult <IEnumerable <double> > Get(string numbers)
        {
            Console.WriteLine("NUMBERS " + numbers);
            int[] values;
            try
            {
                values = Array.ConvertAll(numbers.Split(','), int.Parse);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
                return(BadRequest(e));
            }

            if (values.Length < 5)
            {
                Console.Error.WriteLine("Insufficient values!");
                return(BadRequest("Insufficient values!"));
            }

            foreach (int item in values)
            {
                if (item > 9 || item < -9)
                {
                    Console.Error.WriteLine("All values must be between +9 and -9.");
                    return(BadRequest("All values must be between +9 and -9."));
                }
            }

            return(Ok(new FAHP(Inference.ComparisonMatrix(values)).CriteriaWeights));
        }
Exemplo n.º 5
0
        private void TrainNn_Click(object sender, EventArgs e)
        {
            if (trainingIsRunning)
            {
                return;
            }

            Inference inference = new Inference();

            inference.CreateNeuralNetworkArchitecture();
            Thread thread = new Thread(() =>
            {
                trainingIsRunning = true;
                inference.TrainNeuralNetwork(WriteToOutput);

                BeginInvoke(new Action(() =>
                {
                    new Form1(inference).Show();
                    Hide();
                    trainingIsRunning = false;
                }));
            });

            thread.Start();
        }
Exemplo n.º 6
0
        }         // GetMonthlyRepaymentData

        public Inference GetInferenceIfExists(
            int customerID,
            DateTime time,
            bool includeTryOutData,
            decimal monthlyPayment
            )
        {
            Log.Debug(
                "Engine.GetInferenceIfExists({0}, {1}, {2}, {3}) started...",
                customerID,
                time.ToString("d/MMM/yyyy H:mm:ss", CultureInfo.InvariantCulture),
                includeTryOutData,
                monthlyPayment
                );

            Inference result = Keeper.LoadInferenceIfExists(customerID, time, includeTryOutData, monthlyPayment);

            Log.Debug(
                "Engine.GetInference({0}, {1}, {2}, {3}) complete.",
                customerID,
                time.ToString("d/MMM/yyyy H:mm:ss", CultureInfo.InvariantCulture),
                includeTryOutData,
                monthlyPayment
                );

            return(result);
        }         // GetInferenceIfExists
Exemplo n.º 7
0
        private static void GenAxiom(Inference inference, List <Formula> formulas, HashSet <Formula> allFormulas,
                                     Formula target, Axiom a)
        {
            foreach (var f1 in formulas)
            {
                foreach (var f2 in formulas)
                {
                    foreach (var f3 in formulas)
                    {
                        var f = SubstituteInFormula(a, f1, f2, f3);
                        if (f.Equals(target))
                        {
                            continue;
                        }
                        bool ok;
                        lock (inference)
                        {
                            if (inference.Contains(target))
                            {
                                return;
                            }
                            ok = inference.Push(f);
                        }

                        lock (allFormulas)
                        {
                            if (ok)
                            {
                                ParseFormula(f, allFormulas);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        public void TestOutOfContext()
        {
            using Rhino r = SetUpClass();
            int frameLen = r.FrameLength;

            string       testAudioPath = Path.Combine(_relativeDir, "resources/audio_samples/test_out_of_context.wav");
            List <short> data          = GetPcmFromFile(testAudioPath, r.SampleRate);

            bool isFinalized = false;
            int  framecount  = (int)Math.Floor((float)(data.Count / frameLen));
            var  results     = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * r.FrameLength;
                int          count = r.FrameLength;
                List <short> frame = data.GetRange(start, count);
                isFinalized = r.Process(frame.ToArray());
                if (isFinalized)
                {
                    break;
                }
            }
            Assert.IsTrue(isFinalized, "Failed to finalize.");

            Inference inference = r.GetInference();

            Assert.IsFalse(inference.IsUnderstood, "Shouldn't be able to understand.");
        }
Exemplo n.º 9
0
    private void OnInferenceResult(Inference inference)
    {
        if (inference.IsUnderstood)
        {
            if (inference.Intent == "changeColor")
            {
                Color newColour = _colourLookup["white"];
                if (inference.Slots.ContainsKey("color"))
                {
                    newColour = _colourLookup[inference.Slots["color"]];
                }

                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightColour(locations, newColour);
            }
            else if (inference.Intent == "changeLightState")
            {
                bool state = false;
                if (inference.Slots.ContainsKey("state"))
                {
                    state = inference.Slots["state"] == "on";
                }

                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightState(locations, state);
            }
            else if (inference.Intent == "changeLightStateOff")
            {
                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightState(locations, false);
            }
        }
        else
        {
            Debug.Log("Didn't understand the command.\n");
        }

        (_startButton.targetGraphic as Text).text = "Start Listening";
        _startButton.enabled = true;
        _isProcessing        = false;
    }
Exemplo n.º 10
0
        public void TestEndToEndFlow()
        {
            IEngine engine = InjectorStub.GetEngine();

            Inference inference = engine.GetInference(customerID, 0, false, GetInferenceMode.ForceDownload);

            Log.Info("Inference read: {0}", inference);
        }         // TestEndToEndFlow
Exemplo n.º 11
0
 public static StandardCodeSequence ToStandardCodeSequence(Inference inference)
 {
     return(inference == null
                                 ? null
                                 :
            new StandardCodeSequence(inference.CodeValue, inference.CodeMeaning, inference.CodingSchemeDesignator,
                                     inference.CodingSchemeVersion));
 }
Exemplo n.º 12
0
        private void btnSkipTraining_Click(object sender, EventArgs e)
        {
            Inference inference = new Inference();

            inference.CreateNeuralNetworkArchitecture();
            new Form1(inference).Show();
            Hide();
        }
Exemplo n.º 13
0
 @Override public void onNext(Inference i)
 {
     localInf.sdr(i.getSDR()).recordNum(i.getRecordNum()).classifierInput(i.getClassifierInput()).layerInput(i.getSDR());
     if (i.getSDR().length > 0)
     {
         ((Layer <Inference>)tail).compute(localInf);
     }
 }
Exemplo n.º 14
0
    private void OnInferenceResult(Inference inference)
    {
        if (inference.IsUnderstood)
        {
            if (inference.Intent == "changeColor")
            {
                Color newColour = _colourLookup["white"];
                if (inference.Slots.ContainsKey("color"))
                {
                    newColour = _colourLookup[inference.Slots["color"]];
                }

                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightColour(locations, newColour);
            }
            else if (inference.Intent == "changeLightState")
            {
                bool state = false;
                if (inference.Slots.ContainsKey("state"))
                {
                    state = inference.Slots["state"] == "on";
                }

                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightState(locations, state);
            }
            else if (inference.Intent == "changeLightStateOff")
            {
                Image[] locations = _locationStates;
                if (inference.Slots.ContainsKey("location"))
                {
                    string locationName = inference.Slots["location"];
                    locations = _locationStates.Where(g => g.name == locationName).ToArray();
                }

                ChangeLightState(locations, false);
            }
        }
        else
        {
            Debug.Log("Didn't understand the command.\n");
        }

        _activityText.text = "Say 'Picovoice'!";
    }
Exemplo n.º 15
0
        private static void GenFormulas(Inference inference, HashSet <Formula> formulas, Formula target)
        {
            while (true)
            {
                var form = formulas.OrderBy(x => Rd.Next()).ToList();

                Parallel.ForEach(Axioms.GetAxioms(), a => GenAxiom(inference, form, formulas, target, a));
            }
        }
Exemplo n.º 16
0
        public void TestInit()
        {
            _pv = new Picovoice(Porcupine.KEYWORD_PATHS["picovoice"],
                                _wakeWordCallback,
                                _contextPath,
                                _inferenceCallback);

            _isWakeWordDetected = false;
            _inference          = null;
        }
Exemplo n.º 17
0
        private void dgvInfRecord_DoubleClick(object sender, EventArgs e)
        {
            Inference inf = (Inference)dgvInfRecord.Tag;

            if (inf == null)
            {
                return;
            }
            MessageBox.Show(inf.doPostVariableStat());
        }
Exemplo n.º 18
0
        /// <summary>
        /// Set "niedopytywalne" fakty IsKnown to false
        /// </summary>
        /// <param name="rules"></param>
        private void SetUnknownFacts(List <Rule> rules)
        {
            var unknownFacts = Inference.factsThatAreAlsoConclusions(rules);

            unknownFacts.Select(uf =>
            {
                uf.IsKnown = false;
                uf.IsSet   = false;
                return(uf);
            }).ToList();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Reads through input file and prints the inference result returned by Rhino.
        /// </summary>
        /// <param name="inputAudioPath">Required argument. Absolute path to input audio file.</param>
        /// <param name="contextPath">Required argument. Absolute path to the Rhino context file.</param>
        /// <param name="modelPath">Absolute path to the file containing model parameters. If not set it will be set to the default location.</param>
        /// <param name="sensitivity">
        /// Inference sensitivity. It should be a number within [0, 1]. A higher sensitivity value results in
        /// fewer misses at the cost of (potentially) increasing the erroneous inference rate. If not set, the default value of 0.5 will be used.
        /// </param>
        public static void RunDemo(string inputAudioPath, string contextPath, string modelPath, float sensitivity)
        {
            // init rhino speech-to-intent engine
            using Rhino rhino = Rhino.Create(contextPath, modelPath, sensitivity);

            // open and validate wav file
            using BinaryReader reader = new BinaryReader(File.Open(inputAudioPath, FileMode.Open));
            ValidateWavFile(reader, rhino.SampleRate, 16, out short numChannels);

            // read audio and send frames to rhino
            short[] rhinoFrame = new short[rhino.FrameLength];
            int     frameIndex = 0;

            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                rhinoFrame[frameIndex++] = reader.ReadInt16();

                if (frameIndex == rhinoFrame.Length)
                {
                    bool isFinalized = rhino.Process(rhinoFrame);
                    if (isFinalized)
                    {
                        Inference inference = rhino.GetInference();
                        if (inference.IsUnderstood)
                        {
                            Console.WriteLine("{");
                            Console.WriteLine($"  intent : '{inference.Intent}'");
                            Console.WriteLine("  slots : {");
                            foreach (KeyValuePair <string, string> slot in inference.Slots)
                            {
                                Console.WriteLine($"    {slot.Key} : '{slot.Value}'");
                            }
                            Console.WriteLine("  }");
                            Console.WriteLine("}");
                        }
                        else
                        {
                            Console.WriteLine("Didn't understand the command.");
                        }
                        return;
                    }

                    frameIndex = 0;
                }

                // skip right channel
                if (numChannels == 2)
                {
                    reader.ReadInt16();
                }
            }

            Console.WriteLine("Reached end of audio file before Rhino returned an inference.");
        }
Exemplo n.º 20
0
    static void InferenceCallback(Inference inference)
    {
        if (inference.IsUnderstood)
        {
            if (inference.Intent.Equals("move"))
            {
                if (CheckEndGame())
                {
                    return;
                }

                string srcSide = inference.Slots["srcSide"];
                string srcRank = inference.Slots["srcRank"];
                string srcFile = inference.Slots.ContainsKey("srcFile") ? inference.Slots["srcFile"] : "";

                string dstSide = inference.Slots["dstSide"];
                string dstRank = inference.Slots["dstRank"];
                string dstFile = inference.Slots.ContainsKey("dstFile") ? inference.Slots["dstFile"] : "";

                string playerMove = MakePlayerMove(srcSide, srcFile, srcRank, dstSide, dstFile, dstRank);
                if (playerMove.Equals("Invalid Move"))
                {
                    DrawBoard($" {playerMove}\n");
                    return;
                }

                string theirMove = MakeOpponentMove();
                DrawBoard($" \u2654  {playerMove}\n \u265A  {theirMove}");

                if (CheckEndGame())
                {
                    Console.WriteLine($"\n {GetEndGameReason()}");
                    Console.WriteLine($" Say 'new game' to play again.");
                }
            }
            else if (inference.Intent.Equals("undo"))
            {
                UndoLastMove();
            }
            else if (inference.Intent.Equals("newgame"))
            {
                NewGame();
            }
            else if (inference.Intent.Equals("quit"))
            {
                QuitGame();
            }
        }
        else
        {
            DrawBoard(" Didn't understand move.\n");
        }
    }
Exemplo n.º 21
0
 private void PrintInference(Inference inference) 
 {
     StringBuilder str = new StringBuilder();
     str.Append("{\n");
     str.Append($"  intent : '{inference.Intent}'\n");
     str.Append("  slots : {\n");
     foreach (KeyValuePair<string, string> slot in inference.Slots)
         str.Append($"    {slot.Key} : '{slot.Value}'\n");
     str.Append("  }\n");
     str.Append("}\n");
     Debug.Log(str.ToString());
 }
Exemplo n.º 22
0
        public void TestBasicFlow()
        {
            IEngine engine = InjectorStub.GetTestEngine();

            TestHarvester harvester = (TestHarvester)((Engine)engine).Harvester;

            harvester.ReplyMode = TestHarvester.ReplyModes.Success;

            Inference inference = engine.GetInference(customerID, 0, false, GetInferenceMode.DownloadIfOld);

            Log.Info("Inference read: {0}", inference);
        }         // TestBasicFlow
Exemplo n.º 23
0
        public void TestTimeoutL()
        {
            IEngine engine = InjectorStub.GetTestEngine();

            TestHarvester harvester = (TestHarvester)((Engine)engine).Harvester;

            harvester.ReplyMode = TestHarvester.ReplyModes.TimeoutA;

            Inference inference = engine.GetInference(customerID, 0, false, GetInferenceMode.ForceDownload);

            Log.Info("Inference read: {0}", inference);
        }         // TestTimeoutL
 private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (MaxNumberOfAnswers <= 1 &&
         Inference.SelectedAllowedTerms.Count > 0 &&
         Inference.SelectedAllowedTerms[0] != _comboBox.SelectedItem)
     {
         Inference.ClearSelectedAllowedTerms();
     }
     if (_comboBox.SelectedItem != null)
     {
         ((AimTemplateTreeAllowedTerm)_comboBox.SelectedItem).Selected = true;
     }
 }
Exemplo n.º 25
0
        public Inference GetInference(int customerID, decimal monthlyPayment, bool isTryout, GetInferenceMode mode)
        {
            Log.Debug("Engine.GetInference({0}, {1}) started...", customerID, mode);

            Inference result = null;

            switch (mode)
            {
            case GetInferenceMode.CacheOnly:
                result = GetInference(customerID, Now, isTryout, monthlyPayment);
                break;

            case GetInferenceMode.DownloadIfOld:
                Inference           cachedInference = GetInference(customerID, Now, isTryout, monthlyPayment);
                ModuleConfiguration cfg             = Keeper.LoadModuleConfiguration();

                if (cachedInference.IsUpToDate(Now, cfg.CacheAcceptanceDays))
                {
                    Log.Debug(
                        "Engine.GetInference({0}, {1}): returning cached inference with ResponseID = {2}.",
                        customerID,
                        mode,
                        cachedInference.ResponseID
                        );

                    result = cachedInference;
                    break;
                }                                         // if

                goto case GetInferenceMode.ForceDownload; // !!! fall through !!!

            case GetInferenceMode.ForceDownload:
                result = DownloadAndSave(customerID, monthlyPayment, isTryout);
                break;

            default:
                throw new EngineAlert(
                          Log,
                          new ArgumentOutOfRangeException("mode"),
                          "Failed to get customer {0} inference at mode {1}.",
                          customerID,
                          mode
                          );
            }             // switch

            Log.Debug("Engine.GetInference({0}, {1}) complete.", customerID, mode);

            return(result);
        }         // GetInference (standard, by actual data)
Exemplo n.º 26
0
        public static Inference FindInference(Hypotheses hypotheses, Formula target)
        {
            var inference = new Inference(hypotheses);

            if (inference.Push(target))
            {
                inference.Minimize();
                return(inference);
            }

            var formulas = new HashSet <Formula>();

            if (hypotheses is null == false)
            {
                foreach (var h in hypotheses)
                {
                    inference.Push(h);
                    formulas.Add(h);
                }
            }

            ParseFormula(target, formulas);

            var addingFormulas = new Thread(() => AddingFormulas(inference, formulas, target));
            var genFormulas    = new Thread(() => GenFormulas(inference, formulas, target));

            addingFormulas.Start();
            genFormulas.Start();

            while (true)
            {
                lock (inference)
                {
                    if (inference.Push(target) || inference.Contains(target))
                    {
                        break;
                    }
                }

                Thread.Sleep(1000);
            }

            addingFormulas.Abort();
            genFormulas.Abort();

            inference.Minimize();
            return(inference);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 显示推理节点的详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxInference_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.demoNet == null)
            {
                return;
            }
            List <Inference> infs = this.demoNet.Inferences;

            if (infs == null || infs.Count <= 0)
            {
                return;
            }

            int index = listBoxInference.SelectedIndex;

            if (index < 0)
            {
                return;
            }

            int p = listBoxInference.Items[index].ToString().IndexOf(":");

            if (p < 0)
            {
                return;
            }

            int       id  = int.Parse(listBoxInference.Items[index].ToString().Substring(0, p));
            Inference inf = (Inference)this.demoNet[id];

            if (inf == null)
            {
                return;
            }

            dgvInfRecord.Tag = inf;
            dgvInfRecord.Rows.Clear();
            foreach (InferenceRecord record in inf.ValidRecords)
            {
                index = dgvInfRecord.Rows.Add();
                dgvInfRecord.Rows[index].Cells[0].Value = record.Summary();
                dgvInfRecord.Rows[index].Cells[1].Value = record.acceptCount.ToString();
                dgvInfRecord.Rows[index].Cells[2].Value = record.usedCount.ToString();
                dgvInfRecord.Rows[index].Tag            = record;
            }
        }
Exemplo n.º 28
0
        private void RunTestCase(
            Rhino rhino,
            string audioFileName,
            bool isWithinContext,
            string expectedIntent = null,
            Dictionary <string, string> expectedSlots = null)
        {
            int          frameLen      = rhino.FrameLength;
            string       testAudioPath = Path.Combine(_relativeDir, "resources/audio_samples", audioFileName);
            List <short> data          = GetPcmFromFile(testAudioPath, rhino.SampleRate);

            bool isFinalized = false;
            int  framecount  = (int)Math.Floor((float)(data.Count / frameLen));
            var  results     = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * rhino.FrameLength;
                int          count = rhino.FrameLength;
                List <short> frame = data.GetRange(start, count);
                isFinalized = rhino.Process(frame.ToArray());
                if (isFinalized)
                {
                    break;
                }
            }
            Assert.IsTrue(isFinalized, "Failed to finalize.");

            Inference inference = rhino.GetInference();

            if (isWithinContext)
            {
                Assert.IsTrue(inference.IsUnderstood, "Couldn't understand.");
                Assert.AreEqual(expectedIntent, inference.Intent, "Incorrect intent.");
                Assert.IsTrue(inference.Slots.All((keyValuePair) =>
                                                  expectedSlots.ContainsKey(keyValuePair.Key) &&
                                                  expectedSlots[keyValuePair.Key] == keyValuePair.Value));
            }
            else
            {
                Assert.IsFalse(inference.IsUnderstood, "Shouldn't be able to understand.");
            }
        }
Exemplo n.º 29
0
 static void inferenceCallback(Inference inference)
 {
     if (inference.IsUnderstood)
     {
         Console.WriteLine("{");
         Console.WriteLine($"  intent : '{inference.Intent}'");
         Console.WriteLine("  slots : {");
         foreach (KeyValuePair <string, string> slot in inference.Slots)
         {
             Console.WriteLine($"    {slot.Key} : '{slot.Value}'");
         }
         Console.WriteLine("  }");
         Console.WriteLine("}\n");
     }
     else
     {
         Console.WriteLine("Didn't understand the command");
     }
 }
Exemplo n.º 30
0
        }         // OutOfRangeException

        private Inference ProcessRequest(SafeReader sr)
        {
            Guid?uniqueID = sr["UniqueID"];

            if (uniqueID == null)
            {
                return(null);
            }

            var result = new Inference {
                UniqueID         = uniqueID.Value,
                MonthlyRepayment = sr["MonthlyRepayment"],
                IsTryOut         = sr["IsTryOut"],
            };

            Results.Add(result);

            return(result);
        }         // ProcessRequest
Exemplo n.º 31
0
        /// <summary>
        /// Attempts to infer the type of generic parameters that occur in a formal parameter type
        /// according to its actual argument type. 
        /// </summary>
        /// <returns>False if inference failed; otherwise, true. </returns>
        private bool Infer(IType formalType, IType actualType, Inference inference)
        {
            // Skip unspecified actual types
            if (actualType == null) return true;

            if (formalType is IGenericParameter)
            {
                return InferGenericParameter((IGenericParameter)formalType, actualType, inference);
            }

            if (formalType is ICallableType)
            {
                return InferCallableType((ICallableType)formalType, actualType, inference);
            }

            if (formalType.ConstructedInfo != null)
            {
                return InferConstructedType(formalType, actualType, inference);
            }

            if (formalType is IArrayType)
            {
                return InferArrayType((IArrayType)formalType, actualType, inference);
            }

            return InferSimpleType(formalType, actualType, inference);
        }
Exemplo n.º 32
0
		public static StandardCodeSequence ToStandardCodeSequence(Inference inference)
		{
			return inference == null
					? null
					:
						new StandardCodeSequence(inference.CodeValue, inference.CodeMeaning, inference.CodingSchemeDesignator,
												 inference.CodingSchemeVersion);
		}
 /** Selects the algorithm for INFERENCE. */
 public void setInference(Inference iStrategy)
 {
     inferenceStrategy = iStrategy;
 }
Exemplo n.º 34
0
 private bool InferSimpleType(IType formalType, IType actualType, Inference inference)
 {
     // Inference has no effect on formal parameter types that are not generic parameters
     return true;
 }
Exemplo n.º 35
0
 private bool InferArrayType(IArrayType formalType, IType actualType, Inference inference)
 {
     IArrayType actualArrayType = actualType as IArrayType;
     return
         (actualArrayType != null) &&
         (actualArrayType.GetArrayRank() == formalType.GetArrayRank()) &&
         (Infer(formalType.GetElementType(), actualType.GetElementType(), inference));
 }
Exemplo n.º 36
0
        private bool InferCallableType(ICallableType formalType, IType actualType, Inference inference)
        {
            ICallableType callableActualType = actualType as ICallableType;
            if (callableActualType == null) return false;

            CallableSignature formalSignature = formalType.GetSignature();
            CallableSignature actualSignature = callableActualType.GetSignature();

            // TODO: expand actual signature when it involves varargs?
            if (formalSignature.Parameters.Length != actualSignature.Parameters.Length) return false;

            // Infer return type, maintaining inference direction
            if (!Infer(formalSignature.ReturnType, actualSignature.ReturnType, inference))
            {
                return false;
            }

            // Infer parameter types, inverting inference direction
            for (int i = 0; i < formalSignature.Parameters.Length; ++i)
            {
                bool inferenceSuccessful = Infer(
                    formalSignature.Parameters[i].Type,
                    actualSignature.Parameters[i].Type,
                    Invert(inference));

                if (!inferenceSuccessful) return false;
            }
            return true;
        }
Exemplo n.º 37
0
        private bool InferConstructedType(IType formalType, IType actualType, Inference inference)
        {
            // look for a single occurance of the formal
            // constructed type in the actual type's hierarchy
            IType constructedActualType = GenericsServices.FindConstructedType(
                actualType,
                formalType.ConstructedInfo.GenericDefinition);

            if (constructedActualType == null)
            {
                return false;
            }

            // Exact inference requires the constructed occurance to be
            // the actual type itself
            if (inference == Inference.Exact && actualType != constructedActualType)
            {
                return false;
            }

            for (int i = 0; i < formalType.ConstructedInfo.GenericArguments.Length; ++i)
            {
                bool inferenceSuccessful = Infer(
                    formalType.ConstructedInfo.GenericArguments[i],
                    constructedActualType.ConstructedInfo.GenericArguments[i],
                    Inference.Exact); // Generic arguments must match exactly, no variance allowed

                if (!inferenceSuccessful) return false;
            }
            return true;
        }
Exemplo n.º 38
0
        private bool InferGenericParameter(IGenericParameter formalType, IType actualType, Inference inference)
        {
            if (_inferredTypes.ContainsKey(formalType))
            {
                InferredType inferredType = _inferredTypes[formalType];
                if ((inference & Inference.AllowContravariance) != Inference.AllowContravariance)
                {
                    inferredType.ApplyLowerBound(actualType);
                }
                if ((inference & Inference.AllowCovariance) != Inference.AllowCovariance)
                {
                    inferredType.ApplyUpperBound(actualType);
                }
            }

            return true;
        }
Exemplo n.º 39
0
            public TriggeringEvent oTriggeringEvent; //输出结论与触发事件相关

            #endregion Fields

            #region Constructors

            public OutputInfo()
            {
                oTriggeringEvent = new TriggeringEvent();
                oInference = new Inference();
                oExplanation = new Explanation();
                lstShortDataModel = new List<DataModel>();
            }
Exemplo n.º 40
0
        private Inference Invert(Inference inference)
        {
            switch (inference)
            {
                case Inference.AllowCovariance:
                    return Inference.AllowContravariance;

                case Inference.AllowContravariance:
                    return Inference.AllowCovariance;

                default:
                    return Inference.Exact;
            }
        }