Example #1
0
 public override void OnReset()
 {
     targetGameObject = null;
     componentName = null;
     fieldName = null; 
     fieldValue = null;
 }
Example #2
0
 public void SetVariable(string name, SharedVariable item)
 {
     if (!Variables.ContainsKey(name))
     {
         Variables.Add(name, item);
     }
 }
Example #3
0
 public override void OnReset()
 {
     targetGameObject = null;
     componentName = null;
     propertyName = null;
     propertyValue = null;
 }
Example #4
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="numOfChunks">The number of chunks.</param>
        /// <param name="numOfClasses">The range of classes.</param>
        /// <param name="noise">The noise level.</param>
        /// <param name="weights">The weight shared variable the from training model.</param>
        public TestModel(int numOfChunks, int numOfClasses, double noise, SharedVariable<Vector>[] weights)
            : base(numOfClasses, noise)
        {
            NumberOfChunks = numOfChunks;
            this.weights = weights;

            InitModel();
        }
Example #5
0
 /// <summary>
 /// Set the weight shared variables.
 /// </summary>
 /// <param name="index">The class ID.</param>
 /// <param name="numOfFeatures">The number of features in the class.</param>
 public void SetWeight(int index, int numOfFeatures)
 {
     SharedWeight = (index == 0)
             ? SharedVariable<Vector>.Random(VectorGaussian.PointMass(Vector.Zero(numOfFeatures)))
             : SharedVariable<Vector>.Random(
                 VectorGaussian.FromMeanAndPrecision(
                 Vector.Zero(numOfFeatures),
                 PositiveDefiniteMatrix.Identity(numOfFeatures)));
 }
Example #6
0
 public override void OnReset()
 {
     // Reset the properties back to their original values
     textFormat = string.Empty;
     logError = false;
     arg0 = null;
     arg1 = null;
     arg2 = null;
     arg3 = null;
 }
Example #7
0
 public override void OnReset()
 {
     targetGameObject = null;
     componentName = null;
     methodName = null; 
     parameter1 = null;
     parameter2 = null;
     parameter3 = null;
     parameter4 = null;
     storeResult = null;
 }
Example #8
0
 private void inspector_SharedVariableUpdated(SharedVariable sharedVariable)
 {
     this.BeginInvoke(new EventHandler(delegate(object o, EventArgs e)
     {
         ListViewItem item = lvSharedVariableList.Items[sharedVariable.Name];
         int ixLU = lvSharedVariableList.Columns["LastUpdated"].Index;
         int ixLW = lvSharedVariableList.Columns["LastWriter"].Index;
         item.SubItems[ixLU].Text = sharedVariable.LastUpdated.ToString("hh:mm:ss");
         item.SubItems[ixLW].Text =
             String.IsNullOrEmpty(sharedVariable.LastWriter) ? "(Unknown)" : sharedVariable.LastWriter;
         lvSharedVariableList.Refresh();
         pgSharedVarProperties.Refresh();
     }));
 }
Example #9
0
 private void inspector_SharedVariableAdded(Inspector inspector, SharedVariable sharedVariable)
 {
     this.BeginInvoke(new EventHandler (delegate(object o, EventArgs e)
     {
         string[] row = { sharedVariable.Name,
                            sharedVariable.TypeName + (sharedVariable.IsArray ? "[]" : String.Empty),
                            sharedVariable.LastUpdated.ToString("hh:mm:ss"),
                            String.IsNullOrEmpty(sharedVariable.LastWriter) ? "(Unknown)" : sharedVariable.LastWriter
                        };
         ListViewItem item = new ListViewItem(row);
         item.Name = sharedVariable.Name;
         item.Tag = sharedVariable;
         lvSharedVariableList.Items.Add(item);
         item.BackColor = (item.Index % 2 == 0) ? Color.White : Color.LightGray;
         lvSharedVariableList.Refresh();
     }));
 }
Example #10
0
		/// <summary>
		/// Constructs a multi-component Bayes Point Machine using shared variables for chunking data
		/// </summary>
		/// <param name="nClass">Number of components (classes)</param>
		/// <param name="nFeatures">Number of features</param>
		/// <param name="noisePrec">Noise precision</param>
		/// <param name="trainChunkSize">Chunk size for training</param>
		/// <param name="testChunkSize">Chunk size for testing</param>
		public BPM_Shared(int nClass, int nFeatures, double noisePrec, int trainChunkSize, int testChunkSize)
		{
			this.nClass = nClass;
			this.nFeatures = nFeatures;
			this.trainChunkSize = trainChunkSize;
			this.testChunkSize = testChunkSize;
			NoisePrec = noisePrec;

			feature = new Range(nFeatures).Named("feature");

			// The set of weight vectors (one for each component) are shared between all data chunks
			w = new SharedVariable<Vector>[nClass];
			VectorGaussian wPrior0 = VectorGaussian.PointMass(Vector.Zero(nFeatures));
			VectorGaussian wPrior = VectorGaussian.FromMeanAndPrecision(Vector.Zero(nFeatures), PositiveDefiniteMatrix.Identity(nFeatures));
			for (int c = 0; c < nClass; c++)
			{
				w[c] = (c == 0)
					? SharedVariable<Vector>.Random(VectorGaussian.PointMass(Vector.Zero(nFeatures))).Named("w_" + c)
					: SharedVariable<Vector>.Random(wPrior).Named("w_" + c);
			}
			trainModel = SpecifyTrainModel("_train", trainChunkSize);
			testModel = SpecifyTestModel("_test", testChunkSize);
		}
Example #11
0
 public static void DrawSharedVariableValue(SharedVariable sharedVariable, int width)
 {
     if (sharedVariable == null)
     {
         return;
     }
     try
     {
         switch (sharedVariable.ValueType)
         {
             case SharedVariableTypes.Int:
                 sharedVariable.SetValue(EditorGUILayout.IntField((int)sharedVariable.GetValue(), new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Float:
                 sharedVariable.SetValue(EditorGUILayout.FloatField((float)sharedVariable.GetValue(), new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Bool:
                 sharedVariable.SetValue(EditorGUILayout.Toggle((bool)sharedVariable.GetValue(), EditorStyles.toggle, new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.String:
                 sharedVariable.SetValue(EditorGUILayout.TextField((string)sharedVariable.GetValue(), new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Vector2:
                 sharedVariable.SetValue(VariableInspector.Vector2Field((Vector2)sharedVariable.GetValue()));
                 break;
             case SharedVariableTypes.Vector3:
                 sharedVariable.SetValue(VariableInspector.Vector3Field((Vector3)sharedVariable.GetValue()));
                 break;
             case SharedVariableTypes.Vector4:
                 sharedVariable.SetValue(VariableInspector.Vector4Field((Vector4)sharedVariable.GetValue()));
                 break;
             case SharedVariableTypes.Quaternion:
                 {
                     Vector4 vector = VariableInspector.QuaternionToVector4((Quaternion)sharedVariable.GetValue());
                     Vector4 vector2 = VariableInspector.Vector4Field(vector);
                     if (vector != vector2)
                     {
                         sharedVariable.SetValue(new Quaternion(vector2.x, vector2.y, vector2.z, vector2.w));
                     }
                     break;
                 }
             case SharedVariableTypes.Color:
                 sharedVariable.SetValue(EditorGUILayout.ColorField((Color)sharedVariable.GetValue(), new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Rect:
                 sharedVariable.SetValue(EditorGUILayout.RectField((Rect)sharedVariable.GetValue(), new GUILayoutOption[0]));
                 break;
             case SharedVariableTypes.GameObject:
                 sharedVariable.SetValue(EditorGUILayout.ObjectField((GameObject)sharedVariable.GetValue(), typeof(GameObject), true, new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Transform:
                 sharedVariable.SetValue(EditorGUILayout.ObjectField((Transform)sharedVariable.GetValue(), typeof(Transform), true, new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
             case SharedVariableTypes.Object:
                 sharedVariable.SetValue(EditorGUILayout.ObjectField((UnityEngine.Object)sharedVariable.GetValue(), typeof(UnityEngine.Object), true, new GUILayoutOption[]
                 {
                     GUILayout.Width((float)width)
                 }));
                 break;
         }
     }
     catch (Exception)
     {
     }
 }
		private void SharedVariables_SharedVariableAdded(SharedVariableCollection collection, SharedVariable variable)
		{
			if (variable == null)
				return;
			if (this.InvokeRequired)
			{
				if (!this.IsHandleCreated || this.Disposing || this.IsDisposed)
					return;
				this.BeginInvoke(dlgShvSharedVariableAdded, collection, variable);
				return;
			}

			if(lvSharedVariables.Items.Count < (collection.Count -1))
			{
				UpdateSharedVariables();
				return;
			}

			ListViewItem lvi = lvSharedVariables.Items.Add(variable.Name);
			lvi.Tag = variable;
			lvSharedVariables.Refresh();
		}
 public IEnumerator Do(SharedData share, SharedVariable variable)
 {
     prevActive = share.view.NameTextWindowImage.gameObject.activeSelf;
     share.view.NameTextWindowImage.gameObject.SetActive(true);
     yield break;
 }
 public IEnumerator Undo(SharedData share, SharedVariable variable)
 {
     yield break;
 }
 public IEnumerator Do(SharedData share, SharedVariable variable)
 {
     share.view.NameText.text += variable.FindValue(share.model_.parameters[0]);
     yield break;
 }
 public IEnumerator Undo(SharedData share, SharedVariable variable)
 {
     // Groupまで巻き戻す
     yield break;
 }
Example #17
0
 private bool isValid(SharedVariable sv)
 {
     return(null != sv && !sv.IsNone);
 }
Example #18
0
        private void LearnAPIClick5LabelModel(
            int numLabels,
            bool learnScoreMean,
            bool learnScorePrec,
            bool learnJudgePrec,
            bool learnClickPrec,
            bool learnThresholds,
            double nominalScoreMean,
            double nominalScorePrec,
            double nominalJudgePrec,
            double nominalClickPrec,
            int[] labels,
            int[] clicks,
            int[] exams,
            int chunkSize,
            int nPasses,
            bool printToConsole,
            out Gaussian margScoreMean,
            out Gamma margScorePrec,
            out Gamma margJudgePrec,
            out Gamma margClickPrec,
            out Gaussian[] margThresh)
        {
            //------------------------------------------------------
            // Observations
            //------------------------------------------------------
            Gaussian[][][] allObs    = getClickObservations(numLabels, chunkSize, labels, clicks, exams);
            int            numChunks = allObs.Length;

            ////-------------------------------------------------------------
            //// Prior distributions
            ////-------------------------------------------------------------
            Gaussian priorScoreMean = Gaussian.FromMeanAndVariance(nominalScoreMean, learnScoreMean ? 1 : 0);
            Gamma    priorScorePrec = Gamma.FromMeanAndVariance(nominalScorePrec, learnScorePrec ? 1 : 0);
            Gamma    priorJudgePrec = Gamma.FromMeanAndVariance(nominalJudgePrec, learnJudgePrec ? 1 : 0);
            Gamma    priorClickPrec = Gamma.FromMeanAndVariance(nominalClickPrec, learnClickPrec ? 1 : 0);

            Gaussian[] priorThreshMean;
            CalculatePriors(learnThresholds, numLabels, out priorThreshMean);

            ////-----------------------------------------------------
            //// Creates shared variables
            ////-----------------------------------------------------
            int numThresholds = numLabels + 1;
            SharedVariable <double> scoreMean = SharedVariable <double> .Random(priorScoreMean).Named("scoreMean");

            SharedVariable <double> scorePrec = SharedVariable <double> .Random(priorScorePrec).Named("scorePrec");

            SharedVariable <double> judgePrec = SharedVariable <double> .Random(priorJudgePrec).Named("judgePrec");

            SharedVariable <double> clickPrec = SharedVariable <double> .Random(priorClickPrec).Named("clickPrec");

            SharedVariable <double>[] thresholds = new SharedVariable <double> [numThresholds];
            for (int t = 0; t < numThresholds; t++)
            {
                thresholds[t] = SharedVariable <double> .Random(priorThreshMean[t]).Named("threshMeans" + t);
            }

            //----------------------------------------------------------------------------------
            // The model
            //----------------------------------------------------------------------------------

            Model model = new Model(numChunks);

            VariableArray <Gaussian>[] clickObs       = new VariableArray <Gaussian> [numLabels];
            Variable <int>[]           clickObsLength = new Variable <int> [numLabels];

            for (int i = 0; i < numLabels; i++)
            {
                clickObsLength[i] = Variable.New <int>().Named("clickObsLength" + i);
                Range r = new Range(clickObsLength[i]).Named("dataCount" + i);
                clickObs[i] = Variable.Array <Gaussian>(r).Named("Obs" + i);
                VariableArray <double> scores  = Variable.Array <double>(r).Named("scores" + i);
                VariableArray <double> scoresJ = Variable.Array <double>(r).Named("scoresJ" + i);
                VariableArray <double> scoresC = Variable.Array <double>(r).Named("scoresC" + i);
                scores[r] = Variable <double> .GaussianFromMeanAndPrecision(scoreMean.GetCopyFor(model), scorePrec.GetCopyFor(model)).ForEach(r);

                scoresJ[r] = Variable <double> .GaussianFromMeanAndPrecision(scores[r], judgePrec.GetCopyFor(model));

                scoresC[r] = Variable <double> .GaussianFromMeanAndPrecision(scores[r], clickPrec.GetCopyFor(model));

                Variable.ConstrainBetween(scoresJ[r], thresholds[i].GetCopyFor(model), thresholds[i + 1].GetCopyFor(model));
                Variable.ConstrainEqualRandom <double, Gaussian>(scoresC[r], clickObs[i][r]);
                r.AddAttribute(new Sequential());
            }

            InferenceEngine engine = new InferenceEngine();

            //----------------------------------------------------------
            // Outer loop iterates over a number of passes
            // Inner loop iterates over the unique labels
            //----------------------------------------------------------
            for (int pass = 0; pass < nPasses; pass++)
            {
                for (int c = 0; c < numChunks; c++)
                {
                    for (int i = 0; i < numLabels; i++)
                    {
                        clickObsLength[i].ObservedValue = allObs[c][i].Length;
                        clickObs[i].ObservedValue       = allObs[c][i];
                    }

                    // Infer the output messages
                    model.InferShared(engine, c);

                    if (printToConsole)
                    {
                        margScoreMean = scoreMean.Marginal <Gaussian>();
                        margScorePrec = scorePrec.Marginal <Gamma>();
                        margJudgePrec = judgePrec.Marginal <Gamma>();
                        margClickPrec = clickPrec.Marginal <Gamma>();
                        margThresh    = new Gaussian[numThresholds];
                        for (int i = 0; i < numThresholds; i++)
                        {
                            margThresh[i] = thresholds[i].Marginal <Gaussian>();
                        }
                        Console.WriteLine("****** Pass {0}, chunk {1} ******", pass, c);
                        Console.WriteLine("----- Marginals -----");
                        Console.WriteLine("scoreMean = {0}", margScoreMean);
                        Console.WriteLine("scorePrec = {0}", margScorePrec);
                        Console.WriteLine("judgePrec = {0}", margJudgePrec);
                        Console.WriteLine("clickPrec = {0}", margClickPrec);
                        for (int t = 0; t < numThresholds; t++)
                        {
                            Console.WriteLine("threshMean {0} = {1}", t, margThresh[t]);
                        }
                    }
                }
            }
            margScoreMean = scoreMean.Marginal <Gaussian>();
            margScorePrec = scorePrec.Marginal <Gamma>();
            margJudgePrec = judgePrec.Marginal <Gamma>();
            margClickPrec = clickPrec.Marginal <Gamma>();
            margThresh    = new Gaussian[numThresholds];
            for (int i = 0; i < numThresholds; i++)
            {
                margThresh[i] = thresholds[i].Marginal <Gaussian>();
            }
        }
Example #19
0
        private void LearnClick5LabelModel(
            int numLabels,
            bool learnScoreMean,
            bool learnScorePrec,
            bool learnJudgePrec,
            bool learnClickPrec,
            bool learnThresholds,
            double nominalScoreMean,
            double nominalScorePrec,
            double nominalJudgePrec,
            double nominalClickPrec,
            int[] labels,
            int[] clicks,
            int[] exams,
            int chunkSize,
            int nPasses,
            bool printToConsole,
            out Gaussian margScoreMean,
            out Gamma margScorePrec,
            out Gamma margJudgePrec,
            out Gamma margClickPrec,
            out Gaussian[] margThresh)
        {
            InferenceEngine engine = new InferenceEngine();
            int             numThresholds = numLabels + 1; // Includes end-points

            //-------------------------------------------------------------
            // Priors
            //-------------------------------------------------------------
            Gaussian priorScoreMean = Gaussian.FromMeanAndVariance(nominalScoreMean, learnScoreMean ? 1 : 0);
            Gamma    priorScorePrec = Gamma.FromMeanAndVariance(nominalScorePrec, learnScorePrec ? 1 : 0);
            Gamma    priorJudgePrec = Gamma.FromMeanAndVariance(nominalJudgePrec, learnJudgePrec ? 1 : 0);
            Gamma    priorClickPrec = Gamma.FromMeanAndVariance(nominalClickPrec, learnClickPrec ? 1 : 0);

            Gaussian[] priorThreshMean;
            CalculatePriors(learnThresholds, numLabels, out priorThreshMean);

            //------------------------------------------------------
            // Observations
            //------------------------------------------------------
            Gaussian[][][] clickObs = getClickObservations(numLabels, chunkSize, labels, clicks, exams);
            int            numChunks = clickObs.Length;

            //-----------------------------------------------------
            // Create an array of batch variables
            //-----------------------------------------------------
            Model model = new Model(numChunks);
            SharedVariable <double, Gaussian> scoreMean = (SharedVariable <double, Gaussian>) SharedVariable <double> .Random(priorScoreMean).Named("scoreMean");

            SharedVariable <double, Gamma> scorePrec = (SharedVariable <double, Gamma>) SharedVariable <double> .Random(priorScorePrec).Named("scorePrec");

            SharedVariable <double, Gamma> judgePrec = (SharedVariable <double, Gamma>) SharedVariable <double> .Random(priorJudgePrec).Named("judgePrec");

            SharedVariable <double, Gamma> clickPrec = (SharedVariable <double, Gamma>) SharedVariable <double> .Random(priorClickPrec).Named("clickPrec");

            SharedVariable <double, Gaussian>[] threshMeans = new SharedVariable <double, Gaussian> [numThresholds];
            for (int t = 0; t < numThresholds; t++)
            {
                threshMeans[t] = (SharedVariable <double, Gaussian>) SharedVariable <double, Gaussian> .Random(priorThreshMean[t]).Named("threshMeans" + t);
            }

            engine.Compiler.DeclarationProvider = Microsoft.ML.Probabilistic.Compiler.RoslynDeclarationProvider.Instance;
            var info = GetType().GetMethod("Click5LabelModel", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var ca   = engine.Compiler.CompileWithoutParams(info);

            //----------------------------------------------------------
            // Outer loop iterates over a number of passes
            // Inner loop iterates over the unique labels
            //----------------------------------------------------------
            for (int pass = 0; pass < nPasses; pass++)
            {
                for (int c = 0; c < numChunks; c++)
                {
                    Gaussian[] threshInputs = new Gaussian[threshMeans.Length];
                    for (int i = 0; i < threshInputs.Length; i++)
                    {
                        threshInputs[i] = ((SharedVariable <double, Gaussian>)threshMeans[i]).MessageToBatch(model, c);
                    }
                    ca.SetObservedValue("inputScoreMean", scoreMean.MessageToBatch(model, c));
                    ca.SetObservedValue("inputScorePrec", scorePrec.MessageToBatch(model, c));
                    ca.SetObservedValue("inputJudgePrec", judgePrec.MessageToBatch(model, c));
                    ca.SetObservedValue("inputClickPrec", clickPrec.MessageToBatch(model, c));
                    ca.SetObservedValue("inputThresh", threshInputs);
                    ca.SetObservedValue("clickObservations", clickObs[c]);
                    ca.Execute(10);

                    // Retrieve the output messages
                    model.InferShared(ca, c);

                    if (printToConsole)
                    {
                        Console.WriteLine("****** Pass {0}, chunk {1} ******", pass, c);
                        Console.WriteLine("----- Marginals -----");
                        Console.WriteLine("scoreMean = {0}", scoreMean.Marginal <Gaussian>());
                        Console.WriteLine("scorePrec = {0}", scorePrec.Marginal <Gamma>());
                        Console.WriteLine("judgePrec = {0}", judgePrec.Marginal <Gamma>());
                        Console.WriteLine("clickPrec = {0}", clickPrec.Marginal <Gamma>());
                        for (int t = 0; t < numThresholds; t++)
                        {
                            Console.WriteLine("threshMean {0} = {1}", t, threshMeans[t].Marginal <Gaussian>());
                        }
                    }
                }
            }
            margScoreMean = scoreMean.Marginal <Gaussian>();
            margScorePrec = scorePrec.Marginal <Gamma>();
            margJudgePrec = judgePrec.Marginal <Gamma>();
            margClickPrec = clickPrec.Marginal <Gamma>();
            margThresh    = new Gaussian[numThresholds];
            for (int i = 0; i < margThresh.Length; i++)
            {
                margThresh[i] = threshMeans[i].Marginal <Gaussian>();
            }
        }
        // Token: 0x060002BF RID: 703 RVA: 0x0001B53C File Offset: 0x0001973C
        private static bool DrawSelectedVariable(IVariableSource variableSource, ref List <SharedVariable> variables, SharedVariable sharedVariable, ref int selectedVariableIndex, ref string selectedVariableName, ref int selectedVariableTypeIndex, ref bool deleted)
        {
            bool result = false;

            GUILayout.BeginVertical(BehaviorDesignerUtility.SelectedBackgroundGUIStyle, new GUILayoutOption[0]);
            GUILayout.BeginHorizontal(new GUILayoutOption[0]);
            GUILayout.Label("Name", new GUILayoutOption[]
            {
                GUILayout.Width(70f)
            });
            EditorGUI.BeginChangeCheck();
            selectedVariableName = GUILayout.TextField(selectedVariableName, new GUILayoutOption[]
            {
                GUILayout.Width(140f)
            });
            if (EditorGUI.EndChangeCheck())
            {
                if (VariableInspector.VariableNameValid(variableSource, selectedVariableName))
                {
                    variableSource.UpdateVariableName(sharedVariable, selectedVariableName);
                }
                result = true;
            }
            GUILayout.Space(10f);
            bool enabled = GUI.enabled;

            GUI.enabled = (enabled && selectedVariableIndex < variables.Count - 1);
            if (GUILayout.Button(BehaviorDesignerUtility.DownArrowButtonTexture, BehaviorDesignerUtility.PlainButtonGUIStyle, new GUILayoutOption[]
            {
                GUILayout.Width(19f)
            }))
            {
                SharedVariable value = variables[selectedVariableIndex + 1];
                variables[selectedVariableIndex + 1] = variables[selectedVariableIndex];
                variables[selectedVariableIndex]     = value;
                selectedVariableIndex++;
                result = true;
            }
            GUI.enabled = (enabled && (selectedVariableIndex < variables.Count - 1 || selectedVariableIndex != 0));
            GUILayout.Box(string.Empty, BehaviorDesignerUtility.ArrowSeparatorGUIStyle, new GUILayoutOption[]
            {
                GUILayout.Width(1f),
                GUILayout.Height(18f)
            });
            GUI.enabled = (enabled && selectedVariableIndex != 0);
            if (GUILayout.Button(BehaviorDesignerUtility.UpArrowButtonTexture, BehaviorDesignerUtility.PlainButtonGUIStyle, new GUILayoutOption[]
            {
                GUILayout.Width(20f)
            }))
            {
                SharedVariable value2 = variables[selectedVariableIndex - 1];
                variables[selectedVariableIndex - 1] = variables[selectedVariableIndex];
                variables[selectedVariableIndex]     = value2;
                selectedVariableIndex--;
                result = true;
            }
            GUI.enabled = enabled;
            if (GUILayout.Button(BehaviorDesignerUtility.VariableDeleteButtonTexture, BehaviorDesignerUtility.PlainButtonGUIStyle, new GUILayoutOption[]
            {
                GUILayout.Width(19f)
            }) && EditorUtility.DisplayDialog("Delete Variable", "Are you sure you want to delete this variable?", "Yes", "No"))
            {
                deleted = true;
            }
            GUILayout.EndHorizontal();
            GUILayout.Space(2f);
            GUILayout.BeginHorizontal(new GUILayoutOption[0]);
            GUILayout.Label("Type", new GUILayoutOption[]
            {
                GUILayout.Width(70f)
            });
            EditorGUI.BeginChangeCheck();
            selectedVariableTypeIndex = EditorGUILayout.Popup(selectedVariableTypeIndex, VariableInspector.sharedVariableStrings, EditorStyles.toolbarPopup, new GUILayoutOption[]
            {
                GUILayout.Width(200f)
            });
            if (EditorGUI.EndChangeCheck() && VariableInspector.sharedVariableTypesDict[sharedVariable.GetType().Name] != selectedVariableTypeIndex)
            {
                if (BehaviorDesignerWindow.instance != null)
                {
                    BehaviorDesignerWindow.instance.RemoveSharedVariableReferences(sharedVariable);
                }
                sharedVariable = VariableInspector.CreateVariable(selectedVariableTypeIndex, sharedVariable.Name, sharedVariable.IsGlobal);
                variables[selectedVariableIndex] = sharedVariable;
                result = true;
            }
            GUILayout.EndHorizontal();
            EditorGUI.BeginChangeCheck();
            GUILayout.Space(4f);
            GUILayout.BeginHorizontal(new GUILayoutOption[0]);
            GUI.enabled = VariableInspector.CanNetworkSync(sharedVariable.GetType().GetProperty("Value").PropertyType);
            EditorGUI.BeginChangeCheck();
            sharedVariable.NetworkSync = EditorGUILayout.Toggle(new GUIContent("Network Sync", "Sync this variable over the network. Requires Unity 5.1 or greator. A NetworkIdentity must be attached to the behavior tree GameObject."), sharedVariable.NetworkSync, new GUILayoutOption[0]);
            if (EditorGUI.EndChangeCheck())
            {
                result = true;
            }
            GUILayout.EndHorizontal();
            GUI.enabled = enabled;
            GUILayout.BeginHorizontal(new GUILayoutOption[0]);
            if (VariableInspector.DrawSharedVariable(variableSource, sharedVariable, true))
            {
                result = true;
            }
            if (BehaviorDesignerWindow.instance != null && BehaviorDesignerWindow.instance.ContainsError(null, selectedVariableIndex))
            {
                GUILayout.Box(BehaviorDesignerUtility.ErrorIconTexture, BehaviorDesignerUtility.PlainTextureGUIStyle, new GUILayoutOption[]
                {
                    GUILayout.Width(20f)
                });
            }
            GUILayout.EndHorizontal();
            BehaviorDesignerUtility.DrawContentSeperator(4, 7);
            GUILayout.EndVertical();
            GUILayout.Space(3f);
            return(result);
        }
        // Token: 0x060002BD RID: 701 RVA: 0x0001B144 File Offset: 0x00019344
        public static bool DrawAllVariables(bool showFooter, IVariableSource variableSource, ref List <SharedVariable> variables, bool canSelect, ref List <float> variablePosition, ref int selectedVariableIndex, ref string selectedVariableName, ref int selectedVariableTypeIndex, bool drawRemoveButton, bool drawLastSeparator)
        {
            if (variables == null)
            {
                return(false);
            }
            bool result = false;

            if (canSelect && variablePosition == null)
            {
                variablePosition = new List <float>();
            }
            for (int i = 0; i < variables.Count; i++)
            {
                SharedVariable sharedVariable = variables[i];
                if (sharedVariable != null)
                {
                    if (canSelect && selectedVariableIndex == i)
                    {
                        if (i == 0)
                        {
                            GUILayout.Space(2f);
                        }
                        bool flag = false;
                        if (VariableInspector.DrawSelectedVariable(variableSource, ref variables, sharedVariable, ref selectedVariableIndex, ref selectedVariableName, ref selectedVariableTypeIndex, ref flag))
                        {
                            result = true;
                        }
                        if (flag)
                        {
                            if (BehaviorDesignerWindow.instance != null)
                            {
                                BehaviorDesignerWindow.instance.RemoveSharedVariableReferences(sharedVariable);
                            }
                            variables.RemoveAt(i);
                            if (selectedVariableIndex == i)
                            {
                                selectedVariableIndex = -1;
                            }
                            else if (selectedVariableIndex > i)
                            {
                                selectedVariableIndex--;
                            }
                            result = true;
                            break;
                        }
                    }
                    else
                    {
                        GUILayout.BeginHorizontal();
                        if (VariableInspector.DrawSharedVariable(variableSource, sharedVariable, false))
                        {
                            result = true;
                        }
                        if (drawRemoveButton && GUILayout.Button(BehaviorDesignerUtility.VariableDeleteButtonTexture, BehaviorDesignerUtility.PlainButtonGUIStyle, new GUILayoutOption[]
                        {
                            GUILayout.Width(19f)
                        }) && EditorUtility.DisplayDialog("Delete Variable", "Are you sure you want to delete this variable?", "Yes", "No"))
                        {
                            if (BehaviorDesignerWindow.instance != null)
                            {
                                BehaviorDesignerWindow.instance.RemoveSharedVariableReferences(sharedVariable);
                            }
                            variables.RemoveAt(i);
                            if (canSelect)
                            {
                                if (selectedVariableIndex == i)
                                {
                                    selectedVariableIndex = -1;
                                }
                                else if (selectedVariableIndex > i)
                                {
                                    selectedVariableIndex--;
                                }
                            }
                            result = true;
                            break;
                        }
                        if (BehaviorDesignerWindow.instance != null && BehaviorDesignerWindow.instance.ContainsError(null, i))
                        {
                            GUILayout.Box(BehaviorDesignerUtility.ErrorIconTexture, BehaviorDesignerUtility.PlainTextureGUIStyle, new GUILayoutOption[]
                            {
                                GUILayout.Width(20f)
                            });
                        }
                        GUILayout.Space(10f);
                        GUILayout.EndHorizontal();
                        if (i != variables.Count - 1 || drawLastSeparator)
                        {
                            BehaviorDesignerUtility.DrawContentSeperator(2, 7);
                        }
                    }
                    GUILayout.Space(4f);
                    if (canSelect && (int)Event.current.type == 7)
                    {
                        if (variablePosition.Count <= i)
                        {
                            variablePosition.Add(GUILayoutUtility.GetLastRect().yMax);
                        }
                        else
                        {
                            variablePosition[i] = GUILayoutUtility.GetLastRect().yMax;
                        }
                    }
                }
            }
            if (canSelect && variables.Count < variablePosition.Count)
            {
                for (int j = variablePosition.Count - 1; j >= variables.Count; j--)
                {
                    variablePosition.RemoveAt(j);
                }
            }
            if (showFooter && variables.Count > 0)
            {
                GUI.enabled = true;
                GUILayout.Label("Select a variable to change its properties.", BehaviorDesignerUtility.LabelWrapGUIStyle, new GUILayoutOption[0]);
            }
            return(result);
        }
    private static object LoadField(FieldSerializationData fieldSerializationData, Dictionary <string, int> fieldIndexMap, Type fieldType, string fieldName, IVariableSource variableSource, object obj = null, FieldInfo fieldInfo = null)
    {
        string text = fieldType.Name + fieldName;
        int    num;

        if (fieldIndexMap.TryGetValue(text, out num))
        {
            object obj2 = null;
            if (typeof(IList).IsAssignableFrom(fieldType))
            {
                int num2 = BytesToInt(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
                if (fieldType.IsArray)
                {
                    Type elementType = fieldType.GetElementType();
                    if (elementType == null)
                    {
                        return(null);
                    }
                    Array array = Array.CreateInstance(elementType, num2);
                    for (int i = 0; i < num2; i++)
                    {
                        object obj3 = LoadField(fieldSerializationData, fieldIndexMap, elementType, text + i, variableSource, obj, fieldInfo);
                        array.SetValue((!ReferenceEquals(obj3, null) && !obj3.Equals(null)) ? obj3 : null, i);
                    }
                    obj2 = array;
                }
                else
                {
                    Type type = fieldType;
                    while (!type.IsGenericType)
                    {
                        type = type.BaseType;
                    }
                    Type  type2 = type.GetGenericArguments()[0];
                    IList list;
                    if (fieldType.IsGenericType)
                    {
                        list = (TaskUtility.CreateInstance(typeof(List <>).MakeGenericType(new Type[]
                        {
                            type2
                        })) as IList);
                    }
                    else
                    {
                        list = (TaskUtility.CreateInstance(fieldType) as IList);
                    }
                    for (int j = 0; j < num2; j++)
                    {
                        object obj4 = LoadField(fieldSerializationData, fieldIndexMap, type2, text + j, variableSource, obj, fieldInfo);
                        list.Add((!ReferenceEquals(obj4, null) && !obj4.Equals(null)) ? obj4 : null);
                    }
                    obj2 = list;
                }
            }
            else if (typeof(Task).IsAssignableFrom(fieldType))
            {
                if (fieldInfo != null && TaskUtility.HasAttribute(fieldInfo, typeof(InspectTaskAttribute)))
                {
                    string text2 = BytesToString(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num], GetFieldSize(fieldSerializationData, num));
                    if (!string.IsNullOrEmpty(text2))
                    {
                        Type typeWithinAssembly = TaskUtility.GetTypeWithinAssembly(text2);
                        if (typeWithinAssembly != null)
                        {
                            obj2 = TaskUtility.CreateInstance(typeWithinAssembly);
                            LoadFields(fieldSerializationData, fieldIndexMap, obj2, text, variableSource);
                        }
                    }
                }
                else
                {
                    if (taskIDs == null)
                    {
                        taskIDs = new Dictionary <ObjectFieldMap, List <int> >(new ObjectFieldMapComparer());
                    }
                    int            item = BytesToInt(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
                    ObjectFieldMap key  = new ObjectFieldMap(obj, fieldInfo);
                    if (taskIDs.ContainsKey(key))
                    {
                        taskIDs[key].Add(item);
                    }
                    else
                    {
                        List <int> list2 = new List <int>();
                        list2.Add(item);
                        taskIDs.Add(key, list2);
                    }
                }
            }
            else if (typeof(SharedVariable).IsAssignableFrom(fieldType))
            {
                obj2 = BytesToSharedVariable(fieldSerializationData, fieldIndexMap, fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num], variableSource, true, text);
            }
            else if (typeof(UnityEngine.Object).IsAssignableFrom(fieldType))
            {
                int index = BytesToInt(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
                obj2 = IndexToUnityObject(index, fieldSerializationData);
            }
            else if (fieldType.Equals(typeof(int)) || fieldType.IsEnum)
            {
                obj2 = BytesToInt(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(uint)))
            {
                obj2 = BytesToUInt(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(float)))
            {
                obj2 = BytesToFloat(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(double)))
            {
                obj2 = BytesToDouble(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(long)))
            {
                obj2 = BinaryDeserialization.BytesToLong(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(bool)))
            {
                obj2 = BinaryDeserialization.BytesToBool(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(string)))
            {
                obj2 = BinaryDeserialization.BytesToString(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num], BinaryDeserialization.GetFieldSize(fieldSerializationData, num));
            }
            else if (fieldType.Equals(typeof(byte)))
            {
                obj2 = BinaryDeserialization.BytesToByte(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Vector2)))
            {
                obj2 = BinaryDeserialization.BytesToVector2(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Vector3)))
            {
                obj2 = BinaryDeserialization.BytesToVector3(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Vector4)))
            {
                obj2 = BinaryDeserialization.BytesToVector4(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Quaternion)))
            {
                obj2 = BinaryDeserialization.BytesToQuaternion(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Color)))
            {
                obj2 = BinaryDeserialization.BytesToColor(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Rect)))
            {
                obj2 = BinaryDeserialization.BytesToRect(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(Matrix4x4)))
            {
                obj2 = BinaryDeserialization.BytesToMatrix4x4(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(AnimationCurve)))
            {
                obj2 = BinaryDeserialization.BytesToAnimationCurve(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.Equals(typeof(LayerMask)))
            {
                obj2 = BinaryDeserialization.BytesToLayerMask(fieldSerializationData.byteDataArray, fieldSerializationData.dataPosition[num]);
            }
            else if (fieldType.IsClass || (fieldType.IsValueType && !fieldType.IsPrimitive))
            {
                obj2 = TaskUtility.CreateInstance(fieldType);
                BinaryDeserialization.LoadFields(fieldSerializationData, fieldIndexMap, obj2, text, variableSource);
                return(obj2);
            }
            return(obj2);
        }
        if (typeof(SharedVariable).IsAssignableFrom(fieldType))
        {
            Type type3 = TaskUtility.SharedVariableToConcreteType(fieldType);
            if (type3 == null)
            {
                return(null);
            }
            text = type3.Name + fieldName;
            if (fieldIndexMap.ContainsKey(text))
            {
                SharedVariable sharedVariable = TaskUtility.CreateInstance(fieldType) as SharedVariable;
                sharedVariable.SetValue(BinaryDeserialization.LoadField(fieldSerializationData, fieldIndexMap, type3, fieldName, variableSource, null, null));
                return(sharedVariable);
            }
        }
        if (typeof(SharedVariable).IsAssignableFrom(fieldType))
        {
            return(TaskUtility.CreateInstance(fieldType));
        }
        return(null);
    }
Example #23
0
		/// <summary>
		/// Constructs an LDA model
		/// </summary>
		/// <param name="sizeVocab">Size of vocabulary</param>
		/// <param name="numTopics">Number of topics</param>
		public LDAShared(int numBatches, int sizeVocab, int numTopics)
		{
			SizeVocab = sizeVocab;
			NumTopics = numTopics;
			ThetaSparsity = Sparsity.Dense;
			PhiSparsity = Sparsity.ApproximateWithTolerance(0.00000000001); // Allow for round-off error
			NumDocuments = Variable.New<int>().Named("NumDocuments");
			NumBatches = numBatches;
			IterationsPerPass = new int[] { 1, 3, 5, 7, 9 };

			//---------------------------------------------
			// The model
			//---------------------------------------------
			Range D = new Range(NumDocuments).Named("D");
			Range W = new Range(SizeVocab).Named("W");
			Range T = new Range(NumTopics).Named("T");
			NumWordsInDoc = Variable.Array<int>(D).Named("NumWordsInDoc");
			Range WInD = new Range(NumWordsInDoc[D]).Named("WInD");

			Evidence = SharedVariable<bool>.Random(new Bernoulli(0.5)).Named("Evidence");
			Evidence.IsEvidenceVariable = true;

			Phi = SharedVariable<Vector>.Random(T, CreateUniformDirichletArray(numTopics, sizeVocab, PhiSparsity)).Named("Phi");

			// Phi definition sub-model - just one copy
			PhiDefModel = new Model(1).Named("PhiDefModel");

			IfBlock evidencePhiDefBlock = null;
			EvidencePhiDef = Evidence.GetCopyFor(PhiDefModel).Named("EvidencePhiDef");
			evidencePhiDefBlock = Variable.If(EvidencePhiDef);
			PhiDef = Variable.Array<Vector>(T).Named("PhiDef");
			PhiDef.SetSparsity(PhiSparsity);
			PhiDef.SetValueRange(W);
			PhiPrior = Variable.Array<Dirichlet>(T).Named("PhiPrior");
			PhiDef[T] = Variable<Vector>.Random(PhiPrior[T]);
			Phi.SetDefinitionTo(PhiDefModel, PhiDef);
			evidencePhiDefBlock.CloseBlock();

			// Document sub-model - many copies
			DocModel = new Model(numBatches).Named("DocModel");

			IfBlock evidenceDocBlock = null;
			EvidenceDoc = Evidence.GetCopyFor(DocModel).Named("EvidenceDoc");
			evidenceDocBlock = Variable.If(EvidenceDoc);
			Theta = Variable.Array<Vector>(D).Named("Theta");
			Theta.SetSparsity(ThetaSparsity);
			Theta.SetValueRange(T);
			ThetaPrior = Variable.Array<Dirichlet>(D).Named("ThetaPrior");
			Theta[D] = Variable<Vector>.Random(ThetaPrior[D]);
			PhiDoc = Phi.GetCopyFor(DocModel);
			PhiDoc.AddAttribute(new MarginalPrototype(Dirichlet.Uniform(sizeVocab, PhiSparsity)));
			Words = Variable.Array(Variable.Array<int>(WInD), D).Named("Words");
			WordCounts = Variable.Array(Variable.Array<double>(WInD), D).Named("WordCounts");
			using (Variable.ForEach(D))
			{
				using (Variable.ForEach(WInD))
				{
					using (Variable.Repeat(WordCounts[D][WInD]))
					{
						Variable<int> topic = Variable.Discrete(Theta[D]).Named("topic");
						using (Variable.Switch(topic))
							Words[D][WInD] = Variable.Discrete(PhiDoc[topic]);
					} 
				}
			}
			evidenceDocBlock.CloseBlock();

			// Initialization to break symmetry
			ThetaInit = Variable.New<IDistribution<Vector[]>>().Named("ThetaInit");
			Theta.InitialiseTo(ThetaInit);
			EnginePhiDef = new InferenceEngine(new VariationalMessagePassing());
			EnginePhiDef.Compiler.ShowWarnings = false;
			EnginePhiDef.ModelName = "LDASharedPhiDef";

			Engine = new InferenceEngine(new VariationalMessagePassing());
			Engine.OptimiseForVariables = new IVariable[] { Theta, PhiDoc, EvidenceDoc };

			Engine.Compiler.ShowWarnings = false;
			Engine.ModelName = "LDAShared";
			Engine.Compiler.ReturnCopies = false;
			Engine.Compiler.FreeMemory = true;
		}
        /// <summary>
        /// Executes a create_var command.
        /// Requests the blackboard to create a variable with the specified name and size
        /// </summary>
        /// <param name="command">Command to execute</param>
        protected virtual void CreateVarCommand(Command command)
        {
            SharedVariable variable;
            bool result;
            SharedVariableCollection sharedVariables = this.Parent.VirtualModule.SharedVariables;
            Match match = SharedVariable.RxCreateSharedVariableValidator.Match(command.Parameters);
            if (!match.Success)
            {
                SendResponse(command, false);
                this.Parent.Log.WriteLine(7, this.Name + ": attempt to create variable failed");
                return;
            }
            string varName = match.Result("${name}");
            string varType = match.Result("${type}");
            bool isArray = false;
            string sArraySize;
            int arraySize = -1;
            if (String.IsNullOrEmpty(varType))
                varType = "var";
            if (!String.IsNullOrEmpty(match.Result("${array}")))
            {
                isArray = true;
                sArraySize = match.Result("${size}");
                if (!String.IsNullOrEmpty(sArraySize))
                    arraySize = Int32.Parse(sArraySize);
            }

            if (sharedVariables.Contains(varName))
            {
                variable = sharedVariables[varName];
                result = variable.Type == varType;
                result &= variable.IsArray == isArray;
                result &= arraySize == variable.Size;
                SendResponse(command, result);
                this.Parent.Log.WriteLine(7, this.Name + ": attempt to create variable failed (already exists)");
                return;
            }

            SharedVariable sv = new SharedVariable(this, varType, varName, isArray, arraySize);
            sv.AllowedWriters.Add("*");
            sharedVariables.Add(sv);
            SendResponse(command, true);
            if (this.Parent.Log.VerbosityTreshold < 3)
                this.Parent.Log.WriteLine(2, this.Name + ": created variable " + varName);
            else
                this.Parent.Log.WriteLine(3, this.Name + ": created variable " + varName + " with " + Clamper.Clamp(command.StringToSend, 256));
        }
 public static SharedVariable DrawSharedVariable(Task task, GUIContent guiContent, FieldInfo fieldInfo, Type fieldType, SharedVariable sharedVariable)
 {
     if (!fieldType.Equals(typeof(SharedVariable)) && sharedVariable == null)
     {
         sharedVariable = (Activator.CreateInstance(fieldType, true) as SharedVariable);
         if (TaskUtility.HasAttribute(fieldInfo, typeof(RequiredFieldAttribute)) || TaskUtility.HasAttribute(fieldInfo, typeof(SharedRequiredAttribute)))
         {
             sharedVariable.IsShared = true;
         }
         GUI.changed = true;
     }
     if (sharedVariable == null || sharedVariable.IsShared)
     {
         GUILayout.BeginHorizontal(new GUILayoutOption[0]);
         string[] array           = null;
         int      num             = -1;
         int      num2            = FieldInspector.GetVariablesOfType((sharedVariable == null) ? null : sharedVariable.GetType().GetProperty("Value").PropertyType, sharedVariable != null && sharedVariable.IsGlobal, (sharedVariable == null) ? string.Empty : sharedVariable.Name, FieldInspector.behaviorSource, out array, ref num, fieldType.Equals(typeof(SharedVariable)));
         Color    backgroundColor = GUI.backgroundColor;
         if (num2 == 0 && !TaskUtility.HasAttribute(fieldInfo, typeof(SharedRequiredAttribute)))
         {
             GUI.backgroundColor = Color.red;
         }
         int num3 = num2;
         num2 = EditorGUILayout.Popup(guiContent.text, num2, array, BehaviorDesignerUtility.SharedVariableToolbarPopup, new GUILayoutOption[0]);
         GUI.backgroundColor = backgroundColor;
         if (num2 != num3)
         {
             if (num2 == 0)
             {
                 if (fieldType.Equals(typeof(SharedVariable)))
                 {
                     sharedVariable = null;
                 }
                 else
                 {
                     sharedVariable          = (Activator.CreateInstance(fieldType, true) as SharedVariable);
                     sharedVariable.IsShared = true;
                 }
             }
             else if (num != -1 && num2 >= num)
             {
                 sharedVariable = GlobalVariables.Instance.GetVariable(array[num2].Substring(8, array[num2].Length - 8));
             }
             else
             {
                 sharedVariable = FieldInspector.behaviorSource.GetVariable(array[num2]);
             }
             GUI.changed = true;
         }
         if (!fieldType.Equals(typeof(SharedVariable)) && !TaskUtility.HasAttribute(fieldInfo, typeof(RequiredFieldAttribute)) && !TaskUtility.HasAttribute(fieldInfo, typeof(SharedRequiredAttribute)))
         {
             sharedVariable = FieldInspector.DrawSharedVariableToggleSharedButton(sharedVariable);
             GUILayout.Space(-3f);
         }
         GUILayout.EndHorizontal();
         GUILayout.Space(3f);
     }
     else
     {
         GUILayout.BeginHorizontal(new GUILayoutOption[0]);
         ObjectDrawerAttribute[] array2;
         ObjectDrawer            objectDrawer;
         if (fieldInfo != null && (array2 = (fieldInfo.GetCustomAttributes(typeof(ObjectDrawerAttribute), true) as ObjectDrawerAttribute[])).Length > 0 && (objectDrawer = ObjectDrawerUtility.GetObjectDrawer(task, array2[0])) != null)
         {
             objectDrawer.Value = sharedVariable;
             objectDrawer.OnGUI(guiContent);
         }
         else
         {
             FieldInspector.DrawFields(task, sharedVariable, guiContent);
         }
         if (!TaskUtility.HasAttribute(fieldInfo, typeof(RequiredFieldAttribute)) && !TaskUtility.HasAttribute(fieldInfo, typeof(SharedRequiredAttribute)))
         {
             sharedVariable = FieldInspector.DrawSharedVariableToggleSharedButton(sharedVariable);
         }
         GUILayout.EndHorizontal();
     }
     return(sharedVariable);
 }
Example #26
0
        /// <summary>
        /// Constructs an LDA model
        /// </summary>
        /// <param name="numBatches">Number of batches</param>
        /// <param name="sizeVocab">Size of vocabulary</param>
        /// <param name="numTopics">Number of topics</param>
        public LDAShared(int numBatches, int sizeVocab, int numTopics)
        {
            SizeVocab         = sizeVocab;
            NumTopics         = numTopics;
            ThetaSparsity     = Sparsity.Dense;
            PhiSparsity       = Sparsity.ApproximateWithTolerance(1e-11); // Allow for round-off error
            NumDocuments      = Variable.New <int>().Named("NumDocuments");
            NumBatches        = numBatches;
            IterationsPerPass = new[] { 1, 3, 5, 7, 9 };

            //---------------------------------------------
            // The model
            //---------------------------------------------
            var D = new Range(NumDocuments).Named("D");
            var W = new Range(SizeVocab).Named("W");
            var T = new Range(NumTopics).Named("T");

            NumWordsInDoc = Variable.Array <int>(D).Named("NumWordsInDoc");
            var WInD = new Range(NumWordsInDoc[D]).Named("WInD");

            Evidence = SharedVariable <bool> .Random(new Bernoulli(0.5)).Named("Evidence");

            Evidence.IsEvidenceVariable = true;

            Phi = SharedVariable <Vector> .Random(T, CreateUniformDirichletArray(numTopics, sizeVocab, PhiSparsity)).Named("Phi");

            // Phi definition sub-model - just one copy
            PhiDefModel = new Model(1).Named("PhiDefModel");

            IfBlock evidencePhiDefBlock = null;

            EvidencePhiDef      = Evidence.GetCopyFor(PhiDefModel).Named("EvidencePhiDef");
            evidencePhiDefBlock = Variable.If(EvidencePhiDef);
            PhiDef = Variable.Array <Vector>(T).Named("PhiDef");
            PhiDef.SetSparsity(PhiSparsity);
            PhiDef.SetValueRange(W);
            PhiPrior  = Variable.Array <Dirichlet>(T).Named("PhiPrior");
            PhiDef[T] = Variable <Vector> .Random(PhiPrior[T]);

            Phi.SetDefinitionTo(PhiDefModel, PhiDef);
            evidencePhiDefBlock.CloseBlock();

            // Document sub-model - many copies
            DocModel = new Model(numBatches).Named("DocModel");

            IfBlock evidenceDocBlock = null;

            EvidenceDoc      = Evidence.GetCopyFor(DocModel).Named("EvidenceDoc");
            evidenceDocBlock = Variable.If(EvidenceDoc);
            Theta            = Variable.Array <Vector>(D).Named("Theta");
            Theta.SetSparsity(ThetaSparsity);
            Theta.SetValueRange(T);
            ThetaPrior = Variable.Array <Dirichlet>(D).Named("ThetaPrior");
            Theta[D]   = Variable <Vector> .Random(ThetaPrior[D]);

            PhiDoc = Phi.GetCopyFor(DocModel);
            PhiDoc.AddAttribute(new MarginalPrototype(Dirichlet.Uniform(sizeVocab, PhiSparsity)));
            Words      = Variable.Array(Variable.Array <int>(WInD), D).Named("Words");
            WordCounts = Variable.Array(Variable.Array <double>(WInD), D).Named("WordCounts");
            using (Variable.ForEach(D))
            {
                using (Variable.ForEach(WInD))
                {
                    using (Variable.Repeat(WordCounts[D][WInD]))
                    {
                        var topic = Variable.Discrete(Theta[D]).Named("topic");
                        using (Variable.Switch(topic))
                        {
                            Words[D][WInD] = Variable.Discrete(PhiDoc[topic]);
                        }
                    }
                }
            }
            evidenceDocBlock.CloseBlock();

            // Initialization to break symmetry
            ThetaInit = Variable.New <IDistribution <Vector[]> >().Named("ThetaInit");
            Theta.InitialiseTo(ThetaInit);
            EnginePhiDef = new InferenceEngine(new VariationalMessagePassing());
            EnginePhiDef.Compiler.ShowWarnings = false;
            EnginePhiDef.ModelName             = "LDASharedPhiDef";

            Engine = new InferenceEngine(new VariationalMessagePassing())
            {
                OptimiseForVariables = new IVariable[] { Theta, PhiDoc, EvidenceDoc }
            };

            Engine.Compiler.ShowWarnings = false;
            Engine.ModelName             = "LDAShared";
            Engine.Compiler.ReturnCopies = false;
            Engine.Compiler.FreeMemory   = true;
        }
Example #27
0
        /// <summary>
        /// Creates and configures the shared variables specified in the provided XML document for the specified blackboard
        /// </summary>
        /// <param name="doc">XML document which contains shared variables initialization data</param>
        /// <param name="blackboard">Blackboard object in which the shared variables will be configured</param>
        private static void SetupSharedVariables(XmlDocument doc, Blackboard blackboard)
        {
            if ((doc == null) || (blackboard == null))
                throw new ArgumentNullException();
            if (blackboard.virtualModule == null)
                throw new Exception("Uninitialized blackboard");

            int i, j;
            ILogWriter log;
            XmlDocument tmpDoc;
            XmlNode node;
            XmlNodeList xmlVarList;
            XmlNodeList xmlWriterModuleList;
            SharedVariable shVar;
            List<string> writers;
            string shVarName;
            string shVarType;
            string shVarValue;
            bool shVarIsArray;
            int bracketPos;

            log = blackboard.log;
            tmpDoc = new XmlDocument();

            if (doc.GetElementsByTagName("sharedVariables").Count < 1)
            {
                log.WriteLine(1, "No shared variables was defined in XML file.");
                return;
            }
            tmpDoc.LoadXml(doc.GetElementsByTagName("sharedVariables")[0].OuterXml);

            #region Load of shared variables
            // Load of shared variables
            log.WriteLine(1, "Reading shared variables");
            xmlVarList = tmpDoc.GetElementsByTagName("var");
            for (i = 0; i < xmlVarList.Count; ++i)
            {
                #region Get variable Name
                node = xmlVarList[i];
                if ((node == null) || (node.Name != "var") || (node.Attributes["name"] == null))
                    continue;
                shVarName = node.Attributes["name"].InnerText;
                shVarType = (node.Attributes["type"] != null) ? node.Attributes["type"].InnerText : "var";
                if (String.IsNullOrEmpty(shVarType) || !SharedVariable.RxVarTypeValidator.IsMatch(shVarType))
                    shVarType = "var";
                bracketPos = shVarType.IndexOf("[");
                if (shVarIsArray = (bracketPos != -1))
                    shVarType = shVarType.Remove(bracketPos);
                if (blackboard.VirtualModule.SharedVariables.Contains(shVarName))
                {
                    log.WriteLine(2, "Error loading shared variable " + shVarName + ". Variable already exists.");
                    continue;
                }

                #endregion

                #region Get variable initial value
                shVarValue = "";
                if (node.Attributes["value"] != null)
                {
                    shVarValue = node.Attributes["value"].Value;
                }
                else if (node.Attributes["fromFile"] != null)
                {
                    shVarValue = node.Attributes["fromFile"].Value;
                    if (File.Exists(shVarValue))
                    {
                        try
                        {
                            shVarValue = File.ReadAllText(shVarValue);
                        }
                        catch
                        {
                            log.WriteLine(2, "Error loading variable content from file " + shVarValue + " for the shared variable " + shVarName + ". Variable was set to null");
                            shVarValue = "";
                        }
                    }
                }
                #endregion

                #region Get list of modules with write permission

                writers = new List<string>();
                tmpDoc = new XmlDocument();
                tmpDoc.LoadXml(node.OuterXml);
                xmlWriterModuleList = tmpDoc.GetElementsByTagName("writers");
                if (xmlWriterModuleList.Count == 1)
                {
                    writers.Add(blackboard.VirtualModule.Name);
                    tmpDoc = new XmlDocument();
                    tmpDoc.LoadXml(xmlWriterModuleList[0].OuterXml);
                    xmlWriterModuleList = tmpDoc.GetElementsByTagName("writer");
                    for (j = 0; j < xmlWriterModuleList.Count; ++j)
                    {
                        node = xmlWriterModuleList[j];
                        if (node.InnerText == "*")
                        {
                            writers.Clear();
                            writers.Add("*");
                            break;
                        }
                        if (!blackboard.modules.Contains(node.InnerText))
                            continue;
                        else
                            writers.Add(node.InnerText);
                        /*
                        if (!writers.Contains(node.InnerText))
                            writers.Add(node.InnerText);
                        */
                    }
                }
                else
                    writers.Add("*");

                #endregion

                #region Create and add the shared variable

                shVar = new SharedVariable(blackboard.VirtualModule, shVarType, shVarName, shVarIsArray, -1);
                //shVar.Data = shVarValue;
                shVar.WriteStringData(blackboard.VirtualModule, shVarType, -1, shVarValue);
                writers.Sort();
                shVar.AllowedWriters = writers;
                blackboard.VirtualModule.SharedVariables.Add(shVar);
                log.WriteLine(4, "Added shared variable " + shVarType +" "+ shVarName);

                #endregion
            }
            #endregion
        }
 /// <summary>
 /// Initializes a new instance of SharedVariableInspectorWrapper
 /// </summary>
 public SharedVariableInspectorWrapper(SharedVariable sharedVar)
 {
     if (sharedVar == null)
         throw new ArgumentNullException();
     this.sharedVar = sharedVar;
 }
 public IEnumerator Undo(SharedData share, SharedVariable variable)
 {
     share.view.TextWindowImage.gameObject.SetActive(prevActive);
     yield break;
 }
Example #30
0
    // Token: 0x06000105 RID: 261 RVA: 0x00009A58 File Offset: 0x00007C58
    public static void Load(TaskSerializationData taskData, BehaviorSource behaviorSource)
    {
        behaviorSource.EntryTask     = null;
        behaviorSource.RootTask      = null;
        behaviorSource.DetachedTasks = null;
        behaviorSource.Variables     = null;
        FieldSerializationData fieldSerializationData;

        if (taskData == null || (fieldSerializationData = taskData.fieldSerializationData).byteData == null || fieldSerializationData.byteData.Count == 0)
        {
            return;
        }
        fieldSerializationData.byteDataArray    = fieldSerializationData.byteData.ToArray();
        BinaryDeserializationDeprecated.taskIDs = null;
        if (taskData.variableStartIndex != null)
        {
            List <SharedVariable>    list       = new List <SharedVariable>();
            Dictionary <string, int> dictionary = ObjectPool.Get <Dictionary <string, int> >();
            for (int i = 0; i < taskData.variableStartIndex.Count; i++)
            {
                int num = taskData.variableStartIndex[i];
                int num2;
                if (i + 1 < taskData.variableStartIndex.Count)
                {
                    num2 = taskData.variableStartIndex[i + 1];
                }
                else if (taskData.startIndex != null && taskData.startIndex.Count > 0)
                {
                    num2 = taskData.startIndex[0];
                }
                else
                {
                    num2 = fieldSerializationData.startIndex.Count;
                }
                dictionary.Clear();
                for (int j = num; j < num2; j++)
                {
                    dictionary.Add(fieldSerializationData.typeName[j], fieldSerializationData.startIndex[j]);
                }
                SharedVariable sharedVariable = BinaryDeserializationDeprecated.BytesToSharedVariable(fieldSerializationData, dictionary, fieldSerializationData.byteDataArray, taskData.variableStartIndex[i], behaviorSource, false, string.Empty);
                if (sharedVariable != null)
                {
                    list.Add(sharedVariable);
                }
            }
            ObjectPool.Return <Dictionary <string, int> >(dictionary);
            behaviorSource.Variables = list;
        }
        List <Task> list2 = new List <Task>();

        if (taskData.types != null)
        {
            for (int k = 0; k < taskData.types.Count; k++)
            {
                BinaryDeserializationDeprecated.LoadTask(taskData, fieldSerializationData, ref list2, ref behaviorSource);
            }
        }
        if (taskData.parentIndex.Count != list2.Count)
        {
            Debug.LogError("Deserialization Error: parent index count does not match task list count");
            return;
        }
        for (int l = 0; l < taskData.parentIndex.Count; l++)
        {
            if (taskData.parentIndex[l] == -1)
            {
                if (behaviorSource.EntryTask == null)
                {
                    behaviorSource.EntryTask = list2[l];
                }
                else
                {
                    if (behaviorSource.DetachedTasks == null)
                    {
                        behaviorSource.DetachedTasks = new List <Task>();
                    }
                    behaviorSource.DetachedTasks.Add(list2[l]);
                }
            }
            else if (taskData.parentIndex[l] == 0)
            {
                behaviorSource.RootTask = list2[l];
            }
            else if (taskData.parentIndex[l] != -1)
            {
                ParentTask parentTask = list2[taskData.parentIndex[l]] as ParentTask;
                if (parentTask != null)
                {
                    int index = (parentTask.Children != null) ? parentTask.Children.Count : 0;
                    parentTask.AddChild(list2[l], index);
                }
            }
        }
        if (BinaryDeserializationDeprecated.taskIDs != null)
        {
            foreach (BinaryDeserializationDeprecated.ObjectFieldMap objectFieldMap in BinaryDeserializationDeprecated.taskIDs.Keys)
            {
                List <int> list3     = BinaryDeserializationDeprecated.taskIDs[objectFieldMap];
                Type       fieldType = objectFieldMap.fieldInfo.FieldType;
                if (typeof(IList).IsAssignableFrom(fieldType))
                {
                    if (fieldType.IsArray)
                    {
                        Type  elementType = fieldType.GetElementType();
                        Array array       = Array.CreateInstance(elementType, list3.Count);
                        for (int m = 0; m < array.Length; m++)
                        {
                            array.SetValue(list2[list3[m]], m);
                        }
                        objectFieldMap.fieldInfo.SetValue(objectFieldMap.obj, array);
                    }
                    else
                    {
                        Type  type  = fieldType.GetGenericArguments()[0];
                        IList list4 = TaskUtility.CreateInstance(typeof(List <>).MakeGenericType(new Type[]
                        {
                            type
                        })) as IList;
                        for (int n = 0; n < list3.Count; n++)
                        {
                            list4.Add(list2[list3[n]]);
                        }
                        objectFieldMap.fieldInfo.SetValue(objectFieldMap.obj, list4);
                    }
                }
                else
                {
                    objectFieldMap.fieldInfo.SetValue(objectFieldMap.obj, list2[list3[0]]);
                }
            }
        }
    }
 public IEnumerator Do(SharedData share, SharedVariable variable)
 {
     share.view.NameText.text = "";
     yield break;
 }
Example #32
0
 private int getVariablesOfType(SharedVariable thisVariable, SkillData _data, out string[] names)
 {
     int result = 0;
         int num = 1;
         List<string> list = new List<string>();
         list.Add("None");
         if (_data.Variables != null)
         {
             foreach (var item in _data.Variables.Values)
             {
                 if (item.GetType().Equals(thisVariable.GetType()))
                 {
                     list.Add(item.name);
                     if (item.name.Equals(thisVariable.name))
                     {
                         result = num;
                     }
                     num++;
                 }
             }
         }
         names = list.ToArray();
         return result;
 }
 public IEnumerator Event(SharedData share, SharedVariable variable, EventData e)
 {
     yield break;
 }
Example #34
0
 protected void OnSharedVariableUpdated(SharedVariable sharedVariable)
 {
     if (this.SharedVariableUpdated != null)
         this.SharedVariableUpdated(sharedVariable);
 }
Example #35
0
        public ManipulatorManager(string leftPortName, string rightPortName)
        {
            this.status = new ArmControlStatus();

            if (leftPortName == "disable")
            {
                this.status.LeftArmEnable = false;
            }

            if (rightPortName == "disable")
            {
                this.status.RightArmEnabled = false;
            }

            if (string.IsNullOrEmpty(leftPortName))
            {
                leftPortName = "COM5";
            }
            if (string.IsNullOrEmpty(rightPortName))
            {
                rightPortName = "COM9";
            }

            this.leftArmSerialPort  = new SerialPort(leftPortName, 57600, Parity.None, 8, StopBits.One);
            this.rightArmSerialPort = new SerialPort(rightPortName, 57600, Parity.None, 8, StopBits.One);

            this.status.LeftComPort  = leftPortName;
            this.status.RightComPort = rightPortName;

            this.leftArm  = new Manipulator(this.leftArmSerialPort, ArmType.LeftArm);
            this.rightArm = new Manipulator(this.rightArmSerialPort, ArmType.RightArm);
            this.leftArm.ArmPositionChanged  += new ArmPositionChangedEH(leftArm_ArmPositionChanged);
            this.rightArm.ArmPositionChanged += new ArmPositionChangedEH(rightArm_ArmPositionChanged);

            this.laEndEffectorType = TypeOfEndEffector.gripper;
            this.raEndEffectorType = TypeOfEndEffector.hand;

            this.mapObstacles    = new SortedList <string, MapObstacle>();
            this.mapNodes        = new SortedList <string, MapNode>();
            this.leftPredefPos   = new SortedList <string, PredefPosition>();
            this.leftPredefMovs  = new SortedList <string, PredefMovement>();
            this.rightPredefPos  = new SortedList <string, PredefPosition>();
            this.rightPredefMovs = new SortedList <string, PredefMovement>();
            this.optLeftPath     = new MapOptimalPath();
            this.optRightPath    = new MapOptimalPath();
            this.leftGoal        = new MapGoalPoint();
            this.rightGoal       = new MapGoalPoint();

            this.lowBat = new SharedVariable <bool>("bat_alert");
            this.sharedVarLeftArmPos      = new DoubleArraySharedVariable("leftArmPos");
            this.sharedVarRightArmPos     = new DoubleArraySharedVariable("rightArmPos");
            this.sharedVarEndEffectorType = new StringSharedVariable("endEffectorType");

            this.cmdMan = new CommandManager();
            this.cnnMan = new ConnectionManager("ARMS", 2080, this.cmdMan);
            this.cnnMan.ClientConnected    += new System.Net.Sockets.TcpClientConnectedEventHandler(cnnMan_ClientConnected);
            this.cnnMan.ClientDisconnected += new System.Net.Sockets.TcpClientDisconnectedEventHandler(cnnMan_ClientDisconnected);

            this.status.Running    = true;
            this.checkSystemThread = new Thread(new ThreadStart(this.CheckSystemThreadTask));
            this.checkSystemThread.IsBackground = true;
            this.checkSystemThread.Start();
        }
Example #36
0
 private bool isValid(SharedVariable sv) {
     return null != sv && !sv.IsNone;
 }
Example #37
0
 private void TraceVariable(SharedVariable sv)
 {
     string s = String.Format("[Tracer] {0}{1} {2} = {3}",
         sv.Type, sv.IsArray ? "[]" : String.Empty,
         sv.Name,
         sv.ReadStringData());
     this.consoleManager.Report(s);
 }
Example #38
0
        static private ClickModelMarginals Model2(int numLabels, bool allowNoExams)
        {
            // Inference engine must be EP because of the ConstrainBetween constraint
            InferenceEngine engine = new InferenceEngine();

            if (!(engine.Algorithm is Algorithms.ExpectationPropagation))
            {
                Console.WriteLine("This example only runs with Expectation Propagation");
                return(null);
            }

            engine.NumberOfIterations = 10;

            // Includes lower and upper bounds
            int numThresholds = numLabels + 1;

            // Partition the dat into chunks to improve the schedule
            int chunkSize = 200;

            // Maximum number of passes through the data
            int maxPasses = 5;

            // The marginals at any given stage.
            ClickModelMarginals marginals = new ClickModelMarginals(numLabels);

            // Compare the marginals with the previous marginals to create
            // a convergence criterion
            Gaussian prevMargScoreMean;
            Gamma    prevMargJudgePrec;
            Gamma    prevMargClickPrec;
            double   convergenceThresh = 0.01;

            // Get the arrays of human judgement labels, clicks, and examinations
            int[]  labels;
            int[]  clicks;
            int[]  exams;
            string fileName = Path.Combine(
#if NETCORE
                Path.GetDirectoryName(typeof(ClickModel).Assembly.Location),     // work dir is not the one with Microsoft.ML.Probabilistic.Tests.dll on netcore and neither is .Location on netfull
#endif
                "TutorialData", "ClickModel.txt");

            if (!File.Exists(fileName))
            {
                fileName = Path.Combine(
#if NETCORE
                    Path.GetDirectoryName(typeof(ClickModel).Assembly.Location), // work dir is not the one with Microsoft.ML.Probabilistic.Tests.dll on netcore and neither is .Location on netfull
#endif
                    "..", "Samples", "C#", "ExamplesBrowser", "TutorialData", "ClickModel.txt");
            }

            LoadData(fileName, allowNoExams, out labels, out clicks, out exams);

            // Convert the raw click data into uncertain Gaussian observations chunk-by-chunk
            Gaussian[][][] allObs    = getClickObservations(numLabels, chunkSize, labels, clicks, exams);
            int            numChunks = allObs.Length;

            //-------------------------------------------------------------
            // Specify prior distributions
            //-------------------------------------------------------------
            Gaussian   priorScoreMean = Gaussian.FromMeanAndVariance(0.5, 1.0);
            Gamma      priorScorePrec = Gamma.FromMeanAndVariance(2.0, 0.0);
            Gamma      priorJudgePrec = Gamma.FromMeanAndVariance(2.0, 1.0);
            Gamma      priorClickPrec = Gamma.FromMeanAndVariance(2.0, 1.0);
            Gaussian[] priorThresholds;
            CreateThresholdPriors(numLabels, out priorThresholds);

            //-----------------------------------------------------
            // Create shared variables - these are the variables
            // which are shared between all chunks
            //-----------------------------------------------------
            Model model = new Model(numChunks);
            SharedVariable <double> scoreMean = SharedVariable <double> .Random(priorScoreMean).Named("scoreMean");

            SharedVariable <double> scorePrec = SharedVariable <double> .Random(priorScorePrec).Named("scorePrec");

            SharedVariable <double> judgePrec = SharedVariable <double> .Random(priorJudgePrec).Named("judgePrec");

            SharedVariable <double> clickPrec = SharedVariable <double> .Random(priorClickPrec).Named("clickPrec");

            SharedVariable <double>[] thresholds = new SharedVariable <double> [numThresholds];
            for (int t = 0; t < numThresholds; t++)
            {
                thresholds[t] = SharedVariable <double> .Random(priorThresholds[t]).Named("threshold" + t);
            }

            //----------------------------------------------------------------------------------
            // The model
            //----------------------------------------------------------------------------------

            // Gaussian click observations are given to the model - one set of observations
            // per label class. Also the number of observations per label class is given to the model
            VariableArray <Gaussian>[] observationDistribs  = new VariableArray <Gaussian> [numLabels];
            Variable <int>[]           numberOfObservations = new Variable <int> [numLabels];

            // For each label, and each observation (consisting of a human judgement and
            // a Gaussian click observation), there is a latent score variable, a judgement
            // score variable, and a click score variable
            for (int i = 0; i < numLabels; i++)
            {
                numberOfObservations[i] = Variable.New <int>().Named("NumObs" + i);
                Range r = new Range(numberOfObservations[i]).Named("N" + i);
                observationDistribs[i] = Variable.Array <Gaussian>(r).Named("Obs" + i);
                VariableArray <double> scores  = Variable.Array <double>(r).Named("Scores" + i);
                VariableArray <double> scoresJ = Variable.Array <double>(r).Named("ScoresJ" + i);
                VariableArray <double> scoresC = Variable.Array <double>(r).Named("ScoresC" + i);
                scores[r]  = Variable.GaussianFromMeanAndPrecision(scoreMean.GetCopyFor(model), scorePrec.GetCopyFor(model)).ForEach(r);
                scoresJ[r] = Variable.GaussianFromMeanAndPrecision(scores[r], judgePrec.GetCopyFor(model));
                scoresC[r] = Variable.GaussianFromMeanAndPrecision(scores[r], clickPrec.GetCopyFor(model));
                Variable.ConstrainEqualRandom(scoresC[r], observationDistribs[i][r]);
                Variable.ConstrainBetween(scoresJ[r], thresholds[i].GetCopyFor(model), thresholds[i + 1].GetCopyFor(model));
            }

            //----------------------------------------------------------
            // Outer loop iterates over a number of passes
            // Inner loop iterates over the unique labels
            //----------------------------------------------------------
            Console.WriteLine("Training: sample size: " + labels.Length + "\n");
            for (int pass = 0; pass < maxPasses; pass++)
            {
                prevMargScoreMean = marginals.marginalScoreMean;
                prevMargJudgePrec = marginals.marginalJudgePrec;
                prevMargClickPrec = marginals.marginalClickPrec;
                for (int c = 0; c < numChunks; c++)
                {
                    for (int i = 0; i < numLabels; i++)
                    {
                        numberOfObservations[i].ObservedValue = allObs[c][i].Length;
                        observationDistribs[i].ObservedValue  = allObs[c][i];
                    }

                    model.InferShared(engine, c);

                    // Retrieve marginals
                    marginals.marginalScoreMean = scoreMean.Marginal <Gaussian>();
                    marginals.marginalScorePrec = scorePrec.Marginal <Gamma>();
                    marginals.marginalJudgePrec = judgePrec.Marginal <Gamma>();
                    marginals.marginalClickPrec = clickPrec.Marginal <Gamma>();
                    for (int i = 0; i < numThresholds; i++)
                    {
                        marginals.marginalThresh[i] = thresholds[i].Marginal <Gaussian>();
                    }

                    Console.WriteLine("\n****** Pass {0}, chunk {1} ******", pass, c);
                    Console.WriteLine("----- Marginals -----");
                    Console.WriteLine("scoreMean = {0}", marginals.marginalScoreMean);
                    Console.WriteLine("scorePrec = {0}", marginals.marginalScorePrec);
                    Console.WriteLine("judgePrec = {0}", marginals.marginalJudgePrec);
                    Console.WriteLine("clickPrec = {0}", marginals.marginalClickPrec);
                    for (int t = 0; t < numThresholds; t++)
                    {
                        Console.WriteLine("threshMean {0} = {1}", t, marginals.marginalThresh[t]);
                    }
                }

                // Test for convergence
                if (marginals.marginalScoreMean.MaxDiff(prevMargScoreMean) < convergenceThresh &&
                    marginals.marginalJudgePrec.MaxDiff(prevMargJudgePrec) < convergenceThresh &&
                    marginals.marginalClickPrec.MaxDiff(prevMargClickPrec) < convergenceThresh)
                {
                    Console.WriteLine("\n****** Inference converged ******\n");
                    break;
                }
            }

            return(marginals);
        }
Example #39
0
 private bool isValid(SharedVariable sv)
 {
     return(sv != null && !sv.get_IsNone());
 }
Example #40
0
		static private ClickModelMarginals Model2(int numLabels, bool allowNoExams)
		{
			// Inference engine must be EP because of the ConstrainBetween constraint
			InferenceEngine engine = new InferenceEngine();
			if (!(engine.Algorithm is ExpectationPropagation))
			{
				Console.WriteLine("This example only runs with Expectation Propagation");
				return null;
			}
			engine.NumberOfIterations = 10;

			// Includes lower and upper bounds
			int numThresholds = numLabels + 1;
			// Partition the dat into chunks to improve the schedule
			int chunkSize = 200;
			// Maximum number of passes through the data
			int maxPasses = 5;
			// The marginals at any given stage.
			ClickModelMarginals marginals = new ClickModelMarginals(numLabels);
			// Compare the marginals with the previous marginals to create
			// a convergence criterion
			Gaussian prevMargScoreMean;
			Gamma prevMargJudgePrec;
			Gamma prevMargClickPrec;
			double convergenceThresh = 0.01;

			// Get the arrays of human judgement labels, clicks, and examinations
			int[] labels;
			int[] clicks;
			int[] exams;
			string fileName = @"data\ClickModel.txt";
			if (!File.Exists(fileName))
				fileName = @"..\Samples\C#\ExamplesBrowser\data\ClickModel.txt";
			LoadData(fileName, allowNoExams, out labels, out clicks, out exams);
			// Convert the raw click data into uncertain Gaussian observations chunk-by-chunk
			Gaussian[][][] allObs = getClickObservations(numLabels, chunkSize, labels, clicks, exams);
			int numChunks = allObs.Length;

			//-------------------------------------------------------------
			// Specify prior distributions
			//-------------------------------------------------------------
			Gaussian priorScoreMean = Gaussian.FromMeanAndVariance(0.5, 1.0);
			Gamma priorScorePrec = Gamma.FromMeanAndVariance(2.0, 0.0);
			Gamma priorJudgePrec = Gamma.FromMeanAndVariance(2.0, 1.0);
			Gamma priorClickPrec = Gamma.FromMeanAndVariance(2.0, 1.0);
			Gaussian[] priorThresholds;
			CreateThresholdPriors(numLabels, out priorThresholds);
			//-----------------------------------------------------
			// Create shared variables - these are the variables
			// which are shared between all chunks
			//-----------------------------------------------------
			Model model = new Model(numChunks);
			SharedVariable<double> scoreMean = SharedVariable<double>.Random(priorScoreMean).Named("scoreMean");
			SharedVariable<double> scorePrec = SharedVariable<double>.Random(priorScorePrec).Named("scorePrec");
			SharedVariable<double> judgePrec = SharedVariable<double>.Random(priorJudgePrec).Named("judgePrec");
			SharedVariable<double> clickPrec = SharedVariable<double>.Random(priorClickPrec).Named("clickPrec");
			SharedVariable<double>[] thresholds = new SharedVariable<double>[numThresholds];
			for (int t = 0; t < numThresholds; t++) {
				thresholds[t] = SharedVariable<double>.Random(priorThresholds[t]).Named("threshold" + t);
			}

			//----------------------------------------------------------------------------------
			// The model
			//----------------------------------------------------------------------------------

			// Gaussian click observations are given to the model - one set of observations
			// per label class. Also the number of observations per label class is given to the model
			VariableArray<Gaussian>[] observationDistribs = new VariableArray<Gaussian>[numLabels];
			Variable<int>[] numberOfObservations = new Variable<int>[numLabels];
			// For each label, and each observation (consisting of a human judgement and
			// a Gaussian click observation), there is a latent score variable, a judgement
			// score variable, and a click score variable
			for (int i = 0; i < numLabels; i++) {
				numberOfObservations[i] = Variable.New<int>().Named("NumObs" + i);
				Range r = new Range(numberOfObservations[i]).Named("N" + i);
				observationDistribs[i] = Variable.Array<Gaussian>(r).Named("Obs" + i);
				VariableArray<double> scores = Variable.Array<double>(r).Named("Scores" + i);
				VariableArray<double> scoresJ = Variable.Array<double>(r).Named("ScoresJ" + i);
				VariableArray<double> scoresC = Variable.Array<double>(r).Named("ScoresC" + i);
				scores[r] = Variable.GaussianFromMeanAndPrecision(scoreMean.GetCopyFor(model), scorePrec.GetCopyFor(model)).ForEach(r);
				scoresJ[r] = Variable.GaussianFromMeanAndPrecision(scores[r], judgePrec.GetCopyFor(model));
				scoresC[r] = Variable.GaussianFromMeanAndPrecision(scores[r], clickPrec.GetCopyFor(model));
				Variable.ConstrainEqualRandom(scoresC[r], observationDistribs[i][r]);
				Variable.ConstrainBetween(scoresJ[r], thresholds[i].GetCopyFor(model), thresholds[i + 1].GetCopyFor(model));
			}

			//----------------------------------------------------------
			// Outer loop iterates over a number of passes
			// Inner loop iterates over the unique labels
			//----------------------------------------------------------
			Console.WriteLine("Training: sample size: " + labels.Length + "\n");
			for (int pass = 0; pass < maxPasses; pass++) {
				prevMargScoreMean = marginals.marginalScoreMean;
				prevMargJudgePrec = marginals.marginalJudgePrec;
				prevMargClickPrec = marginals.marginalClickPrec;
				for (int c = 0; c < numChunks; c++) {
					for (int i = 0; i < numLabels; i++) {
						numberOfObservations[i].ObservedValue = allObs[c][i].Length;
						observationDistribs[i].ObservedValue = allObs[c][i];
					}

					model.InferShared(engine,c);

					// Retrieve marginals
					marginals.marginalScoreMean = scoreMean.Marginal<Gaussian>();
					marginals.marginalScorePrec = scorePrec.Marginal<Gamma>();
					marginals.marginalJudgePrec = judgePrec.Marginal<Gamma>();
					marginals.marginalClickPrec = clickPrec.Marginal<Gamma>();
					for (int i = 0; i < numThresholds; i++)
						marginals.marginalThresh[i] = thresholds[i].Marginal<Gaussian>();

					Console.WriteLine("\n****** Pass {0}, chunk {1} ******", pass, c);
					Console.WriteLine("----- Marginals -----");
					Console.WriteLine("scoreMean = {0}", marginals.marginalScoreMean);
					Console.WriteLine("scorePrec = {0}", marginals.marginalScorePrec);
					Console.WriteLine("judgePrec = {0}", marginals.marginalJudgePrec);
					Console.WriteLine("clickPrec = {0}", marginals.marginalClickPrec);
					for (int t = 0; t < numThresholds; t++)
						Console.WriteLine("threshMean {0} = {1}", t, marginals.marginalThresh[t]);
				}
				// Test for convergence
				if (marginals.marginalScoreMean.MaxDiff(prevMargScoreMean) < convergenceThresh &&
						marginals.marginalJudgePrec.MaxDiff(prevMargJudgePrec) < convergenceThresh &&
						marginals.marginalClickPrec.MaxDiff(prevMargClickPrec) < convergenceThresh) {
					Console.WriteLine("\n****** Inference converged ******\n");
					break;
				}
			}
			return marginals;
		}
Example #41
0
 protected void OnSharedVariableAdded(SharedVariable sharedVariable)
 {
     if (this.SharedVariableAdded != null)
         this.SharedVariableAdded(this, sharedVariable);
 }
 public void GetShare()
 {
     SharedVariable sharedVariable = behaviorTree.GetVariable("shader");
 }
Example #43
0
 private void sv_Updated(SharedVariable sharedVariable)
 {
     OnSharedVariableUpdated(sharedVariable);
 }
Example #44
0
        public void LoadTask(Task task, Behavior owner, ref int id)
        {
            if (task == null)
            {
                return;
            }
            this.mTask       = task;
            this.mTask.Owner = owner;
            this.mTask.ID    = id++;
            this.mTask.NodeData.NodeDesigner = this;
            this.mTask.NodeData.InitWatchedFields(this.mTask);
            if (!this.mTask.NodeData.FriendlyName.Equals(string.Empty))
            {
                this.mTask.FriendlyName          = this.mTask.NodeData.FriendlyName;
                this.mTask.NodeData.FriendlyName = string.Empty;
            }
            this.LoadTaskIcon();
            this.Init();
            RequiredComponentAttribute[] array;
            if (this.mTask.Owner != null && (array = (this.mTask.GetType().GetCustomAttributes(typeof(RequiredComponentAttribute), true) as RequiredComponentAttribute[])).Length > 0)
            {
                Type componentType = array[0].ComponentType;
                if (typeof(Component).IsAssignableFrom(componentType) && this.mTask.Owner.gameObject.GetComponent(componentType) == null)
                {
                    this.mTask.Owner.gameObject.AddComponent(componentType);
                }
            }
            List <Type>  baseClasses = FieldInspector.GetBaseClasses(this.mTask.GetType());
            BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            for (int i = baseClasses.Count - 1; i > -1; i--)
            {
                FieldInfo[] fields = baseClasses[i].GetFields(bindingAttr);
                for (int j = 0; j < fields.Length; j++)
                {
                    if (typeof(SharedVariable).IsAssignableFrom(fields[j].FieldType) && !fields[j].FieldType.IsAbstract)
                    {
                        SharedVariable sharedVariable = fields[j].GetValue(this.mTask) as SharedVariable;
                        if (sharedVariable == null)
                        {
                            sharedVariable = (Activator.CreateInstance(fields[j].FieldType) as SharedVariable);
                        }
                        if (TaskUtility.HasAttribute(fields[j], typeof(RequiredFieldAttribute)) || TaskUtility.HasAttribute(fields[j], typeof(SharedRequiredAttribute)))
                        {
                            sharedVariable.IsShared = true;
                        }
                        fields[j].SetValue(this.mTask, sharedVariable);
                    }
                }
            }
            if (this.isParent)
            {
                ParentTask parentTask = this.mTask as ParentTask;
                if (parentTask.Children != null)
                {
                    for (int k = 0; k < parentTask.Children.Count; k++)
                    {
                        NodeDesigner nodeDesigner = ScriptableObject.CreateInstance <NodeDesigner>();
                        nodeDesigner.LoadTask(parentTask.Children[k], owner, ref id);
                        NodeConnection nodeConnection = ScriptableObject.CreateInstance <NodeConnection>();
                        nodeConnection.LoadConnection(this, NodeConnectionType.Fixed);
                        this.AddChildNode(nodeDesigner, nodeConnection, true, true, k);
                    }
                }
                this.mConnectionIsDirty = true;
            }
        }