Exemplo n.º 1
0
        public void ApplyRemoteResolution(ISqlDataStore dataStore, ISyncSessionInfo syncSession, ISyncStatProvider statProvider)
        {
            if (EntitiesConflict == null || EntitiesConflict.Count == 0)
            {
                return;
            }

            var progression = new LinearProgression(EntitiesConflict.Count);

            statProvider.SetNewState(SyncStates.ApplyRemoteResolution, progression);

            foreach (var entityConflict in EntitiesConflict)
            {
                entityConflict.ApplyRemoteResolution(dataStore, syncSession);
                progression.CurrentStepFinished();
            }
        }
Exemplo n.º 2
0
        public void ApplyChanges(ISqlDataStore datastore, ISyncStatProvider statProvider, IConflictsManager conflictsManager)
        {
            if (EntityChangeset.Count == 0)
            {
                return;
            }

            var progression = new LinearProgression(EntityChangeset.Count * 3);

            statProvider.SetNewState(SyncStates.ApplyingRemoteChange, progression);

            var changeSets = new List <ChangeSet>();

            foreach (var entityChangeset in EntityChangeset)
            {
                entityChangeset.SetDatastore(datastore);
                var conflic = conflictsManager.CreateEntityConflict(entityChangeset, _syncSessionInfo);
                changeSets.Add(new ChangeSet(entityChangeset, conflic, conflictsManager));
            }

            // Update FK changes before delete
            foreach (var entityChange in changeSets)
            {
                entityChange.ApplyUpdate();
                progression.CurrentStepFinished();
            }

            // Delete FK before delete PK
            changeSets.Reverse();
            foreach (var entityChange in changeSets)
            {
                entityChange.ApplyDelete();
                progression.CurrentStepFinished();
            }

            // Insert PK before insert FK
            changeSets.Reverse();
            foreach (var entityChange in changeSets)
            {
                entityChange.ApplyInsert();
                entityChange.ApplyLastSync();
                entityChange.ResolveConflicts(datastore);
                progression.CurrentStepFinished();
            }
        }
Exemplo n.º 3
0
        public void Build(SyncStatProvider statProvider)
        {
            var syncableEntities = _dataStore.Entities
                                   // ReSharper disable once RedundantTypeArgumentsOfMethod Need for vs 2008
                                   .Select <IEntityInfo, SyncEntity>(SyncEntity.Create)
                                   .Where(_ => _ != null && !ShouldSkipLocalChange(_))
                                   .ToList();

            var progression = new LinearProgression(syncableEntities.Count);

            statProvider.SetNewState(GetStepName(), progression);
            foreach (var syncableEntity in syncableEntities)
            {
                var entityName   = syncableEntity.GetNameInStore();
                var entityChange = CreateEntityChangeset(syncableEntity);
                entityChange.Populate();
                statProvider.Info("Local change ({0}) {1}", entityName, entityChange);
                progression.CurrentStepFinished();
            }

            statProvider.SetLocalChanges(this);
        }
        public Participation_BinComparison_View(Engine engine, IEnumerable <Activity> activitiesToPredictFrom, Activity activityToPredict, TimeSpan windowSize)
        {
            DateTime now = DateTime.Now;

            engine.EnsureRatingsAreAssociated();

            LinearProgression progressionToPredict = activityToPredict.ParticipationsSmoothed((new TimeSpan()).Subtract(windowSize));

            StatList <NeighborhoodInterpolation, Activity> results = new StatList <NeighborhoodInterpolation, Activity>(new Neighborhood_MiddleOutputMean_Comparer(), new NoopCombiner <Activity>());

            foreach (Activity activity in activitiesToPredictFrom)
            {
                System.Diagnostics.Debug.WriteLine("comparing " + activity + " and " + activityToPredict.Name);
                List <Datapoint> datapoints = activity.compareParticipations(windowSize, progressionToPredict, now.Subtract(windowSize));

                // put data into the interpolator
                FloatRange inputRange = new FloatRange(0, true, windowSize.TotalSeconds, true);
                AdaptiveLinearInterpolator <Distribution> interpolator = new AdaptiveLinearInterpolator <Distribution>(new HyperBox <Distribution>(new FloatRange[] { inputRange }), new DistributionAdder());
                foreach (Datapoint datapoint in datapoints)
                {
                    interpolator.AddDatapoint(new AdaptiveInterpolation.Datapoint <Distribution>(datapoint.Input, Distribution.MakeDistribution(datapoint.Output, 0, datapoint.Weight)));
                }

                // ask the interpolator which input has the highest average output
                IEnumerable <double[]> representativePoints = interpolator.FindRepresentativePoints();
                if (representativePoints.Count() > 0)
                {
                    double[] bestInput = new double[1];
                    AdaptiveInterpolation.Distribution bestOutput = null;
                    foreach (double[] coordinates in representativePoints)
                    {
                        AdaptiveInterpolation.Distribution output = interpolator.Interpolate(coordinates);
                        if (bestOutput == null || output.Mean > bestOutput.Mean)
                        {
                            bestInput  = coordinates;
                            bestOutput = output;
                        }
                    }

                    // Check nearby regions for their outputs too
                    HyperBox <Distribution> inputNeighborhood = interpolator.FindNeighborhoodCoordinates(bestInput);
                    double inputNeighborhoodWidth             = inputNeighborhood.Coordinates[0].Width;
                    double lowerInput  = Math.Max(inputNeighborhood.Coordinates[0].LowCoordinate - inputNeighborhoodWidth, inputRange.LowCoordinate);
                    double higherInput = Math.Min(inputNeighborhood.Coordinates[0].HighCoordinate + inputNeighborhoodWidth, inputRange.HighCoordinate);

                    NeighborhoodInterpolation result = new NeighborhoodInterpolation();
                    result.Middle = new Interpolation(bestInput[0], bestOutput);
                    result.Left   = new Interpolation(lowerInput, interpolator.Interpolate(new double[] { lowerInput }));
                    result.Right  = new Interpolation(higherInput, interpolator.Interpolate(new double[] { higherInput }));

                    results.Add(result, activity);
                }
            }

            IEnumerable <ListItemStats <NeighborhoodInterpolation, Activity> > resultList = results.AllItems;

            if (resultList.Count() <= 0)
            {
                // This shouldn't be able to happen unless we disallow predicting the activity from itself
                this.SubLayout = new TextblockLayout("No activities found!");
            }
            else
            {
                int numWindowDays = (int)windowSize.TotalDays;
                GridLayout_Builder layoutBuilder = new Vertical_GridLayout_Builder().Uniform();
                if (resultList.Count() > 1)
                {
                    string title = "Activities that when done most strongly predict future participations in " + activityToPredict.Name;
                    layoutBuilder.AddLayout(new TextblockLayout(title));
                }
                else
                {
                    string title = "Predicting future participations in " + activityToPredict.Name;
                    layoutBuilder.AddLayout(new TextblockLayout(title));
                }

                string explanation = "A block of the form a->{b,c,d} means that when you have spent an average of <a> min/day on the given activity over the last " + numWindowDays + " days, " +
                                     "you have spent on average <c> min/day on " + activityToPredict.Name + " over the next " + numWindowDays + " days, with <b> and <d> marking -1 and +1 standard deviation, respectively";
                layoutBuilder.AddLayout(new TextblockLayout(explanation));

                int count = 0;
                foreach (ListItemStats <NeighborhoodInterpolation, Activity> result in resultList.Reverse())
                {
                    count++;
                    if (count > 3)
                    {
                        break;
                    }
                    Activity activity = result.Value;
                    NeighborhoodInterpolation neighborhood = result.Key;
                    layoutBuilder.AddLayout(new TextblockLayout("After " + activity.Name + ":"));
                    foreach (Interpolation interpolation in neighborhood.Items)
                    {
                        double inputSecondsPerWindow = interpolation.Input;
                        double inputMinutesPerDay    = inputSecondsPerWindow / windowSize.TotalDays / 60;

                        double avgOutputSecondsPerWindow = interpolation.Output.Mean;
                        double avgOutputMinutesPerDay    = avgOutputSecondsPerWindow / windowSize.TotalDays / 60;

                        double stddevOutputSecondsPerWindow = interpolation.Output.StdDev;
                        double stddevOutputMinutesPerDay    = stddevOutputSecondsPerWindow / windowSize.TotalDays / 60;

                        string itemLine = Math.Round(inputMinutesPerDay, 1) + " -> {" +
                                          Math.Round((avgOutputMinutesPerDay - stddevOutputMinutesPerDay), 1) + "," +
                                          Math.Round(avgOutputMinutesPerDay, 1) + "," +
                                          Math.Round((avgOutputMinutesPerDay + stddevOutputMinutesPerDay), 1) + "}";
                        layoutBuilder.AddLayout(new TextblockLayout(itemLine));
                    }
                }

                this.SubLayout = layoutBuilder.Build();
            }
        }
Exemplo n.º 5
0
        public ParticipationCorrelationView(Engine engine, IEnumerable <Activity> activitiesToPredictFrom, Activity activityToPredict, TimeSpan windowSize)
        {
            DateTime now = DateTime.Now;

            engine.EnsureRatingsAreAssociated();

            LinearProgression progressionToPredict = activityToPredict.ParticipationsSmoothed((new TimeSpan()).Subtract(windowSize));

            StatList <double, Activity> results = new StatList <double, Activity>(new DoubleComparer(), new NoopCombiner <Activity>());

            foreach (Activity activity in activitiesToPredictFrom)
            {
                System.Diagnostics.Debug.WriteLine("comparing " + activity + " and " + activityToPredict.Name);
                List <Datapoint> datapoints = activity.compareParticipations(windowSize, progressionToPredict, now.Subtract(windowSize));

                // now compute the value of the formula
                Correlator correlator = new Correlator();
                foreach (Datapoint datapoint in datapoints)
                {
                    correlator.Add(datapoint);
                }

                double outputIncreasePerInputIncrease = correlator.Slope;
                if (!double.IsNaN(outputIncreasePerInputIncrease))
                {
                    results.Add(outputIncreasePerInputIncrease, activity);
                }
            }

            IEnumerable <ListItemStats <double, Activity> > resultList = results.AllItems;

            GridLayout_Builder layoutBuilder = new Vertical_GridLayout_Builder().Uniform();
            List <ListItemStats <double, Activity> > mostPositivelyCorrelated = new List <ListItemStats <double, Activity> >();
            List <ListItemStats <double, Activity> > mostNegativelyCorrelated = new List <ListItemStats <double, Activity> >();
            int i            = 0;
            int numPositives = Math.Min(4, resultList.Count());

            foreach (ListItemStats <double, Activity> result in resultList.Reverse())
            {
                mostPositivelyCorrelated.Add(result);
                i++;
                if (i > numPositives)
                {
                    break;
                }
            }
            i = 0;
            int numNegatives = Math.Min(4, resultList.Count() - numPositives);

            foreach (ListItemStats <double, Activity> result in resultList)
            {
                mostNegativelyCorrelated.Add(result);
                i++;
                if (i > numNegatives)
                {
                    break;
                }
            }

            if (resultList.Count() <= 0)
            {
                // This shouldn't be able to happen unless we disallow predicting the activity from itself
                this.SubLayout = new TextblockLayout("No activities found!");
            }
            else
            {
                string title = "Things you do that are correlated with doing more or less of " + activityToPredict.Name + " over the following " +
                               Math.Round(windowSize.TotalDays, 0) + " days";
                layoutBuilder.AddLayout(new TextblockLayout(title));

                if (numPositives > 0)
                {
                    if (numPositives > 1)
                    {
                        layoutBuilder.AddLayout(new TextblockLayout("Doing one minute of these activities adds this many minutes:"));
                    }
                    else
                    {
                        layoutBuilder.AddLayout(new TextblockLayout("Doing one minute of this activity adds this many minutes:"));
                    }
                    foreach (ListItemStats <double, Activity> result in mostPositivelyCorrelated)
                    {
                        double   correlation = result.Key;
                        Activity activity    = result.Value;
                        String   message     = activity.Name + ": " + Math.Round(correlation, 5);
                        layoutBuilder.AddLayout(new TextblockLayout(message));
                    }
                }

                if (numNegatives > 0)
                {
                    if (numNegatives > 1)
                    {
                        layoutBuilder.AddLayout(new TextblockLayout("Doing one minute of these activities subtracts this many minutes:"));
                    }
                    else
                    {
                        layoutBuilder.AddLayout(new TextblockLayout("Doing one minute of this activity subtracts this many minutes:"));
                    }
                    foreach (ListItemStats <double, Activity> result in mostNegativelyCorrelated)
                    {
                        double   correlation = result.Key;
                        Activity activity    = result.Value;
                        String   message     = activity.Name + ": " + Math.Round(correlation, 5);
                        layoutBuilder.AddLayout(new TextblockLayout(message));
                    }
                }

                this.SubLayout = layoutBuilder.Build();
            }
        }