summaryrefslogtreecommitdiffstats
path: root/kicker/applets/launcher/popularity.cpp
blob: e446a2ec74f695b8e69602990d0b6c98514dece3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*****************************************************************

Copyright (c) 2005 Fred Schaettgen <kde.sch@ttgen.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include "popularity.h"
#include "prefs.h"
#include <assert.h>
#include <algorithm>
#include <iterator>
#include <kconfig.h>
#include <kdebug.h>
#include <list>
#include <set>
#include <map>
#include <cmath>
#include <vector>

using namespace std;

class PopularityStatisticsImpl
{
public:
    struct SingleFalloffHistory
    {
    public:
        // fallof is a number between 0 and 1. The popularity of
        // each service is multiplied with the falloff value
        // every time a service is used. Only the used service
        // gets also  1-falloff added to its popularity.
        double falloff;
        // popularity values for each service
        map<TQString, double> vals;
        // accumulated popularity of the unknown programs
        // started before the statistic started
        double iniVal;
    };
    
    struct Popularity
    {
        TQString service;
        double popularity;
        bool operator<(const Popularity& p) const
        { 
            return popularity > p.popularity;
        }
    };
    
    PopularityStatisticsImpl();
    void normalizeHistory(SingleFalloffHistory& h);
    void updateServiceRanks();

    vector<SingleFalloffHistory> m_stats;
    vector<Popularity> m_servicesByPopularity;
    map<TQString, int> m_serviceRanks;
    double m_historyHorizon;
};

// ---- Public methods ----

PopularityStatistics::PopularityStatistics() :
    d(new PopularityStatisticsImpl())
{
}

PopularityStatistics::~PopularityStatistics() 
{
    delete d;
}

void PopularityStatistics::useService(const TQString& service)
{
    vector<PopularityStatisticsImpl::SingleFalloffHistory>::iterator 
        it(d->m_stats.begin()), end(d->m_stats.end());
    for (; it != end; ++it)
    {
        map<TQString, double>::iterator valIt;
        bool found(false);
        for (valIt = it->vals.begin(); valIt != it->vals.end(); ++valIt)
        {
            valIt->second = valIt->second * it->falloff;
            if (valIt->first == service)
            {
                found = true;
                valIt->second += 1-it->falloff;
            }
        }
        it->iniVal = it->iniVal * it->falloff;
        if (found == false)
        {
           it->vals[service] = 1-it->falloff;
        }
        d->normalizeHistory(*it);
    }
    d->updateServiceRanks();
}

void PopularityStatistics::moveToTop(const TQStringList& newTopServiceList)
{
    vector<PopularityStatisticsImpl::SingleFalloffHistory>::iterator 
    histIt(d->m_stats.begin()), histEnd(d->m_stats.end());
    for (; histIt != histEnd; ++histIt)
    {
        set<TQString> newTopServices;
        for (uint n=0; n<newTopServiceList.size(); ++n)
            newTopServices.insert(newTopServiceList[n]);

        // Sort by popularity
        vector<PopularityStatisticsImpl::Popularity> ranking;
        map<TQString, double>::iterator valIt;
        for (valIt = histIt->vals.begin(); valIt != histIt->vals.end(); ++valIt)
        {
            PopularityStatisticsImpl::Popularity pop;
            pop.service = valIt->first;
            pop.popularity = valIt->second;
            ranking.push_back(pop);
        }
        stable_sort(ranking.begin(), ranking.end());
        
        // Get the new positions of each service in the ranking.
        // We don't touch the popularity values in the ranking.
        list<TQString> topServiceList, bottomServiceList;
        vector<PopularityStatisticsImpl::Popularity>:: iterator rankIt;
        for (rankIt = ranking.begin(); rankIt != ranking.end(); ++rankIt)
        {
            if (newTopServices.find(rankIt->service) != newTopServices.end())
            {
                topServiceList.push_back(rankIt->service);
                //kdDebug() << "top service: " << valIt->first << endl;
                newTopServices.erase(rankIt->service);
            }
            else
            {
                //kdDebug() << "bottom service: " << valIt->first << endl;
                bottomServiceList.push_back(rankIt->service);
            }
        }
        // Append remaining new services to the topServices list
        while (newTopServices.size() > 0)
        {
            topServiceList.push_back(*newTopServices.begin());
            newTopServices.erase(newTopServices.begin());
        }
        
        list<TQString> newServiceList;
        copy(topServiceList.begin(), topServiceList.end(),
            back_insert_iterator<list<TQString> >(newServiceList)); 
        copy(bottomServiceList.begin(), bottomServiceList.end(),
            back_insert_iterator<list<TQString> >(newServiceList)); 
        
        // Merge the old list of service popularities
        // with the new ordering of the services
        histIt->vals.clear();
        list<TQString>::iterator servIt;
        uint serviceIndex = 0;
        //kdDebug() << endl;
        
        for (servIt = newServiceList.begin(); servIt != newServiceList.end();
             ++servIt)
        {
            if (serviceIndex < ranking.size())
            {
                histIt->vals[*servIt] = ranking[serviceIndex].popularity;
                //kdDebug() << "->Re-Added service " << 
                //ranking[serviceIndex].popularity 
                //    << " " << *servIt << endl;
                //kdDebug() << "...was tqreplaced by " << *servIt << endl;
            }
            else
            {
                //kdDebug() << "Service " << *servIt << endl;
                //kdDebug() << "...was set to popularity=0" << endl;
                histIt->vals[*servIt] = 0.00001;
            }
            // Make sure that the topServices are actually bigger than
            // the bottomServices and not just bigger or equal
            // and also that no services have popularity==0
            if (serviceIndex >= topServiceList.size())
            {
                histIt->vals[*servIt] *= histIt->falloff;
            }
            ++serviceIndex;
        }
        d->normalizeHistory(*histIt);
    }
    d->updateServiceRanks();
}

/*v
Old version - moves everything else one position up
and 'service' to the bottom
void PopularityStatistics::moveToBottom(const TQString& service)
{
    // Moves a service to the bottom of the ranking
    // by moving everything else to the top
    d->updateServiceRanks();
    TQStringList allButOneServices;
    vector<PopularityStatisticsImpl::Popularity>::iterator 
        it(d->m_servicesByPopularity.begin()),
        end(d->m_servicesByPopularity.end());
    for (; it != end; ++it)
    {
        if (it->service != service)
            allButOneServices << it->service;
    }
    moveToTop(allButOneServices);
}*/

void PopularityStatistics::moveToBottom(const TQString& service)
{
    vector<PopularityStatisticsImpl::SingleFalloffHistory>::iterator 
        it(d->m_stats.begin()), end(d->m_stats.end());
    for (; it != end; ++it)
    {
        it->iniVal += it->vals[service];
        it->vals[service] = 0;
        d->normalizeHistory(*it);
    }
    d->updateServiceRanks();
}

TQString PopularityStatistics::serviceByRank(int n) const
{
    if (n >= 0 && n < int(d->m_servicesByPopularity.size()))
        return d->m_servicesByPopularity[n].service;
    else
        return TQString();
}

double PopularityStatistics::popularityByRank(int n) const
{
    if (n >= 0 && n < int(d->m_servicesByPopularity.size()))
        return d->m_servicesByPopularity[n].popularity;
    else
        return 0.0;
}

int PopularityStatistics::rankByService(const TQString service)
{
    if (d->m_serviceRanks.find(service) != d->m_serviceRanks.end())
    {
        return d->m_serviceRanks[service];
    }
    return -1;
}

void PopularityStatistics::writeConfig(Prefs* prefs) const
{
    TQStringList serviceNames, serviceHistories;
    int limit = prefs->serviceCacheSize();
    //kdDebug() << "popularityData: writeConfig" << endl;
    for (int n=0; n<int(d->m_servicesByPopularity.size()) && n<limit; ++n)
    {
        PopularityStatisticsImpl::Popularity pop = d->m_servicesByPopularity[n];
        TQStringList historyData;
        for (int i=0; i<int(d->m_stats.size()); ++i)
        {
            historyData << TQString::number(d->m_stats[i].vals[pop.service]);
        }
        serviceNames << pop.service;
        serviceHistories << historyData.join("/");
        //kdDebug() << "popularityData: writeConfig -- " << pop.service << endl;
    }
    prefs->setServiceNames(serviceNames);
    prefs->setServiceHistories(serviceHistories);
}

void PopularityStatistics::readConfig(Prefs* prefs)
{
    int n = 0;
    TQStringList serviceNames = prefs->serviceNames();
    TQStringList histories = prefs->serviceHistories();
    for (n = std::min(serviceNames.size(), histories.size())-1; n>=0; --n)
    {
        TQString serviceName = serviceNames[n];
        TQStringList serviceHistory =
            TQStringList::split("/", histories[n]);
        for (int i=min(serviceHistory.size(), d->m_stats.size())-1; i>=0; --i)
        {
            d->m_stats[i].vals[serviceName] = serviceHistory[i].toDouble();
        }
    }
    
    for (int i=0; i<int(d->m_stats.size()); ++i)
    {
        map<TQString, double>::iterator valIt;
        double valSum = 0;
        for (valIt = d->m_stats[i].vals.begin(); 
             valIt != d->m_stats[i].vals.end(); ++valIt)
        {
            if (valIt->second < 0) valIt->second = 0;
            valSum += valIt->second;
        }
        // Scale down values if their sum is bigger than 1 
        // because of rounding errors or a corrupted config file
        if (valSum > 1)
        {
            for (valIt = d->m_stats[i].vals.begin(); 
                 valIt != d->m_stats[i].vals.end(); ++valIt)
            {
                valIt->second = valIt->second / valSum;
            }
        }
        d->m_stats[i].iniVal = 1-valSum;
    }
    d->updateServiceRanks();
}

void PopularityStatistics::setHistoryHorizon(double h)
{
    d->m_historyHorizon = std::max(std::min(h, 1.0), 0.0);
    d->updateServiceRanks();
}

double PopularityStatistics::historyHorizon()
{
    return d->m_historyHorizon;
}


// ---- Implementation methods ----

PopularityStatisticsImpl::PopularityStatisticsImpl()
{
    const int rateBaseCount(8);

    m_historyHorizon = 0.0;
    
    for (int n=0; n<rateBaseCount; ++n) 
    {
        SingleFalloffHistory h;
        h.falloff = 1.0 - (0.5 / std::exp(double(n)*1.5));
        m_stats.push_back(h);
    }
}

void PopularityStatisticsImpl::normalizeHistory(SingleFalloffHistory& h)
{
    //kdDebug() << "Normalize history" << endl;
    double sum = h.iniVal;
    map<TQString, double>::iterator it;
    for (it = h.vals.begin(); it != h.vals.end(); ++it)
    {
        sum += it->second;
    }
    for (it = h.vals.begin(); it != h.vals.end(); ++it)
    {
        it->second = it->second / sum;
    }
    h.iniVal = h.iniVal / sum;
}

void PopularityStatisticsImpl::updateServiceRanks()
{
    // For each service calculate the average over the popularity
    // for all falloff values and then sort by these averaged values

    vector<SingleFalloffHistory>::iterator 
        it(m_stats.begin()), end(m_stats.end());
    map<TQString, double> serviceValSum, serviceValWeightSum;
    int numStats = m_stats.size();
    for (int statIndex = 0; it != end; ++it, ++statIndex)
    {
        // Put more weight on the short term history if m_historyHorizon==0
        // and more on the the long term history for m_historyHorizon==1
        double a = 2*(numStats-1)*m_historyHorizon - numStats + 0.5;
        if (statIndex < a || statIndex > a + numStats)
        {
            continue;
        }

        map<TQString, double>::iterator valIt;
        /*double valSum = 0;
        for (valIt = it->vals.begin(); valIt != it->vals.end(); ++valIt)
        {
            valSum += valIt->second;
        }
        if (valSum == 0) valSum = 1;*/
        for (valIt = it->vals.begin(); valIt != it->vals.end(); ++valIt)
        {
            serviceValWeightSum[valIt->first] += 1;
            serviceValSum[valIt->first] += valIt->second;
        }
    }
    
    m_servicesByPopularity.clear();
    map<TQString, double>::iterator sIt;
    for (sIt = serviceValWeightSum.begin(); 
         sIt != serviceValWeightSum.end(); ++sIt)
    {
        Popularity p;
        p.service = sIt->first;
        assert(sIt->second > 0);
        p.popularity = serviceValSum[sIt->first] / sIt->second;
        m_servicesByPopularity.push_back(p);
    }
    stable_sort(m_servicesByPopularity.begin(), m_servicesByPopularity.end());
    m_serviceRanks.clear();
    for (uint n = 0; n < m_servicesByPopularity.size(); ++n)
    {
        m_serviceRanks[m_servicesByPopularity[n].service] = n;
        /*kdDebug() << TQString("Rank %1: %2 %3").arg(n)
            .arg(m_servicesByPopularity[n].popularity)
            .arg(m_servicesByPopularity[n].service) << endl;*/
    }
}