public CritSearchResultViewModel(Dictionary <Criterion, IEnumerable <HealthRecord> > crHrs, IEnumerable <HealthRecord> topHrs, Estimator est) { this.est = est; // select patients from hrs var crps = (from pair in crHrs let ps = from hr in pair.Value group hr by hr.GetPatient() into g orderby g.Key select g.Key select new { Cr = pair.Key, Ps = ps }).ToDictionary(x => x.Cr, x => x.Ps); var patCrs = crps.ReverseManyToMany(); var patHeadHrs = topHrs .GroupBy(x => x.GetPatient()) .ToDictionary(x => x.Key, x => x.ToList()); var vms = patCrs.Select(x => new CritResultItemViewModel(x.Key, patHeadHrs.GetValueOrDefault(x.Key), x.Value)); Patients = new ObservableCollection <IResultItem>(vms); Statistic = new CritStatistic(patCrs); var view = (ListCollectionView)CollectionViewSource.GetDefaultView(Patients); view.GroupDescriptions.Add(new PropertyGroupDescription("Patient")); }
/** * {@inheritDoc} */ public override IList <RecommendedItem> Recommend(Object userID, int howMany, Rescorer <Item> rescorer) { if (userID == null) { throw new ArgumentNullException("userID is null"); } if (howMany < 1) { throw new ArgumentException("howMany must be at least 1"); } if (rescorer == null) { throw new ArgumentNullException("rescorer is null"); } if (log.IsDebugEnabled) { log.Debug("Recommending items for user ID '" + userID + '\''); } User theUser = this.DataModel.GetUser(userID); ISet <Item> allItems = diffStorage.GetRecommendableItems(userID); TopItems.Estimator <Item> estimator = new Estimator(this, theUser); IList <RecommendedItem> topItems = TopItems.GetTopItems(howMany, allItems, rescorer, estimator); if (log.IsDebugEnabled) { log.Debug("Recommendations are: " + topItems); } return(topItems); }
public (double fixedTime, double variableTime, double totalTime) GetLayerTimes() { IntPoint lastPosition = gcodeExport.GetPosition(); double fixedTime = 0.0; double variableTime = 0.0; foreach (var path in paths) { for (int pointIndex = 0; pointIndex < path.Polygon.Count; pointIndex++) { IntPoint currentPosition = path.Polygon[pointIndex]; double thisTime = (lastPosition - currentPosition).LengthMm() / (double)(path.Speed); thisTime = Estimator.GetSecondsForMovement((lastPosition - currentPosition).LengthMm(), path.Speed, config.MaxAcceleration, config.MaxVelocity, config.JerkVelocity) * config.PrintTimeEstimateMultiplier; if (PathCanAdjustSpeed(path)) { variableTime += thisTime; } else { fixedTime += thisTime; } lastPosition = currentPosition; } } return(fixedTime, variableTime, fixedTime + variableTime); }
private void Window_Loaded(object sender, RoutedEventArgs e) { newQuotationData.Update(QuotationData); using (SqlConnection connection = new SqlConnection(Database.ConnectionString)) { string query = $"Select * From [Quotation].[_ProjectsContactsView] Where InquiryId = {newQuotationData.Inquiry.Id}"; projectContacts = new ObservableCollection <Contact>(connection.Query <Contact>(query)); viewProjectContacts = new CollectionViewSource { Source = projectContacts }; ProjectContactsList.ItemsSource = viewProjectContacts.View; query = $"Select * From Customer._Customers Where Id = {newQuotationData.Inquiry.CustomerId}"; customerData = connection.QueryFirstOrDefault <Customer>(query); query = $"Select * From [User].[_Salesmen] Where Id = {newQuotationData.Inquiry.SalesmanId}"; salesmanData = connection.QueryFirstOrDefault <Salesman>(query); query = $"Select * From [User].[_Estimators] Where Id = {newQuotationData.Inquiry.EstimatorId}"; estimatorData = connection.QueryFirstOrDefault <Estimator>(query); query = $"Select * From [Customer].[_Consultants] Where Id = {newQuotationData.Inquiry.ConsultantId}"; consultantData = connection.QueryFirstOrDefault <Consultant>(query); } if (OpenPanelsWindow) { Cancel.Visibility = Visibility.Collapsed; } viewProjectContacts.View.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged); DataContext = new { newQuotationData, customerData, consultantData, salesmanData, estimatorData }; }
private void GammaEstimator(double shape, double rate) { Rand.Restart(12347); Gamma g = Gamma.FromShapeAndRate(shape, rate); Estimator <Gamma> ge = EstimatorFactory.Instance.CreateEstimator <Gamma, double>(Gamma.Uniform()); Accumulator <double> gea = ge as Accumulator <double>; for (int i = 0; i < 10000; i++) { double d = g.Sample(); gea.Add(d); } Gamma gest = Gamma.Uniform(); gest = ge.GetDistribution(gest); double expectedMean = g.GetMean(); double expectedSDev = System.Math.Sqrt(g.GetVariance()); double estimatedMean = gest.GetMean(); double estimatedSDev = System.Math.Sqrt(gest.GetVariance()); Assert.True(System.Math.Abs(expectedMean - estimatedMean) < 0.02); Assert.True(System.Math.Abs(expectedSDev - estimatedSDev) < 0.02); }
private Estimator GetTransformerEstimator() { var paramList = this.GetParamaterList(); var estimator = new Estimator("transformer", "prefix", EstimatorType.Transformer, paramList); return(estimator); }
private float EvaluatePosition(int depth, Dot player, float alpha, float beta) { if (depth == 0) { return(Estimator.Estimate(player)); } Dot nextPlayer = player.NextPlayer(); var moves = MoveGenerator.GenerateMovesForPlayer(player); foreach (var move in moves) { if (alpha < beta) { Field.MakeMove(move); float tmp = -EvaluatePosition(depth - 1, nextPlayer, -beta, -alpha); Field.UnmakeMove(); if (tmp > alpha) { alpha = tmp; } } } return(alpha); }
public AlvaroAgent(double exploreConstant, int maxTime, string selectionAction, double scoreImportance, string treePolicy, int treeMaximumDepth, string simulationPolicy, double childrenConsideredSimulating, string estimationMode, int numSimulations, string HERO_HEALTH_REDUCED, string HERO_ATTACK_REDUCED, string MINION_HEALTH_REDUCED, string MINION_ATTACK_REDUCED, string MINION_APPEARED, string MINION_KILLED, string SECRET_REMOVED, string MANA_REDUCED, string M_HEALTH, string M_ATTACK, string M_HAS_CHARGE, string M_HAS_DEAHTRATTLE, string M_HAS_DIVINE_SHIELD, string M_HAS_INSPIRE, string M_HAS_LIFE_STEAL, string M_HAS_STEALTH, string M_HAS_TAUNT, string M_HAS_WINDFURY, string M_RARITY, string M_MANA_COST, string M_POISONOUS, float weaponAttack, float weaponDurability, float health, float boardStats, float handSize, float deckRemaining, float mana, float secret, float overload, float minionCost, float secretCost, float cardCost, float weaponCost) { EXPLORE_CONSTANT = exploreConstant; MAX_TIME = maxTime; SELECTION_ACTION_METHOD = selectionAction; SCORE_IMPORTANCE = scoreImportance; TREE_POLICY = treePolicy; TREE_MAXIMUM_DEPTH = treeMaximumDepth; SIMULATION_POLICY = simulationPolicy; CHILDREN_CONSIDERED_SIMULATING = childrenConsideredSimulating; ESTIMATION_MODE = estimationMode; NUM_SIMULATIONS = numSimulations; greedyAgent = new ParametricGreedyAgent(HERO_HEALTH_REDUCED + "#" + HERO_ATTACK_REDUCED + "#" + MINION_HEALTH_REDUCED + "#" + MINION_ATTACK_REDUCED + "#" + MINION_APPEARED + "#" + MINION_KILLED + "#" + SECRET_REMOVED + "#" + MANA_REDUCED + "#" + M_HEALTH + "#" + M_ATTACK + "#" + M_HAS_CHARGE + "#" + M_HAS_DEAHTRATTLE + "#" + M_HAS_DIVINE_SHIELD + "#" + M_HAS_INSPIRE + "#" + M_HAS_LIFE_STEAL + "#" + M_HAS_STEALTH + "#" + M_HAS_TAUNT + "#" + M_HAS_WINDFURY + "#" + M_RARITY + "#" + M_MANA_COST + "#" + M_POISONOUS); Estimator.setWeights(weaponAttack, weaponDurability, health, boardStats, handSize, deckRemaining, mana, secret, overload, minionCost, secretCost, cardCost, weaponCost, float.Parse(M_HAS_CHARGE), float.Parse(M_HAS_DEAHTRATTLE), float.Parse(M_HAS_DIVINE_SHIELD), float.Parse(M_HAS_INSPIRE), float.Parse(M_HAS_LIFE_STEAL), float.Parse(M_HAS_TAUNT), float.Parse(M_HAS_WINDFURY)); }
private static IList <RecommendedItem> ComputeTopRecsForCluster(ICollection <User> cluster) { ICollection <Item> allItems = new HashedSet <Item>(); foreach (User user in cluster) { Preference[] prefs = user.GetPreferencesAsArray(); foreach (Preference pref in prefs) { allItems.Add(pref.Item); } } TopItems.Estimator <Item> estimator = new Estimator(cluster); IList <RecommendedItem> topItems = TopItems.GetTopItems(int.MaxValue, allItems, NullRescorer <Item> .Instance, estimator); if (log.IsDebugEnabled) { log.Debug("Recommendations are: " + topItems); } //return new ReadOnlyCollection<RecommendedItem>(topItems); return(topItems); }
public void EmptyInput_GetDefaultValue() { var estimator = new Estimator(new TimeSpan(0, 0, 10)); var calculateEstimate = estimator.CalculateEstimate(new List <TimeSpan>()); Assert.AreEqual(10, calculateEstimate.Seconds); }
public ActionResult Estimate(double height, double width, double depth, double weight) { Estimator myParcel = new Estimator(height, width, depth, weight); myParcel.VolumeCalc(); return(View("Index", myParcel)); }
private void buttonUseTestClass_Click(object sender, EventArgs e) { var classTest = new Estimator(); richTextBoxIncoming.Text = ""; richTextBoxResolve.Text = ""; double bestFunc = Math.Pow(10, 300); var better = classTest.DeviationCollections(new[] { 754.23171986103057, 142.85790967464447 }, 30); //double[] readLeafs = ClassTest.Out_Constants[bestIndex]; //richTextBoxResolve.Text += "Отклонение: " + BestFunc + "\rГенотип #" + bestIndex + "\rИтераций Н-М: " + ClassTest.Out_NM_Restarts[bestIndex]; try { //for (int i = 0; i < readLeafs.Length; i++) // richTextBoxResolve.Text += "\rЛист " + i + ": " + Math.Round(readLeafs[i], 3); } catch { //ignore } }
public static void Bar() { IHostEnvironment env = null; var text = TextLoader.CreateReader(env, ctx => ( label: ctx.LoadBool(0), text: ctx.LoadText(1), numericFeatures: ctx.LoadFloat(2, 5))); var est = Estimator.MakeNew(text); // This should work. est.Append(r => r.text); // These should not. est.Append(r => 5); est.Append(r => new { r.text }); est.Append(r => Tuple.Create(r.text, r.numericFeatures)); // This should work. est.Append(r => (a: r.text, b: r.label, c: (d: r.text, r.label))); // This should not, and it should indicate a path to the problematic item. est.Append(r => (a: r.text, b: r.label, c: (d: r.text, "yo"))); // Check a different entrance into static land now, with one of the asserts. var view = text.Read(null).AsDynamic; // Despite the fact that the names are all wrong, this should still work // from the point of view of this analyzer. view.AssertStatic(env, c => ( stay: c.KeyU4.TextValues.Scalar, awhile: c.KeyU1.I4Values.Vector)); // However, this should not. view.AssertStatic(env, c => ( and: c.KeyU4.TextValues.Scalar, listen: "dawg")); }
public void Evaluating4000Records_ExpectedTime_200ms() { // Arrange var engine = new V8ScriptEngine(); var exprected_time = TimeSpan.FromMilliseconds(200); var exprected_count = 4000; var actual_time = new TimeSpan(); var actual_results = new Stack <int>(4000); // Act try { actual_time = Estimator.Estimate(() => { for (int i = 0; i < 4000; i++) { actual_results.Push((int)engine.Evaluate("1+1")); } }); } finally { engine.Dispose(); } // Expect Assert.AreEqual(exprected_count, actual_results.Count); Assert.That(actual_time, Is.LessThanOrEqualTo(exprected_time)); }
public EstimatorViewModel(Estimator e) { Contract.Requires(e != null); est = e; validatableEntity = est; est.PropertyChanged += model_PropertyChanged; }
public ModelInfo(ModelType type = ModelType.MarkowitzMeanVariance, Objective opt = Objective.MinimizeRisk, Estimator est = Estimator.Sample) { // Initialize with default values if none are passed as parameters Type = type; OptimizationObjective = opt; Estimator = est; }
internal void setModelEstimator(Estimator estim) { var mtype = modelInfo.Type; var obj = modelInfo.OptimizationObjective; this.modelInfo = new ModelInfo(type: mtype, opt: obj, est: estim); this.ChangedFlag = true; }
public override long[] getUserNeighborhood(long userID) { DataModel model = this.getDataModel(); TopItems.Estimator <long> estimator = new Estimator(this.getUserSimilarity(), userID, this.minSimilarity); IEnumerator <long> allUserIDs = SamplingLongPrimitiveIterator.maybeWrapIterator(model.getUserIDs(), this.getSamplingRate()); return(TopItems.getTopUsers(this.n, allUserIDs, null, estimator)); }
private float Simulation(Node nodeToSimulate, POGame poGame) { float result = -1; int simulationSteps = 0; PlayerTask task = null; List <PlayerTask> taskToSimulate = new List <PlayerTask>(); if (poGame == null) { return(0.5f); } if (nodeToSimulate.task.PlayerTaskType == PlayerTaskType.END_TURN) { return(Estimator.estimateFromState(ESTIMATION_MODE, poGame)); } while (poGame.getGame().State != SabberStoneCore.Enums.State.COMPLETE) { task = SimulationPolicies.selectSimulationPolicy(SIMULATION_POLICY, poGame, Rnd, greedyAgent, CHILDREN_CONSIDERED_SIMULATING); taskToSimulate.Add(task); if (task.PlayerTaskType != PlayerTaskType.END_TURN) { poGame = poGame.Simulate(taskToSimulate)[taskToSimulate[0]]; } taskToSimulate.Clear(); if (poGame == null) { return(0.5f); } if (task.PlayerTaskType == PlayerTaskType.END_TURN) { return(Estimator.estimateFromState(ESTIMATION_MODE, poGame)); } simulationSteps++; } if (poGame.CurrentPlayer.PlayState == SabberStoneCore.Enums.PlayState.CONCEDED || poGame.CurrentPlayer.PlayState == SabberStoneCore.Enums.PlayState.LOST) { result = 0; } else if (poGame.CurrentPlayer.PlayState == SabberStoneCore.Enums.PlayState.WON) { result = 1; } return(result); }
public static string ToRString(this Estimator est) { switch (est) { case Estimator.Sample: return("covEstimator"); default: return("covEstimator"); } }
public void Estimator2CrGroup() { var e = new Estimator(); var gr = e.AddCriteriaGroup(); Assert.AreEqual(gr, e.CriteriaGroups.Single()); Assert.AreEqual(e, gr.Estimator); e.RemoveCriteriaGroup(gr); Assert.IsFalse(e.CriteriaGroups.Contains(gr)); Assert.IsNull(gr.Estimator); }
public override List <RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) { log.debug("Recommending items for user ID '{}'", new object[] { userID }); PreferenceArray preferencesFromUser = this.getDataModel().getPreferencesFromUser(userID); FastIDSet set = this.getAllOtherItems(userID, preferencesFromUser); TopItems.Estimator <long> estimator = new Estimator(this); List <RecommendedItem> list = TopItems.getTopItems(howMany, set.GetEnumerator(), rescorer, estimator); log.debug("Recommendations are: {}", new object[] { list }); return(list); }
public override long[] GetUserNeighborhood(long userID) { IDataModel dataModel = getDataModel(); IUserSimilarity userSimilarityImpl = getUserSimilarity(); TopItems.IEstimator <long> estimator = new Estimator(userSimilarityImpl, userID, minSimilarity); var userIDs = SamplinglongPrimitiveIterator.MaybeWrapIterator(dataModel.GetUserIDs(), getSamplingRate()); return(TopItems.GetTopUsers(n, userIDs, null, estimator)); }
public void Case2() { var estimator = new Estimator(new TimeSpan(0, 0, 10)); var calculateEstimate = estimator.CalculateEstimate(new List <TimeSpan> { new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 8), }); Assert.AreEqual(123484691, calculateEstimate.Ticks); }
public void Case1() { var estimator = new Estimator(new TimeSpan(0, 0, 10)); var calculateEstimate = estimator.CalculateEstimate(new List <TimeSpan> { new TimeSpan(0, 0, 2), new TimeSpan(0, 0, 4), new TimeSpan(0, 0, 6), }); Assert.AreEqual(8, calculateEstimate.Seconds); }
/// <summary> /// 初始化 Path, 需要给定起始节点, 终止节点, 代理, 以及地图是否为静态(默认为否) /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <param name="agent"></param> /// <param name="mapStatic"></param> public Path( Node start, Node end, Agent agent, bool mapStatic = false) { Start = start; End = end; Agent = agent; Estimator = new Estimator <Properties>(agent.WeightTable); MapStatic = mapStatic; Reset(); }
public override IList <RecommendedItem> Recommend(Object userID, int howMany, Rescorer <Item> rescorer) { if (userID == null) { throw new ArgumentNullException("userID is null"); } if (howMany < 1) { throw new ArgumentException("howMany must be at least 1"); } if (rescorer == null) { throw new ArgumentNullException("rescorer is null"); } if (log.IsDebugEnabled) { log.DebugFormat("Recommending items for user ID '{0}'", userID); } User theUser = this.DataModel.GetUser(userID); ICollection <User> theNeighborhood = neighborhood.GetUserNeighborhood(userID); if (log.IsDebugEnabled) { log.DebugFormat("UserNeighborhood is: {0} ", neighborhood); } if (theNeighborhood.Count == 0) { return(new List <RecommendedItem>()); } ISet <Item> allItems = GetAllOtherItems(theNeighborhood, theUser); if (log.IsDebugEnabled) { log.Debug("Items in Neighborhood which user doesn't prefer already are: " + allItems); } TopItems.Estimator <Item> estimator = new Estimator(this, theUser, theNeighborhood); IList <RecommendedItem> topItems = TopItems.GetTopItems(howMany, allItems, rescorer, estimator); if (log.IsDebugEnabled) { log.Debug("Recommendations are: " + topItems); // TODO: Format this better } return(topItems); }
public void CalcularPrecioUnitario() { var cotizacion = new Cotizacion { TotalCol = 100, Cantidad = 5, Material = new Material() }; var instance = new Estimator(cotizacion); instance.CalcularPrecioUnitario(); Assert.AreEqual(20, cotizacion.PrecioUnitario); }
public override List <RecommendedItem> recommend(long userID, int howMany, taste.recommender.IDRescorer rescorer) { //Preconditions.checkArgument(howMany >= 1, "howMany must be at least 1"); log.debug("Recommending items for user ID '{}'", userID); FastIDSet possibleItemIDs = diffStorage.getRecommendableItemIDs(userID); TopItems.Estimator <long> estimator = new Estimator(this, userID); List <RecommendedItem> topItems = TopItems.getTopItems(howMany, possibleItemIDs.GetEnumerator(), rescorer, estimator); log.debug("Recommendations are: {}", topItems); return(topItems); }
private unsafe float EvaluatePosition(byte depth, Dot player, float alpha, float beta, ulong key, HashSet <int> moves) { float oldAlpha = alpha; Dot nextPlayer = player.NextPlayer(); float score = CheckCollision(player, depth, alpha, beta, key, moves); if (score >= 0) { return(score); } if (depth == 0) { return(Estimator.Estimate(player)); } foreach (var move in moves) { if (Field.MakeMove(move)) { HashField.UpdateHash(); float tmp = -EvaluatePosition((byte)(depth - 1), nextPlayer, -beta, -alpha, HashField.Key, MoveGenerator.GenerateMoves(nextPlayer, moves)); Field.UnmakeMove(); HashField.UpdateHash(); if (tmp > alpha) { TranspositionTable.RecordHash( (byte)depth, tmp, tmp < beta ? enmHashEntryType.Exact : enmHashEntryType.Beta, HashField.Key, (ushort)move); alpha = tmp; if (alpha >= beta) { return(beta); } } } } if (alpha == oldAlpha) { TranspositionTable.RecordHash((byte)depth, alpha, enmHashEntryType.Alpha, HashField.Key, 0); } return(alpha); }
public AlphaBetaAlgoritm(Field field, MoveGenerator moveGenerator = null, Estimator estimator = null) { Field = field; MoveGenerator = moveGenerator ?? new StandartMoveGenerator(field); Estimator = estimator ?? new Estimator(field); }
/// <summary> Sets up the priors for numeric class attributes from the /// training class values that have been seen so far. /// </summary> protected internal virtual void setNumericPriorsFromBuffer() { double numPrecision = 0.01; // Default value if (m_NumTrainClassVals > 1) { double[] temp = new double[m_NumTrainClassVals]; Array.Copy(m_TrainClassVals, 0, temp, 0, m_NumTrainClassVals); int[] index = Utils.sort(temp); double lastVal = temp[index[0]]; double deltaSum = 0; int distinct = 0; for (int i = 1; i < temp.Length; i++) { double current = temp[index[i]]; if (current != lastVal) { deltaSum += current - lastVal; lastVal = current; distinct++; } } if (distinct > 0) { numPrecision = deltaSum / distinct; } } m_PriorErrorEstimator = new KernelEstimator(numPrecision); m_ErrorEstimator = new KernelEstimator(numPrecision); m_ClassPriors[0] = m_ClassPriorsSum = 0; for (int i = 0; i < m_NumTrainClassVals; i++) { m_ClassPriors[0] += m_TrainClassVals[i] * m_TrainClassWeights[i]; m_ClassPriorsSum += m_TrainClassWeights[i]; m_PriorErrorEstimator.addValue(m_TrainClassVals[i], m_TrainClassWeights[i]); } }