rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if selected: self.set_selected(selected, jump=True) else: self.set_selected(None, jump=True)
self.set_selected(selected, jump=True)
def fill(self, songs): restore = self.__restore_values selected = (restore and restore.pop(0)) or self.get_selected() model = self.get_model() if len(model) == len(selected): selected = None self.inhibit() model.clear() self._add(songs) self.uninhibit() if selected: self.set_selected(selected, jump=True) else: self.set_selected(None, jump=True)
values = map(util.escape, self.__format(song)) for row in self.get_model(): if row[0] in values:
values = self.__get_format_keys(song) for row in self.__model: if row[0] != ALL and row[1].key in values:
def scroll(self, song): values = map(util.escape, self.__format(song)) for row in self.get_model(): if row[0] in values: self.scroll_to_cell( row.path[0], use_align=True, row_align=0.5) sel = self.get_selection() sel.unselect_all() sel.select_path(row.path[0]) break
try: model, rows = self.get_selection().get_selected_rows()
try: model, paths = self.get_selection().get_selected_rows()
def get_selected(self): try: model, rows = self.get_selection().get_selected_rows() except AttributeError: return [] else: return [model[row][0] for row in rows]
else: return [model[row][0] for row in rows]
else: if not paths: return [] if model[paths[0]][0] == ALL: return [model[p][1].key for p in paths[1:]] + [None] else: return [model[p][1].key for p in paths]
def get_selected(self): try: model, rows = self.get_selection().get_selected_rows() except AttributeError: return [] else: return [model[row][0] for row in rows]
model = self.get_model()
model = self.__model if not len(model): return
def set_selected(self, values, jump=False): model = self.get_model() selection = self.get_selection() if values == self.get_selected(): model, rows = selection.get_selected_rows() for row in rows: self.scroll_to_cell(row) break return elif values is None and selection.path_is_selected((0,)): return
if values == self.get_selected(): model, rows = selection.get_selected_rows() for row in rows: self.scroll_to_cell(row)
if values is None and selection.path_is_selected((0,)): self.scroll_to_cell((0,)) return elif values == self.get_selected(): model, paths = selection.get_selected_rows() for path in paths: self.scroll_to_cell(path)
def set_selected(self, values, jump=False): model = self.get_model() selection = self.get_selection() if values == self.get_selected(): model, rows = selection.get_selected_rows() for row in rows: self.scroll_to_cell(row) break return elif values is None and selection.path_is_selected((0,)): return
elif values is None and selection.path_is_selected((0,)): return
if values is None: selection.select_path((0,)) if jump: self.scroll_to_cell((0,)) return
def set_selected(self, values, jump=False): model = self.get_model() selection = self.get_selection() if values == self.get_selected(): model, rows = selection.get_selected_rows() for row in rows: self.scroll_to_cell(row) break return elif values is None and selection.path_is_selected((0,)): return
first = 0 if values is None: selection.select_path((0,)) else: for row in model: if row[0] in values: selection.select_path(row.path) first = first or row.path[0] if first == 0: selection.select_path((0,)) if jump and len(model): self.scroll_to_cell(first)
first = None if None in values: selection.select_path((0,)) first = ((0,)) for row in model: if row[0] != ALL and row[1].key in values: selection.select_path(row.path) first = first or row.path if jump and first: self.scroll_to_cell(first)
def set_selected(self, values, jump=False): model = self.get_model() selection = self.get_selection() if values == self.get_selected(): model, rows = selection.get_selected_rows() for row in rows: self.scroll_to_cell(row) break return elif values is None and selection.path_is_selected((0,)): return
model = self.get_model()
if len(self.tags) == 1 and tag in self.tags: self.set_selected(values, jump) return
def set_selected_by_tag(self, tag, values, jump=False): model = self.get_model() pattern_values = [] values = set(values) for row in model: if row[1]: song = iter(row[1]).next() if set(song.list(tag)) & values: pattern_values.append(row[0]) self.set_selected(pattern_values, jump)
values = set(values) for row in model: if row[1]: song = iter(row[1]).next() if set(song.list(tag)) & values: pattern_values.append(row[0])
for type, data in self.__model: if type == SONGS: for value in values: if data.all_have(tag, value): pattern_values.append(data.key) break if "" in values: pattern_values.append("")
def set_selected_by_tag(self, tag, values, jump=False): model = self.get_model() pattern_values = [] values = set(values) for row in model: if row[1]: song = iter(row[1]).next() if set(song.list(tag)) & values: pattern_values.append(row[0]) self.set_selected(pattern_values, jump)
def __get_songs(self):
def __get_selected_songs(self, sort=False):
def __get_songs(self): model, rows = self.get_selection().get_selected_rows() s = set() if rows and rows[0] == (0,): for row in model: if row[1]: s.update(row[1]) else: for row in rows: s.update(model[row][1]) return s
if rows and rows[0] == (0,):
if not rows: return s if model[rows[0]][0] == ALL:
def __get_songs(self): model, rows = self.get_selection().get_selected_rows() s = set() if rows and rows[0] == (0,): for row in model: if row[1]: s.update(row[1]) else: for row in rows: s.update(model[row][1]) return s
if row[1]: s.update(row[1])
if row[0] != ALL: s |= row[1].songs
def __get_songs(self): model, rows = self.get_selection().get_selected_rows() s = set() if rows and rows[0] == (0,): for row in model: if row[1]: s.update(row[1]) else: for row in rows: s.update(model[row][1]) return s
s.update(model[row][1])
s |= model[row][1].songs if sort: return sorted(s, key=operator.attrgetter("sort_key"))
def __get_songs(self): model, rows = self.get_selection().get_selected_rows() s = set() if rows and rows[0] == (0,): for row in model: if row[1]: s.update(row[1]) else: for row in rows: s.update(model[row][1]) return s
prefs.connect('clicked', Preferences) select.connect('clicked', self.__all)
s = prefs.connect('clicked', Preferences) self.connect_object('destroy', prefs.disconnect, s) s = select.connect('clicked', self.__all) self.connect_object('destroy', select.disconnect, s)
def __init__(self, library, player): super(PanedBrowser, self).__init__(library, player, limit=False)
def can_filter(self, key):
def __get_filter_pane(self, key): """Get the best pane for filtering etc.""" canditates = []
def can_filter(self, key): for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): return True else: return False
return True else: return False
canditates.append((len(pane.tags), pane)) canditates.sort() return (canditates and canditates[0][1]) or None def can_filter(self, key): return (self.__get_filter_pane(key) is not None)
def can_filter(self, key): for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): return True else: return False
self.__panes[-1].inhibit() for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): pane.set_selected_by_tag(key, values, True) else: pane.set_selected(None, True) self.__panes[-1].uninhibit() self.__panes[-1].get_selection().emit('changed')
filter_pane = self.__get_filter_pane(key) for pane in self.__panes: if pane is filter_pane: filter_pane.set_selected_by_tag(key, values, True) return pane.set_selected(None, True)
def filter(self, key, values): self.__panes[-1].inhibit() for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): pane.set_selected_by_tag(key, values, True) else: pane.set_selected(None, True) self.__panes[-1].uninhibit() self.__panes[-1].get_selection().emit('changed')
for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): return [util.unescape(row[0]) for row in pane.get_model() if row[0] and not row[0].startswith("<")] else: return []
filter_pane = self.__get_filter_pane(key) for pane in self.__panes: if pane is filter_pane: return filter_pane.list(key) pane.set_selected(None, True) return []
def list(self, key): for pane in self.__panes: if (key in pane.tags or (key in PEOPLE and "~people" in pane.tags)): return [util.unescape(row[0]) for row in pane.get_model() if row[0] and not row[0].startswith("<")] else: return []
selected.append("\t".join(pane.get_selected()))
values = pane.get_selected() all = None in values if all: values.remove(None) all = str(int(bool(all))) values.insert(0, all) selected.append("\t".join(values))
def save(self): super(PanedBrowser, self).save() selected = [] for pane in self.__panes: selected.append("\t".join(pane.get_selected())) config.set("browsers", "pane_selection", "\n".join(selected))
PanedBrowser.Pane.set_restore([sel.split("\t") for sel in selected])
pane_values = [sel.split("\t") for sel in selected] for pane in pane_values: try: if int(pane[0]): pane[0] = None else: del pane[0] except (ValueError, IndexError): pass PanedBrowser.Pane.set_restore(pane_values)
def restore(self): super(PanedBrowser, self).restore() selected = config.get("browsers", "pane_selection").split("\n") PanedBrowser.Pane.set_restore([sel.split("\t") for sel in selected])
int(prop_get(prop_if, 'partition-type')) == 0:
int(prop_get(prop_if, 'partition-type'), 16) == 0:
def __build_dev(self, path): """Return the right device instance by determining the supported AccessProtocol""" prop_if = self.__get_dev_prop_interface(path) prop_get = self.__get_dev_property
self.bin.set_state(gst.STATE_PLAYING)
if not self._inhibit_play: self.bin.set_state(gst.STATE_PLAYING)
def _set_paused(self, paused): if paused != self._paused: self._paused = paused if self.song: if not self.bin: if self.__init_pipeline(): self.bin.set_property('uri', self.song("~uri")) else: # Backend error; show message and halt playback ErrorMessage(None, _("Output Error"), _("GStreamer output pipeline could not be " "initialized. The pipeline might be invalid, " "or the device may be in use. Check the " "player preferences.")).run() self._paused = paused = True self.emit((paused and 'paused') or 'unpaused') if self.bin: if not self._paused: self.bin.set_state(gst.STATE_PLAYING) elif self.song.is_file: self.bin.set_state(gst.STATE_PAUSED) else: self.__destroy_pipeline() elif paused is True: # Something wants us to pause between songs, or when # we've got no song playing (probably StopAfterMenu). self.emit('paused') self.__destroy_pipeline()
try: self._times = config.get("plugins", self._pref_name).split()[:7]
try: self._times = config.get("plugins", self._pref_name).split(' ')[:7]
def __init__(self): try: self._times = config.get("plugins", self._pref_name).split()[:7] except: pass else: self._times = (self._times + ["HH:MM"] * 7)[:7] gobject.timeout_add(30000, self._check)
alb = album[0].comma("album").replace('"', '') art = get_artist(album).replace('"', '') sq.set_text('"%s" AND artist:"%s" AND tracks:%d' % (alb, art, get_trackcount(album)) )
alb = '"%s"' % album[0].comma("album").replace('"', '') art = get_artist(album) if art: alb = '%s AND artist:"%s"' % (alb, art.replace('"', '')) sq.set_text('%s AND tracks:%d' % (alb, get_trackcount(album)) )
def __init__(self, album, cache): self.album = album
**NOTE: precision loss if P,Q in the infinite disc INPUT: - P point on self - Q point on self - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points) OUTPUT: the Coleman integrals \int_P^Q w_i for w_i basis elements
Computes the Coleman integrals on basis differentials INPUT: - P point on self - Q point on self - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points) OUTPUT: the Coleman integrals \int_P^Q w_i for w_i basis elements
def coleman_integrals_on_basis(self, P, Q, algorithm=None): """
dim = 2*self.genus()
prec = K.precision_cap() g = self.genus() dim = 2*g
def coleman_integrals_on_basis(self, P, Q, algorithm=None): """
L = [f(R(PP[0]), R(PP[1])) for f in forms]
L = [f(PP[0], PP[1]) for f in forms]
def coleman_integrals_on_basis(self, P, Q, algorithm=None): """
A simple example, integrating dx::
A simple example, integrating dx:
def coleman_integral(self, w, P, Q, algorithm = 'None'): """ INPUT: - w differential (if one of P,Q is Weierstrass, w must be odd) - P point on self - Q point on self - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
Yet another example::
Yet another example:
def coleman_integral(self, w, P, Q, algorithm = 'None'): """ INPUT: - w differential (if one of P,Q is Weierstrass, w must be odd) - P point on self - Q point on self - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
R = self.base_ring()[str(self.variables()[0])]
if self.is_constant(): R = self.base_ring()[self.parent().variable_names()[0]] else: R = self.base_ring()[str(self.variables()[0])]
def univariate_polynomial(self, R=None): """ Returns a univariate polynomial associated to this multivariate polynomial. INPUT: - ``R`` - (default: None) PolynomialRing If this polynomial is not in at most one variable, then a ValueError exception is raised. This is checked using the is_univariate() method. The new Polynomial is over the same base ring as the given MPolynomial. EXAMPLES:: sage: R.<x,y> = QQbar[] sage: f = 3*x^2 - 2*y + 7*x^2*y^2 + 5 sage: f.univariate_polynomial() Traceback (most recent call last): ... TypeError: polynomial must involve at most one variable sage: g = f.subs({x:10}); g 700*y^2 + (-2)*y + 305 sage: g.univariate_polynomial () 700*y^2 - 2*y + 305 sage: g.univariate_polynomial(PolynomialRing(QQ,'z')) 700*z^2 - 2*z + 305
def eval(self, command, **kwds):
def eval(self, command, *args, **kwds):
def eval(self, command, **kwds): """ Evaluates commands.
'scilab-5.0...'
'scilab-...'
def version(self): """ Returns the version of the Scilab software used.
The log function also works in finite fields as long as the base is generator of the multiplicative group::
The log function also works in finite fields as long as the argument lies in the multiplicative group generated by the base::
def log(x, base=None): """ Return the logarithm of x to the given base. Calls the ``log`` method of the object x when computing the logarithm, thus allowing use of logarithm on any object containing a ``log`` method. In other words, log works on more than just real numbers. EXAMPLES:: sage: log(e^2) 2 sage: log(1024, 2); RDF(log(1024, 2)) 10 10.0 sage: log(10, 4); RDF(log(10, 4)) log(10)/log(4) 1.66096404744 :: sage: log(10, 2) log(10)/log(2) sage: n(log(10, 2)) 3.32192809488736 sage: log(10, e) log(10) sage: n(log(10, e)) 2.30258509299405 The log function works for negative numbers, complex numbers, and symbolic numbers too, picking the branch with angle between `-pi` and `pi`:: sage: log(-1+0*I) I*pi sage: log(CC(-1)) 3.14159265358979*I sage: log(-1.0) 3.14159265358979*I For input zero, the following behavior occurs:: sage: log(0) -Infinity sage: log(CC(0)) -infinity sage: log(0.0) -infinity The log function also works in finite fields as long as the base is generator of the multiplicative group:: sage: F = GF(13); g = F.multiplicative_generator(); g 2 sage: a = F(8) sage: log(a,g); g^log(a,g) 3 8 sage: log(a,3) Traceback (most recent call last): ... ValueError: base (=3) for discrete log must generate multiplicative group The log function also works for p-adics (see documentation for p-adics for more information):: sage: R = Zp(5); R 5-adic Ring with capped relative precision 20 sage: a = R(16); a 1 + 3*5 + O(5^20) sage: log(a) 3*5 + 3*5^2 + 3*5^4 + 3*5^5 + 3*5^6 + 4*5^7 + 2*5^8 + 5^9 + 5^11 + 2*5^12 + 5^13 + 3*5^15 + 2*5^16 + 4*5^17 + 3*5^18 + 3*5^19 + O(5^20) """ if base is None: try: return x.log() except AttributeError: return ln(x) else: try: return x.log(base) except (AttributeError, TypeError): return log(x) / log(base)
ValueError: base (=3) for discrete log must generate multiplicative group
ValueError: No discrete log of 8 found to base 3 sage: log(F(9), 3) 2
def log(x, base=None): """ Return the logarithm of x to the given base. Calls the ``log`` method of the object x when computing the logarithm, thus allowing use of logarithm on any object containing a ``log`` method. In other words, log works on more than just real numbers. EXAMPLES:: sage: log(e^2) 2 sage: log(1024, 2); RDF(log(1024, 2)) 10 10.0 sage: log(10, 4); RDF(log(10, 4)) log(10)/log(4) 1.66096404744 :: sage: log(10, 2) log(10)/log(2) sage: n(log(10, 2)) 3.32192809488736 sage: log(10, e) log(10) sage: n(log(10, e)) 2.30258509299405 The log function works for negative numbers, complex numbers, and symbolic numbers too, picking the branch with angle between `-pi` and `pi`:: sage: log(-1+0*I) I*pi sage: log(CC(-1)) 3.14159265358979*I sage: log(-1.0) 3.14159265358979*I For input zero, the following behavior occurs:: sage: log(0) -Infinity sage: log(CC(0)) -infinity sage: log(0.0) -infinity The log function also works in finite fields as long as the base is generator of the multiplicative group:: sage: F = GF(13); g = F.multiplicative_generator(); g 2 sage: a = F(8) sage: log(a,g); g^log(a,g) 3 8 sage: log(a,3) Traceback (most recent call last): ... ValueError: base (=3) for discrete log must generate multiplicative group The log function also works for p-adics (see documentation for p-adics for more information):: sage: R = Zp(5); R 5-adic Ring with capped relative precision 20 sage: a = R(16); a 1 + 3*5 + O(5^20) sage: log(a) 3*5 + 3*5^2 + 3*5^4 + 3*5^5 + 3*5^6 + 4*5^7 + 2*5^8 + 5^9 + 5^11 + 2*5^12 + 5^13 + 3*5^15 + 2*5^16 + 4*5^17 + 3*5^18 + 3*5^19 + O(5^20) """ if base is None: try: return x.log() except AttributeError: return ln(x) else: try: return x.log(base) except (AttributeError, TypeError): return log(x) / log(base)
- ``m``, ``n`` - two moduli, or None.
- ``m``, ``n`` - (default: ``None``) two moduli, or ``None``.
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
If ``m``, ``n`` are not None, returns a solution `x` to the
If ``m``, ``n`` are not ``None``, returns a solution `x` to the
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`.
n`, if one exists. By the Chinese Remainder Theorem, a solution to the simultaneous congruences exists if and only if `a\equiv b\pmod{\gcd(m,n)}`. The solution `x` is only well-defined modulo `\text{lcm}(m,n)`.
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
EXAMPLES::
.. SEEALSO:: - :func:`CRT_list` EXAMPLES: Using ``crt`` by giving it pairs of residues and moduli::
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
sage: crt(13,20,100,301)
sage: crt(13, 20, 100, 301) 28013 sage: crt([2, 1], [3, 5]) 11 sage: crt([13, 20], [100, 301])
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
if isinstance(a, list): return CRT_list(a, b) g, alpha, beta = XGCD(m, n) q, r = (b - a).quo_rem(g) if r != 0: raise ValueError("No solution to crt problem since gcd(%s,%s) does not divide %s-%s" % (m, n, a, b)) return (a + q*alpha*m) % lcm(m, n)
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity.
def valuation(m,*args1, **args2): """ This actually just calls the m.valuation() method. See the documentation of m.valuation() for a more precise description. Use of this function by developers is discouraged. Use m.valuation() instead. .. NOTE:: This is not always a valuation in the mathematical sense. For more information see: sage.rings.finite_rings.integer_mod.IntegerMod_int.valuation
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
""" if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): r += 1 power *= p return r
sage: y = QQ['y'].gen() sage: valuation(y^3, y) 3 sage: x = QQ[['x']].gen() sage: valuation((x^3-x^2)/(x-4)) 2 sage: valuation(4r,2r) 2 """ if isinstance(m,(int,long)): m=ZZ(m) return m.valuation(*args1, **args2)
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
sage: cmp(P1xP1, 1)
sage: cmp(P1xP1, 1) * cmp(1, P1xP1)
def __cmp__(self, right): r""" Compare ``self`` and ``right``.
- ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function
- ``algorithm`` - string (default: 'gmp'): - ``'gmp'`` - use the GMP C-library factorial function
def factorial(n, algorithm='gmp'): r""" Compute the factorial of `n`, which is the product `1\cdot 2\cdot 3 \cdots (n-1)\cdot n`. INPUT: - ``n`` - an integer - ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function OUTPUT: an integer EXAMPLES:: sage: from sage.rings.arith import factorial sage: factorial(0) 1 sage: factorial(4) 24 sage: factorial(10) 3628800 sage: factorial(1) == factorial(0) True sage: factorial(6) == 6*5*4*3*2 True sage: factorial(1) == factorial(0) True sage: factorial(71) == 71* factorial(70) True sage: factorial(-32) Traceback (most recent call last): ... ValueError: factorial -- must be nonnegative PERFORMANCE: This discussion is valid as of April 2006. All timings below are on a Pentium Core Duo 2Ghz MacBook Pro running Linux with a 2.6.16.1 kernel. - It takes less than a minute to compute the factorial of `10^7` using the GMP algorithm, and the factorial of `10^6` takes less than 4 seconds. - The GMP algorithm is faster and more memory efficient than the PARI algorithm. E.g., PARI computes `10^7` factorial in 100 seconds on the core duo 2Ghz. - For comparison, computation in Magma `\leq` 2.12-10 of `n!` is best done using ``*[1..n]``. It takes 113 seconds to compute the factorial of `10^7` and 6 seconds to compute the factorial of `10^6`. Mathematica V5.2 compute the factorial of `10^7` in 136 seconds and the factorial of `10^6` in 7 seconds. (Mathematica is notably very efficient at memory usage when doing factorial calculations.) """ if n < 0: raise ValueError, "factorial -- must be nonnegative" if algorithm == 'gmp': return ZZ(n).factorial() elif algorithm == 'pari': return pari.factorial(n) else: raise ValueError, 'unknown algorithm'
modulo `m\*n`.
modulo `m*n`.
def crt(a,b,m=None,n=None): r""" Use the Chinese Remainder Theorem to find some `x` such that `x=a \bmod m` and `x=b \bmod n`. Note that `x` is only well-defined modulo `m\*n`. EXAMPLES:: sage: crt(2, 1, 3, 5) -4 sage: crt(13,20,100,301) -2087 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) if g != 1: raise ValueError, "arguments a and b must be coprime" return a+(b-a)*alpha*m
sage: r.install_package('Hmisc') [1] 4 5 6 """ if UNAME == "Darwin": warn = "** You are using OS X. Unfortunately, the R optional package system currently doesn't support OS X very well. We are working on this. **" else: warn = None if warn is not None: print warn
sage: r.install_packages('aaMI') ... R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. ... Please restart Sage in order to use 'aaMI'. """
def install_packages(self, package_name): """ Install an R package into Sage's R installation.
print "Please restart Sage or restart the R interface (via r.restart()) in order to use '%s'."%package_name if warn is not None: print warn
print "Please restart Sage in order to use '%s'."%package_name
def install_packages(self, package_name): """ Install an R package into Sage's R installation.
command = 'magma'
command = 'sage-native-execute magma'
def __init__(self, maxread=10000, script_subdirectory=None, logfile=None, server=None, server_tmpdir=None, user_config=False): """ INPUT: - ``maxread`` - affects buffering - ``script_subdirectory`` - directory where scripts are read from - ``logfile`` - output logged to this file - ``server`` - address of remote server - ``user_config`` - if True, then local user configuration files will be read by Magma. If False (the default), then Magma is started with the -n option which suppresses user configuration files. EXAMPLES:: sage: Magma(maxread=1000, logfile=tmp_filename()) Magma """ #command = 'magma -b ' command = 'magma' if not user_config: command += ' -n' Expect.__init__(self, name = "magma", prompt = ">>SAGE>>", command = command, maxread = maxread, server = server, server_tmpdir = server_tmpdir, script_subdirectory = script_subdirectory, restart_on_ctrlc = False, logfile = logfile, eval_using_file_cutoff=100) # We use "-n" above in the Magma startup command so # local user startup configuration is not read.
console('magma')
console('sage-native-execute magma')
def magma_console(): """ Run a command line Magma session. EXAMPLES:: sage: magma_console() # not tested Magma V2.14-9 Sat Oct 11 2008 06:36:41 on one [Seed = 1157408761] Type ? for help. Type <Ctrl>-D to quit. > Total time: 2.820 seconds, Total memory usage: 3.95MB """ console('magma')
'Sphere center 1.0 2.0 3.0 Rad 0.015 texture84'
'Sphere center 1.0 2.0 3.0 Rad 0.015 texture85'
def tachyon_repr(self, render_params): """ Returns representation of the point suitable for plotting using the Tachyon ray tracer.
['g obj_1', 'usemtl texture86']
['g obj_1', 'usemtl texture87']
def obj_repr(self, render_params): """ Returns complete representation of the point as a sphere.
'FCylinder base 1.0 0.0 0.0 apex 0.999950000417 0.00999983333417 0.0001 rad 0.005 texture126'
'FCylinder base 1.0 0.0 0.0 apex 0.999950000417 0.00999983333417 0.0001 rad 0.005 texture127'
def tachyon_repr(self, render_params): """ Returns representation of the line suitable for plotting using the Tachyon ray tracer.
if any([type(arg).__module__ == 'numpy' for arg in args]):
if any([type(arg).__module__ == 'numpy' and type(arg).__name__ == "ndarray" for arg in args]):
def _call_element_(self, _the_element, *args, **kwds): """ Calling a callable symbolic expression returns a symbolic expression with the appropriate arguments substituted. EXAMPLES:: sage: var('a, x, y, z') (a, x, y, z) sage: f(x,y) = a + 2*x + 3*y + z sage: f (x, y) |--> a + 2*x + 3*y + z sage: f(1,2) a + z + 8 sage: f(y=2, a=-1) 2*x + z + 5 Note that keyword arguments will override the regular arguments. :: sage: f.arguments() (x, y) sage: f(1,2) a + z + 8 sage: f(10,2) a + z + 26 sage: f(10,2,x=1) a + z + 8 sage: f(z=100) a + 2*x + 3*y + 100 """ if any([type(arg).__module__ == 'numpy' for arg in args]): # avoid importing raise NotImplementedError("Numpy arrays are not supported as arguments for symbolic expressions")
""" S = self.__heilbronn_operator(self, [[-d,0, 0,d]], 1)
We test that the sign issue at sage: M = Newforms(Gamma1(13),names = 'a')[0].modular_symbols(sign=0) sage: M.diamond_bracket_operator(4) Hecke module morphism defined by the matrix [ 0 0 1 -1] [-1 -1 0 1] [-1 -1 0 0] [ 0 -1 1 -1] Domain: Modular Symbols subspace of dimension 4 of Modular Symbols space ... Codomain: Modular Symbols subspace of dimension 4 of Modular Symbols space ... """ S = self.__heilbronn_operator(self, [[d,0, 0,d]], 1)
def diamond_bracket_operator(self, d): r""" Return the diamond bracket d operator on this modular symbols space.
def induced_subgraph_search(self, G):
def subgraph_search(self, G, induced=False):
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
Returns an induced copy of `G` in self.
Returns a copy of ``G`` in ``self``.
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
- ``G`` -- the graph whose copy we are looking for in ``self``
- ``G`` -- the graph whose copy we are looking for in ``self``. - ``induced`` -- boolean (default: ``False``). Whether or not to search for an induced copy of ``G`` in ``self``. OUTPUT: - If ``induced=False``, return a copy of ``G`` in this graph. Otherwise, return an induced copy of ``G`` in ``self``. If ``G`` is the empty graph, return the empty graph since it is a subgraph of every graph. Now suppose ``G`` is not the empty graph. If there is no copy (induced or otherwise) of ``G`` in ``self``, we return ``None``.
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
Brute-force
Brute-force search.
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
A Petersen Graph contains a `P_5` ::
The Petersen graph contains the path graph `P_5`::
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
sage: h1 = g.induced_subgraph_search(graphs.PathGraph(5)) sage: h1
sage: h1 = g.subgraph_search(graphs.PathGraph(5)); h1
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
It also contains a Claw (`K_{1,3}`):: sage: h2 = g.induced_subgraph_search(graphs.ClawGraph()) sage: h2
It also contains the claw `K_{1,3}`:: sage: h2 = g.subgraph_search(graphs.ClawGraph()); h2
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
Of course both copies are isomorphic to the graphs we were looking for :: sage: h1.is_isomorphic(graphs.PathGraph(5))
sage: I2 = g.subgraph_search(graphs.ClawGraph(), induced=True); I2 Subgraph of (Petersen graph): Graph on 4 vertices sage: I2.vertices() [0, 1, 4, 5] Of course the induced copies are isomorphic to the graphs we were looking for:: sage: I1.is_isomorphic(graphs.PathGraph(5))
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
sage: h2.is_isomorphic(graphs.ClawGraph())
sage: I2.is_isomorphic(graphs.ClawGraph())
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
However, as it contains no induced subgraphs isomorphic to `P_6`, an exception is raised in this case :: sage: g.induced_subgraph_search(graphs.PathGraph(6)) Traceback (most recent call last): ... ValueError: No induced copy of the graph exists
However, the Petersen graph does not contain a subgraph isomorphic to `K_3`:: sage: g.subgraph_search(graphs.CompleteGraph(3)) is None True Nor does it contain a nonempty induced subgraph isomorphic to `P_6`:: sage: g.subgraph_search(graphs.PathGraph(6), induced=True) is None True The empty graph is a subgraph of every graph:: sage: g.subgraph_search(graphs.EmptyGraph()) Graph on 0 vertices sage: g.subgraph_search(graphs.EmptyGraph(), induced=True) Graph on 0 vertices
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
H = subgraph_search(self, G, induced = True)
from sage.graphs.graph_generators import GraphGenerators if G.order() == 0: return GraphGenerators().EmptyGraph() H = subgraph_search(self, G, induced=induced)
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
raise ValueError('No induced copy of the graph exists') return self.subgraph(H) def subgraph_search(self, G): r""" Returns an of `G` included in self. INPUT: - ``G`` -- the graph whose copy we are looking for in ``self`` ALGORITHM: Brute-force EXAMPLES: A Petersen Graph contains a `P_5` :: sage: g = graphs.PetersenGraph() sage: h1 = g.subgraph_search(graphs.PathGraph(5)) sage: h1 Subgraph of (Petersen graph): Graph on 5 vertices sage: h1.vertices() [0, 1, 2, 3, 4] It also contains a Claw (`K_{1,3}`):: sage: h2 = g.subgraph_search(graphs.ClawGraph()) sage: h2 Subgraph of (Petersen graph): Graph on 4 vertices sage: h2.vertices() [0, 1, 4, 5] However, as it contains no subgraph isomorphic to `K_3`, an exception is raised in this case :: sage: g.subgraph_search(graphs.CompleteGraph(3)) Traceback (most recent call last): ... ValueError: No copy of the graph exists """ from sage.graphs.generic_graph_pyx import subgraph_search H = subgraph_search(self, G) if H == []: raise ValueError('No copy of the graph exists')
return None
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
linewidths = options['linewidths']
linewidths = options.get('linewidths',None)
def _render_on_subplot(self, subplot): """ TESTS:
linestyles = options['linestyles']
linestyles = options.get('linestyles',None)
def _render_on_subplot(self, subplot): """ TESTS:
@suboptions('label', fontsize=9, colors=None, inline=None, inline_spacing=3, fmt="%1.2f")
@suboptions('label', fontsize=9, colors='blue', inline=None, inline_spacing=3, fmt="%1.2f")
def _render_on_subplot(self, subplot): """ TESTS:
If fill is True (the default), then we may have to color the labels so that we can see them::
We can change the color of the labels if so desired::
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables `x`, `y`:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) :: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) :: sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) :: sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') :: sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) :: sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) :: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') :: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: P :: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed']) sage: P We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',\ ... labels=True, label_fmt="%1.0f", label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',labels=True,\ ... contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: P :: sage: P= contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline=False) sage: P If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) :: sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
sage: f = attrcall('core', 3) sage: loads(dumps(f))
sage: f = attrcall('core', 3); f
def __init__(self, name, args, kwds): """ TESTS:: sage: f = attrcall('core', 3) sage: loads(dumps(f)) *.core(3) """ self.name = name self.args = args self.kwds = kwds
def __eq__(self, other): """ Equality testing EXAMPLES:: sage: attrcall('core', 3, flatten = True) == attrcall('core', 3, flatten = True) True sage: attrcall('core', 2) == attrcall('core', 3) False sage: attrcall('core', 2) == 1 False """ return self.__class__ == other.__class__ and self.__dict__ == other.__dict__ def __ne__(self, other): """ Equality testing EXAMPLES:: sage: attrcall('core', 3, flatten = True) != attrcall('core', 3, flatten = True) False sage: attrcall('core', 2) != attrcall('core', 3) True sage: attrcall('core', 2) != 1 True """ return not self == other
def __repr__(self): """ Returns a string representation of this object. The star in the output represents the object passed into self. EXAMPLES:: sage: attrcall('core', 3) *.core(3) sage: attrcall('hooks', flatten=True) *.hooks(flatten=True) sage: attrcall('hooks', 3, flatten=True) *.hooks(3, flatten=True) """ s = "*.%s(%s"%(self.name, ", ".join(map(repr, self.args))) if self.kwds: if len(self.args) > 0: s += ", " s += ", ".join("%s=%s"%keyvalue for keyvalue in self.kwds.items()) s += ")" return s
if not principal_flag: pi = K.uniformizer(P, 'negative') pie = pi a1 /= pie pie *= pi a2 /= pie pie *= pi a3 /= pie pie *= pi a4 /= pie pie *= pi pie *= pi a6 /= pie
if pi_neg is None: if principal_flag: pi_neg = pi else: pi_neg = K.uniformizer(P, 'negative') pi_neg2 = pi_neg*pi_neg pi_neg3 = pi_neg*pi_neg2 pi_neg4 = pi_neg*pi_neg3 pi_neg6 = pi_neg4*pi_neg2 a1 /= pi_neg a2 /= pi_neg2 a3 /= pi_neg3 a4 /= pi_neg4 a6 /= pi_neg6
def _pcubicroots(b, c, d): r""" Local function returning the number of roots of `x^3 + b*x^2 + c*x + d` modulo `P`, counting multiplicities """ return sum([rr[1] for rr in PolynomialRing(F, 'x')([d, c, b, 1]).roots()],0)
if len(value) > parent.degree(): raise ValueError, "list too long" self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() for i in range(len(value)): self.__value = self.__value + pari(int(value[i])).Mod(parent._pari_modulus())*pari("a^%s"%i)
self.__value = (pari(value).Polrev("a") * parent._pari_one()).Mod(parent._pari_modulus())
def __init__(self, parent, value, check=True): """ Create element of a finite field. EXAMPLES:: sage: from sage.rings.finite_rings.finite_field_ext_pari import FiniteField_ext_pari sage: k = FiniteField_ext_pari(9,'a') sage: a = k(11); a 2 sage: a.parent() Finite Field in a of size 3^2 sage: V = k.vector_space(); v = V((1,2)) sage: k(v) 2*a + 1 """ field_element.FieldElement.__init__(self, parent) self.__class__ = dynamic_FiniteField_ext_pariElement if isinstance(value, str): raise TypeError, "value must not be a string" if not check: if not value: # see comment below about this workaround self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() else: self.__value = value return try: if isinstance(value, pari_gen): try: # In some cases we get two different versions of # the 0 element of a finite field. This has to do # with how PARI's Mod function works -- it treats # 0 differently. In particular, if value is a a # pari t_POLMOD that is 0, modding it simply # doesn't work correctly. We fix this by changing # the value in the 0 case to the standard pari 0, # which works correctly. Note -- probably all # this code should be replaced by much faster # finite field arithmetic programmed against NTL. if not value: value = pari(0) if value.type() == "t_POLMOD": self.__value = value * parent._pari_one() else: self.__value = value.Mod(parent._pari_modulus())*parent._pari_one() except RuntimeError: raise TypeError, "no possible coercion implemented" elif isinstance(value, FiniteField_ext_pariElement): if parent != value.parent(): raise TypeError, "no coercion implemented" else: self.__value = value.__value elif isinstance(value, FreeModuleElement): if parent.vector_space() != value.parent(): raise TypeError, "e.parent must match self.vector_space" self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() for i in range(len(value)): self.__value = self.__value + pari(int(value[i])).Mod(parent._pari_modulus())*pari("a^%s"%i) elif isinstance(value, list): if len(value) > parent.degree(): # could do something here... raise ValueError, "list too long" self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() for i in range(len(value)): self.__value = self.__value + pari(int(value[i])).Mod(parent._pari_modulus())*pari("a^%s"%i) else: try: self.__value = pari(value).Mod(parent._pari_modulus())*parent._pari_one() except RuntimeError: raise TypeError, "no coercion implemented"
flags = [re.IGNORECASE]
flags = re.IGNORECASE
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
flags = []
flags = 0
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
if re.search(string, line, *flags):
if re.search(string, line, flags):
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
if re.search(string, line, *flags)]
if re.search(string, line, flags)]
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
re.MULTILINE, *flags),
re.MULTILINE | flags),
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: V = VectorSpace(QQ,5,sparse=True) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U
sage: VV = VectorSpace(QQ,5,sparse=True) sage: UU = VV.submodule([ VV.gen(i) - VV.gen(0) for i in range(1,5) ]) sage: print UU
def _repr_(self): """ The printing representation of self. EXAMPLES:: sage: V = VectorSpace(QQ,5) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U # indirect doctest Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] sage: print U._repr_() Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] The system representation can be overwritten, but leaves _repr_ unmodified. :: sage: U.rename('U') sage: print U U sage: print U._repr_() Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] Sparse vector spaces print this fact. :: sage: V = VectorSpace(QQ,5,sparse=True) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U # indirect doctest Sparse vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] """ if self.is_sparse(): return "Sparse vector space of degree %s and dimension %s over %s\n"%( self.degree(), self.dimension(), self.base_field()) + \ "User basis matrix:\n%s"%self.basis_matrix() else: return "Vector space of degree %s and dimension %s over %s\n"%( self.degree(), self.dimension(), self.base_field()) + \ "User basis matrix:\n%s"%self.basis_matrix()
sage: V = VectorSpace(QQ,5,sparse=True) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U
sage: VV = VectorSpace(QQ,5,sparse=True) sage: UU = VV.submodule([ VV.gen(i) - VV.gen(0) for i in range(1,5) ]) sage: print UU
def _repr_(self): """ The default printing representation of self. EXAMPLES:: sage: V = VectorSpace(QQ,5) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U # indirect doctest Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] sage: print U._repr_() Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] The system representation can be overwritten, but leaves _repr_ unmodified. :: sage: U.rename('U') sage: print U U sage: print U._repr_() Vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] Sparse vector spaces print this fact. :: sage: V = VectorSpace(QQ,5,sparse=True) sage: U = V.submodule([ V.gen(i) - V.gen(0) for i in range(1,5) ]) sage: print U # indirect doctest Sparse vector space of degree 5 and dimension 4 over Rational Field Basis matrix: [ 1 0 0 0 -1] [ 0 1 0 0 -1] [ 0 0 1 0 -1] [ 0 0 0 1 -1] """ if self.is_sparse(): return "Sparse vector space of degree %s and dimension %s over %s\n"%( self.degree(), self.dimension(), self.base_field()) + \ "Basis matrix:\n%s"%self.basis_matrix() else: return "Vector space of degree %s and dimension %s over %s\n"%( self.degree(), self.dimension(), self.base_field()) + \ "Basis matrix:\n%s"%self.basis_matrix()
more planar areas get fewer triangles, and areas with higher curvature get more triangles
more planar areas get fewer triangles, and areas with higher curvature get more triangles.
def get_colors(self, list): """ Parameters: list: an iterable collection of values which can be cast into colors -- typically an RGB triple, or an RGBA 4-tuple Returns: a list of single parameters which can be passed into the set_color method of the Triangle or SmoothTriangle objects generated by this factory. TESTS:: sage: from sage.plot.plot3d.tri_plot import TriangleFactory sage: factory = TriangleFactory() sage: factory.get_colors([1,2,3]) [1, 2, 3] """ return list
- ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions.
- ``solution_dict`` - bool (default: False); if True or non-zero, return a list of dictionaries containing the solutions. If there are no solutions, return an empty list (rather than a list containing an empty dictionary). Likewise, if there's only a single solution, return a list containing one dictionary with that solution.
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
If we ask for a dictionary for the solutions, we get it::
If we ask for dictionaries containing the solutions, we get them::
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x]
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] sage: solve(0==1,x) Traceback (most recent call last): ... TypeError: object of type 'bool' has no len() Test if the empty list is returned, too, when (a list of) dictionaries (is) are requested ( sage: solve([0==1],x) [] sage: solve([0==1],x,solution_dict=True) [] sage: solve([x==1,x==-1],x) [] sage: solve([x==1,x==-1],x,solution_dict=True) [] sage: solve((x==1,x==-1),x,solution_dict=0) [] Relaxed form, suggested by Mike Hansen ( sage: solve([x^2-1],x,solution_dict=-1) [{x: -1}, {x: 1}] sage: solve([x^2-1],x,solution_dict=1) [{x: -1}, {x: 1}] sage: solve((x==1,x==-1),x,solution_dict=-1) [] sage: solve((x==1,x==-1),x,solution_dict=1) []
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
if 'solution_dict' in kwds and kwds['solution_dict']==True:
if kwds.get('solution_dict', False): if len(sol_list)==0: return []
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
- ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions.
- ``solution_dict`` - bool (default: False); if True or non-zero, return a list of dictionaries containing the solutions. If there are no solutions, return an empty list (rather than a list containing an empty dictionary). Likewise, if there's only a single solution, return a list containing one dictionary with that solution.
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
We solve an simple equation modulo 2::
We solve a simple equation modulo 2::
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
if solution_dict == True:
if solution_dict:
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
We solve an simple equation modulo 2::
We solve a simple equation modulo 2::
def solve_mod_enumerate(eqns, modulus): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. The solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: Currently this naively enumerates all possible solutions. The interface is good, but the algorithm is horrible if the modulus is at all large! Sage *does* have the ability to do something much faster in certain cases at least by using the Chinese Remainder Theorem, Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At the very least, it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing from sage.symbolic.expression import is_Expression from sage.misc.all import cartesian_product_iterator if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) R = Integers(modulus) S = PolynomialRing(R, len(vars), vars) eqns_mod = [S(eq) if is_Expression(eq) else S(eq.lhs() - eq.rhs()) for eq in eqns] ans = [] for t in cartesian_product_iterator([R]*len(vars)): is_soln = True for e in eqns_mod: if e(t) != 0: is_soln = False break if is_soln: ans.append(t) return ans
Returns the Hasse invariant of an elliptic curve over a field of positive characteristic, which is an element of the field.
Returns the Hasse invariant of this elliptic curve. OUTPUT: The Hasse invariant of this elliptic curve, as an element of the base field. This is only defined over fields of positive characteristic, and is an element of the field which is zero if and only if the curve is supersingular. Over a field of characteristic zero, where the Hasse invariant is undefined, a ``ValueError`` is returned.
def hasse_invariant(self): r""" Returns the Hasse invariant of an elliptic curve over a field of positive characteristic, which is an element of the field.
return self.a2()+self.a1()**2
return self.b2() elif p == 5: return self.c4() elif p == 7: return -self.c6()
def hasse_invariant(self): r""" Returns the Hasse invariant of an elliptic curve over a field of positive characteristic, which is an element of the field.
A map from '(' to open_symbol and ')' to close_symbol and otherwise an error is raised.
A map from ``'('`` to ``open_symbol`` and ``')'`` to ``close_symbol`` and otherwise an error is raised. The values of the constants ``open_symbol`` and ``close_symbol`` are subject to change. This is the inverse map of :func:`replace_symbols`. INPUT: - ``x`` -- either an opening or closing parenthesis. OUTPUT: - If ``x`` is an opening parenthesis, replace ``x`` with the constant ``open_symbol``. - If ``x`` is a closing parenthesis, replace ``x`` with the constant ``close_symbol``. - Raises a ``ValueError`` if ``x`` is neither an opening nor closing parenthesis. .. SEEALSO:: - :func:`replace_symbols`
def replace_parens(x): r""" A map from '(' to open_symbol and ')' to close_symbol and otherwise an error is raised. EXAMPLES:: sage: from sage.combinat.dyck_word import replace_parens sage: replace_parens('(') 1 sage: replace_parens(')') 0 sage: replace_parens(1) Traceback (most recent call last): ... ValueError """ if x == '(': return open_symbol elif x == ')': return close_symbol else: raise ValueError
A map from open_symbol to '(' and close_symbol to ')' and otherwise an error is raised.
A map from ``open_symbol`` to ``'('`` and ``close_symbol`` to ``')'`` and otherwise an error is raised. The values of the constants ``open_symbol`` and ``close_symbol`` are subject to change. This is the inverse map of :func:`replace_parens`. INPUT: - ``x`` -- either ``open_symbol`` or ``close_symbol``. OUTPUT: - If ``x`` is ``open_symbol``, replace ``x`` with ``'('``. - If ``x`` is ``close_symbol``, replace ``x`` with ``')'``. - If ``x`` is neither ``open_symbol`` nor ``close_symbol``, a ``ValueError`` is raised. .. SEEALSO:: - :func:`replace_parens`
def replace_symbols(x): r""" A map from open_symbol to '(' and close_symbol to ')' and otherwise an error is raised. EXAMPLES:: sage: from sage.combinat.dyck_word import replace_symbols sage: replace_symbols(1) '(' sage: replace_symbols(0) ')' sage: replace_symbols(3) Traceback (most recent call last): ... ValueError """ if x == open_symbol: return '(' elif x == close_symbol: return ')' else: raise ValueError
Returns a Dyck word object or a head of a Dyck word object if the Dyck word is not complete
Returns a Dyck word object or a head of a Dyck word object if the Dyck word is not complete.
def DyckWord(dw=None, noncrossing_partition=None): r""" Returns a Dyck word object or a head of a Dyck word object if the Dyck word is not complete EXAMPLES:: sage: dw = DyckWord([1, 0, 1, 0]); dw [1, 0, 1, 0] sage: print dw ()() sage: print dw.height() 1 sage: dw.to_noncrossing_partition() [[1], [2]] :: sage: DyckWord('()()') [1, 0, 1, 0] sage: DyckWord('(())') [1, 1, 0, 0] sage: DyckWord('((') [1, 1] :: sage: DyckWord(noncrossing_partition=[[1],[2]]) [1, 0, 1, 0] sage: DyckWord(noncrossing_partition=[[1,2]]) [1, 1, 0, 0] TODO: In functions where a Dyck word is necessary, an error should be raised (e.g. a_statistic, b_statistic)? """ if noncrossing_partition is not None: return from_noncrossing_partition(noncrossing_partition) elif isinstance(dw, str): l = map(replace_parens, dw) else: l = dw if isinstance(l, DyckWord_class): return l elif l in DyckWords() or is_a_prefix(l): return DyckWord_class(l) else: raise ValueError, "invalid Dyck word"
TODO: In functions where a Dyck word is necessary, an error should be raised (e.g. a_statistic, b_statistic)?
TODO: In functions where a Dyck word is necessary, an error should be raised (e.g. ``a_statistic``, ``b_statistic``)?
def DyckWord(dw=None, noncrossing_partition=None): r""" Returns a Dyck word object or a head of a Dyck word object if the Dyck word is not complete EXAMPLES:: sage: dw = DyckWord([1, 0, 1, 0]); dw [1, 0, 1, 0] sage: print dw ()() sage: print dw.height() 1 sage: dw.to_noncrossing_partition() [[1], [2]] :: sage: DyckWord('()()') [1, 0, 1, 0] sage: DyckWord('(())') [1, 1, 0, 0] sage: DyckWord('((') [1, 1] :: sage: DyckWord(noncrossing_partition=[[1],[2]]) [1, 0, 1, 0] sage: DyckWord(noncrossing_partition=[[1,2]]) [1, 1, 0, 0] TODO: In functions where a Dyck word is necessary, an error should be raised (e.g. a_statistic, b_statistic)? """ if noncrossing_partition is not None: return from_noncrossing_partition(noncrossing_partition) elif isinstance(dw, str): l = map(replace_parens, dw) else: l = dw if isinstance(l, DyckWord_class): return l elif l in DyckWords() or is_a_prefix(l): return DyckWord_class(l) else: raise ValueError, "invalid Dyck word"
report the position for the parenthesis that matches the one at position ``pos``
Report the position for the parenthesis that matches the one at position ``pos``.
def associated_parenthesis(self, pos): r""" report the position for the parenthesis that matches the one at position ``pos``
- ``pos`` - the index of the parenthesis in the list
- ``pos`` - the index of the parenthesis in the list.
def associated_parenthesis(self, pos): r""" report the position for the parenthesis that matches the one at position ``pos``