/// <summary> /// Initialise an array with 'naturally' random integers. /// The array will contain sub-spans of sorted integers, in both ascending and descending order. /// </summary> /// <param name="arr">The array to initialise.</param> /// <param name="rng">Random number generator.</param> public static void InitNatural(int[] arr, IRandomSource rng) { // Init with an incrementing sequence. for (int i = 0; i < arr.Length; i++) { arr[i] = i; } // Reverse multiple random sub-ranges. int reverseCount = (int)(Math.Sqrt(arr.Length) * 2.0); int len = arr.Length; for (int i = 0; i < reverseCount; i++) { int idx = rng.Next(arr.Length); int idx2 = rng.Next(arr.Length); if (idx > idx2) { VariableUtils.Swap(ref idx, ref idx2); } if (i % 2 == 0) { Array.Reverse(arr, 0, idx + 1); Array.Reverse(arr, idx2, len - idx2); } else { Array.Reverse(arr, idx, idx2 - idx); } } }
private NeatGenome <T> CreateGenomeInner(NeatGenome <T> parent1, NeatGenome <T> parent2) { // Randomly select one parent as being the primary parent. if (_rng.NextBool()) { VariableUtils.Swap(ref parent1, ref parent2); } // Enumerate over the connection genes in both parents. foreach (var geneIndexPair in EnumerateParentGenes(parent1.ConnectionGenes, parent2.ConnectionGenes)) { // Create a connection gene based on the current position in both parents. ConnectionGene <T>?connGene = CreateConnectionGene( parent1.ConnectionGenes, parent2.ConnectionGenes, geneIndexPair.Item1, geneIndexPair.Item2, out bool isSecondaryGene); if (connGene.HasValue) { // Attempt to add the gene to the child genome we are building. _builder.TryAddGene(connGene.Value, isSecondaryGene); } } // Convert the genes to the structure required by NeatGenome. var connGenes = _builder.ToConnectionGenes(); // Create and return a new genome. return(_genomeBuilder.Create( _genomeIdSeq.Next(), _generationSeq.Peek, connGenes)); }
/// <summary> /// Initialise a span with 'naturally' ordered random integers. /// The initialised span will contain sub-spans of sorted integers, in both ascending and descending order. /// </summary> /// <param name="keys">The span to initialise.</param> /// <param name="rng">Random number generator.</param> public static void InitNatural(Span <int> keys, IRandomSource rng) { // Init with an incrementing sequence. for (int i = 0; i < keys.Length; i++) { keys[i] = i; } // Reverse multiple random sub-ranges. int reverseCount = (int)(Math.Sqrt(keys.Length) * 2.0); int len = keys.Length; for (int i = 0; i < reverseCount; i++) { int idx = rng.Next(keys.Length); int idx2 = rng.Next(keys.Length); if (idx > idx2) { VariableUtils.Swap(ref idx, ref idx2); } if (rng.NextBool()) { keys[0..idx].Reverse();
public void VariableUtils_TryParseVariables_InputValueIsNullOrEmpty_NoErrors() { //------------Setup for test-------------------------- var util = new VariableUtils(); //------------Execute Test--------------------------- var error = util.TryParseVariables(null, out string outputValue, () => { }); //------------Assert Results------------------------- Assert.IsNull(error); }
public void VariableUtils_TryParseVariables_InputValueIsInvalidExpression_HasErrors() { //------------Setup for test-------------------------- var util = new VariableUtils(); //------------Execute Test--------------------------- var error = util.TryParseVariables("a]]", out string outputValue, () => { }); //------------Assert Results------------------------- Assert.IsNotNull(error); Assert.AreEqual("Result - Invalid expression: opening and closing brackets don't match", error.Message); }
public void VariableUtils_TryParseVariables_InputValueIsValidExpressionAndNoInputs_UsesVariableValueAndHasNoErrors() { //------------Setup for test-------------------------- var variableValue = "xxx"; var util = new VariableUtils(); //------------Execute Test--------------------------- var error = util.TryParseVariables("[[a]]", out string outputValue, () => { }, variableValue: variableValue); //------------Assert Results------------------------- Assert.IsNull(error); Assert.AreEqual(variableValue, outputValue); }
public void VariableUtils_TryParseVariables_InputValueIsValidExpressionAndHasInputs_UsesInputsValueAndHasNoErrors() { //------------Setup for test-------------------------- var variableValue = "xxx"; var inputs = new ObservableCollection <ObservablePair <string, string> >(); inputs.Add(new ObservablePair <string, string>("[[a]]", variableValue)); var util = new VariableUtils(); //------------Execute Test--------------------------- var error = util.TryParseVariables("[[a]]", out string outputValue, () => { }, "a", null, inputs); //------------Assert Results------------------------- Assert.IsNull(error); Assert.AreEqual(variableValue, outputValue); }
/// <summary> /// 移除不存在的路径按钮 /// </summary> private void removeNotExist_Click(object sender, System.EventArgs e) { operateAllButtons(false); new Thread(() => { if (VariableUtils.SavePath(PathValuesUtils.RemoveNotExistPathInPathValues())) { MessageBox.Show("操作成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("操作失败!请退出程序后重新右键-以管理员身份运行此程序再试!", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } operateAllButtons(true); }).Start(); }
protected virtual string ValidatePath(string label, string path, Action onError, bool pathIsRequired) { if (!pathIsRequired && string.IsNullOrWhiteSpace(path)) { return(string.Empty); } var errors = new List <IActionableErrorInfo>(); var fileActivityRuleSet = new RuleSet(); var variableUtils = new VariableUtils(); var isValidExpressionRule = new IsValidExpressionRule(() => path, DataListSingleton.ActiveDataList.Resource.DataList, variableUtils); fileActivityRuleSet.Add(isValidExpressionRule); errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError)); variableUtils.TryParseVariables(path, out string pathValue, onError, variableValue: ValidUriSchemes[0] + "://temp"); if (errors.Count == 0) { var isStringEmptyOrWhiteSpaceRuleUserName = new IsStringEmptyOrWhiteSpaceRule(() => path) { LabelText = label, DoError = onError }; var isValidFileNameRule = new IsValidFileNameRule(() => path) { LabelText = label, DoError = onError }; fileActivityRuleSet.Add(isStringEmptyOrWhiteSpaceRuleUserName); fileActivityRuleSet.Add(isValidExpressionRule); errors.AddRange(fileActivityRuleSet.ValidateRules(label, onError)); } UpdateErrors(errors); return(pathValue); }
/// <summary> /// 加入路径至Path环境变量-确认按钮 /// </summary> private void otherOK_Click(object sender, EventArgs e) { if (StringUtils.IsEmpty(otherSetValue.Text)) { MessageBox.Show("请先指定待添加路径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (otherSetValue.Text.Contains("\"")) { MessageBox.Show("添加的路径中不能包含英文双引号(\")!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } otherOK.Enabled = false; otherSettingTip.Visible = true; new Thread(() => { VariableUtils.AddValueToPath(otherSetValue.Text, isAppend.Checked); otherSettingTip.Visible = false; otherOK.Enabled = true; }).Start(); }
public void IterationSetup_NaturallyOrderedKeys() { // Init with an incrementing sequence. for (int i = 0; i < _keys.Length; i++) { _keys[i] = i; } // Reverse multiple random sub-ranges. int reverseCount = (int)(Math.Sqrt(_keys.Length) * 2.0); int len = _keys.Length; for (int i = 0; i < reverseCount; i++) { int idx = _rng.Next(len); int idx2 = _rng.Next(len); if (idx > idx2) { VariableUtils.Swap(ref idx, ref idx2); } if (_rng.NextBool()) { Array.Reverse(_keys, 0, idx + 1); Array.Reverse(_keys, idx2, len - idx2); } else { Array.Reverse(_keys, idx, idx2 - idx); } } // Init value arrays (just copy key value into these). for (int i = 0; i < _keys.Length; i++) { _values[i] = _keys[i]; _values2[i] = _keys[i]; } }
/// <summary> /// 保存按钮 /// </summary> private void save_Click(object sender, EventArgs e) { List <string> totalPathValue = new List <string>(); foreach (string value in pathContentValue.Items) { totalPathValue.Add(value); } applyTip.Visible = true; save.Enabled = false; cancel.Enabled = false; new Thread(() => { if (VariableUtils.SavePath(totalPathValue.ToArray())) { MessageBox.Show("修改完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("修改失败!请关闭程序然后右键-以管理员身份运行此程序重试!也可能是Path变量总长度超出限制!", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } Close(); }).Start(); }
private void CreateSpeciesOffspringSexual( Species <T>[] speciesArr, Species <T> species, DiscreteDistribution speciesDistUpdated, DiscreteDistribution[] genomeDistArr, DiscreteDistribution genomeDist, int offspringCount, List <NeatGenome <T> > offspringList, double interspeciesMatingProportion, IRandomSource rng) { // Calc the number of offspring to create via inter-species sexual reproduction. int offspringCountSexualInter; if (interspeciesMatingProportion == 0.0) { offspringCountSexualInter = 0; } else { offspringCountSexualInter = (int)NumericsUtils.ProbabilisticRound(interspeciesMatingProportion * offspringCount, rng); } // Calc the number of offspring to create via intra-species sexual reproduction. int offspringCountSexualIntra = offspringCount - offspringCountSexualInter; // Get genome list for the current species. var genomeList = species.GenomeList; // Produce the required number of offspring from inter-species sexual reproduction. for (int i = 0; i < offspringCountSexualInter; i++) { // Select/sample parent A from the current species. int genomeIdx = DiscreteDistribution.Sample(rng, genomeDist); var parentGenomeA = genomeList[genomeIdx]; // Select another species to select parent B from. int speciesIdx = DiscreteDistribution.Sample(rng, speciesDistUpdated); Species <T> speciesB = speciesArr[speciesIdx]; // Select parent B from species B. DiscreteDistribution genomeDistB = genomeDistArr[speciesIdx]; genomeIdx = DiscreteDistribution.Sample(rng, genomeDistB); var parentGenomeB = speciesB.GenomeList[genomeIdx]; // Ensure parentA is the fittest of the two parents. if (_fitnessComparer.Compare(parentGenomeA.FitnessInfo, parentGenomeB.FitnessInfo) < 0) { VariableUtils.Swap(ref parentGenomeA, ref parentGenomeB); } // Create a child genome and add it to offspringList. var childGenome = _reproductionSexual.CreateGenome(parentGenomeA, parentGenomeB, rng); offspringList.Add(childGenome); } // Produce the required number of offspring from intra-species sexual reproduction. for (int i = 0; i < offspringCountSexualIntra; i++) { // Select/sample parent A from the species. int genomeIdx = DiscreteDistribution.Sample(rng, genomeDist); var parentGenomeA = genomeList[genomeIdx]; // Create a new distribution with parent A removed from the set of possibilities. DiscreteDistribution genomeDistUpdated = genomeDist.RemoveOutcome(genomeIdx); // Select/sample parent B from the species. genomeIdx = DiscreteDistribution.Sample(rng, genomeDistUpdated); var parentGenomeB = genomeList[genomeIdx]; // Create a child genome and add it to offspringList. var childGenome = _reproductionSexual.CreateGenome(parentGenomeA, parentGenomeB, rng); offspringList.Add(childGenome); } }
static void OnCopyVariable(DashVariables p_variables, string p_name) { VariableUtils.CopyVariable(p_variables.GetVariable(p_name)); }
protected void DrawVariablesGUI(Vector2 p_position, bool p_global, Color p_color, DashVariables p_variables, ref bool p_minimized, GameObject p_boundObject) { Rect rect = new Rect(p_position.x, p_position.y, 380, p_minimized ? 32 : 200); DrawBoxGUI(rect, p_global ? "Global Variables" : "Graph Variables", TextAnchor.UpperCenter, p_color); var minStyle = new GUIStyle(); minStyle.normal.textColor = Color.white; minStyle.fontStyle = FontStyle.Bold; minStyle.fontSize = 20; if (GUI.Button(new Rect(rect.x + rect.width - 20 + (p_minimized ? 0 : 2), rect.y + 2, 20, 20), p_minimized ? "+" : "-", minStyle)) { p_minimized = !p_minimized; GUI.FocusControl(""); } if (p_minimized) { return; } if (p_global && PrefabUtility.GetPrefabInstanceStatus(p_boundObject) != PrefabInstanceStatus.NotAPrefab) { var style = new GUIStyle(); style.alignment = TextAnchor.MiddleCenter; style.normal.textColor = Color.white; style.fontSize = 20; style.wordWrap = true; EditorGUI.TextArea(new Rect(rect.x + 5, rect.y + 30, rect.width - 10, rect.height - 30), "Global variables on prefab instances are not supported!", style); return; } GUILayout.BeginArea(new Rect(rect.x + 5, rect.y + 30, rect.width - 10, rect.height - 79)); scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, false); EditorGUI.BeginChangeCheck(); if (p_variables != null) { int index = 0; foreach (var variable in p_variables) { GUIVariableUtils.VariableField(p_variables, variable.Name, p_boundObject, rect.width - 10); EditorGUILayout.Space(4); index++; } } GUILayout.EndScrollView(); GUILayout.EndArea(); if (GUI.Button(new Rect(rect.x + 4, rect.y + rect.height - 48, rect.width - 8, 20), "Add Variable")) { TypesMenu.Show((type) => OnAddVariable(p_variables, type)); } if (GUI.Button(new Rect(rect.x + 4, rect.y + rect.height - 24, rect.width / 2 - 6, 20), "Copy Variables")) { VariableUtils.CopyVariables(p_variables); } if (GUI.Button(new Rect(rect.x + rect.width / 2 + 2, rect.y + rect.height - 24, rect.width / 2 - 6, 20), "Paste Variables")) { VariableUtils.PasteVariables(p_variables, p_boundObject); } if (EditorGUI.EndChangeCheck()) { DashEditorCore.SetDirty(); } UseEvent(new Rect(rect.x, rect.y, rect.width, rect.height)); }