1
0

template.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. from abc import ABCMeta, abstractmethod
  2. import os
  3. import logging
  4. from sympy import simplify, count_ops, Float, Integer, Rational, sympify, factor, factor_list, expand, collect, Add, \
  5. Mul, ratsimp, cancel, apart, together, radsimp, trigsimp, expand_trig, expand_mul, expand_multinomial, powdenest, \
  6. powsimp, expand_power_base, expand_power_exp, logcombine, expand_log, ceiling, expand_complex, expand_func, Eq, \
  7. Symbol, solve, true, false, plot
  8. from sympy.plotting import plot3d
  9. from sympy.core.sympify import SympifyError
  10. from system import plugin_class_loading, get_path, plugin_func_loading, basicConfig
  11. logging.basicConfig(**basicConfig)
  12. class DictNameError(Exception):
  13. pass
  14. class SymbolError(Exception):
  15. pass
  16. class ExpError(Exception):
  17. pass
  18. class FormatError(Exception):
  19. pass
  20. class SplitError(Exception):
  21. pass
  22. class MergeError(Exception):
  23. pass
  24. class AlgebraInit:
  25. def __init__(self, new=lambda x: x):
  26. self.symbol_dict = {"self": self} # 命名空间
  27. self.symbol_dict.update(globals())
  28. self.symbol_dict.update(locals())
  29. exec('from sympy import *', self.symbol_dict)
  30. self.algebra_dict = {}
  31. self.algebra_dict_view = {} # 门面(str)
  32. self.symbol_describe = {} # 描述文件
  33. self.out_status = new
  34. logging.info('AlgebraInit init')
  35. def get_expression(self, name, exp_str=False):
  36. try:
  37. if exp_str:
  38. return self.algebra_dict_view[name]
  39. else:
  40. return self.algebra_dict[name]
  41. except KeyError:
  42. raise DictNameError
  43. class AlgebraSymbolBase(AlgebraInit, metaclass=ABCMeta):
  44. @abstractmethod
  45. def del_symbol(self, x):
  46. pass
  47. @abstractmethod
  48. def add_symbol(self, name, is_generation, is_rational, is_prime, is_even, is_finite, is_complex, is_natural,
  49. is_integer, no_constraint, describe):
  50. pass
  51. @abstractmethod
  52. def variable_prediction(self, n):
  53. pass
  54. @plugin_class_loading(get_path(fr"template{os.sep}algebraicfactory"))
  55. class AlgebraSymbol(AlgebraSymbolBase):
  56. def del_symbol(self, x):
  57. del self.symbol_describe[x]
  58. del self.symbol_dict[x]
  59. def add_symbol(
  60. self,
  61. name,
  62. is_generation=0,
  63. is_rational=0,
  64. is_prime=0,
  65. is_even=0,
  66. is_finite=0,
  67. is_complex=None,
  68. is_natural=None,
  69. is_integer=0,
  70. no_constraint=0,
  71. describe="自定义符号",
  72. ):
  73. k = {}
  74. try:
  75. name = name.replace(" ", "")
  76. exec(f"{name} = 5", {}) # 测试name有没有做符号名字的资质
  77. if no_constraint == 1:
  78. raise Exception
  79. if is_generation == 1: # 代数
  80. k["algebraic"] = True
  81. elif is_generation == 2: # 超越数
  82. k["transcendental"] = True
  83. if is_rational == 1: # 有理数
  84. k["rational"] = True
  85. elif is_rational == 2: # 无理数
  86. k["irrational"] = True
  87. if is_prime == 1: # 质数
  88. k["prime"] = True
  89. elif is_prime == 2: # 合数
  90. k["composite"] = True
  91. if is_even == 1: # 偶数
  92. k["even"] = True
  93. elif is_even == 2: # 奇数
  94. k["odd"] = True
  95. if is_finite == 1: # 有限实数
  96. k["finite"] = True
  97. elif is_finite == 2: # 无穷
  98. k["infinite"] = True
  99. elif is_finite == 3: # 广义实数
  100. k["extended_real"] = True
  101. if is_integer == 1:
  102. k["integer"] = True
  103. try: # 避免CIR不是list而是None
  104. k[is_complex[0]] = is_complex[1]
  105. except IndexError:
  106. pass
  107. try: # 避免NZ不是list而是None
  108. k[is_natural[0]] = is_natural[1]
  109. except (TypeError, IndexError):
  110. pass
  111. except (TypeError, IndexError):
  112. pass
  113. new_name = self.symbol_dict.copy()
  114. new_name.update({"k": k})
  115. try:
  116. exec(f"self.symbol_dict['{name}'] = Symbol('{name}', **k)", new_name) # 创建一个Symbols
  117. except BaseException:
  118. logging.error(f"add_symbol exec self.symbol_dict['{name}'] = Symbol('{name}', **k)")
  119. raise SymbolError
  120. self.symbol_describe[name] = describe
  121. return True
  122. def variable_prediction(self, n):
  123. value = self.symbol_dict[n]
  124. get = value.assumptions0
  125. establish_forecast = [] # 成立的预测
  126. no_prediction = [] # 不成立的预测
  127. for i in get:
  128. if get[i]:
  129. establish_forecast.append(f"{interpreter(i)} >>> {get[i]}")
  130. else:
  131. no_prediction.append(f"{interpreter(i)} >>> {get[i]}")
  132. return establish_forecast + no_prediction
  133. class AlgebraExpBase(AlgebraInit, metaclass=ABCMeta):
  134. @abstractmethod
  135. def formula_export(self, f):
  136. pass
  137. @abstractmethod
  138. def format_func(self, args, name, result_str):
  139. pass
  140. @abstractmethod
  141. def format_rational(self, f, result_str):
  142. pass
  143. @abstractmethod
  144. def format_mul(self, args, result_str):
  145. pass
  146. @abstractmethod
  147. def format_add(self, args, result_str):
  148. pass
  149. @abstractmethod
  150. def format_log(self, args, result_str):
  151. pass
  152. @abstractmethod
  153. def format_pow(self, args, f, result_str):
  154. pass
  155. @abstractmethod
  156. def print_expression_core(self, e, level, first, q):
  157. pass
  158. @abstractmethod
  159. def print_expression_str(self, e, level, first):
  160. pass
  161. @abstractmethod
  162. def split_func_core(self, exp, deep, name_list, first):
  163. pass
  164. @abstractmethod
  165. def merge_func_core(self, name_list, func):
  166. pass
  167. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  168. class AlgebraFormat(AlgebraExpBase, metaclass=ABCMeta):
  169. def formula_export(self, f):
  170. result_str = []
  171. try:
  172. name = f.func.__name__
  173. args = f.args
  174. if name == "Pow":
  175. self.format_pow(args, f, result_str)
  176. elif name == "log":
  177. self.format_log(args, result_str)
  178. elif name == "Add":
  179. result_str = self.format_add(args, result_str)
  180. elif name == "Mul":
  181. result_str = self.format_mul(args, result_str)
  182. elif name == "Rational":
  183. self.format_rational(f, result_str)
  184. elif len(args) < 1:
  185. raise FormatError
  186. else: # 增添逗号
  187. result_str = self.format_func(args, name, result_str)
  188. return result_str
  189. except FormatError:
  190. a = str(f)
  191. if a.startswith('-'):
  192. a = f"({a})"
  193. result_str.append(["A", a])
  194. return result_str
  195. def format_func(self, args, name, result_str):
  196. result_str.append(["A", f"{str(name)}( "])
  197. a = 0
  198. for i in args:
  199. get = self.formula_export(i)
  200. if a != 0:
  201. result_str.append(["A", " , "])
  202. result_str += get
  203. a += 1
  204. result_str.append(["A", " )"])
  205. return result_str
  206. def format_rational(self, f, result_str):
  207. q = str(f).split("/")
  208. a = [["A", q[0]]]
  209. b = [["A", q[1]]]
  210. result_str.append(["D", a, b])
  211. def format_mul(self, args, result_str):
  212. a = 0
  213. for i in args:
  214. get = self.formula_export(i)
  215. if a != 0:
  216. result_str.append(["A", " × "])
  217. result_str += get
  218. a += 1
  219. return result_str
  220. def format_add(self, args, result_str):
  221. a = 0
  222. for i in args:
  223. get = self.formula_export(i)
  224. if a != 0:
  225. result_str.append(["A", " + "])
  226. result_str += get
  227. a += 1
  228. return result_str
  229. def format_log(self, args, result_str):
  230. b = self.formula_export(args[0])
  231. result_str.append(["C", [["A", "ln "]], b])
  232. def format_pow(self, args, f, result_str):
  233. try:
  234. if args[1] < 0:
  235. a = [["A", "1"]]
  236. b = self.formula_export(f.func(args[0], -args[1]))
  237. result_str.append(["D", a, b])
  238. else:
  239. raise FormatError
  240. except FormatError:
  241. a = self.formula_export(args[0])
  242. b = self.formula_export(args[1])
  243. result_str.append(["B", a, b])
  244. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  245. class AlgebraPrint(AlgebraExpBase, metaclass=ABCMeta):
  246. def print_expression_core(self, e, level=0, first=True, q=1): # 递归
  247. str_print = " " * level
  248. if first:
  249. str_print = f"[{e}]\n" + str_print
  250. try:
  251. name = e.func.__name__
  252. args = e.args
  253. if args == ():
  254. raise FormatError
  255. if name == "log":
  256. name = "ln"
  257. str_print += f"({q}){name}\n"
  258. n = len(name)
  259. for i in args:
  260. self.out_status("正在迭代运算中")
  261. str_print += self.print_expression_core(
  262. i, level + n, first=False, q=q + 1
  263. )
  264. return str_print
  265. except FormatError:
  266. return str_print + f"({q}){str(e)}\n"
  267. def print_expression_str(self, e, level=0, first=True): # 直接打印
  268. e = simplify(e) # 转换为sympy可以执行的对象
  269. return self.print_expression_core(e, level, first)
  270. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  271. class AlgebraSplit(AlgebraExpBase, metaclass=ABCMeta):
  272. def split_func_core(self, exp, deep, name_list, first=True): # 递归
  273. try:
  274. name = exp.func.__name__
  275. args = exp.args
  276. if name not in name_list or args == ():
  277. if name_list != ["All"]:
  278. raise SplitError
  279. else:
  280. deep = 1
  281. if deep == 1:
  282. if name_list == ["All"] and not first:
  283. re = [exp]
  284. else:
  285. re = []
  286. for i in args:
  287. self.out_status("正在迭代运算中")
  288. get = self.split_func_core(i, deep, name_list, False)
  289. re += get
  290. return re
  291. else:
  292. return args
  293. except SplitError:
  294. return [exp]
  295. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  296. class AlgebraMerge(AlgebraExpBase, metaclass=ABCMeta):
  297. def merge_func_core(self, name_list, func):
  298. if len(name_list) < 2:
  299. raise MergeError('长度小于2')
  300. st = name_list[0]
  301. for n in name_list[1:]:
  302. st = func(st, n)
  303. return st
  304. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  305. class AlgebraBase(AlgebraSymbol, AlgebraFormat, AlgebraPrint, AlgebraSplit, AlgebraMerge):
  306. def the_simplify(self, alg, radio=1.7, func=None, rat=True, inv=False): # 函数简化
  307. if func is None:
  308. func = count_ops
  309. self.out_status("正在标准化")
  310. try:
  311. return simplify(alg, ratio=radio, func=func, rational=rat, inverse=inv)
  312. except SympifyError:
  313. raise ExpError('表达式化简错误')
  314. def creat_num(self, num, num_type):
  315. if num_type == 0: # 浮点数
  316. return Float(num)
  317. elif num_type == 1: # 整数
  318. return Integer(num)
  319. elif num_type == 2: # 有理数
  320. n = num.split("/")
  321. return Rational(n[0], n[1])
  322. else:
  323. return sympify(num, locals=self.symbol_dict)
  324. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  325. class AlgebraVisualization(AlgebraBase):
  326. def add_expression(self, name, alg): # 添加表达式
  327. try:
  328. name = name.replace(" ", "")
  329. try:
  330. exec(f"{name}=5", {}) # 检查name是否符合标准
  331. except SyntaxError:
  332. name = f"F{str(len(self.algebra_dict))}"
  333. eval(f"{alg}", self.symbol_dict) # 检查
  334. self.algebra_dict[name] = sympify(alg, locals=self.symbol_dict)
  335. self.algebra_dict_view[name] = str(alg)
  336. except BaseException as e:
  337. raise ExpError(str(e))
  338. def del_expression(self, name):
  339. del self.algebra_dict[name]
  340. del self.algebra_dict_view[name]
  341. def clean_expression(self):
  342. self.algebra_dict = {}
  343. self.algebra_dict_view = {}
  344. def print_expression(self, name, level=0, first=True): # 根据名字打印
  345. return self.print_expression_core(self.get_expression(name), level, first)
  346. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  347. class AlgebraPolynomialSplit(AlgebraBase):
  348. def split_mul(self, name, return_num=False, return_one=False):
  349. exp = self.get_expression(name)
  350. factor_exp = factor(exp) # 因式分解
  351. split_list = list(factor_list(exp))
  352. useful_exp = []
  353. for i in split_list:
  354. if type(i) in (list, tuple):
  355. split_list += list(i)
  356. else:
  357. try:
  358. if return_num:
  359. if return_one:
  360. raise SplitError
  361. else:
  362. if i == 1:
  363. continue
  364. else:
  365. Float(i)
  366. continue # 排除数字
  367. except SplitError:
  368. pass
  369. useful_exp.append(i)
  370. return useful_exp, factor_exp
  371. def split_add(self, name, collect_exp, return_type):
  372. exp = self.get_expression(name)
  373. exp = expand(exp)
  374. coll = collect(exp, collect_exp)
  375. coll_dict = collect(exp, collect_exp, evaluate=False)
  376. if return_type == 0:
  377. return list(coll_dict.keys()), coll
  378. elif return_type == 1:
  379. return list(coll_dict.values()), coll
  380. else:
  381. re = []
  382. for i in coll_dict:
  383. re.append(i * coll_dict[i])
  384. return re, coll
  385. def split_func(self, name, deep, func_name, return_all=True):
  386. alg = self.get_expression(name)
  387. if func_name == [""]:
  388. try:
  389. return alg.args, alg
  390. except AttributeError:
  391. return None, alg
  392. get = self.split_func_core(alg, deep, func_name)
  393. re = []
  394. if not return_all:
  395. for i in get:
  396. try:
  397. if not i.args:
  398. re.append(i)
  399. except AttributeError:
  400. pass
  401. return re, alg
  402. return get, alg
  403. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  404. class AlgebraPolynomialMerge(AlgebraBase):
  405. def merge_add(self, name_list):
  406. exp = []
  407. for n in name_list:
  408. try:
  409. exp.append(self.get_expression(n))
  410. except DictNameError:
  411. pass
  412. return self.merge_func_core(exp, Add)
  413. def merge_mul(self, name_list):
  414. exp = []
  415. for n in name_list:
  416. try:
  417. exp.append(self.get_expression(n))
  418. except DictNameError:
  419. pass
  420. return self.merge_func_core(exp, Mul)
  421. def merge_func(self, name_list, f):
  422. name = []
  423. func = self.symbol_dict[f]
  424. for n in name_list:
  425. try:
  426. name.append(self.get_expression(n))
  427. except DictNameError:
  428. pass
  429. return self.merge_func_core(name, func)
  430. class AlgebraMath(AlgebraBase, metaclass=ABCMeta):
  431. @abstractmethod
  432. def fractional_merge(self, name):
  433. pass
  434. @abstractmethod
  435. def fraction_reduction(self, name):
  436. pass
  437. @abstractmethod
  438. def fractional_fission(self, name, x):
  439. pass
  440. @abstractmethod
  441. def as_fraction(self, name, deep):
  442. pass
  443. @abstractmethod
  444. def fractional_rat(self, name, rationalized_unknown, maximum_irrational_term):
  445. pass
  446. @abstractmethod
  447. def trig_simp(self, name):
  448. pass
  449. @abstractmethod
  450. def trig_expansion(self, name, deep):
  451. pass
  452. @abstractmethod
  453. def mul_expansion(self, name):
  454. pass
  455. @abstractmethod
  456. def multinomial_expansion(self, name):
  457. pass
  458. @abstractmethod
  459. def pow_simp_multinomial(self, name):
  460. pass
  461. @abstractmethod
  462. def pow_simp_core(self, name, keep_assumptions, combine):
  463. pass
  464. @abstractmethod
  465. def pow_simp_base(self, name, keep_assumptions):
  466. pass
  467. @abstractmethod
  468. def pow_simp_exp(self, name, keep_assumptions):
  469. pass
  470. @abstractmethod
  471. def pow_expansion_base(self, name, deep):
  472. pass
  473. @abstractmethod
  474. def pow_expansion_exp(self, name, deep):
  475. pass
  476. @abstractmethod
  477. def pow_expansion_core(self, name, deep):
  478. pass
  479. @abstractmethod
  480. def log_simp(self, name, keep_assumptions):
  481. pass
  482. @abstractmethod
  483. def log_expansion(self, name, deep, keep_assumptions):
  484. pass
  485. @abstractmethod
  486. def expansion(self, name, is_expand_complex):
  487. pass
  488. @abstractmethod
  489. def factor(self, name, modulus, is_gaussian, deep, rat):
  490. pass
  491. @abstractmethod
  492. def merger_of_similar_items(self, name, x):
  493. pass
  494. @abstractmethod
  495. def expand_complex(self, name):
  496. pass
  497. @abstractmethod
  498. def expand_special(self, name):
  499. pass
  500. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  501. class Fractional(AlgebraMath, metaclass=ABCMeta):
  502. def fractional_merge(self, name): # 最小公分母合并
  503. alg = self.get_expression(name)
  504. return ratsimp(alg)
  505. def fraction_reduction(self, name): # 分式化简
  506. alg = self.get_expression(name)
  507. return cancel(alg)
  508. def fractional_fission(self, name, x): # 分式裂项
  509. x = self.symbol_dict[x]
  510. alg = self.get_expression(name)
  511. return apart(alg, x)
  512. def as_fraction(self, name, deep): # 合成分式
  513. alg = self.get_expression(name)
  514. return together(alg, deep)
  515. def fractional_rat(
  516. self, name, rationalized_unknown, maximum_irrational_term
  517. ): # 分母有理化
  518. alg = self.get_expression(name)
  519. return radsimp(alg, rationalized_unknown, maximum_irrational_term)
  520. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  521. class Trig(AlgebraMath, metaclass=ABCMeta):
  522. def trig_simp(self, name): # 三角化简
  523. alg = self.get_expression(name)
  524. return trigsimp(alg)
  525. def trig_expansion(self, name, deep): # 三角化简
  526. alg = self.get_expression(name)
  527. return expand_trig(alg, deep)
  528. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  529. class AlgebraMul(AlgebraMath, metaclass=ABCMeta):
  530. def mul_expansion(self, name):
  531. alg = self.get_expression(name)
  532. return expand_mul(alg)
  533. def multinomial_expansion(self, name):
  534. alg = self.get_expression(name)
  535. return expand_multinomial(alg)
  536. def pow_simp_multinomial(self, name):
  537. alg = self.get_expression(name)
  538. return powdenest(alg)
  539. def pow_simp_core(self, name, keep_assumptions, combine="all"): # 均处理
  540. alg = self.get_expression(name)
  541. return powsimp(alg, force=keep_assumptions, combine=combine)
  542. def pow_simp_base(self, name, keep_assumptions): # 处理底数
  543. return self.pow_simp_core(name, keep_assumptions, "base")
  544. def pow_simp_exp(self, name, keep_assumptions): # 处理指数
  545. return self.pow_simp_core(name, keep_assumptions, "exp")
  546. def pow_expansion_base(self, name, deep):
  547. alg = self.get_expression(name)
  548. return expand_power_base(alg, deep)
  549. def pow_expansion_exp(self, name, deep):
  550. alg = self.get_expression(name)
  551. return expand_power_exp(alg, deep)
  552. def pow_expansion_core(self, name, deep):
  553. alg = self.get_expression(name)
  554. return expand(
  555. alg,
  556. deep=deep,
  557. log=False,
  558. mul=False,
  559. power_exp=True,
  560. power_base=True,
  561. multinomial=True,
  562. basic=False,
  563. )
  564. def log_simp(self, name, keep_assumptions):
  565. alg = self.get_expression(name)
  566. return logcombine(alg, keep_assumptions)
  567. def log_expansion(self, name, deep, keep_assumptions):
  568. alg = self.get_expression(name)
  569. return expand_log(alg, deep, keep_assumptions)
  570. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  571. class General(AlgebraMath, metaclass=ABCMeta):
  572. def expansion(self, name, is_expand_complex):
  573. alg = self.get_expression(name)
  574. return expand(alg, complex=is_expand_complex)
  575. def factor(self, name, modulus, is_gaussian, deep, rat):
  576. k = {}
  577. if modulus is not None:
  578. k["modulus"] = modulus
  579. if is_gaussian:
  580. k["gaussian"] = True
  581. alg = self.get_expression(name)
  582. return factor(alg, deep=deep, fraction=rat, **k)
  583. def merger_of_similar_items(self, name, x):
  584. alg = self.get_expression(name)
  585. try:
  586. return collect(alg, x)
  587. except BaseException as e:
  588. logging.debug(str(e))
  589. return ceiling(alg)
  590. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  591. class AlgebraComplex(AlgebraMath, metaclass=ABCMeta):
  592. def expand_complex(self, name):
  593. alg = self.get_expression(name)
  594. return expand_complex(alg)
  595. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  596. class AlgebraSpecialFunc(AlgebraMath, metaclass=ABCMeta):
  597. def expand_special(self, name):
  598. alg = self.get_expression(name)
  599. return expand_func(alg)
  600. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  601. class Simultaneous(AlgebraBase):
  602. def value_algebraic_simultaneous(self, name, simultaneous_dict):
  603. alg = self.get_expression(name)
  604. sympy_dict = {}
  605. for i in simultaneous_dict: # i是符号,Dic[i]是代数式名字
  606. try:
  607. v_alg = self.get_expression(simultaneous_dict[i]) # 获得代数式
  608. get = self.symbol_dict[i] # 处理符号
  609. sympy_dict[get] = v_alg
  610. except (DictNameError, KeyError):
  611. pass
  612. return alg.subs(sympy_dict)
  613. def algebragic_value_simultaneous(self, name, simultaneous_dict):
  614. alg = self.get_expression(name)
  615. sympy_dict = {}
  616. for i in simultaneous_dict: # i是代数式名字,Dic[i]是符号
  617. try:
  618. v_alg = self.get_expression(i) # 获得代数式
  619. get = self.symbol_dict[simultaneous_dict[i]] # 处理符号
  620. sympy_dict[v_alg] = get
  621. except (DictNameError, KeyError):
  622. pass
  623. return alg.subs(sympy_dict)
  624. def algebraic_assignment(self, name, simultaneous_dict):
  625. alg = self.get_expression(name)
  626. sympy_dict = {}
  627. for i in simultaneous_dict: # i是符号,Dic[i]是数字
  628. try:
  629. get = self.symbol_dict[i] # 处理符号
  630. sympy_dict[get] = simultaneous_dict[i]
  631. except (DictNameError, KeyError):
  632. pass
  633. return alg.subs(sympy_dict)
  634. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  635. class Sloving(AlgebraBase):
  636. def solving_equations(self, equation_set):
  637. alg = []
  638. x_list = set()
  639. for i in equation_set:
  640. z = self.get_expression(i[0])
  641. y = self.get_expression(i[1])
  642. alg.append(Eq(z, y))
  643. x_list = x_list | alg[-1].atoms(Symbol)
  644. x_list = list(x_list)
  645. result = []
  646. for x in x_list: # 遍历原子
  647. get = solve(alg, x, dict=True)
  648. for i in get: # 遍历答案
  649. for a in i:
  650. result.append((a, i[a]))
  651. return result
  652. def solving_inequality(self, inequalities, inequality_symbol):
  653. inequality_symbol = [">", "<", ">=", "<="][inequality_symbol]
  654. z = self.get_expression(inequalities[0])
  655. y = self.get_expression(inequalities[1])
  656. f = sympify(f"{z} {inequality_symbol} {y}", locals=self.symbol_dict)
  657. answer = solve(f)
  658. if answer is true:
  659. return ["恒成立"]
  660. elif answer is false:
  661. return ["恒不成立"]
  662. get = self.split_func_core(answer, 1, ["Or"])
  663. return get
  664. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  665. class Digitization(AlgebraBase):
  666. def algebraic_digitization(self, name, n):
  667. alg = self.get_expression(name)
  668. return alg.evalf(n)
  669. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  670. class AlgebraSimplify(AlgebraBase):
  671. def simplify(self, name, ratdio=1.7, func=None, rat=True, inv=False):
  672. alg = self.get_expression(name)
  673. return self.the_simplify(alg, ratdio, func, rat, inv)
  674. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  675. class Rewrite(AlgebraBase):
  676. def rewrite_exp(self, name, rewrite_func, rewrite_object, deep=False):
  677. alg = self.get_expression(name)
  678. initial_object = sympify(rewrite_func, locals=self.symbol_dict)
  679. if rewrite_object:
  680. sympify_rewrite_object = [] # 重写对象
  681. for i in rewrite_object:
  682. sympify_rewrite_object.append(sympify(i, locals=self.symbol_dict))
  683. return alg.rewrite(sympify_rewrite_object, initial_object, deep=deep)
  684. else:
  685. return alg.rewrite(initial_object, deep=deep)
  686. @plugin_class_loading(get_path(r"template/algebraicfactory"))
  687. class AlgebraPlot(AlgebraBase):
  688. def plot(self, name, list_2d, list_3d=None):
  689. list_2d = list_2d.copy()
  690. alg = self.get_expression(name)
  691. list_2d[0] = self.symbol_dict[list_2d[0]]
  692. if list_3d is None:
  693. self.out_status("正在绘制图像")
  694. plot(
  695. alg,
  696. tuple(list_2d),
  697. xlabel=f"{list_2d[0]}",
  698. ylabel=f"{alg}",
  699. title="CoTan Algebra",
  700. )
  701. else:
  702. list_3d = list_3d.copy()
  703. list_3d[0] = self.symbol_dict[list_3d[0]]
  704. self.out_status("正在绘制图像")
  705. plot3d(
  706. alg,
  707. tuple(list_2d),
  708. tuple(list_3d),
  709. xlabel=f"{list_2d[0]}",
  710. ylabel=f"{list_3d[0]}",
  711. zlable=f"{alg}",
  712. title="CoTan Algebra",
  713. )
  714. @plugin_func_loading(get_path(r"template/algebraicfactory"))
  715. def interpreter(word: str):
  716. book = {
  717. "algebraic": "代数",
  718. "transcendental": "超越数",
  719. "rational": "有理数",
  720. "irrational": "无理数",
  721. "odd": "奇数",
  722. "even": "偶数",
  723. "negative": "负数",
  724. "positive": "正数",
  725. "zero": "零",
  726. "complex": "复数",
  727. "imaginary": "虚数",
  728. "real": "实数",
  729. "integer": "整数",
  730. "prime": "质数",
  731. "composite": "合数",
  732. "finite": "有限数字",
  733. "infinite": "无穷",
  734. "extended_real": "广义实数",
  735. "commutative": "满足交换律",
  736. "hermitian": "厄米特矩阵",
  737. "nonnegative": "非负数",
  738. "nonpositive": "非正数",
  739. "nonzero": "非零实数",
  740. "noninteger": "非整数",
  741. "extended_nonzero": "广义非零数",
  742. "extended_negative": "广义负数",
  743. "extended_nonpositive": "广义非正数",
  744. "extended_nonnegative": "广义非负数",
  745. "extended_positive": "广义正数",
  746. }
  747. try:
  748. results = book[word]
  749. return f"{results}({word})"
  750. except KeyError:
  751. return word