source: orange/orange/Orange/misc/__init__.py @ 7742:f8f8bdab658d

Revision 7742:f8f8bdab658d, 5.7 KB checked in by markotoplak, 3 years ago (diff)

Moved orngServerFiles to a new hierarchy.

Line 
1"""
2
3.. index:: misc
4
5Module Orange.misc contains common functions and classes which are used in other modules.
6
7==================
8Counters
9==================
10
11.. index:: misc
12.. index::
13   single: misc; counters
14
15.. automodule:: Orange.misc.counters
16  :members:
17
18==================
19Render
20==================
21
22.. index:: misc
23.. index::
24   single: misc; render
25
26.. automodule:: Orange.misc.render
27  :members:
28
29==================
30Selection
31==================
32
33.. index:: selection
34.. index::
35   single: misc; selection
36
37Many machine learning techniques generate a set different solutions or have to
38choose, as for instance in classification tree induction, between different
39features. The most trivial solution is to iterate through the candidates,
40compare them and remember the optimal one. The problem occurs, however, when
41there are multiple candidates that are equally good, and the naive approaches
42would select the first or the last one, depending upon the formulation of
43the if-statement.
44
45:class:`Orange.misc.selection` provides a class that makes a random choice
46in such cases. Each new candidate is compared with the currently optimal
47one; it replaces the optimal if it is better, while if they are equal,
48one is chosen by random. The number of competing optimal candidates is stored,
49so in this random choice the probability to select the new candidate (over the
50current one) is 1/w, where w is the current number of equal candidates,
51including the present one. One can easily verify that this gives equal
52chances to all candidates, independent of the order in which they are presented.
53
54.. automodule:: Orange.misc.selection
55  :members:
56
57Example
58--------
59
60The following snippet loads the data set lymphography and prints out the
61feature with the highest information gain.
62
63part of `misc-selection-bestonthefly.py`_ (uses `lymphography.tab`_)
64
65.. literalinclude:: code/misc-selection-bestonthefly.py
66  :lines: 7-16
67
68Our candidates are tuples gain ratios and features, so we set
69:obj:`callCompareOn1st` to make the compare function compare the first element
70(gain ratios). We could achieve the same by initializing the object like this:
71
72part of `misc-selection-bestonthefly.py`_ (uses `lymphography.tab`_)
73
74.. literalinclude:: code/misc-selection-bestonthefly.py
75  :lines: 18-18
76
77
78The other way to do it is through indices.
79
80`misc-selection-bestonthefly.py`_ (uses `lymphography.tab`_)
81
82.. literalinclude:: code/misc-selection-bestonthefly.py
83  :lines: 25-
84
85.. _misc-selection-bestonthefly.py: code/misc-selection-bestonthefly.py.py
86.. _lymphography.tab: code/lymphography.tab
87
88Here we only give gain ratios to :obj:`bestOnTheFly`, so we don't have to specify a
89special compare operator. After checking all features we get the index of the
90optimal one by calling :obj:`winnerIndex`.
91
92==================
93Server files
94==================
95
96.. index:: server files
97
98.. automodule:: Orange.misc.serverfiles
99
100"""
101
102import counters
103import selection
104import render
105import serverfiles
106
107__all__ = ["counters", "selection", "render", "serverfiles"]
108
109import random, types, sys
110
111def getobjectname(x, default=""):
112    if type(x)==types.StringType:
113        return x
114     
115    for i in ["name", "shortDescription", "description", "func_doc", "func_name"]:
116        if getattr(x, i, ""):
117            return getattr(x, i)
118
119    if hasattr(x, "__class__"):
120        r = repr(x.__class__)
121        if r[1:5]=="type":
122            return str(x.__class__)[7:-2]
123        elif r[1:6]=="class":
124            return str(x.__class__)[8:-2]
125    return default
126
127
128def demangleExamples(x):
129    if type(x)==types.TupleType:
130        return x
131    else:
132        return x, 0
133
134
135def frange(*argw):
136    start, stop, step = 0.0, 1.0, 0.1
137    if len(argw)==1:
138        start=step=argw[0]
139    elif len(argw)==2:
140        stop, step = argw
141    elif len(argw)==3:
142        start, stop, step = argw
143    elif len(argw)>3:
144        raise AttributeError, "1-3 arguments expected"
145
146    stop+=1e-10
147    i=0
148    res=[]
149    while 1:
150        f=start+i*step
151        if f>stop:
152            break
153        res.append(f)
154        i+=1
155    return res
156
157verbose = 0
158
159def printVerbose(text, *verb):
160    if len(verb) and verb[0] or verbose:
161        print text
162
163class ConsoleProgressBar(object):
164    def __init__(self, title="", charwidth=40, step=1, output=sys.stderr):
165        self.title = title + " "
166        self.charwidth = charwidth
167        self.step = step
168        self.currstring = ""
169        self.state = 0
170        self.output = output
171
172    def clear(self, i=-1):
173        try:
174            if hasattr(self.output, "isatty") and self.output.isatty():
175                self.output.write("\b" * (i if i != -1 else len(self.currstring)))
176            else:
177                self.output.seek(-i if i != -1 else -len(self.currstring), 2)
178        except Exception: ## If for some reason we failed
179            self.output.write("\n")
180
181    def getstring(self):
182        progchar = int(round(float(self.state) * (self.charwidth - 5) / 100.0))
183        return self.title + "=" * (progchar) + ">" + " " * (self.charwidth\
184            - 5 - progchar) + "%3i" % int(round(self.state)) + "%"
185
186    def printline(self, string):
187        try:
188            self.clear()
189            self.output.write(string)
190            self.output.flush()
191        except Exception:
192            pass
193        self.currstring = string
194
195    def __call__(self, newstate=None):
196        if newstate == None:
197            newstate = self.state + self.step
198        if int(newstate) != int(self.state):
199            self.state = newstate
200            self.printline(self.getstring())
201        else:
202            self.state = newstate
203
204    def finish(self):
205        self.__call__(100)
206        self.output.write("\n")
207
208def progressBarMilestones(count, iterations=100):
209    return set([int(i*count/float(iterations)) for i in range(iterations)])
Note: See TracBrowser for help on using the repository browser.