-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotGraph.py
More file actions
163 lines (120 loc) · 3.3 KB
/
plotGraph.py
File metadata and controls
163 lines (120 loc) · 3.3 KB
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
import code
import collections
import math
import numbers
import threading
import time
import warnings
from warnings import warn as _warn
import matplotlib.pyplot as plt
import numpy as np
class _FRange(collections.Sequence):
# Mind that some methods have not been overriden yet, and the
# complexity of running them might be huge.
__eps = 1e-9
def __init__(self, src, dst, step=1, closed=False):
self.__src = src
self.__dst = dst
self.__step = step
self.__isClosed = closed
def __iter__(self):
return self
def __next__(self):
if not len(self):
raise StopIteration
rep = self.__src
self.__src += self.__step
return rep
def __len__(self):
src, dst, step = self.__src, self.__dst, self.__step
eps = _FRange.__eps
dist = (dst - src) / step
remain = math.floor(dist + eps)
if not (not self.__isClosed and abs((src + remain*step) - dst) < eps):
remain += 1
return max(remain, 0)
def __getitem__(self, k):
return self.__src + __step*k
def viewRect(xlim=None, ylim=None):
"""
Get or set the limits of the XY axes.
Optional Parameters:
xlim - the new X limits.
ylim - the new Y limits.
Returns:
xlim, ylim - the new XY axes.
Remarks:
Both parameters are optional, so call this function with
no parameter to retrieve the axes.
"""
if xlim:
plt.xlim(xlim)
if ylim:
plt.ylim(ylim)
plt.draw()
return dict(xlim=plt.xlim(), ylim=plt.ylim())
def _checkIntegral(x):
return isinstance(x, numbers.Number)
def setFunction(func, domain=(-100, 100), precision=.01):
"""
Set the plotted function.
Parameters:
func - The function f to be plotted.
Optional Parameters:
domain - The domain of the function as tuple (min_x, max_x).
precision - The precision of graph (the length between
neighboring sampled point).
"""
isNumber = _checkIntegral
frange = _FRange
if not (isNumber(precision) and precision > 0):
raise Exception('precision {} is not a positive number.'.format(precision))
elif precision <= 1e-9:
_warn('Precision less than 1e-9 migth have precision error.')
if not (type(domain) == tuple and len(domain)==2 and all(isNumber(x) for x in domain)) :
raise Exception('domain {} is not valid.'.format(domain))
devx, devy = [], []
for x in frange(*domain, precision):
try:
xval, yval = x, func(x)
except:
pass
else:
devx.append(xval)
devy.append(yval)
plt.clf()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Plot of f(x)')
plt.plot(devx, devy, label='f(x)')
plt.legend()
plt.draw()
def _initPlot():
plt.ioff()
plt.gcf().canvas.set_window_title('plotGraph')
setFunction(lambda x: x)
plt.show()
def _latterJoinDict(*args):
sumdict = {}
for dct in args:
for key in dct:
sumdict[key] = dct[key]
return sumdict
def _interactiveShell(extNames={}):
shell = code.InteractiveConsole(_latterJoinDict(globals(), locals(), extNames))
shell.interact()
_plotStarted = False
def startPlot(extNames={}):
"""
Start the plotting functions.
Optional Parameters:
extNames: Extra variables used in interaction.
Exceptions:
Raises Exception if called more than once.
"""
global _plotStarted
if _plotStarted:
raise Exception('startPlot() called more than once.')
_plotStarted = True
threading.Thread(target=_interactiveShell, args=(extNames,)).start()
_initPlot()