protected void lnk_Delete_Click(object sender, System.EventArgs e) { if (!base.IsAuthorizedOp(ActionType.Delete.ToString())) { base.ShowAjaxMsg(this.UpdatePanel1, "Không có thẩm quyền"); } else { int @int = WebUtils.GetInt((sender as LinkButton).CommandArgument); EvaluationInfo dataById = Evaluation.GetDataById(@int); if (dataById == null) { base.ShowAjaxMsg(this.UpdatePanel1, "Những thông tin này không được tìm thấy, các dữ liệu không tồn tại hoặc đã bị xóa"); } else if (Evaluation.Delete(@int)) { this.BindData(); PageBase.log.AddEvent(base.LoginAccount.AccountName, string.Concat(new string[] { "删除会员[", dataById.UserName, "]对商品[", dataById.ProName, "]的评价成功" })); base.ShowAjaxMsg(this.UpdatePanel1, "Thao tác thành công"); } else { base.ShowAjaxMsg(this.UpdatePanel1, "删除失败"); } } }
protected void btnok_Click(object sender, System.EventArgs e) { if (base.Action.Equals("Reply") && !base.IsAuthorizedOp("Reply")) { base.ShowMsg("Không có thẩm quyền"); } else { EvaluationInfo dataById = Evaluation.GetDataById(base.OpID); dataById.ReplyContent = base.Server.HtmlEncode(this.txtReply.Text); if (!string.IsNullOrEmpty(dataById.ReplyContent)) { dataById.Replier = base.AccountName; dataById.ReplyTime = System.DateTime.Now; } else { dataById.Replier = string.Empty; dataById.ReplyTime = new System.DateTime(1900, 1, 1); } if (Evaluation.Update(dataById)) { PageBase.log.AddEvent(base.LoginAccount.AccountName, "回复评论[" + this.eva.Content + "] thành công"); MessageUtils.DialogCloseAndParentReload(this); } else { base.ShowMsg("Thao tác thất bại"); } } }
public ModelInvokeResult <EvaluationInfoPK> Nullify(string strId) { ModelInvokeResult <EvaluationInfoPK> result = new ModelInvokeResult <EvaluationInfoPK> { Success = true }; try { List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>(); int _Id = Convert.ToInt32(strId); EvaluationInfo evaluationInfo = new EvaluationInfo { Id = _Id, Status = 0 }; /***********************begin 自定义代码*******************/ evaluationInfo.OperatedBy = NormalSession.UserId.ToGuid(); evaluationInfo.OperatedOn = DateTime.Now; /***********************end 自定义代码*********************/ statements.Add(new IBatisNetBatchStatement { StatementName = evaluationInfo.GetUpdateMethodName(), ParameterObject = evaluationInfo.ToStringObjectDictionary(false), Type = SqlExecuteType.UPDATE }); /***********************begin 自定义代码*******************/ /***********************此处添加自定义代码*****************/ /***********************end 自定义代码*********************/ BuilderFactory.DefaultBulder(GetHttpHeader("ConnectId")).ExecuteNativeSqlNoneQuery(statements); result.instance = new EvaluationInfoPK { Id = _Id }; } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
public override void Evaluate(ComputationContext ctx) { if (this.Evaluation == null) { this.Evaluation = EvaluationInfo.Create(ctx.Env.BoolType.InstanceOf.Build(Lifetime.Create(this))); } }
public override void Evaluate(ComputationContext ctx) { // in theory we would like to write legal code like // (*local_int_ptr) = 1 // but the problem is dereference can be seen as omitting setter (property or special functions) logic // so for now we disable it, and see when for the first time it will be needed in practice // note: swap function does not count since we already have parallel assignments // // and one more small thing, without dereference there is no ambiguity here // ref = value // does it mean (*ref) = value or ref = &value if (!ctx.Env.Options.AllowDereference) { throw new InvalidOperationException(); } if (this.Evaluation == null) { if (!ctx.Env.Dereferenced(Expr.Evaluation.Components, out IEntityInstance inner_comp)) { ctx.AddError(ErrorCode.DereferencingValue, this.Expr); } ctx.Env.Dereferenced(Expr.Evaluation.Aggregate, out IEntityInstance inner_aggr); this.typename = inner_comp.NameOf; this.typename.AttachTo(this); this.typename.Evaluated(ctx, EvaluationCall.AdHocCrossJump); this.Evaluation = EvaluationInfo.Create(inner_comp, inner_aggr.Cast <EntityInstance>()); } }
public override void Evaluate(ComputationContext ctx) { if (this.Evaluation == null) { this.Evaluation = EvaluationInfo.Create(ctx.Env.BoolType.InstanceOf); this.DataTransfer(ctx, ref this.lhs, ctx.Env.BoolType.InstanceOf); this.DataTransfer(ctx, ref this.rhs, ctx.Env.BoolType.InstanceOf); } }
public ActionResult Index() { if (userType != "s") { return(PartialView("NoPermission")); } EvaluationInfo model = services.GetData(userId, stuBJID, currentYearTerm); return(View(model)); }
public static int Add(EvaluationInfo entity) { int result; if (entity == null) { result = 0; } else { result = BizBase.dbo.InsertModel <EvaluationInfo>(entity); } return(result); }
protected override void EvaluateNovelty(TuringController controller, ref EvaluationInfo evaluation) { Reset(); double[] enviromentOutput = Environment.InitialObservation; // Environment loop while (!Environment.IsTerminated) { // Activate the controller with the environment output. // The turing controller will handle the turing machine I/O double[] environmentInput = controller.ActivateNeuralNetwork(enviromentOutput); // Activate the environment with the output from the controller (NN) enviromentOutput = Environment.PerformAction(environmentInput); } evaluation.NoveltyVectors = NoveltySearchInfo.NoveltyVectors; evaluation.MinimumCriteria = NoveltySearchInfo.MinimumCriteria; }
private static void GeneralizeAllChamps() { string[] xmls = Directory.GetFiles(_currentDir, "champion_genome*.xml", SearchOption.AllDirectories); Console.WriteLine($"Found {xmls.Length} champion genomes"); int count = xmls.Length; int iterations = GetIntegerConsoleInput("Enter number of iterations:"); NextExperiment(); EvaluationInfo[] results = new EvaluationInfo[count]; for (int i = 0; i < count; i++) { results[i] = _experiment.TestSavedChampion(xmls[i], iterations, 1, true, true)[0]; } try { string genDataFile = $"{_currentDir}/{DATA_FILE_GEN}"; using (StreamWriter sw = File.AppendText(genDataFile)) { sw.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", "Genome", "Iterations", "Mean", "Standard Deviation", "Max", "Min"); for (int i = 0; i < count; i++) { EvaluationInfo res = results[i]; sw.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0},{1},{2:F4},{3:F4},{4:F4},{5:F4}", xmls[i], res.Iterations, res.ObjectiveFitnessMean, res.ObjectiveFitnessStandardDeviation, res.ObjectiveFitnessMax, res.ObjectiveFitnessMin)); } } } catch (Exception ex) { _logger.Warn($"Could not write to generalization file: {ex.Message}", ex); } Console.WriteLine("Done. Press any key to exit..."); Console.ReadKey(); }
public InvokeResult NullifySelected(string strIds) { InvokeResult result = new InvokeResult { Success = true }; try { List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>(); string[] arrIds = strIds.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (arrIds.Length == 0) { result.Success = false; result.ErrorCode = 59996; return(result); } string statementName = new EvaluationInfo().GetUpdateMethodName(); foreach (string strId in arrIds) { EvaluationInfo evaluationInfo = new EvaluationInfo { Id = Convert.ToInt32(strId), Status = 0 }; /***********************begin 自定义代码*******************/ evaluationInfo.OperatedBy = NormalSession.UserId.ToGuid(); evaluationInfo.OperatedOn = DateTime.Now; /***********************end 自定义代码*********************/ statements.Add(new IBatisNetBatchStatement { StatementName = statementName, ParameterObject = evaluationInfo.ToStringObjectDictionary(false), Type = SqlExecuteType.UPDATE }); } BuilderFactory.DefaultBulder(GetHttpHeader("ConnectId")).ExecuteNativeSqlNoneQuery(statements); } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
private static void ExperimentCompleteEvent(object sender, ExperimentCompleteEventArgs e) { string timeSpent = Utilities.TimeToString(e.TimeSpent); _logger.Info($"Time spent: {timeSpent}"); EvaluationInfo testedFitness = _experiment.TestCurrentChampion(100); EvaluationInfo testedGenFitness = _experiment.TestCurrentChampionGeneralization(100); string resultsFile = $"{e.Directory}{RESULTS_FILE}"; bool writeHeader = !File.Exists(resultsFile); try { using (StreamWriter sw = File.AppendText(resultsFile)) { if (writeHeader) { sw.WriteLine( "Experiment,Comment,Start Time,Time,Solved,Generations,Champion Fitness,Champion Complexity,Champion Hidden Nodes,Champion Birth Generation,Tested Fitness,Tested Generalization Fitness"); } sw.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0},\"{1}\",{9},{2},{3},{4},{5:F4},{6:F0},{7},{8},{10:F4},{11:F4}", e.Experiment, e.Comment, timeSpent, e.Solved, e.Generations, e.ChampFitness, e.ChampComplexity, e.ChampHiddenNodes, e.ChampBirthGen, _experimentStartedTime.ToString("ddMMyyyy-HHmmss"), testedFitness.ObjectiveFitnessMean, testedGenFitness.ObjectiveFitnessMean)); } } catch (Exception ex) { _logger.Warn($"Could not write to results file: {ex.Message}", ex); } NextExperiment(); }
public InvokeResult DeleteSelected(string strIds) { InvokeResult result = new InvokeResult { Success = true }; try { List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>(); string[] arrIds = strIds.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (arrIds.Length == 0) { result.Success = false; result.ErrorCode = 59996; return(result); } string statementName = new EvaluationInfo().GetDeleteMethodName(); foreach (string strId in arrIds) { EvaluationInfoPK pk = new EvaluationInfoPK { Id = Convert.ToInt32(strId) }; DeleteCascade(statements, pk); statements.Add(new IBatisNetBatchStatement { StatementName = statementName, ParameterObject = pk, Type = SqlExecuteType.DELETE }); } BuilderFactory.DefaultBulder(GetHttpHeader("ConnectId")).ExecuteNativeSqlNoneQuery(statements); } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.Message; } return(result); }
private void InitForModify() { this.eva = Evaluation.GetDataById(base.OpID); this.txtReply.Text = this.eva.ReplyContent; }
public static Mesh Evaluate(IBlackBox phenome, VoxelVolume volume, out EvaluationInfo evaluationInfo) { var processedOutput = new float[volume.width, volume.height, volume.length]; var cleanOutput = new float[volume.width, volume.height, volume.length]; var distanceToCenter = new float[volume.width, volume.height, volume.length]; var minOutputValue = 1f; var maxOutputValue = -1f; float r = 0, g = 0, b = 0; for (int x = 0; x < volume.width; x++) { for (int y = 0; y < volume.height; y++) { for (int z = 0; z < volume.length; z++) { AssingInput(phenome, volume, x, y, z); // activate phenome phenome.Activate(); // store output values ISignalArray outputArr = phenome.OutputSignalArray; processedOutput[x, y, z] = phenome.OutputSignalArray.Length >= 4 ? (float)outputArr[3] : (float)outputArr[0]; cleanOutput[x, y, z] = processedOutput[x, y, z]; if (phenome.OutputSignalArray.Length >= 4) { r += (float)outputArr[0]; g += (float)outputArr[1]; b += (float)outputArr[2]; } // store min and max output values if (processedOutput[x, y, z] < minOutputValue) minOutputValue = processedOutput[x, y, z]; if (processedOutput[x, y, z] > maxOutputValue) maxOutputValue = processedOutput[x, y, z]; // Clamps the final shape within a sphere //distanceToCenter[x, y, z] = DistanceFunctions.DistanceToCenter(x, y, z, volume); //if (DistanceFunctions.DistanceToCenter(x, y, z, volume) > -0.5f) //{ // cleanOutput[x, y, z] = -1; // processedOutput[x, y, z] = -1; //} // border should have negative values if (x == 0 || x == volume.width - 1 || y == 0 || y == volume.height - 1 || z == 0 || z == volume.length - 1) processedOutput[x, y, z] = -1f; } } } r /= volume.width*volume.width*volume.width; g /= volume.width*volume.width*volume.width; b /= volume.width*volume.width*volume.width; artefactColor = new Color((r + 1f) / 2f, (g + 1f) / 2f, (b + 1f) / 2f); //Debug.Log(artefactColor); //Debug.Log("Output in range [" + minOutputValue + ", " + maxOutputValue + "]"); // TODO: need to find a workaround for this. It results in cubes. In multiplayer we don't want to spawn cubes as seeds. // Either save network to disk, look and see what's wrong or maybe if this happens on the client it could request another regeneration. if (Mathf.Approximately(minOutputValue, maxOutputValue)) { //Debug.LogWarning("All output values are the same! Min equals max!"); } for (int index00 = 1; index00 < processedOutput.GetLength(0) - 1; index00++) for (int index01 = 1; index01 < processedOutput.GetLength(1) - 1; index01++) for (int index02 = 1; index02 < processedOutput.GetLength(2) - 1; index02++) { // if initially, border value at 0,0,0 was maxFill, we invert all values so minFill is on the border if (Mathf.Approximately(cleanOutput[0, 0, 0], maxOutputValue)) processedOutput[index00, index01, index02] = minOutputValue + (maxOutputValue - processedOutput[index00, index01, index02]); // based on a threshold ( middle value between min and max) we change the value to either 0 or 1. This give a blocky look instead of smooth details processedOutput[index00, index01, index02] = processedOutput[index00, index01, index02] < minOutputValue + (maxOutputValue - minOutputValue) / 2f ? 0f : 1f; } // fill evaluation info struct with data evaluationInfo = new EvaluationInfo(); evaluationInfo.cleanOutput = cleanOutput.Clone() as float[,,]; evaluationInfo.processedOutput = processedOutput.Clone() as float[,,]; evaluationInfo.distanceToCenter = distanceToCenter.Clone() as float[,,]; evaluationInfo.minOutputValue = minOutputValue; evaluationInfo.maxOutputValue = maxOutputValue; // Apply marching cubes on processed output and return Mesh Profiler.BeginSample("MarchingCubes"); var mesh = MarchingCubes.CreateMesh(processedOutput); Profiler.EndSample(); return mesh; }
protected override void EvaluateNovelty(DefaultController controller, ref EvaluationInfo evaluation) { throw new System.NotImplementedException(); }
protected override void EvaluateRecord(DefaultController controller, int iterations, ref EvaluationInfo evaluation) { Reset(); Recorder = new Recorder(); Recorder.Start(); Environment.RecordTimeSteps = true; Recorder.Record(Environment.InitialTimeStep); double[] envOutput = Environment.InitialObservation; while (!Environment.IsTerminated) { var envInput = Controller.ActivateNeuralNetwork(envOutput); envOutput = Environment.PerformAction(envInput); Recorder.Record(Environment.PreviousTimeStep); } evaluation.ObjectiveFitness = 600 - Environment.NormalizedScore; }
public override ResignHint ResignHint(GameState gamestate, bool has_moved) { int lost_with_single, lost_with_gammon, lost_with_backgammon; if (gamestate.GameType == GameType.Match) { int opp_score = gamestate.Score(1 - gamestate.PlayerOnTurn); lost_with_backgammon = Math.Min(gamestate.MatchTo, opp_score + gamestate.Cube.Value * 3); lost_with_gammon = Math.Min(gamestate.MatchTo, opp_score + gamestate.Cube.Value * 2); lost_with_single = Math.Min(gamestate.MatchTo, opp_score + gamestate.Cube.Value); } else { lost_with_backgammon = gamestate.Cube.Centered ? gamestate.Stake : Math.Min(gamestate.Limit, gamestate.Stake * gamestate.Cube.Value * 3); lost_with_gammon = gamestate.Cube.Centered ? gamestate.Stake : Math.Min(gamestate.Limit, gamestate.Stake * gamestate.Cube.Value * 2); lost_with_single = gamestate.Cube.Centered ? gamestate.Stake : Math.Min(gamestate.Limit, gamestate.Stake * gamestate.Cube.Value); } if (!has_moved) { // Dice not rolled yet EvaluationInfo eval_info = resign_gnubg.Eval(gamestate); /*Console.WriteLine(eval_info.Win); * Console.WriteLine(eval_info.WinGammon); * Console.WriteLine(eval_info.WinBackgammon); * Console.WriteLine(eval_info.LoseGammon); * Console.WriteLine(eval_info.LoseBackgammon); * Console.WriteLine(eval_info.Lose);*/ if (eval_info.LoseBackgammon > 0.995) { return(new ResignHint(ResignValue.Backgammon)); } if (eval_info.LoseGammon > 0.995 && (eval_info.LoseBackgammon <= 0.0000001)) // || (int)capped_loss >= 2)) { return(new ResignHint(ResignValue.Gammon)); } if (eval_info.Lose > 0.995 && ((eval_info.LoseGammon <= 0.0000001 && eval_info.LoseBackgammon <= 0.0000001))) // || (int)capped_loss >= 1)) { return(new ResignHint(ResignValue.Single)); } if (eval_info.Lose > 0.995 && lost_with_single == lost_with_gammon && lost_with_single == lost_with_backgammon && lost_with_gammon == lost_with_backgammon) { return(new ResignHint(ResignValue.Single)); } if (eval_info.Lose > 0.995 && lost_with_single == lost_with_gammon) { return(new ResignHint(ResignValue.Single)); } } else { // The optimal move has been made, change the turn to opp to see the effect of the move on eval int player_on_roll = gamestate.PlayerOnRoll; int player_on_turn = gamestate.PlayerOnTurn; int[] dice = new int[2]; Array.Copy(gamestate.Dice, dice, 2); gamestate.ChangeTurn(); EvaluationInfo eval_info = resign_gnubg.Eval(gamestate); /*Console.WriteLine(eval_info.Win); * Console.WriteLine(eval_info.WinGammon); * Console.WriteLine(eval_info.WinBackgammon); * Console.WriteLine(eval_info.LoseGammon); * Console.WriteLine(eval_info.LoseBackgammon); * Console.WriteLine(eval_info.Lose);*/ gamestate.SetDice(dice[0], dice[1]); gamestate.PlayerOnTurn = player_on_turn; gamestate.PlayerOnRoll = player_on_roll; if (eval_info.WinBackgammon > 0.995) { return(new ResignHint(ResignValue.Backgammon)); } if (eval_info.WinGammon > 0.995 && (eval_info.WinBackgammon <= 0.0000001)) // || (int)capped_loss >= 2)) { return(new ResignHint(ResignValue.Gammon)); } if (eval_info.Win > 0.995 && ((eval_info.WinGammon <= 0.0000001 && eval_info.WinBackgammon <= 0.0000001))) // || (int)capped_loss >= 1)) { return(new ResignHint(ResignValue.Single)); } if (eval_info.Win > 0.995 && lost_with_single == lost_with_gammon && lost_with_single == lost_with_backgammon && lost_with_gammon == lost_with_backgammon) { return(new ResignHint(ResignValue.Single)); } if (eval_info.Win > 0.995 && lost_with_single == lost_with_gammon) { return(new ResignHint(ResignValue.Single)); } } return(new ResignHint(ResignValue.None)); }
protected override void EvaluateObjective(DefaultController controller, int iterations, ref EvaluationInfo evaluation) { double totalScore = 0; double activationRangeAcc = 0.0; for (int i = 0; i < iterations; i++) { Reset(); double[] envOutput = Environment.InitialObservation; while (!Environment.IsTerminated) { var envInput = Controller.ActivateNeuralNetwork(envOutput); envOutput = Environment.PerformAction(envInput); } totalScore += Environment.NormalizedScore; } const double threshold = MeanLineSquareRootMeanSquareLength * VisualFieldLength; double rmsd = Math.Sqrt(totalScore / iterations); if (rmsd > threshold) { evaluation.ObjectiveFitness = 0.0; } else { evaluation.ObjectiveFitness = (threshold - rmsd) * 100.0 / threshold + activationRangeAcc / 7.5; } evaluation.ObjectiveFitness = 1 / (rmsd + 1); }
public void Register(IQueryElement expr, EvaluationInfo info) { _evaluationCache ??= new Dictionary <IQueryElement, EvaluationInfo>(Utils.ObjectReferenceEqualityComparer <IQueryElement> .Default); _evaluationCache.Add(expr, info); }
protected override void EvaluateRecord(TuringController controller, int iterations, ref EvaluationInfo evaluation) { // Iteration loop for (int i = 0; i < iterations; i++) { Reset(); // Only record first iteration, as subsequent ones will overwrite if (i == 0) { Recorder = new Recorder(); Recorder.Start(); controller.TuringMachine.RecordTimeSteps = true; Environment.RecordTimeSteps = true; Recorder.Record(Environment.InitialTimeStep, controller.TuringMachine.InitialTimeStep); } double[] enviromentOutput = Environment.InitialObservation; // Environment loop while (!Environment.IsTerminated) { double[] environmentInput = controller.ActivateNeuralNetwork(enviromentOutput); enviromentOutput = Environment.PerformAction(environmentInput); if (i == 0) { // Record the state of the environment and turing machine Recorder.Record(Environment.PreviousTimeStep, controller.TuringMachine.PreviousTimeStep); } } evaluation.ObjectiveFitnessIt[i] = Environment.NormalizedScore; if (i == 0) { // Record the final state of the turing machine tape Recorder.FinalTuringTape = Controller.TuringMachine.TapeValues; } } }
protected override void EvaluateObjective(DefaultController controller, int iterations, ref EvaluationInfo evaluation) { double totalScore = 0; for (int i = 0; i < iterations; i++) { Reset(); double[] environmnentOutput = Environment.InitialObservation; while (!Environment.IsTerminated) { var envInput = Controller.ActivateNeuralNetwork(environmnentOutput); environmnentOutput = Environment.PerformAction(envInput); } totalScore += Environment.NormalizedScore; } evaluation.ObjectiveFitness = totalScore / iterations; }
protected override void EvaluateObjective(TuringController controller, int iterations, ref EvaluationInfo evaluation) { Utility.Debug.DLogHeader("STARTING EVAULATION", true); double totalScore = 0; // Iteration loop for (int i = 0; i < iterations; i++) { Utility.Debug.DLogHeader($"EVALUATION ITERATION {i}", true); Reset(); double[] enviromentOutput = Environment.InitialObservation; // Environment loop while (!Environment.IsTerminated) { // Activate the controller with the environment output. // The turing controller will handle the turing machine I/O double[] environmentInput = controller.ActivateNeuralNetwork(enviromentOutput); // Activate the environment with the output from the controller (NN) enviromentOutput = Environment.PerformAction(environmentInput); } totalScore += Environment.NormalizedScore; Utility.Debug.DLog($"EVALUATION Total Score: {totalScore}, Iteration Score: {Environment.CurrentScore}", true); } // Calculate the total normalized score (0-1) evaluation.ObjectiveFitness = Math.Max(0d, totalScore / iterations); }
public void Evaluate(ComputationContext ctx) { if (this.Evaluation == null) { // trap only lambdas, name reference is a call, not passing function around // for example here trapping lambda into closure is necessary // ((x) => x*x)() // and here is not (regular call) // f() if (this.TrapLambdaClosure(ctx, ref this.callee)) { ConvertToExplicitInvoke(ctx); } { EntityInstance eval = this.Callee.Evaluation.Components.Cast <EntityInstance>(); this.Callee.DereferencedCount_LEGACY = ctx.Env.DereferencedOnce(eval, out IEntityInstance __eval, out bool via_pointer) ? 1 : 0; this.DereferencingCount = this.Callee.DereferencedCount_LEGACY; if (this.Callee.DereferencedCount_LEGACY > 0) { eval = __eval.Cast <EntityInstance>(); } if (!(this.Name.Binding.Match.Instance.Target is FunctionDefinition) && eval.Target.Cast <TypeDefinition>().InvokeFunctions().Any()) { // if we call a "closure", like my_closure() it is implicit calling "invoke" // so make it explicit on the fly ConvertToExplicitInvoke(ctx); } } IEnumerable <EntityInstance> matches = this.Name.Binding.Matches .Select(it => { if (it.Instance.Target.IsFunction()) { return(it.Instance); } else if (it.Instance.Target is Property prop) { return(prop.Getter?.InstanceOf?.TranslateThrough(it.Instance)); } else { return(null); } }) .Where(it => it != null); if (!matches.Any()) { this.resolution = new Option <CallResolution>(null); if (!this.Callee.Evaluation.Components.IsJoker) // do not cascade errors { ctx.AddError(ErrorCode.NotFunctionType, this.Callee); } } else { IEnumerable <CallResolution> targets = matches .Select(it => CallResolution.Create(ctx, this.Name.TemplateArguments, this, createCallContext(ctx, this.Name, it.TargetFunction), targetFunctionInstance: it)) .Where(it => it != null) .StoreReadOnly(); targets = targets.Where(it => it.RequiredParametersUsed()).StoreReadOnly(); targets = targets.Where(it => it.CorrectlyFormedArguments()).StoreReadOnly(); targets = targets.Where(it => it.ArgumentTypesMatchParameters(ctx)).StoreReadOnly(); if (this.RequestedOutcomeTypeName != null) { targets = targets.Where(it => it.OutcomeMatchesRequest(ctx)).StoreReadOnly(); } targets = resolveOverloading(targets).StoreReadOnly(); this.resolution = new Option <CallResolution>(targets.FirstOrDefault()); if (!targets.Any()) { ctx.AddError(ErrorCode.TargetFunctionNotFound, this); } else { if (targets.Count() > 1) { ctx.ErrorManager.AddError(ErrorCode.NOTEST_AmbiguousOverloadedCall, this, targets.Select(it => it.TargetFunctionInstance.Target)); } foreach (var group in this.Resolution.GetArgumentsMultipleTargeted()) { // we only report second "override" because if there are more // it is more likely user forgot to mark parameter variadic ctx.ErrorManager.AddError(ErrorCode.ArgumentForFunctionAlreadyGiven, group.Skip(1).FirstOrDefault()); } foreach (FunctionParameter param in this.Resolution.GetUnfulfilledVariadicParameters()) { ctx.ErrorManager.AddError(ErrorCode.InvalidNumberVariadicArguments, this, param); } if (targets.Count() == 1) { this.Resolution.EnhanceArguments(ctx); } this.Resolution.SetMappings(ctx); // filtering here is a bit shaky -- if we don't use type inference // we have to filter by what we bind to, but if we use inference // we use target instance (functor or function, not a variable) because only it // is altered by type inference if (this.Resolution.InferredTemplateArguments == null) { // leave only binding which was used for mapping this.Name.Binding.Filter(it => it.IsIdentical(this.Resolution.TargetFunctionInstance)); } else { NameReference this_name = this.Name; this_name.DetachFrom(this); this.callee = this_name.Recreate(this.Resolution.InferredTemplateArguments .Select(it => new TemplateArgument(it)), this.Resolution.TargetFunctionInstance, this_name.Binding.Match.IsLocal); this.callee.AttachTo(this); this.Callee.Evaluated(ctx, EvaluationCall.AdHocCrossJump); if (!this.Name.Binding.HasMatch) { throw new Exception("We've just lost our binding, probably something wrong with template translations"); } } this.Evaluation = this.Resolution.Evaluation; if (ctx.Env.IsReferenceOfType(this.Evaluation.Aggregate)) { // basically we are saying that the outcome of the function has the lifetime // equal to the shortest lifetime of arguments // or local if the function has not arguments at all Lifetime lifetime = null; foreach (FunctionArgument arg in this.Resolution.ActualArguments) { // todo: we should check if the expression is not passed implictly by reference if (arg == this.Resolution.MetaThisArgument || ctx.Env.IsReferenceOfType(arg.Evaluation.Aggregate)) { lifetime = arg.Evaluation.Aggregate.Lifetime.Shorter(lifetime); } } if (lifetime == null) { lifetime = Lifetime.Create(this); } if (this.Evaluation.Aggregate.Lifetime != lifetime) { this.Evaluation = EvaluationInfo.Create( this.Evaluation.Components.Rebuild(ctx, lifetime, deep: false), this.Evaluation.Aggregate.Build(lifetime)); } } } } if (this.Evaluation == null) { this.Evaluation = Environment.JokerEval; } foreach (IExpression arg in UserArguments) { arg.ValidateValueExpression(ctx); } } }
public static bool Update(EvaluationInfo entity) { return(entity != null && BizBase.dbo.UpdateModel <EvaluationInfo>(entity)); }
protected override void EvaluateObjective(TuringController controller, int iterations, ref EvaluationInfo evaluation) { Utility.Debug.DLogHeader("STARTING EVAULATION", true); double totalScore = 0; evaluation.TapeSizes = new int[iterations]; // Iteration loop for (int i = 0; i < iterations; i++) { Utility.Debug.DLogHeader($"EVALUATION ITERATION {i}", true); Reset(); double[] enviromentOutput = Environment.InitialObservation; // Environment loop while (!Environment.IsTerminated) { // Activate the controller with the environment output. // The turing controller will handle the turing machine I/O double[] environmentInput = controller.ActivateNeuralNetwork(enviromentOutput); if (_turingMachineProps.MemorySizeHardLimit > 0 && controller.TuringMachine.TapeSize > _turingMachineProps.MemorySizeHardLimit) { evaluation.ObjectiveFitness = 0d; // Phenome is disqualified, no need to do any further evaluation. return; } // Activate the environment with the output from the controller (NN) enviromentOutput = Environment.PerformAction(environmentInput); } totalScore += Environment.NormalizedScore; evaluation.TapeSizes[i] = controller.TuringMachine.TapeSize; Utility.Debug.DLog($"EVALUATION Total Score: {totalScore}, Iteration Score: {Environment.CurrentScore}", true); } // Calculate the total normalized score (0-1) evaluation.ObjectiveFitness = Math.Max(0d, totalScore / iterations); }