-
Notifications
You must be signed in to change notification settings - Fork 2
/
mlib
315 lines (250 loc) · 9.88 KB
/
mlib
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
# (c) Trin Wasinger 2021-2023
# Load using exec(__import__('requests').get('https://stevebeeblebrox.github.io/mlib').text)
from sympy import *;
import sympy as sym;
import sympy;
import numpy as num;
import numpy;
import IPython as ipy;
import matplotlib.pyplot as plt;
import re as regex;
import math;
import json;
import random;
import platform;
import requests;
import markdown;
import itertools;
from collections import deque;
#from forbiddenfruit import curse;
MLIB_VERSION='1.3.3';
MLIB_MOTD=f'''
**Welcome to MLib version {MLIB_VERSION}!**
Changelog:
+ Added `isclose(a,b,**kwargs)` function
+ New pattern matching functions (`extract(pattern,expr)` and `unknown(name)`)
+ Improved `pzr(r,theta)` phasor and utils
''';
false = False;
true = True;
null = None;
def let(**kwargs):
for key in kwargs:
value = globals()[key] = kwargs[key];
return value;
def nlet(**kwargs):
return sympy.N(let(**kwargs));
def put(**kwargs):
for key in kwargs:
value = let(**{key:kwargs[key]});
prints(f'''{regex.sub(r'(?<=.)_(?P<sub>.*)',lambda match: '_{%s}' % match.group('sub').replace('_', ' '),key)} = ''', value);
return value;
def nput(**kwargs):
for key in kwargs:
value = let(**{key:kwargs[key]});
prints(f'''{regex.sub(r'(?<=.)_(?P<sub>.*)',lambda match: '_{%s}' % match.group('sub').replace('_', ' '),key)} = ''', sympy.N(value));
return sympy.N(value);
def br():
print();
def delete(name):
t = globals()[name];
del globals()[name];
return t;
def var(name,*,__lookup=False,**kwargs):
if name in globals() and isinstance(globals()[name],sympy.Symbol):
if __lookup or sympy.Symbol(name,**kwargs) == globals()[name]:
return globals()[name];
else:
raise NameError('Cannot create two variables with the same name but different assumptions. Delete the old one first.');
globals()[name] = sympy.Symbol(name,**kwargs);
return globals()[name];
def func(name,*symbols):
# TODO, lookup like var()?
globals()[name] = sympy.Function(name)(*symbols);
return globals()[name];
def varlist(*args,**kwargs):
return [var(name.strip(),**kwargs) for names in args for name in regex.split(r'[, ]+', names.strip())];
def try_or(func, fallback=None, expected_exc=(Exception,)):
try:
return func();
except expected_exc:
return fallback() if fallback is not None else None;
# Note, phi is z angle
def RVec(r,theta,phi=None):
if phi is not None:
return Vec(
r*sympy.sin(phi)*sympy.cos(theta),
r*sympy.sin(phi)*sympy.sin(theta),
r*sympy.cos(phi),
);
else:
return Vec(
r*sympy.cos(theta),
r*sympy.sin(theta)
);
# To expand a Vec, use Vec(*Vec(...),0)
def Vec(*args,r=None,theta=None,phi=None):
if r is not None or theta is not None or phi is not None:
if r is not None and theta is not None and len(args) == 0:
return RVec(r,theta,phi);
else:
raise ValueError('theta and mag must be given together instead of *args');
if isinstance(args[0],str):
return sympy.Matrix([[try_or(lambda: int(c), lambda: try_or(lambda: float(c), lambda: mexpr(c[1:], globals=globals(), locals={}) if c.startswith('@') else globals()[c]))] for c in regex.split(r' +', args[0].replace('−','-').replace('−','-').strip())]);
else:
return sympy.Matrix([[x] for x in args]);
def unknown(name):
if not name.startswith('_'):
raise ValueError('Unknown Symbol names must start with a \'_\'');
globals()[name] = sympy.Wild(name);
return globals()[name];
def extract(pattern, expr):
r=pattern.matches(expr);
if r is None:
raise Exception('Could not match pattern!');
for unknown, value in r.items():
globals()[unknown.name[1:]] = value;
return r;
class Vlt(numpy.ndarray):
def __new__(cls, *args):
return numpy.asarray([*args]).view(cls);
def __str__(self):
return super().tolist().__str__();
def __repr__(self):
return super().tolist().__repr__();
def Mtx(str,globals=globals(), locals=locals()):
return sympy.Matrix() if str.strip() == '' else sympy.Matrix([[try_or(lambda: int(c), lambda: try_or(lambda: float(c), lambda: mexpr(c[1:], globals=globals, locals=locals) if c.startswith('@') else locals[c])) for c in regex.split(r' +', r.strip())] for r in regex.split(r'\n|;',str.replace('−','-').strip()) if not r.startswith('#')])
def IdentMtx(n):
return sympy.Matrix([([(row == column) + 0 for column in range(n)]) for row in range(n)]);
def RandMtx(m, n, min = 0, max = 9):
return sympy.Matrix([([random.randint(min, max) for column in range(n)]) for row in range(m)]);
def ZeroMtx(m, n=None):
return sympy.Matrix([([0 for column in range(m if n is None else n)]) for row in range(m)]);
def error(arg):
print("\x1b[1;31m{}\x1b[0;30m".format(arg));
def warn(arg):
print("\x1b[1;33m{}\x1b[0;30m".format(arg));
def execexpr(script, globals=globals(), locals=locals()):
import ast
stmts = list(ast.iter_child_nodes(ast.parse(script)))
if not stmts:
return None
if isinstance(stmts[-1], ast.Expr):
if len(stmts) > 1:
exec(compile(ast.Module(body=stmts[:-1],type_ignores=[]), filename="<ast>", mode="exec"), globals, locals)
return eval(compile(ast.Expression(body=stmts[-1].value), filename="<ast>", mode="eval"), globals, locals)
else:
return exec(script, globals, locals)
# Phazor
def pzr(arg0=0,arg1=None,/):
return f'{pzrlen(arg0):.5f}\u2220{pzrangle(arg0):.5f}\u00b0' if arg1 is None else arg0*cos(rad(deg=arg1))+sympy.I*arg0*sin(rad(deg=arg1));
def pzrlen(phasor):
return sympy.sqrt(sympy.re(phasor)**2+sympy.im(phasor)**2);
def pzrangle(phasor):
return deg(rad=sympy.atan2(*ri(phasor)[::-1])); # atan(y,x)
def ri(arg0, arg1=None,/):
return [sympy.re(arg0), sympy.im(arg0)] if arg1 is None else arg0 + sympy.I * arg1;
from sympy.physics.quantum.dagger import Dagger as dag;
from sympy.functions import conjugate as con;
def veclen(v,/):
return sympy.sqrt(v.dot(v));
def vecangle(v1,v2=None):
if len(v1) == 2:
return sympy.atan2(*v1[::-1]);
else:
return sympy.acos(v1.dot(v2)/(veclen(v1)*veclen(v2)));
def dot(a,b):
return a.dot(b);
def chain(arg1,arg2,*varargs,func):
value = func(arg1, arg2);
for arg in varargs:
value = func(value, arg);
return value;
def cross(*args):
return chain(*args,func=lambda a,b: a.cross(b));
def tensor(*args):
from sympy.physics.quantum import TensorProduct;
return chain(*args,func=TensorProduct);
def invsum(*args):
return 1/sum([1/x for x in args]);
def sqrsum(*args):
return sqrt(sum([x**2 for x in args]));
def stdsum(*args):
return sum(args);
def mexpr(*strs, globals=globals(), locals=locals()):
r = [sympy.parsing.sympy_parser.parse_expr(text.replace('−','-'),global_dict=globals,local_dict=locals,transformations=sympy.parsing.sympy_parser.T[:]) for text in strs];
return r[0] if len(r) == 1 else r;
#curse(int, '__div__', lambda self, other: sympy.S(self)/other);
j = i = sympy.I
e = sympy.E
infinity=sympy.oo
def rad(*,deg):
return sympy.S(deg)/180*sympy.pi;
def deg(*,rad):
return sympy.S(rad)*180/sympy.pi;
def sublist(expr,symbols,values):
for i in range(0,len(values)):
expr = expr.subs(symbols[i],values[i])
return expr;
def sub(arg, values = {},/,**kwargs):
arg = S(arg);
for name, value in kwargs.items():
arg = arg.subs(var(name, __lookup=True), value);
for item in values.items():
arg = arg.subs(*item);
return arg;
def nsub(arg, constants = {}, **kwargs):
return sympy.N(nsimplify(sub(arg,constants,**kwargs)));
fyzx = type('fyzx', (object,), {
'g' : 9.81,'G': 6.67e-11,
'ep0':8.854187812813e-12,
'elcharge':1.60217663e-19,
'emass':9.10938356e-31,
'pmass':1.672621898e-27,
'mu0':1.25663706212e-6,
'h':6.62607015-34
})()
fyzx.c=1/sqrt(fyzx.mu0*fyzx.ep0)
def uvecs():
return [Vec(1,0,0), Vec(0,1,0), Vec(0,0,1)];
def strcheck(str,/):
return bool(s and s.strip());
def isclose(a,b,/,**kwargs):
return math.isclose(sympy.re(a),sympy.re(b),**kwargs) and math.isclose(sympy.im(a),sympy.im(b),**kwargs);
def clamp(value,minv,maxv):
return max(min(value, maxv), minv);
def prints(*args, simplify = False):
display(ipy.display.HTML('<style>span[style="display: block; text-align: center;"] {text-align: left !important;}<style>'));
display(ipy.display.Markdown(f'<span data-force-inline>$${(" ".join([(arg if isinstance(arg,str) else latex(try_or(lambda:sympy.simplify(arg) if simplify else arg,lambda:arg))) for arg in args]))}$$</span>'));
from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic);
from IPython.display import clear_output as clear;
from IPython import get_ipython;
# %%context or %context
@register_line_cell_magic
def context(line, cell=None):
get_ipython().run_line_magic('reset', '-f');
globals()['__mlib'] = True;
exec(__import__('requests').get('https://stevebeeblebrox.github.io/mlib').text, globals());
del globals()['__mlib'];
if line or cell:
display(ipy.display.HTML(f'''<div title="New MLib Context (v{MLIB_VERSION})">{markdown.markdown('# ' + (line or cell))}</div>'''));
else:
display(ipy.display.HTML(f'<hr style="width:40ch;margin-left:0;" title="New MLib Context (v{MLIB_VERSION})">'));
del context;
@register_line_cell_magic
def md(line, cell=None):
display(ipy.display.Markdown(line if cell is None else line+'\n'+cell));
del md;
@register_line_cell_magic
def html(line, cell=None):
display(ipy.display.HTML(line if cell is None else line+'\n'+cell));
del html;
if not '__mlib' in globals() and MLIB_MOTD != None:
display(ipy.display.Markdown(MLIB_MOTD));
display(ipy.display.HTML('''
<style>
span[data-force-inline] div {
display: inline !important;
}
</style>
'''));