body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
61bd7f7add47bc4fa714901c0d3d82e238c5c3c71a83e5a226290ce24b56b14c | @property
def xy(self):
'Separate arrays of X and Y coordinate values\n\n Example:\n\n >>> x, y = LineString(((0, 0), (1, 1))).xy\n >>> list(x)\n [0.0, 1.0]\n >>> list(y)\n [0.0, 1.0]\n '
return self.coords.xy | Separate arrays of X and Y coordinate values
Example:
>>> x, y = LineString(((0, 0), (1, 1))).xy
>>> list(x)
[0.0, 1.0]
>>> list(y)
[0.0, 1.0] | shapely/geometry/linestring.py | xy | jGaboardi/shapely | 189 | python | @property
def xy(self):
'Separate arrays of X and Y coordinate values\n\n Example:\n\n >>> x, y = LineString(((0, 0), (1, 1))).xy\n >>> list(x)\n [0.0, 1.0]\n >>> list(y)\n [0.0, 1.0]\n '
return self.coords.xy | @property
def xy(self):
'Separate arrays of X and Y coordinate values\n\n Example:\n\n >>> x, y = LineString(((0, 0), (1, 1))).xy\n >>> list(x)\n [0.0, 1.0]\n >>> list(y)\n [0.0, 1.0]\n '
return self.coords.xy<|docstring|>Separate arrays of X and Y coordinate values
Example:
>>> x, y = LineString(((0, 0), (1, 1))).xy
>>> list(x)
[0.0, 1.0]
>>> list(y)
[0.0, 1.0]<|endoftext|> |
859c9485521352530e1573084118b5684ac5f3d5900cdc0943858ef759b58041 | def parallel_offset(self, distance, side='right', resolution=16, join_style=JOIN_STYLE.round, mitre_limit=5.0):
"Returns a LineString or MultiLineString geometry at a distance from\n the object on its right or its left side.\n\n The side parameter may be 'left' or 'right' (default is 'right'). The\n resolution of the buffer around each vertex of the object increases by\n increasing the resolution keyword parameter or third positional\n parameter. Vertices of right hand offset lines will be ordered in\n reverse.\n\n The join style is for outside corners between line segments. Accepted\n values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and\n JOIN_STYLE.bevel (3).\n\n The mitre ratio limit is used for very sharp corners. It is the ratio\n of the distance from the corner to the end of the mitred offset corner.\n When two line segments meet at a sharp angle, a miter join will extend\n far beyond the original geometry. To prevent unreasonable geometry, the\n mitre limit allows controlling the maximum length of the join corner.\n Corners with a ratio which exceed the limit will be beveled.\n "
if (mitre_limit == 0.0):
raise ValueError('Cannot compute offset from zero-length line segment')
if (side == 'right'):
distance *= (- 1)
return shapely.offset_curve(self, distance, resolution, join_style, mitre_limit) | Returns a LineString or MultiLineString geometry at a distance from
the object on its right or its left side.
The side parameter may be 'left' or 'right' (default is 'right'). The
resolution of the buffer around each vertex of the object increases by
increasing the resolution keyword parameter or third positional
parameter. Vertices of right hand offset lines will be ordered in
reverse.
The join style is for outside corners between line segments. Accepted
values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and
JOIN_STYLE.bevel (3).
The mitre ratio limit is used for very sharp corners. It is the ratio
of the distance from the corner to the end of the mitred offset corner.
When two line segments meet at a sharp angle, a miter join will extend
far beyond the original geometry. To prevent unreasonable geometry, the
mitre limit allows controlling the maximum length of the join corner.
Corners with a ratio which exceed the limit will be beveled. | shapely/geometry/linestring.py | parallel_offset | jGaboardi/shapely | 189 | python | def parallel_offset(self, distance, side='right', resolution=16, join_style=JOIN_STYLE.round, mitre_limit=5.0):
"Returns a LineString or MultiLineString geometry at a distance from\n the object on its right or its left side.\n\n The side parameter may be 'left' or 'right' (default is 'right'). The\n resolution of the buffer around each vertex of the object increases by\n increasing the resolution keyword parameter or third positional\n parameter. Vertices of right hand offset lines will be ordered in\n reverse.\n\n The join style is for outside corners between line segments. Accepted\n values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and\n JOIN_STYLE.bevel (3).\n\n The mitre ratio limit is used for very sharp corners. It is the ratio\n of the distance from the corner to the end of the mitred offset corner.\n When two line segments meet at a sharp angle, a miter join will extend\n far beyond the original geometry. To prevent unreasonable geometry, the\n mitre limit allows controlling the maximum length of the join corner.\n Corners with a ratio which exceed the limit will be beveled.\n "
if (mitre_limit == 0.0):
raise ValueError('Cannot compute offset from zero-length line segment')
if (side == 'right'):
distance *= (- 1)
return shapely.offset_curve(self, distance, resolution, join_style, mitre_limit) | def parallel_offset(self, distance, side='right', resolution=16, join_style=JOIN_STYLE.round, mitre_limit=5.0):
"Returns a LineString or MultiLineString geometry at a distance from\n the object on its right or its left side.\n\n The side parameter may be 'left' or 'right' (default is 'right'). The\n resolution of the buffer around each vertex of the object increases by\n increasing the resolution keyword parameter or third positional\n parameter. Vertices of right hand offset lines will be ordered in\n reverse.\n\n The join style is for outside corners between line segments. Accepted\n values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and\n JOIN_STYLE.bevel (3).\n\n The mitre ratio limit is used for very sharp corners. It is the ratio\n of the distance from the corner to the end of the mitred offset corner.\n When two line segments meet at a sharp angle, a miter join will extend\n far beyond the original geometry. To prevent unreasonable geometry, the\n mitre limit allows controlling the maximum length of the join corner.\n Corners with a ratio which exceed the limit will be beveled.\n "
if (mitre_limit == 0.0):
raise ValueError('Cannot compute offset from zero-length line segment')
if (side == 'right'):
distance *= (- 1)
return shapely.offset_curve(self, distance, resolution, join_style, mitre_limit)<|docstring|>Returns a LineString or MultiLineString geometry at a distance from
the object on its right or its left side.
The side parameter may be 'left' or 'right' (default is 'right'). The
resolution of the buffer around each vertex of the object increases by
increasing the resolution keyword parameter or third positional
parameter. Vertices of right hand offset lines will be ordered in
reverse.
The join style is for outside corners between line segments. Accepted
values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and
JOIN_STYLE.bevel (3).
The mitre ratio limit is used for very sharp corners. It is the ratio
of the distance from the corner to the end of the mitred offset corner.
When two line segments meet at a sharp angle, a miter join will extend
far beyond the original geometry. To prevent unreasonable geometry, the
mitre limit allows controlling the maximum length of the join corner.
Corners with a ratio which exceed the limit will be beveled.<|endoftext|> |
7b566fcda48ddf002ede475c94b0410ea337c81502a437998ba306d3b74a55e3 | def label_accuracy_score(label_trues, label_preds, n_class, det_metrics=None):
'Returns accuracy score evaluation result.\n\n - average pixelwise accuracy\n - mean classwise accuracy (not the same, if classes have different frequency)\n - mean Intersection over Union\n - Frequency Weighted Averaged Accuracy\n '
if (det_metrics is None):
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = label_accuracy_score_detailed(label_trues, label_preds, n_class)
else:
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = det_metrics
avg_acc = (tr_all / px_all)
with np.errstate(divide='ignore', invalid='ignore'):
avg_cls_acc = (tr_cls_wise / cls_pixel_counts)
avg_cls_acc = np.nanmean(avg_cls_acc)
mean_iou = np.nanmean(iou)
freq = (cls_pixel_counts / px_all)
fw_mean_iou = (freq[(freq > 0)] * iou[(freq > 0)]).sum()
return (avg_acc, avg_cls_acc, mean_iou, fw_mean_iou) | Returns accuracy score evaluation result.
- average pixelwise accuracy
- mean classwise accuracy (not the same, if classes have different frequency)
- mean Intersection over Union
- Frequency Weighted Averaged Accuracy | torchfcn/utils.py | label_accuracy_score | simplexsigil/pytorch-fcn | 0 | python | def label_accuracy_score(label_trues, label_preds, n_class, det_metrics=None):
'Returns accuracy score evaluation result.\n\n - average pixelwise accuracy\n - mean classwise accuracy (not the same, if classes have different frequency)\n - mean Intersection over Union\n - Frequency Weighted Averaged Accuracy\n '
if (det_metrics is None):
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = label_accuracy_score_detailed(label_trues, label_preds, n_class)
else:
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = det_metrics
avg_acc = (tr_all / px_all)
with np.errstate(divide='ignore', invalid='ignore'):
avg_cls_acc = (tr_cls_wise / cls_pixel_counts)
avg_cls_acc = np.nanmean(avg_cls_acc)
mean_iou = np.nanmean(iou)
freq = (cls_pixel_counts / px_all)
fw_mean_iou = (freq[(freq > 0)] * iou[(freq > 0)]).sum()
return (avg_acc, avg_cls_acc, mean_iou, fw_mean_iou) | def label_accuracy_score(label_trues, label_preds, n_class, det_metrics=None):
'Returns accuracy score evaluation result.\n\n - average pixelwise accuracy\n - mean classwise accuracy (not the same, if classes have different frequency)\n - mean Intersection over Union\n - Frequency Weighted Averaged Accuracy\n '
if (det_metrics is None):
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = label_accuracy_score_detailed(label_trues, label_preds, n_class)
else:
(px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, iou, _) = det_metrics
avg_acc = (tr_all / px_all)
with np.errstate(divide='ignore', invalid='ignore'):
avg_cls_acc = (tr_cls_wise / cls_pixel_counts)
avg_cls_acc = np.nanmean(avg_cls_acc)
mean_iou = np.nanmean(iou)
freq = (cls_pixel_counts / px_all)
fw_mean_iou = (freq[(freq > 0)] * iou[(freq > 0)]).sum()
return (avg_acc, avg_cls_acc, mean_iou, fw_mean_iou)<|docstring|>Returns accuracy score evaluation result.
- average pixelwise accuracy
- mean classwise accuracy (not the same, if classes have different frequency)
- mean Intersection over Union
- Frequency Weighted Averaged Accuracy<|endoftext|> |
5ab2e900c67208653ed9ac0dd95dd309fb15f038803f784ca71ec48038a51185 | def label_accuracy_score_detailed(label_trues, label_preds, n_class, rt_cnf_mat=False):
'\n Returns metrics given true and predicted labels of an image segmentation.\n :param label_trues: Segmentation ground truths of shape (batch_size, height, width).\n :param label_preds: Segmentation predictions of shape (batch_size, height, width).\n :param n_class: Number of classes.\n :param rt_cnf_mat: If true, a confusion matrix is returned as last parameter, None otherwise.\n :return: px_all (All pixel count), tr_all (All correctly classified pixel count),\n tr_cls_wise (Class wise correctly classified pixel count),\n cls_pixel_counts (True pixel count per class),\n cls_clsfd_pixel_counts (Classwise classified pixel count - TP and FP),\n iou (Intersection over Union - TP / TP + FP + FN),\n cnf_mat (Confusion matrix)\n '
cnf_mat = np.zeros((n_class, n_class))
for (lt, lp) in zip(label_trues, label_preds):
cnf_mat += _fast_hist(lt.flatten(), lp.flatten(), n_class)
tr_cls_wise = np.diag(cnf_mat)
tr_all = tr_cls_wise.sum()
px_all = cnf_mat.sum()
cls_pixel_counts = cnf_mat.sum(axis=1)
cls_clsfd_pixel_counts = cnf_mat.sum(axis=0)
with np.errstate(divide='ignore', invalid='ignore'):
cls_iou = (tr_cls_wise / ((cls_pixel_counts + cls_clsfd_pixel_counts) - tr_cls_wise))
return (px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, cls_iou, (cnf_mat if rt_cnf_mat else None)) | Returns metrics given true and predicted labels of an image segmentation.
:param label_trues: Segmentation ground truths of shape (batch_size, height, width).
:param label_preds: Segmentation predictions of shape (batch_size, height, width).
:param n_class: Number of classes.
:param rt_cnf_mat: If true, a confusion matrix is returned as last parameter, None otherwise.
:return: px_all (All pixel count), tr_all (All correctly classified pixel count),
tr_cls_wise (Class wise correctly classified pixel count),
cls_pixel_counts (True pixel count per class),
cls_clsfd_pixel_counts (Classwise classified pixel count - TP and FP),
iou (Intersection over Union - TP / TP + FP + FN),
cnf_mat (Confusion matrix) | torchfcn/utils.py | label_accuracy_score_detailed | simplexsigil/pytorch-fcn | 0 | python | def label_accuracy_score_detailed(label_trues, label_preds, n_class, rt_cnf_mat=False):
'\n Returns metrics given true and predicted labels of an image segmentation.\n :param label_trues: Segmentation ground truths of shape (batch_size, height, width).\n :param label_preds: Segmentation predictions of shape (batch_size, height, width).\n :param n_class: Number of classes.\n :param rt_cnf_mat: If true, a confusion matrix is returned as last parameter, None otherwise.\n :return: px_all (All pixel count), tr_all (All correctly classified pixel count),\n tr_cls_wise (Class wise correctly classified pixel count),\n cls_pixel_counts (True pixel count per class),\n cls_clsfd_pixel_counts (Classwise classified pixel count - TP and FP),\n iou (Intersection over Union - TP / TP + FP + FN),\n cnf_mat (Confusion matrix)\n '
cnf_mat = np.zeros((n_class, n_class))
for (lt, lp) in zip(label_trues, label_preds):
cnf_mat += _fast_hist(lt.flatten(), lp.flatten(), n_class)
tr_cls_wise = np.diag(cnf_mat)
tr_all = tr_cls_wise.sum()
px_all = cnf_mat.sum()
cls_pixel_counts = cnf_mat.sum(axis=1)
cls_clsfd_pixel_counts = cnf_mat.sum(axis=0)
with np.errstate(divide='ignore', invalid='ignore'):
cls_iou = (tr_cls_wise / ((cls_pixel_counts + cls_clsfd_pixel_counts) - tr_cls_wise))
return (px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, cls_iou, (cnf_mat if rt_cnf_mat else None)) | def label_accuracy_score_detailed(label_trues, label_preds, n_class, rt_cnf_mat=False):
'\n Returns metrics given true and predicted labels of an image segmentation.\n :param label_trues: Segmentation ground truths of shape (batch_size, height, width).\n :param label_preds: Segmentation predictions of shape (batch_size, height, width).\n :param n_class: Number of classes.\n :param rt_cnf_mat: If true, a confusion matrix is returned as last parameter, None otherwise.\n :return: px_all (All pixel count), tr_all (All correctly classified pixel count),\n tr_cls_wise (Class wise correctly classified pixel count),\n cls_pixel_counts (True pixel count per class),\n cls_clsfd_pixel_counts (Classwise classified pixel count - TP and FP),\n iou (Intersection over Union - TP / TP + FP + FN),\n cnf_mat (Confusion matrix)\n '
cnf_mat = np.zeros((n_class, n_class))
for (lt, lp) in zip(label_trues, label_preds):
cnf_mat += _fast_hist(lt.flatten(), lp.flatten(), n_class)
tr_cls_wise = np.diag(cnf_mat)
tr_all = tr_cls_wise.sum()
px_all = cnf_mat.sum()
cls_pixel_counts = cnf_mat.sum(axis=1)
cls_clsfd_pixel_counts = cnf_mat.sum(axis=0)
with np.errstate(divide='ignore', invalid='ignore'):
cls_iou = (tr_cls_wise / ((cls_pixel_counts + cls_clsfd_pixel_counts) - tr_cls_wise))
return (px_all, tr_all, tr_cls_wise, cls_pixel_counts, cls_clsfd_pixel_counts, cls_iou, (cnf_mat if rt_cnf_mat else None))<|docstring|>Returns metrics given true and predicted labels of an image segmentation.
:param label_trues: Segmentation ground truths of shape (batch_size, height, width).
:param label_preds: Segmentation predictions of shape (batch_size, height, width).
:param n_class: Number of classes.
:param rt_cnf_mat: If true, a confusion matrix is returned as last parameter, None otherwise.
:return: px_all (All pixel count), tr_all (All correctly classified pixel count),
tr_cls_wise (Class wise correctly classified pixel count),
cls_pixel_counts (True pixel count per class),
cls_clsfd_pixel_counts (Classwise classified pixel count - TP and FP),
iou (Intersection over Union - TP / TP + FP + FN),
cnf_mat (Confusion matrix)<|endoftext|> |
18ea75b2c9ba3305a88fbee685dbc8fcdd838c3bf0d2427bfb9ec77f17688ecc | def determinist_cluster(dist_df, method, n_clusters):
'\n Clustering of the songs from the dataframe, indicating\n the number of clusters to use.\n\n :param pandas.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :param int n_clusters:\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
y = n_cluster_methods[method](n_clusters=n_clusters).fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series | Clustering of the songs from the dataframe, indicating
the number of clusters to use.
:param pandas.DataFrame dist_df:
:param str method: name of the sklearn.cluster.
- cluster.AgglomerativeClustering.
- cluster.SpectralClustering.
- cluster.KMeans.
:param int n_clusters:
:return: pandas.DataFrame with a column with clusters. | foucluster/cluster.py | determinist_cluster | cperales/Fourier-Clustering-song | 15 | python | def determinist_cluster(dist_df, method, n_clusters):
'\n Clustering of the songs from the dataframe, indicating\n the number of clusters to use.\n\n :param pandas.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :param int n_clusters:\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
y = n_cluster_methods[method](n_clusters=n_clusters).fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series | def determinist_cluster(dist_df, method, n_clusters):
'\n Clustering of the songs from the dataframe, indicating\n the number of clusters to use.\n\n :param pandas.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :param int n_clusters:\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
y = n_cluster_methods[method](n_clusters=n_clusters).fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series<|docstring|>Clustering of the songs from the dataframe, indicating
the number of clusters to use.
:param pandas.DataFrame dist_df:
:param str method: name of the sklearn.cluster.
- cluster.AgglomerativeClustering.
- cluster.SpectralClustering.
- cluster.KMeans.
:param int n_clusters:
:return: pandas.DataFrame with a column with clusters.<|endoftext|> |
a730bd84fbe0e68f86753a8a0f85df4868a5c6946379636cff3badffe7ffd3c8 | def automatic_cluster(dist_df, method):
'\n\n :param pd.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AffinityPropagation.\n - cluster.MeanShift.\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
if (method in n_cluster_methods.keys()):
n_clusters = jump_method(dist_df=df_matrix)
clf = n_cluster_methods[method](n_clusters=n_clusters)
else:
clf = non_n_cluster_methods[method]()
y = clf.fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series | :param pd.DataFrame dist_df:
:param str method: name of the sklearn.cluster.
- cluster.AffinityPropagation.
- cluster.MeanShift.
- cluster.AgglomerativeClustering.
- cluster.SpectralClustering.
- cluster.KMeans.
:return: pandas.DataFrame with a column with clusters. | foucluster/cluster.py | automatic_cluster | cperales/Fourier-Clustering-song | 15 | python | def automatic_cluster(dist_df, method):
'\n\n :param pd.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AffinityPropagation.\n - cluster.MeanShift.\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
if (method in n_cluster_methods.keys()):
n_clusters = jump_method(dist_df=df_matrix)
clf = n_cluster_methods[method](n_clusters=n_clusters)
else:
clf = non_n_cluster_methods[method]()
y = clf.fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series | def automatic_cluster(dist_df, method):
'\n\n :param pd.DataFrame dist_df:\n :param str method: name of the sklearn.cluster.\n\n - cluster.AffinityPropagation.\n - cluster.MeanShift.\n - cluster.AgglomerativeClustering.\n - cluster.SpectralClustering.\n - cluster.KMeans.\n\n :return: pandas.DataFrame with a column with clusters.\n '
if (not isinstance(dist_df, pd.DataFrame)):
dist_df = dist_df.to_df().T
dist_values = dist_df.values
df_matrix = zero_scale(dist_values)
if (method in n_cluster_methods.keys()):
n_clusters = jump_method(dist_df=df_matrix)
clf = n_cluster_methods[method](n_clusters=n_clusters)
else:
clf = non_n_cluster_methods[method]()
y = clf.fit_predict(df_matrix)
cluster_series = pd.Series(y, index=dist_df.index)
return cluster_series<|docstring|>:param pd.DataFrame dist_df:
:param str method: name of the sklearn.cluster.
- cluster.AffinityPropagation.
- cluster.MeanShift.
- cluster.AgglomerativeClustering.
- cluster.SpectralClustering.
- cluster.KMeans.
:return: pandas.DataFrame with a column with clusters.<|endoftext|> |
2c8a8abcbe53e14b686bcd0ac3d37e884ce2a622150d8d8c6d76d8f4b61a44c6 | def jump_method(dist_df, n_max=50):
'\n Method based on information theory to determine best\n number of clusters.\n\n :param np.array dist_df:\n :param int n_max: maximum number of clusters to test.\n :return: optimal number of clusters\n '
dim = dist_df.shape[0]
if (n_max > dim):
n_max = dim
Y = (dim / 2)
distortions = np.empty((n_max + 1))
jump_vector = np.empty(n_max)
distortions[0] = 0.0
for k in range(1, (n_max + 1)):
kmean_model = cluster.KMeans(n_clusters=k).fit(dist_df)
distortion = ((np.min(cdist(dist_df, kmean_model.cluster_centers_, 'euclidean').ravel()) / dim) + eps)
distortions[k] = (distortion ** (- Y))
jump_vector[(k - 1)] = (distortions[k] - distortions[(k - 1)])
n_cluster = (np.argmax(jump_vector) + 1)
instance_alone = True
while (instance_alone is True):
y = cluster.KMeans(n_clusters=n_cluster).fit_predict(dist_df)
group_member = [len(list(group)) for (key, group) in groupby(np.sort(y))]
if ((np.min(group_member) > 1) or (n_cluster == 2)):
instance_alone = False
else:
n_cluster -= 1
return n_cluster | Method based on information theory to determine best
number of clusters.
:param np.array dist_df:
:param int n_max: maximum number of clusters to test.
:return: optimal number of clusters | foucluster/cluster.py | jump_method | cperales/Fourier-Clustering-song | 15 | python | def jump_method(dist_df, n_max=50):
'\n Method based on information theory to determine best\n number of clusters.\n\n :param np.array dist_df:\n :param int n_max: maximum number of clusters to test.\n :return: optimal number of clusters\n '
dim = dist_df.shape[0]
if (n_max > dim):
n_max = dim
Y = (dim / 2)
distortions = np.empty((n_max + 1))
jump_vector = np.empty(n_max)
distortions[0] = 0.0
for k in range(1, (n_max + 1)):
kmean_model = cluster.KMeans(n_clusters=k).fit(dist_df)
distortion = ((np.min(cdist(dist_df, kmean_model.cluster_centers_, 'euclidean').ravel()) / dim) + eps)
distortions[k] = (distortion ** (- Y))
jump_vector[(k - 1)] = (distortions[k] - distortions[(k - 1)])
n_cluster = (np.argmax(jump_vector) + 1)
instance_alone = True
while (instance_alone is True):
y = cluster.KMeans(n_clusters=n_cluster).fit_predict(dist_df)
group_member = [len(list(group)) for (key, group) in groupby(np.sort(y))]
if ((np.min(group_member) > 1) or (n_cluster == 2)):
instance_alone = False
else:
n_cluster -= 1
return n_cluster | def jump_method(dist_df, n_max=50):
'\n Method based on information theory to determine best\n number of clusters.\n\n :param np.array dist_df:\n :param int n_max: maximum number of clusters to test.\n :return: optimal number of clusters\n '
dim = dist_df.shape[0]
if (n_max > dim):
n_max = dim
Y = (dim / 2)
distortions = np.empty((n_max + 1))
jump_vector = np.empty(n_max)
distortions[0] = 0.0
for k in range(1, (n_max + 1)):
kmean_model = cluster.KMeans(n_clusters=k).fit(dist_df)
distortion = ((np.min(cdist(dist_df, kmean_model.cluster_centers_, 'euclidean').ravel()) / dim) + eps)
distortions[k] = (distortion ** (- Y))
jump_vector[(k - 1)] = (distortions[k] - distortions[(k - 1)])
n_cluster = (np.argmax(jump_vector) + 1)
instance_alone = True
while (instance_alone is True):
y = cluster.KMeans(n_clusters=n_cluster).fit_predict(dist_df)
group_member = [len(list(group)) for (key, group) in groupby(np.sort(y))]
if ((np.min(group_member) > 1) or (n_cluster == 2)):
instance_alone = False
else:
n_cluster -= 1
return n_cluster<|docstring|>Method based on information theory to determine best
number of clusters.
:param np.array dist_df:
:param int n_max: maximum number of clusters to test.
:return: optimal number of clusters<|endoftext|> |
7b37542be0665fea2d229bb4915b03043f70acd9fdf06b2b0d94d401529290e9 | def score_cluster(cluster_df):
'\n When `automatic_cluster` is used, then the clusters must be\n grouped into the categories we want into predict, in order to score\n our method.\n\n :param pandas.DataFrame cluster_df:\n :return: accuracy score. cluster_df have now `Cluster_corrected` column.\n '
accurate_class = [int(n[0][0]) for n in cluster_df.index.tolist()]
accurate_class -= np.unique(accurate_class).min()
accurate_class = np.array(accurate_class, dtype=int)
cluster_class = np.array(cluster_df.values.tolist(), dtype=int)
correspondence_dict = {}
for p in np.unique(cluster_class):
max_c = 0.0
pos_p = (cluster_class == p)
for e in np.unique(accurate_class):
pos_e = (accurate_class == e)
c = (pos_p == pos_e).sum()
if (c > max_c):
correspondence_dict.update({p: e})
max_c = c
cluster_class_corrected = [correspondence_dict[p] for p in cluster_class]
cluster_df['Cluster_corrected'] = pd.Series(cluster_class_corrected, index=cluster_df.index)
score_vector = [(e == p_c) for (e, p_c) in zip(accurate_class, cluster_class_corrected)]
return np.average(score_vector) | When `automatic_cluster` is used, then the clusters must be
grouped into the categories we want into predict, in order to score
our method.
:param pandas.DataFrame cluster_df:
:return: accuracy score. cluster_df have now `Cluster_corrected` column. | foucluster/cluster.py | score_cluster | cperales/Fourier-Clustering-song | 15 | python | def score_cluster(cluster_df):
'\n When `automatic_cluster` is used, then the clusters must be\n grouped into the categories we want into predict, in order to score\n our method.\n\n :param pandas.DataFrame cluster_df:\n :return: accuracy score. cluster_df have now `Cluster_corrected` column.\n '
accurate_class = [int(n[0][0]) for n in cluster_df.index.tolist()]
accurate_class -= np.unique(accurate_class).min()
accurate_class = np.array(accurate_class, dtype=int)
cluster_class = np.array(cluster_df.values.tolist(), dtype=int)
correspondence_dict = {}
for p in np.unique(cluster_class):
max_c = 0.0
pos_p = (cluster_class == p)
for e in np.unique(accurate_class):
pos_e = (accurate_class == e)
c = (pos_p == pos_e).sum()
if (c > max_c):
correspondence_dict.update({p: e})
max_c = c
cluster_class_corrected = [correspondence_dict[p] for p in cluster_class]
cluster_df['Cluster_corrected'] = pd.Series(cluster_class_corrected, index=cluster_df.index)
score_vector = [(e == p_c) for (e, p_c) in zip(accurate_class, cluster_class_corrected)]
return np.average(score_vector) | def score_cluster(cluster_df):
'\n When `automatic_cluster` is used, then the clusters must be\n grouped into the categories we want into predict, in order to score\n our method.\n\n :param pandas.DataFrame cluster_df:\n :return: accuracy score. cluster_df have now `Cluster_corrected` column.\n '
accurate_class = [int(n[0][0]) for n in cluster_df.index.tolist()]
accurate_class -= np.unique(accurate_class).min()
accurate_class = np.array(accurate_class, dtype=int)
cluster_class = np.array(cluster_df.values.tolist(), dtype=int)
correspondence_dict = {}
for p in np.unique(cluster_class):
max_c = 0.0
pos_p = (cluster_class == p)
for e in np.unique(accurate_class):
pos_e = (accurate_class == e)
c = (pos_p == pos_e).sum()
if (c > max_c):
correspondence_dict.update({p: e})
max_c = c
cluster_class_corrected = [correspondence_dict[p] for p in cluster_class]
cluster_df['Cluster_corrected'] = pd.Series(cluster_class_corrected, index=cluster_df.index)
score_vector = [(e == p_c) for (e, p_c) in zip(accurate_class, cluster_class_corrected)]
return np.average(score_vector)<|docstring|>When `automatic_cluster` is used, then the clusters must be
grouped into the categories we want into predict, in order to score
our method.
:param pandas.DataFrame cluster_df:
:return: accuracy score. cluster_df have now `Cluster_corrected` column.<|endoftext|> |
40bbacce03b12056cc69f9665825b3d4037c454f055b915f075d7a208c49a6f8 | def party_list(song_df, song=None):
'\n A list of song of all the songs from the cluster dataframe\n sorted, from similarity between them.\n\n :param pandas.DataFrame song_df:\n :param str song:\n :return:\n '
song_df_rev = song_df.T
if ((song is None) or (song not in song_df_rev.index)):
song = song_df_rev.index[0]
final_index = list(song_df_rev.sort_values(song, axis='columns')[song].index)
return final_index | A list of song of all the songs from the cluster dataframe
sorted, from similarity between them.
:param pandas.DataFrame song_df:
:param str song:
:return: | foucluster/cluster.py | party_list | cperales/Fourier-Clustering-song | 15 | python | def party_list(song_df, song=None):
'\n A list of song of all the songs from the cluster dataframe\n sorted, from similarity between them.\n\n :param pandas.DataFrame song_df:\n :param str song:\n :return:\n '
song_df_rev = song_df.T
if ((song is None) or (song not in song_df_rev.index)):
song = song_df_rev.index[0]
final_index = list(song_df_rev.sort_values(song, axis='columns')[song].index)
return final_index | def party_list(song_df, song=None):
'\n A list of song of all the songs from the cluster dataframe\n sorted, from similarity between them.\n\n :param pandas.DataFrame song_df:\n :param str song:\n :return:\n '
song_df_rev = song_df.T
if ((song is None) or (song not in song_df_rev.index)):
song = song_df_rev.index[0]
final_index = list(song_df_rev.sort_values(song, axis='columns')[song].index)
return final_index<|docstring|>A list of song of all the songs from the cluster dataframe
sorted, from similarity between them.
:param pandas.DataFrame song_df:
:param str song:
:return:<|endoftext|> |
0614ac04cf162969eb14f2b0d892117187c9366f82f5eaf173132d3baddcd43d | def zero_scale(X):
'\n\n :param numpy.array X:\n :return:\n '
(n, m) = X.shape
x = np.empty_like(X)
for j in range(m):
feature_column = X[(:, j)]
max_value = feature_column.max()
min_value = feature_column.min()
feature_column = ((feature_column - min_value) / (max_value - min_value))
x[(:, j)] = feature_column
return x | :param numpy.array X:
:return: | foucluster/cluster.py | zero_scale | cperales/Fourier-Clustering-song | 15 | python | def zero_scale(X):
'\n\n :param numpy.array X:\n :return:\n '
(n, m) = X.shape
x = np.empty_like(X)
for j in range(m):
feature_column = X[(:, j)]
max_value = feature_column.max()
min_value = feature_column.min()
feature_column = ((feature_column - min_value) / (max_value - min_value))
x[(:, j)] = feature_column
return x | def zero_scale(X):
'\n\n :param numpy.array X:\n :return:\n '
(n, m) = X.shape
x = np.empty_like(X)
for j in range(m):
feature_column = X[(:, j)]
max_value = feature_column.max()
min_value = feature_column.min()
feature_column = ((feature_column - min_value) / (max_value - min_value))
x[(:, j)] = feature_column
return x<|docstring|>:param numpy.array X:
:return:<|endoftext|> |
60a51f7a5e30524cdf8f6eb55b4c55192710deaa867368cfa4ab8b116372fdc4 | def plot(self, traj, plot='x', show=True):
"\n Create a figure with trajectories for states, inputs, outputs and cost\n ----------------------------------------------------------------------\n plot = 'All'\n plot = 'xu'\n plot = 'xy'\n plot = 'x'\n plot = 'u'\n plot = 'y'\n plot = 'j'\n plot = 'z'\n "
if (('j' in plot) and ((traj.J is None) or (traj.dJ is None))):
raise ValueError("Trajectory does not contain cost data but plotting 'j' was requested")
sys = self.sys
if (plot == 'All'):
l = (((sys.n + sys.m) + sys.p) + 2)
elif (plot == 'xuj'):
l = ((sys.n + sys.m) + 2)
elif (plot == 'xu'):
l = (sys.n + sys.m)
elif (plot == 'xy'):
l = (sys.n + sys.p)
elif (plot == 'x'):
l = sys.n
elif (plot == 'u'):
l = sys.m
elif (plot == 'y'):
l = sys.p
elif (plot == 'j'):
l = 2
elif (plot == 'z'):
l = sys.controller.l
else:
raise ValueError('not a valid ploting argument')
(simfig, plots) = plt.subplots(l, sharex=True, figsize=self.figsize, dpi=self.dpi, frameon=True)
if (l == 1):
plots = [plots]
simfig.canvas.manager.set_window_title(('Trajectory for ' + self.sys.name))
j = 0
if ((plot == 'All') or (plot == 'x') or (plot == 'xu') or (plot == 'xy') or (plot == 'xuj')):
for i in range(sys.n):
plots[j].plot(traj.t, traj.x[(:, i)], 'b')
plots[j].set_ylabel(((sys.state_label[i] + '\n') + sys.state_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'u') or (plot == 'xu') or (plot == 'xuj')):
for i in range(sys.m):
plots[j].plot(traj.t, traj.u[(:, i)], 'r')
plots[j].set_ylabel(((sys.input_label[i] + '\n') + sys.input_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'y') or (plot == 'xy')):
for i in range(sys.p):
plots[j].plot(traj.t, traj.y[(:, i)], 'k')
plots[j].set_ylabel(((sys.output_label[i] + '\n') + sys.output_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'j') or (plot == 'xuj')):
plots[j].plot(traj.t, traj.dJ[:], 'b')
plots[j].set_ylabel('dJ', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[j].plot(traj.t, traj.J[:], 'r')
plots[j].set_ylabel('J', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if (plot == 'z'):
n = (sys.n - sys.controller.l)
for i in range(l):
plots[j].plot(traj.t, traj.x[(:, (i + n))], 'b')
plots[j].set_ylabel(((sys.state_label[(i + n)] + '\n') + sys.state_units[(i + n)]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[(l - 1)].set_xlabel('Time [sec]', fontsize=self.fontsize)
simfig.tight_layout()
simfig.canvas.draw()
plt.draw()
plt.show()
self.fig = simfig
self.plots = plots | Create a figure with trajectories for states, inputs, outputs and cost
----------------------------------------------------------------------
plot = 'All'
plot = 'xu'
plot = 'xy'
plot = 'x'
plot = 'u'
plot = 'y'
plot = 'j'
plot = 'z' | pyro/analysis/graphical.py | plot | alx87grd/AlexRobotics | 9 | python | def plot(self, traj, plot='x', show=True):
"\n Create a figure with trajectories for states, inputs, outputs and cost\n ----------------------------------------------------------------------\n plot = 'All'\n plot = 'xu'\n plot = 'xy'\n plot = 'x'\n plot = 'u'\n plot = 'y'\n plot = 'j'\n plot = 'z'\n "
if (('j' in plot) and ((traj.J is None) or (traj.dJ is None))):
raise ValueError("Trajectory does not contain cost data but plotting 'j' was requested")
sys = self.sys
if (plot == 'All'):
l = (((sys.n + sys.m) + sys.p) + 2)
elif (plot == 'xuj'):
l = ((sys.n + sys.m) + 2)
elif (plot == 'xu'):
l = (sys.n + sys.m)
elif (plot == 'xy'):
l = (sys.n + sys.p)
elif (plot == 'x'):
l = sys.n
elif (plot == 'u'):
l = sys.m
elif (plot == 'y'):
l = sys.p
elif (plot == 'j'):
l = 2
elif (plot == 'z'):
l = sys.controller.l
else:
raise ValueError('not a valid ploting argument')
(simfig, plots) = plt.subplots(l, sharex=True, figsize=self.figsize, dpi=self.dpi, frameon=True)
if (l == 1):
plots = [plots]
simfig.canvas.manager.set_window_title(('Trajectory for ' + self.sys.name))
j = 0
if ((plot == 'All') or (plot == 'x') or (plot == 'xu') or (plot == 'xy') or (plot == 'xuj')):
for i in range(sys.n):
plots[j].plot(traj.t, traj.x[(:, i)], 'b')
plots[j].set_ylabel(((sys.state_label[i] + '\n') + sys.state_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'u') or (plot == 'xu') or (plot == 'xuj')):
for i in range(sys.m):
plots[j].plot(traj.t, traj.u[(:, i)], 'r')
plots[j].set_ylabel(((sys.input_label[i] + '\n') + sys.input_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'y') or (plot == 'xy')):
for i in range(sys.p):
plots[j].plot(traj.t, traj.y[(:, i)], 'k')
plots[j].set_ylabel(((sys.output_label[i] + '\n') + sys.output_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'j') or (plot == 'xuj')):
plots[j].plot(traj.t, traj.dJ[:], 'b')
plots[j].set_ylabel('dJ', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[j].plot(traj.t, traj.J[:], 'r')
plots[j].set_ylabel('J', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if (plot == 'z'):
n = (sys.n - sys.controller.l)
for i in range(l):
plots[j].plot(traj.t, traj.x[(:, (i + n))], 'b')
plots[j].set_ylabel(((sys.state_label[(i + n)] + '\n') + sys.state_units[(i + n)]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[(l - 1)].set_xlabel('Time [sec]', fontsize=self.fontsize)
simfig.tight_layout()
simfig.canvas.draw()
plt.draw()
plt.show()
self.fig = simfig
self.plots = plots | def plot(self, traj, plot='x', show=True):
"\n Create a figure with trajectories for states, inputs, outputs and cost\n ----------------------------------------------------------------------\n plot = 'All'\n plot = 'xu'\n plot = 'xy'\n plot = 'x'\n plot = 'u'\n plot = 'y'\n plot = 'j'\n plot = 'z'\n "
if (('j' in plot) and ((traj.J is None) or (traj.dJ is None))):
raise ValueError("Trajectory does not contain cost data but plotting 'j' was requested")
sys = self.sys
if (plot == 'All'):
l = (((sys.n + sys.m) + sys.p) + 2)
elif (plot == 'xuj'):
l = ((sys.n + sys.m) + 2)
elif (plot == 'xu'):
l = (sys.n + sys.m)
elif (plot == 'xy'):
l = (sys.n + sys.p)
elif (plot == 'x'):
l = sys.n
elif (plot == 'u'):
l = sys.m
elif (plot == 'y'):
l = sys.p
elif (plot == 'j'):
l = 2
elif (plot == 'z'):
l = sys.controller.l
else:
raise ValueError('not a valid ploting argument')
(simfig, plots) = plt.subplots(l, sharex=True, figsize=self.figsize, dpi=self.dpi, frameon=True)
if (l == 1):
plots = [plots]
simfig.canvas.manager.set_window_title(('Trajectory for ' + self.sys.name))
j = 0
if ((plot == 'All') or (plot == 'x') or (plot == 'xu') or (plot == 'xy') or (plot == 'xuj')):
for i in range(sys.n):
plots[j].plot(traj.t, traj.x[(:, i)], 'b')
plots[j].set_ylabel(((sys.state_label[i] + '\n') + sys.state_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'u') or (plot == 'xu') or (plot == 'xuj')):
for i in range(sys.m):
plots[j].plot(traj.t, traj.u[(:, i)], 'r')
plots[j].set_ylabel(((sys.input_label[i] + '\n') + sys.input_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'y') or (plot == 'xy')):
for i in range(sys.p):
plots[j].plot(traj.t, traj.y[(:, i)], 'k')
plots[j].set_ylabel(((sys.output_label[i] + '\n') + sys.output_units[i]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if ((plot == 'All') or (plot == 'j') or (plot == 'xuj')):
plots[j].plot(traj.t, traj.dJ[:], 'b')
plots[j].set_ylabel('dJ', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[j].plot(traj.t, traj.J[:], 'r')
plots[j].set_ylabel('J', fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
if (plot == 'z'):
n = (sys.n - sys.controller.l)
for i in range(l):
plots[j].plot(traj.t, traj.x[(:, (i + n))], 'b')
plots[j].set_ylabel(((sys.state_label[(i + n)] + '\n') + sys.state_units[(i + n)]), fontsize=self.fontsize)
plots[j].grid(True)
plots[j].tick_params(labelsize=self.fontsize)
j = (j + 1)
plots[(l - 1)].set_xlabel('Time [sec]', fontsize=self.fontsize)
simfig.tight_layout()
simfig.canvas.draw()
plt.draw()
plt.show()
self.fig = simfig
self.plots = plots<|docstring|>Create a figure with trajectories for states, inputs, outputs and cost
----------------------------------------------------------------------
plot = 'All'
plot = 'xu'
plot = 'xy'
plot = 'x'
plot = 'u'
plot = 'y'
plot = 'j'
plot = 'z'<|endoftext|> |
51ca8b8f53ff90eb573392fa42a04910990df6fc427883d08db562ff953aba32 | def __init__(self, sys):
'\n \n sys = system.ContinuousDynamicSystem()\n \n sys needs to implement:\n \n get configuration from states, inputs and time\n ----------------------------------------------\n q = sys.xut2q( x , u , t )\n \n get graphic output list of lines from configuration\n ----------------------------------------------\n lines_pts = sys.forward_kinematic_lines( q )\n \n get graphic domain from configuration\n ----------------------------------------------\n ((,),(,),(,)) = sys.forward_kinematic_domain( q )\n \n '
self.sys = sys
self.x_axis = 0
self.y_axis = 1
self.figsize = (4, 3)
self.dpi = 300
self.linestyle = sys.linestyle
self.fontsize = 5
self.top_right_label = None | sys = system.ContinuousDynamicSystem()
sys needs to implement:
get configuration from states, inputs and time
----------------------------------------------
q = sys.xut2q( x , u , t )
get graphic output list of lines from configuration
----------------------------------------------
lines_pts = sys.forward_kinematic_lines( q )
get graphic domain from configuration
----------------------------------------------
((,),(,),(,)) = sys.forward_kinematic_domain( q ) | pyro/analysis/graphical.py | __init__ | alx87grd/AlexRobotics | 9 | python | def __init__(self, sys):
'\n \n sys = system.ContinuousDynamicSystem()\n \n sys needs to implement:\n \n get configuration from states, inputs and time\n ----------------------------------------------\n q = sys.xut2q( x , u , t )\n \n get graphic output list of lines from configuration\n ----------------------------------------------\n lines_pts = sys.forward_kinematic_lines( q )\n \n get graphic domain from configuration\n ----------------------------------------------\n ((,),(,),(,)) = sys.forward_kinematic_domain( q )\n \n '
self.sys = sys
self.x_axis = 0
self.y_axis = 1
self.figsize = (4, 3)
self.dpi = 300
self.linestyle = sys.linestyle
self.fontsize = 5
self.top_right_label = None | def __init__(self, sys):
'\n \n sys = system.ContinuousDynamicSystem()\n \n sys needs to implement:\n \n get configuration from states, inputs and time\n ----------------------------------------------\n q = sys.xut2q( x , u , t )\n \n get graphic output list of lines from configuration\n ----------------------------------------------\n lines_pts = sys.forward_kinematic_lines( q )\n \n get graphic domain from configuration\n ----------------------------------------------\n ((,),(,),(,)) = sys.forward_kinematic_domain( q )\n \n '
self.sys = sys
self.x_axis = 0
self.y_axis = 1
self.figsize = (4, 3)
self.dpi = 300
self.linestyle = sys.linestyle
self.fontsize = 5
self.top_right_label = None<|docstring|>sys = system.ContinuousDynamicSystem()
sys needs to implement:
get configuration from states, inputs and time
----------------------------------------------
q = sys.xut2q( x , u , t )
get graphic output list of lines from configuration
----------------------------------------------
lines_pts = sys.forward_kinematic_lines( q )
get graphic domain from configuration
----------------------------------------------
((,),(,),(,)) = sys.forward_kinematic_domain( q )<|endoftext|> |
ec08109c270b8cfe76ac8b89b3a1baa452d2c5c36a11f226ea1b212bb855b8e6 | def show(self, q, x_axis=0, y_axis=1):
' Plot figure of configuration q '
self.x_axis = x_axis
self.y_axis = y_axis
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.showfig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.showfig.canvas.manager.set_window_title(('2D Configuration of ' + self.sys.name))
self.showax = self.showfig.add_subplot(111, autoscale_on=False)
self.showax.grid()
self.showax.axis('equal')
self.showax.set_xlim(domain[x_axis])
self.showax.set_ylim(domain[y_axis])
self.showax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.showlines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, x_axis)]
y_pts = pts[(:, y_axis)]
linestyle = (lines_style[j] + lines_color[j])
line = self.showax.plot(x_pts, y_pts, linestyle)
self.showlines.append(line)
plt.show() | Plot figure of configuration q | pyro/analysis/graphical.py | show | alx87grd/AlexRobotics | 9 | python | def show(self, q, x_axis=0, y_axis=1):
' '
self.x_axis = x_axis
self.y_axis = y_axis
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.showfig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.showfig.canvas.manager.set_window_title(('2D Configuration of ' + self.sys.name))
self.showax = self.showfig.add_subplot(111, autoscale_on=False)
self.showax.grid()
self.showax.axis('equal')
self.showax.set_xlim(domain[x_axis])
self.showax.set_ylim(domain[y_axis])
self.showax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.showlines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, x_axis)]
y_pts = pts[(:, y_axis)]
linestyle = (lines_style[j] + lines_color[j])
line = self.showax.plot(x_pts, y_pts, linestyle)
self.showlines.append(line)
plt.show() | def show(self, q, x_axis=0, y_axis=1):
' '
self.x_axis = x_axis
self.y_axis = y_axis
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.showfig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.showfig.canvas.manager.set_window_title(('2D Configuration of ' + self.sys.name))
self.showax = self.showfig.add_subplot(111, autoscale_on=False)
self.showax.grid()
self.showax.axis('equal')
self.showax.set_xlim(domain[x_axis])
self.showax.set_ylim(domain[y_axis])
self.showax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.showlines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, x_axis)]
y_pts = pts[(:, y_axis)]
linestyle = (lines_style[j] + lines_color[j])
line = self.showax.plot(x_pts, y_pts, linestyle)
self.showlines.append(line)
plt.show()<|docstring|>Plot figure of configuration q<|endoftext|> |
502171ab91b5aee1684d04ee497f456f0022e63ee686e075c6c98477d2c9ade9 | def show3(self, q):
' Plot figure of configuration q '
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.show3fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.show3fig.canvas.manager.set_window_title(('3D Configuration of ' + self.sys.name))
self.show3ax = self.show3fig.gca(projection='3d')
self.show3lines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, 0)]
y_pts = pts[(:, 1)]
z_pts = pts[(:, 2)]
linestyle = (lines_style[j] + lines_color[j])
line = self.show3ax.plot(x_pts, y_pts, z_pts, linestyle)
self.show3lines.append(line)
self.show3ax.set_xlim3d(domain[0])
self.show3ax.set_xlabel('X')
self.show3ax.set_ylim3d(domain[1])
self.show3ax.set_ylabel('Y')
self.show3ax.set_zlim3d(domain[2])
self.show3ax.set_zlabel('Z')
self.show3ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
plt.show() | Plot figure of configuration q | pyro/analysis/graphical.py | show3 | alx87grd/AlexRobotics | 9 | python | def show3(self, q):
' '
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.show3fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.show3fig.canvas.manager.set_window_title(('3D Configuration of ' + self.sys.name))
self.show3ax = self.show3fig.gca(projection='3d')
self.show3lines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, 0)]
y_pts = pts[(:, 1)]
z_pts = pts[(:, 2)]
linestyle = (lines_style[j] + lines_color[j])
line = self.show3ax.plot(x_pts, y_pts, z_pts, linestyle)
self.show3lines.append(line)
self.show3ax.set_xlim3d(domain[0])
self.show3ax.set_xlabel('X')
self.show3ax.set_ylim3d(domain[1])
self.show3ax.set_ylabel('Y')
self.show3ax.set_zlim3d(domain[2])
self.show3ax.set_zlabel('Z')
self.show3ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
plt.show() | def show3(self, q):
' '
lines = self.sys.forward_kinematic_lines(q)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
self.show3fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
self.show3fig.canvas.manager.set_window_title(('3D Configuration of ' + self.sys.name))
self.show3ax = self.show3fig.gca(projection='3d')
self.show3lines = []
for (j, pts) in enumerate(lines_pts):
x_pts = pts[(:, 0)]
y_pts = pts[(:, 1)]
z_pts = pts[(:, 2)]
linestyle = (lines_style[j] + lines_color[j])
line = self.show3ax.plot(x_pts, y_pts, z_pts, linestyle)
self.show3lines.append(line)
self.show3ax.set_xlim3d(domain[0])
self.show3ax.set_xlabel('X')
self.show3ax.set_ylim3d(domain[1])
self.show3ax.set_ylabel('Y')
self.show3ax.set_zlim3d(domain[2])
self.show3ax.set_zlabel('Z')
self.show3ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
plt.show()<|docstring|>Plot figure of configuration q<|endoftext|> |
bdc21c62de058ada2c6a381bb6e5e8f9568c8351e94062a76a3919e365d86cfb | def get_lines(self, x, u, t):
' \n shorcut to get all graphic output data\n '
q = self.sys.xut2q(x, u, t)
lines = self.sys.forward_kinematic_lines(q)
lines_plus = self.sys.forward_kinematic_lines_plus(x, u, t)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
if (type(lines_plus) is tuple):
lines_plus_pts = lines_plus[0]
lines_plus_style = lines_plus[1]
lines_plus_color = lines_plus[2]
else:
lines_plus_pts = lines_plus
lines_plus_style = []
lines_plus_color = []
for (j, line_plus) in enumerate(lines_plus):
lines_plus_style.append(self.sys.linestyle_plus)
lines_plus_color.append(self.sys.linescolor_plus)
lines_data = (lines_pts, lines_style, lines_color, lines_plus_pts, lines_plus_style, lines_plus_color, domain)
return lines_data | shorcut to get all graphic output data | pyro/analysis/graphical.py | get_lines | alx87grd/AlexRobotics | 9 | python | def get_lines(self, x, u, t):
' \n \n '
q = self.sys.xut2q(x, u, t)
lines = self.sys.forward_kinematic_lines(q)
lines_plus = self.sys.forward_kinematic_lines_plus(x, u, t)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
if (type(lines_plus) is tuple):
lines_plus_pts = lines_plus[0]
lines_plus_style = lines_plus[1]
lines_plus_color = lines_plus[2]
else:
lines_plus_pts = lines_plus
lines_plus_style = []
lines_plus_color = []
for (j, line_plus) in enumerate(lines_plus):
lines_plus_style.append(self.sys.linestyle_plus)
lines_plus_color.append(self.sys.linescolor_plus)
lines_data = (lines_pts, lines_style, lines_color, lines_plus_pts, lines_plus_style, lines_plus_color, domain)
return lines_data | def get_lines(self, x, u, t):
' \n \n '
q = self.sys.xut2q(x, u, t)
lines = self.sys.forward_kinematic_lines(q)
lines_plus = self.sys.forward_kinematic_lines_plus(x, u, t)
domain = self.sys.forward_kinematic_domain(q)
if (type(lines) is tuple):
lines_pts = lines[0]
lines_style = lines[1]
lines_color = lines[2]
else:
lines_pts = lines
lines_style = []
lines_color = []
for (j, line) in enumerate(lines):
lines_style.append(self.sys.linestyle)
lines_color.append(self.sys.linescolor)
if (type(lines_plus) is tuple):
lines_plus_pts = lines_plus[0]
lines_plus_style = lines_plus[1]
lines_plus_color = lines_plus[2]
else:
lines_plus_pts = lines_plus
lines_plus_style = []
lines_plus_color = []
for (j, line_plus) in enumerate(lines_plus):
lines_plus_style.append(self.sys.linestyle_plus)
lines_plus_color.append(self.sys.linescolor_plus)
lines_data = (lines_pts, lines_style, lines_color, lines_plus_pts, lines_plus_style, lines_plus_color, domain)
return lines_data<|docstring|>shorcut to get all graphic output data<|endoftext|> |
c6e41e11f04eb33092cd7f47fbb936a243ee411bf50364f4e4d1f42a81451928 | def animate_simulation(self, traj, time_factor_video=1.0, is_3d=False, save=False, file_name='Animation', show=True):
' \n Show Animation of the simulation \n ----------------------------------\n time_factor_video < 1 --> Slow motion video \n \n '
self.is_3d = is_3d
self.ani_lines_pts = []
self.ani_lines_style = []
self.ani_lines_color = []
self.ani_lines_plus_pts = []
self.ani_lines_plus_style = []
self.ani_lines_plus_color = []
self.ani_domains = []
nsteps = traj.t.size
self.sim_dt = ((traj.t[(- 1)] - traj.t[0]) / (traj.t.size - 1))
for i in range(nsteps):
x = traj.x[(i, :)]
u = traj.u[(i, :)]
t = traj.t[i]
lines_data = self.get_lines(x, u, t)
self.ani_lines_pts.append(lines_data[0])
self.ani_lines_style.append(lines_data[1])
self.ani_lines_color.append(lines_data[2])
self.ani_lines_plus_pts.append(lines_data[3])
self.ani_lines_plus_style.append(lines_data[4])
self.ani_lines_plus_color.append(lines_data[5])
self.ani_domains.append(lines_data[6])
self.ani_fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
if is_3d:
self.ani_ax = p3.Axes3D(self.ani_fig)
self.ani_ax.set_xlim3d(self.ani_domains[0][0])
self.ani_ax.set_xlabel('X')
self.ani_ax.set_ylim3d(self.ani_domains[0][1])
self.ani_ax.set_ylabel('Y')
self.ani_ax.set_zlim3d(self.ani_domains[0][2])
self.ani_ax.set_zlabel('Z')
self.ani_fig.canvas.manager.set_window_title(('3D Animation of ' + self.sys.name))
else:
self.ani_ax = self.ani_fig.add_subplot(111, autoscale_on=True)
self.ani_ax.axis('equal')
self.ani_ax.set_xlim(self.ani_domains[0][self.x_axis])
self.ani_ax.set_ylim(self.ani_domains[0][self.y_axis])
self.ani_fig.canvas.manager.set_window_title(('2D Animation of ' + self.sys.name))
self.ani_ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.ani_ax.grid()
self.lines = []
self.lines_plus = []
for (j, line_pts) in enumerate(self.ani_lines_pts[0]):
linestyle = (self.ani_lines_style[0][j] + self.ani_lines_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
self.time_text = self.ani_ax.text(0, 0, 0, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.9, 0.9, 0.9, self.top_right_label)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.time_text = self.ani_ax.text(0.05, 0.9, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.75, 0.8, self.top_right_label, transform=self.ani_ax.transAxes)
self.ani_fig.tight_layout()
self.lines.append(line)
if self.sys.lines_plus:
for (j, line_pts) in enumerate(self.ani_lines_plus_pts[0]):
linestyle = (self.ani_lines_plus_style[0][j] + self.ani_lines_plus_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.lines_plus.append(line)
self.time_template = 'time = %.1fs'
inter = 40.0
frame_dt = (inter / 1000.0)
if ((frame_dt * time_factor_video) < self.sim_dt):
self.skip_steps = 1
inter = ((self.sim_dt * 1000.0) / time_factor_video)
n_frame = nsteps
else:
factor = ((frame_dt / self.sim_dt) * time_factor_video)
self.skip_steps = int(factor)
n_frame = int((nsteps / self.skip_steps))
if self.is_3d:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter)
else:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter, init_func=self.__ani_init__)
if save:
self.ani.save((file_name + '.gif'), writer='imagemagick', fps=30)
if show:
plt.ioff()
plt.show()
else:
plt.close(self.ani_fig) | Show Animation of the simulation
----------------------------------
time_factor_video < 1 --> Slow motion video | pyro/analysis/graphical.py | animate_simulation | alx87grd/AlexRobotics | 9 | python | def animate_simulation(self, traj, time_factor_video=1.0, is_3d=False, save=False, file_name='Animation', show=True):
' \n Show Animation of the simulation \n ----------------------------------\n time_factor_video < 1 --> Slow motion video \n \n '
self.is_3d = is_3d
self.ani_lines_pts = []
self.ani_lines_style = []
self.ani_lines_color = []
self.ani_lines_plus_pts = []
self.ani_lines_plus_style = []
self.ani_lines_plus_color = []
self.ani_domains = []
nsteps = traj.t.size
self.sim_dt = ((traj.t[(- 1)] - traj.t[0]) / (traj.t.size - 1))
for i in range(nsteps):
x = traj.x[(i, :)]
u = traj.u[(i, :)]
t = traj.t[i]
lines_data = self.get_lines(x, u, t)
self.ani_lines_pts.append(lines_data[0])
self.ani_lines_style.append(lines_data[1])
self.ani_lines_color.append(lines_data[2])
self.ani_lines_plus_pts.append(lines_data[3])
self.ani_lines_plus_style.append(lines_data[4])
self.ani_lines_plus_color.append(lines_data[5])
self.ani_domains.append(lines_data[6])
self.ani_fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
if is_3d:
self.ani_ax = p3.Axes3D(self.ani_fig)
self.ani_ax.set_xlim3d(self.ani_domains[0][0])
self.ani_ax.set_xlabel('X')
self.ani_ax.set_ylim3d(self.ani_domains[0][1])
self.ani_ax.set_ylabel('Y')
self.ani_ax.set_zlim3d(self.ani_domains[0][2])
self.ani_ax.set_zlabel('Z')
self.ani_fig.canvas.manager.set_window_title(('3D Animation of ' + self.sys.name))
else:
self.ani_ax = self.ani_fig.add_subplot(111, autoscale_on=True)
self.ani_ax.axis('equal')
self.ani_ax.set_xlim(self.ani_domains[0][self.x_axis])
self.ani_ax.set_ylim(self.ani_domains[0][self.y_axis])
self.ani_fig.canvas.manager.set_window_title(('2D Animation of ' + self.sys.name))
self.ani_ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.ani_ax.grid()
self.lines = []
self.lines_plus = []
for (j, line_pts) in enumerate(self.ani_lines_pts[0]):
linestyle = (self.ani_lines_style[0][j] + self.ani_lines_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
self.time_text = self.ani_ax.text(0, 0, 0, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.9, 0.9, 0.9, self.top_right_label)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.time_text = self.ani_ax.text(0.05, 0.9, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.75, 0.8, self.top_right_label, transform=self.ani_ax.transAxes)
self.ani_fig.tight_layout()
self.lines.append(line)
if self.sys.lines_plus:
for (j, line_pts) in enumerate(self.ani_lines_plus_pts[0]):
linestyle = (self.ani_lines_plus_style[0][j] + self.ani_lines_plus_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.lines_plus.append(line)
self.time_template = 'time = %.1fs'
inter = 40.0
frame_dt = (inter / 1000.0)
if ((frame_dt * time_factor_video) < self.sim_dt):
self.skip_steps = 1
inter = ((self.sim_dt * 1000.0) / time_factor_video)
n_frame = nsteps
else:
factor = ((frame_dt / self.sim_dt) * time_factor_video)
self.skip_steps = int(factor)
n_frame = int((nsteps / self.skip_steps))
if self.is_3d:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter)
else:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter, init_func=self.__ani_init__)
if save:
self.ani.save((file_name + '.gif'), writer='imagemagick', fps=30)
if show:
plt.ioff()
plt.show()
else:
plt.close(self.ani_fig) | def animate_simulation(self, traj, time_factor_video=1.0, is_3d=False, save=False, file_name='Animation', show=True):
' \n Show Animation of the simulation \n ----------------------------------\n time_factor_video < 1 --> Slow motion video \n \n '
self.is_3d = is_3d
self.ani_lines_pts = []
self.ani_lines_style = []
self.ani_lines_color = []
self.ani_lines_plus_pts = []
self.ani_lines_plus_style = []
self.ani_lines_plus_color = []
self.ani_domains = []
nsteps = traj.t.size
self.sim_dt = ((traj.t[(- 1)] - traj.t[0]) / (traj.t.size - 1))
for i in range(nsteps):
x = traj.x[(i, :)]
u = traj.u[(i, :)]
t = traj.t[i]
lines_data = self.get_lines(x, u, t)
self.ani_lines_pts.append(lines_data[0])
self.ani_lines_style.append(lines_data[1])
self.ani_lines_color.append(lines_data[2])
self.ani_lines_plus_pts.append(lines_data[3])
self.ani_lines_plus_style.append(lines_data[4])
self.ani_lines_plus_color.append(lines_data[5])
self.ani_domains.append(lines_data[6])
self.ani_fig = plt.figure(figsize=self.figsize, dpi=self.dpi)
if is_3d:
self.ani_ax = p3.Axes3D(self.ani_fig)
self.ani_ax.set_xlim3d(self.ani_domains[0][0])
self.ani_ax.set_xlabel('X')
self.ani_ax.set_ylim3d(self.ani_domains[0][1])
self.ani_ax.set_ylabel('Y')
self.ani_ax.set_zlim3d(self.ani_domains[0][2])
self.ani_ax.set_zlabel('Z')
self.ani_fig.canvas.manager.set_window_title(('3D Animation of ' + self.sys.name))
else:
self.ani_ax = self.ani_fig.add_subplot(111, autoscale_on=True)
self.ani_ax.axis('equal')
self.ani_ax.set_xlim(self.ani_domains[0][self.x_axis])
self.ani_ax.set_ylim(self.ani_domains[0][self.y_axis])
self.ani_fig.canvas.manager.set_window_title(('2D Animation of ' + self.sys.name))
self.ani_ax.tick_params(axis='both', which='both', labelsize=self.fontsize)
self.ani_ax.grid()
self.lines = []
self.lines_plus = []
for (j, line_pts) in enumerate(self.ani_lines_pts[0]):
linestyle = (self.ani_lines_style[0][j] + self.ani_lines_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
self.time_text = self.ani_ax.text(0, 0, 0, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.9, 0.9, 0.9, self.top_right_label)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.time_text = self.ani_ax.text(0.05, 0.9, 'time =', transform=self.ani_ax.transAxes)
self.label_text = self.ani_ax.text(0.75, 0.8, self.top_right_label, transform=self.ani_ax.transAxes)
self.ani_fig.tight_layout()
self.lines.append(line)
if self.sys.lines_plus:
for (j, line_pts) in enumerate(self.ani_lines_plus_pts[0]):
linestyle = (self.ani_lines_plus_style[0][j] + self.ani_lines_plus_color[0][j])
if is_3d:
thisx = line_pts[(:, 0)]
thisy = line_pts[(:, 1)]
thisz = line_pts[(:, 2)]
(line,) = self.ani_ax.plot(thisx, thisy, thisz, linestyle)
else:
thisx = line_pts[(:, self.x_axis)]
thisy = line_pts[(:, self.y_axis)]
(line,) = self.ani_ax.plot(thisx, thisy, linestyle)
self.lines_plus.append(line)
self.time_template = 'time = %.1fs'
inter = 40.0
frame_dt = (inter / 1000.0)
if ((frame_dt * time_factor_video) < self.sim_dt):
self.skip_steps = 1
inter = ((self.sim_dt * 1000.0) / time_factor_video)
n_frame = nsteps
else:
factor = ((frame_dt / self.sim_dt) * time_factor_video)
self.skip_steps = int(factor)
n_frame = int((nsteps / self.skip_steps))
if self.is_3d:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter)
else:
self.ani = animation.FuncAnimation(self.ani_fig, self.__animate__, n_frame, interval=inter, init_func=self.__ani_init__)
if save:
self.ani.save((file_name + '.gif'), writer='imagemagick', fps=30)
if show:
plt.ioff()
plt.show()
else:
plt.close(self.ani_fig)<|docstring|>Show Animation of the simulation
----------------------------------
time_factor_video < 1 --> Slow motion video<|endoftext|> |
1ad03d441e5c787615b2c6f102b43e76aa7ec789d719f3d573266624609b8258 | def chunks(l, n):
'Yield successive n-sized chunks from a list.\n\n Args:\n l: List of elements to split\n n: Number of chunks to split into\n Yields:\n n-sized chunks\n '
for i in range(0, len(l), n):
(yield l[i:(i + n)]) | Yield successive n-sized chunks from a list.
Args:
l: List of elements to split
n: Number of chunks to split into
Yields:
n-sized chunks | tradefed_cluster/host_event_api.py | chunks | maksonlee/tradefed_cluster | 0 | python | def chunks(l, n):
'Yield successive n-sized chunks from a list.\n\n Args:\n l: List of elements to split\n n: Number of chunks to split into\n Yields:\n n-sized chunks\n '
for i in range(0, len(l), n):
(yield l[i:(i + n)]) | def chunks(l, n):
'Yield successive n-sized chunks from a list.\n\n Args:\n l: List of elements to split\n n: Number of chunks to split into\n Yields:\n n-sized chunks\n '
for i in range(0, len(l), n):
(yield l[i:(i + n)])<|docstring|>Yield successive n-sized chunks from a list.
Args:
l: List of elements to split
n: Number of chunks to split into
Yields:
n-sized chunks<|endoftext|> |
4205106db5b66febc125670aaac2c3facbbc33aaa726aa6631a1022f4af07749 | @endpoints.method(HostEventList, message_types.VoidMessage, path='/host_events', http_method='POST', name='submit')
@api_common.with_ndb_context
def SubmitHostEvents(self, request):
'Submit a bundle of cluster host events for processing.\n\n Args:\n request: a HostEventList\n Returns:\n a VoidMessage\n '
encoded_message = protojson.encode_message(request)
json_message = json.loads(encoded_message)
host_events = json_message.get('host_events')
if (not host_events):
raise endpoints.BadRequestException('Request has no host_events.')
logging.info('Submitting host event message with size %d and %d events', len(encoded_message), len(host_events))
for event_chunk in chunks(host_events, CHUNK_SIZE):
logging.info('Queuing host event chunk of size %d', len(event_chunk))
task_scheduler.AddCallableTask(self._ProcessHostEventWithNDB, event_chunk, _queue=host_event.HOST_EVENT_QUEUE_NDB, _target=('%s.%s' % (common.GetServiceVersion(), common.GetServiceName())))
logging.debug('Submitted host event message.')
return message_types.VoidMessage() | Submit a bundle of cluster host events for processing.
Args:
request: a HostEventList
Returns:
a VoidMessage | tradefed_cluster/host_event_api.py | SubmitHostEvents | maksonlee/tradefed_cluster | 0 | python | @endpoints.method(HostEventList, message_types.VoidMessage, path='/host_events', http_method='POST', name='submit')
@api_common.with_ndb_context
def SubmitHostEvents(self, request):
'Submit a bundle of cluster host events for processing.\n\n Args:\n request: a HostEventList\n Returns:\n a VoidMessage\n '
encoded_message = protojson.encode_message(request)
json_message = json.loads(encoded_message)
host_events = json_message.get('host_events')
if (not host_events):
raise endpoints.BadRequestException('Request has no host_events.')
logging.info('Submitting host event message with size %d and %d events', len(encoded_message), len(host_events))
for event_chunk in chunks(host_events, CHUNK_SIZE):
logging.info('Queuing host event chunk of size %d', len(event_chunk))
task_scheduler.AddCallableTask(self._ProcessHostEventWithNDB, event_chunk, _queue=host_event.HOST_EVENT_QUEUE_NDB, _target=('%s.%s' % (common.GetServiceVersion(), common.GetServiceName())))
logging.debug('Submitted host event message.')
return message_types.VoidMessage() | @endpoints.method(HostEventList, message_types.VoidMessage, path='/host_events', http_method='POST', name='submit')
@api_common.with_ndb_context
def SubmitHostEvents(self, request):
'Submit a bundle of cluster host events for processing.\n\n Args:\n request: a HostEventList\n Returns:\n a VoidMessage\n '
encoded_message = protojson.encode_message(request)
json_message = json.loads(encoded_message)
host_events = json_message.get('host_events')
if (not host_events):
raise endpoints.BadRequestException('Request has no host_events.')
logging.info('Submitting host event message with size %d and %d events', len(encoded_message), len(host_events))
for event_chunk in chunks(host_events, CHUNK_SIZE):
logging.info('Queuing host event chunk of size %d', len(event_chunk))
task_scheduler.AddCallableTask(self._ProcessHostEventWithNDB, event_chunk, _queue=host_event.HOST_EVENT_QUEUE_NDB, _target=('%s.%s' % (common.GetServiceVersion(), common.GetServiceName())))
logging.debug('Submitted host event message.')
return message_types.VoidMessage()<|docstring|>Submit a bundle of cluster host events for processing.
Args:
request: a HostEventList
Returns:
a VoidMessage<|endoftext|> |
87e2688e40f6a9befed0f9ef0bf9080e2b3aa1889bc98820e23ba03808baada3 | def _ProcessHostEventWithNDB(self, events):
"Deferred function to process submitted host events.\n\n Do not change this function's name (_ProcessHostEventWithNDB) as deferred\n stores it as part of the tasks in the push queue which is used to know\n what to execute when the tasked is dequeued.\n\n Args:\n events: a A list of host events.\n "
logging.debug('Processing %d events.', len(events))
for e in events:
logging.debug('Processing event: %s.', e)
if (not device_manager.IsHostEventValid(e)):
logging.warning('Host event is invalid. Ignoring: %s', e)
continue
event = host_event.HostEvent(**e)
device_manager.HandleDeviceSnapshotWithNDB(event)
logging.debug('Finished processing event.')
logging.debug('Finished processing %d events.', len(events)) | Deferred function to process submitted host events.
Do not change this function's name (_ProcessHostEventWithNDB) as deferred
stores it as part of the tasks in the push queue which is used to know
what to execute when the tasked is dequeued.
Args:
events: a A list of host events. | tradefed_cluster/host_event_api.py | _ProcessHostEventWithNDB | maksonlee/tradefed_cluster | 0 | python | def _ProcessHostEventWithNDB(self, events):
"Deferred function to process submitted host events.\n\n Do not change this function's name (_ProcessHostEventWithNDB) as deferred\n stores it as part of the tasks in the push queue which is used to know\n what to execute when the tasked is dequeued.\n\n Args:\n events: a A list of host events.\n "
logging.debug('Processing %d events.', len(events))
for e in events:
logging.debug('Processing event: %s.', e)
if (not device_manager.IsHostEventValid(e)):
logging.warning('Host event is invalid. Ignoring: %s', e)
continue
event = host_event.HostEvent(**e)
device_manager.HandleDeviceSnapshotWithNDB(event)
logging.debug('Finished processing event.')
logging.debug('Finished processing %d events.', len(events)) | def _ProcessHostEventWithNDB(self, events):
"Deferred function to process submitted host events.\n\n Do not change this function's name (_ProcessHostEventWithNDB) as deferred\n stores it as part of the tasks in the push queue which is used to know\n what to execute when the tasked is dequeued.\n\n Args:\n events: a A list of host events.\n "
logging.debug('Processing %d events.', len(events))
for e in events:
logging.debug('Processing event: %s.', e)
if (not device_manager.IsHostEventValid(e)):
logging.warning('Host event is invalid. Ignoring: %s', e)
continue
event = host_event.HostEvent(**e)
device_manager.HandleDeviceSnapshotWithNDB(event)
logging.debug('Finished processing event.')
logging.debug('Finished processing %d events.', len(events))<|docstring|>Deferred function to process submitted host events.
Do not change this function's name (_ProcessHostEventWithNDB) as deferred
stores it as part of the tasks in the push queue which is used to know
what to execute when the tasked is dequeued.
Args:
events: a A list of host events.<|endoftext|> |
c372745f827da941531c1df205accf60807cedebaa50614c1742ca2aa5a87ea3 | def starfish_ish(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.040431211565) + 0.388620268274j)
return (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p)))))))))) | par_set['zoom'] = 5/8
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | starfish_ish | dlanier/FlyingMachineFractal | 4 | python | def starfish_ish(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.040431211565) + 0.388620268274j)
return (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p)))))))))) | def starfish_ish(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.040431211565) + 0.388620268274j)
return (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p))))))))))<|docstring|>par_set['zoom'] = 5/8
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
65c6a21b0d1d1c9c667e0a751ac4abed026a09a82385cfecc79cc08e1108456c | def starfish_ish_II(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.05144829323) + 0.304348945637j)
Z = (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p)))))))))))))
return Z | par_set['zoom'] = 5/8
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | starfish_ish_II | dlanier/FlyingMachineFractal | 4 | python | def starfish_ish_II(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.05144829323) + 0.304348945637j)
Z = (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p)))))))))))))
return Z | def starfish_ish_II(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 5/8\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = ((- 0.05144829323) + 0.304348945637j)
Z = (Z ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- (np.exp((Z ** p)) ** (np.exp((Z ** p)) ** (- np.exp((Z ** p)))))))))))))
return Z<|docstring|>par_set['zoom'] = 5/8
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
4f36205b711493b90060cce2eaf924b5aed1fa08bb51ed64fd19b98dd1c3fa2f | def Nautuliz(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [2.792422080721, (1.227827869496 + 0.063564967216j)]
Z = ((Z ** (- (p[0] ** (- (Z ** (- p[1])))))) - (p[0] ** (- (Z ** p[1]))))
return Z | par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | Nautuliz | dlanier/FlyingMachineFractal | 4 | python | def Nautuliz(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [2.792422080721, (1.227827869496 + 0.063564967216j)]
Z = ((Z ** (- (p[0] ** (- (Z ** (- p[1])))))) - (p[0] ** (- (Z ** p[1]))))
return Z | def Nautuliz(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [2.792422080721, (1.227827869496 + 0.063564967216j)]
Z = ((Z ** (- (p[0] ** (- (Z ** (- p[1])))))) - (p[0] ** (- (Z ** p[1]))))
return Z<|docstring|>par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
29d641031d73f81fb06154054c2afab9447255b1aa90f6ae6da5a1a83de7b25a | def decPwrAFx(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/8\n\n Args:\n Z: a real or complex number\n p: array real of complex number\n Returns:\n Z: the result (complex)\n Z = 1/Z - Z^(n*Z^(P(n)^n) / sqrt(pi));\n "
if (p is None):
p = [np.sqrt(np.pi), 1.13761386, (- 0.11556857)]
for n in range(1, len(p)):
Z = ((1 / Z) - (Z ** ((n * (Z ** (p[n] ** n))) / p[0])))
return Z | par_set['zoom'] = 1/8
Args:
Z: a real or complex number
p: array real of complex number
Returns:
Z: the result (complex)
Z = 1/Z - Z^(n*Z^(P(n)^n) / sqrt(pi)); | pyreimpic/functions_demo_01.py | decPwrAFx | dlanier/FlyingMachineFractal | 4 | python | def decPwrAFx(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/8\n\n Args:\n Z: a real or complex number\n p: array real of complex number\n Returns:\n Z: the result (complex)\n Z = 1/Z - Z^(n*Z^(P(n)^n) / sqrt(pi));\n "
if (p is None):
p = [np.sqrt(np.pi), 1.13761386, (- 0.11556857)]
for n in range(1, len(p)):
Z = ((1 / Z) - (Z ** ((n * (Z ** (p[n] ** n))) / p[0])))
return Z | def decPwrAFx(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/8\n\n Args:\n Z: a real or complex number\n p: array real of complex number\n Returns:\n Z: the result (complex)\n Z = 1/Z - Z^(n*Z^(P(n)^n) / sqrt(pi));\n "
if (p is None):
p = [np.sqrt(np.pi), 1.13761386, (- 0.11556857)]
for n in range(1, len(p)):
Z = ((1 / Z) - (Z ** ((n * (Z ** (p[n] ** n))) / p[0])))
return Z<|docstring|>par_set['zoom'] = 1/8
Args:
Z: a real or complex number
p: array real of complex number
Returns:
Z: the result (complex)
Z = 1/Z - Z^(n*Z^(P(n)^n) / sqrt(pi));<|endoftext|> |
4e0a222c1c4913305d0815c18b2c833887f8df9626b02db44ce3c48e8a586cdb | def dreadSkull(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 0.4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n p[0]\n\n MATLAB:\n Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x))))))))\n "
if (p is None):
p = (- 0.295887110004)
ZEP = np.exp((Z ** p))
Zout = ((- Z) ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- ZEP)))))))))))
return Zout | par_set['zoom'] = 0.4
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)
p[0]
MATLAB:
Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)))))))) | pyreimpic/functions_demo_01.py | dreadSkull | dlanier/FlyingMachineFractal | 4 | python | def dreadSkull(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 0.4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n p[0]\n\n MATLAB:\n Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x))))))))\n "
if (p is None):
p = (- 0.295887110004)
ZEP = np.exp((Z ** p))
Zout = ((- Z) ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- ZEP)))))))))))
return Zout | def dreadSkull(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 0.4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n p[0]\n\n MATLAB:\n Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x))))))))\n "
if (p is None):
p = (- 0.295887110004)
ZEP = np.exp((Z ** p))
Zout = ((- Z) ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- (ZEP ** (ZEP ** (- ZEP)))))))))))
return Zout<|docstring|>par_set['zoom'] = 0.4
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)
p[0]
MATLAB:
Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x))))))))<|endoftext|> |
bb08de461035497809cae4593cc91b4be1d00ec606b3e432c314d10c146068d3 | def IslaLace(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.444476893762, (0.508164683992 + 0.420921535772j)]
x = p[0]
c = p[1]
Z = ((((Z ** (- (x ** (Z ** (- c))))) + (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) - (Z ** (- (x ** (- (Z ** (- c)))))))) + (((Z ** (- (x ** (Z ** (- c))))) - (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) + (Z ** (- (x ** (- (Z ** (- c)))))))))
return Z | par_set['zoom'] = 1/4
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | IslaLace | dlanier/FlyingMachineFractal | 4 | python | def IslaLace(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.444476893762, (0.508164683992 + 0.420921535772j)]
x = p[0]
c = p[1]
Z = ((((Z ** (- (x ** (Z ** (- c))))) + (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) - (Z ** (- (x ** (- (Z ** (- c)))))))) + (((Z ** (- (x ** (Z ** (- c))))) - (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) + (Z ** (- (x ** (- (Z ** (- c)))))))))
return Z | def IslaLace(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/4\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.444476893762, (0.508164683992 + 0.420921535772j)]
x = p[0]
c = p[1]
Z = ((((Z ** (- (x ** (Z ** (- c))))) + (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) - (Z ** (- (x ** (- (Z ** (- c)))))))) + (((Z ** (- (x ** (Z ** (- c))))) - (x ** (- (Z ** (- (c ** Z)))))) * ((c ** (- (Z ** (- (x ** Z))))) + (Z ** (- (x ** (- (Z ** (- c)))))))))
return Z<|docstring|>par_set['zoom'] = 1/4
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
289ff2ce6a62f3ebb8012a2234fa3425b3a31f8292e0308b3de1b9cf56f9dfdc | def RoyalZ(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.340859990388, 0.26928225032, (- 0.255017720861)]
nc = len(p)
for n in range(0, nc):
Z = (Z ** ((- 1) * np.exp((Z * p[n]))))
return Z | par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | RoyalZ | dlanier/FlyingMachineFractal | 4 | python | def RoyalZ(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.340859990388, 0.26928225032, (- 0.255017720861)]
nc = len(p)
for n in range(0, nc):
Z = (Z ** ((- 1) * np.exp((Z * p[n]))))
return Z | def RoyalZ(Z, p=None, Z0=None, ET=None):
"\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.340859990388, 0.26928225032, (- 0.255017720861)]
nc = len(p)
for n in range(0, nc):
Z = (Z ** ((- 1) * np.exp((Z * p[n]))))
return Z<|docstring|>par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
96c0ed88b532797362e318a6554bd8eaef3c9aabcb1bcc472815c2395defa2db | def T_Spake_Z(Z, p, Z0=None, ET=None):
" Z = T_Spake_Z(Z, p)\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [1.92846051108342, 2.27919841968635, 3.37327534248407, 2.17984103218476]
d = np.abs((Z - Z0))
Zxy = np.sqrt((Z / np.abs(Z)))
x = np.real(Zxy)
y = (np.imag(Zxy) * 1j)
Z = (Z - (((((p[0] * (x ** 3)) + (((3 * p[1]) * (x ** 2)) * y)) + (((3 * p[2]) * x) * (y ** 2))) + (p[3] * (y ** 3))) ** (Z * d)))
return Z | Z = T_Spake_Z(Z, p)
par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | T_Spake_Z | dlanier/FlyingMachineFractal | 4 | python | def T_Spake_Z(Z, p, Z0=None, ET=None):
" Z = T_Spake_Z(Z, p)\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [1.92846051108342, 2.27919841968635, 3.37327534248407, 2.17984103218476]
d = np.abs((Z - Z0))
Zxy = np.sqrt((Z / np.abs(Z)))
x = np.real(Zxy)
y = (np.imag(Zxy) * 1j)
Z = (Z - (((((p[0] * (x ** 3)) + (((3 * p[1]) * (x ** 2)) * y)) + (((3 * p[2]) * x) * (y ** 2))) + (p[3] * (y ** 3))) ** (Z * d)))
return Z | def T_Spake_Z(Z, p, Z0=None, ET=None):
" Z = T_Spake_Z(Z, p)\n par_set['zoom'] = 1/3\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [1.92846051108342, 2.27919841968635, 3.37327534248407, 2.17984103218476]
d = np.abs((Z - Z0))
Zxy = np.sqrt((Z / np.abs(Z)))
x = np.real(Zxy)
y = (np.imag(Zxy) * 1j)
Z = (Z - (((((p[0] * (x ** 3)) + (((3 * p[1]) * (x ** 2)) * y)) + (((3 * p[2]) * x) * (y ** 2))) + (p[3] * (y ** 3))) ** (Z * d)))
return Z<|docstring|>Z = T_Spake_Z(Z, p)
par_set['zoom'] = 1/3
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
5d0c9effa504f2864882b35a88e1cdf155cd3569d32b4081762436c57fdb73ef | def ItchicuPpwrF(Z, p=None, Z0=None, ET=None, Zm1=0, Zm2=0):
"\n par_set['zoom'] = 0.16\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.56890021, (- 0.25564542), (- 0.37746896), (- 0.29588711), (- 1.47513451), (- 0.23400405), 0.11844484]
for n in range(0, (len(p) - 1)):
try:
Zn = (Z ** (2 * (Z ** (- (p[n] ** (Z ** (- p[(n + 1)])))))))
except:
return Z
pass
if np.isfinite(Zn):
Z = Zn
else:
return Z
return Z | par_set['zoom'] = 0.16
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex) | pyreimpic/functions_demo_01.py | ItchicuPpwrF | dlanier/FlyingMachineFractal | 4 | python | def ItchicuPpwrF(Z, p=None, Z0=None, ET=None, Zm1=0, Zm2=0):
"\n par_set['zoom'] = 0.16\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.56890021, (- 0.25564542), (- 0.37746896), (- 0.29588711), (- 1.47513451), (- 0.23400405), 0.11844484]
for n in range(0, (len(p) - 1)):
try:
Zn = (Z ** (2 * (Z ** (- (p[n] ** (Z ** (- p[(n + 1)])))))))
except:
return Z
pass
if np.isfinite(Zn):
Z = Zn
else:
return Z
return Z | def ItchicuPpwrF(Z, p=None, Z0=None, ET=None, Zm1=0, Zm2=0):
"\n par_set['zoom'] = 0.16\n\n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n "
if (p is None):
p = [0.56890021, (- 0.25564542), (- 0.37746896), (- 0.29588711), (- 1.47513451), (- 0.23400405), 0.11844484]
for n in range(0, (len(p) - 1)):
try:
Zn = (Z ** (2 * (Z ** (- (p[n] ** (Z ** (- p[(n + 1)])))))))
except:
return Z
pass
if np.isfinite(Zn):
Z = Zn
else:
return Z
return Z<|docstring|>par_set['zoom'] = 0.16
Args:
Z: a real or complex number
p: a real of complex number
Returns:
Z: the result (complex)<|endoftext|> |
5ac2c34a8dee823406d327534fe2d90341d49d86342adb263194575540db67a0 | def get_lines_from_content(content: str, filemode: Filemode, is_patch: bool, show_secrets: bool) -> List[Line]:
'\n Return the secrets and the lines with line number.\n\n :param scan_result: Scan result from the API call\n :param show_secrets: Option to hide secrets value\n :param is_patch: Is the content a patch\n '
if is_patch:
return list(get_lines_from_patch(content, filemode))
return list(get_lines_from_file(content)) | Return the secrets and the lines with line number.
:param scan_result: Scan result from the API call
:param show_secrets: Option to hide secrets value
:param is_patch: Is the content a patch | ggshield/utils.py | get_lines_from_content | SofienM/ggtest-ci | 0 | python | def get_lines_from_content(content: str, filemode: Filemode, is_patch: bool, show_secrets: bool) -> List[Line]:
'\n Return the secrets and the lines with line number.\n\n :param scan_result: Scan result from the API call\n :param show_secrets: Option to hide secrets value\n :param is_patch: Is the content a patch\n '
if is_patch:
return list(get_lines_from_patch(content, filemode))
return list(get_lines_from_file(content)) | def get_lines_from_content(content: str, filemode: Filemode, is_patch: bool, show_secrets: bool) -> List[Line]:
'\n Return the secrets and the lines with line number.\n\n :param scan_result: Scan result from the API call\n :param show_secrets: Option to hide secrets value\n :param is_patch: Is the content a patch\n '
if is_patch:
return list(get_lines_from_patch(content, filemode))
return list(get_lines_from_file(content))<|docstring|>Return the secrets and the lines with line number.
:param scan_result: Scan result from the API call
:param show_secrets: Option to hide secrets value
:param is_patch: Is the content a patch<|endoftext|> |
df8df4f7241f94de61d08b62ed9bf692f5f6815ad6c20fb967e21731333e0429 | def get_lines_from_file(content: str) -> Iterable[Line]:
'Return the lines with line number from a file.'
for (line_count, line_content) in enumerate(content.split('\n')):
(yield Line(content=line_content, category=LineCategory.data, pre_index=(line_count + 1))) | Return the lines with line number from a file. | ggshield/utils.py | get_lines_from_file | SofienM/ggtest-ci | 0 | python | def get_lines_from_file(content: str) -> Iterable[Line]:
for (line_count, line_content) in enumerate(content.split('\n')):
(yield Line(content=line_content, category=LineCategory.data, pre_index=(line_count + 1))) | def get_lines_from_file(content: str) -> Iterable[Line]:
for (line_count, line_content) in enumerate(content.split('\n')):
(yield Line(content=line_content, category=LineCategory.data, pre_index=(line_count + 1)))<|docstring|>Return the lines with line number from a file.<|endoftext|> |
d115363f79bf3d55458b35f6863747b4babbcd978dda46666b23fa9fa9db1caa | def get_lines_from_patch(content: str, filemode: Filemode) -> Iterable[Line]:
'Return the lines with line number from a git patch.'
content += '\n'
pre_index = 0
post_index = 0
for line in content.split('\n'):
line_type = line[:1]
line_content = ''
line_pre_index = None
line_post_index = None
category = None
if (line_type == ' '):
line_content = line[1:]
pre_index += 1
post_index += 1
line_pre_index = pre_index
line_post_index = post_index
elif (line_type == '@'):
m = REGEX_PATCH_HEADER.search(line)
if (m is None):
continue
pre_index = int(m.groupdict()['pre_index'])
post_index = int(m.groupdict()['post_index'])
line_content = m.groupdict()['line_content'][:(- 1)]
if ((filemode == Filemode.NEW) or (filemode == Filemode.DELETE)):
pre_index = 1
post_index = 1
if line_content:
line_type = ' '
pre_index -= 1
post_index -= 1
line_pre_index = None
line_post_index = None
category = LineCategory.empty
elif (line_type == '+'):
post_index += 1
line_post_index = post_index
line_content = line[1:]
category = LineCategory.addition
elif (line_type == '-'):
pre_index += 1
line_pre_index = pre_index
line_content = line[1:]
category = LineCategory.deletion
if (line_type and (line_content is not None)):
(yield Line(content=line_content, category=category, pre_index=line_pre_index, post_index=line_post_index)) | Return the lines with line number from a git patch. | ggshield/utils.py | get_lines_from_patch | SofienM/ggtest-ci | 0 | python | def get_lines_from_patch(content: str, filemode: Filemode) -> Iterable[Line]:
content += '\n'
pre_index = 0
post_index = 0
for line in content.split('\n'):
line_type = line[:1]
line_content =
line_pre_index = None
line_post_index = None
category = None
if (line_type == ' '):
line_content = line[1:]
pre_index += 1
post_index += 1
line_pre_index = pre_index
line_post_index = post_index
elif (line_type == '@'):
m = REGEX_PATCH_HEADER.search(line)
if (m is None):
continue
pre_index = int(m.groupdict()['pre_index'])
post_index = int(m.groupdict()['post_index'])
line_content = m.groupdict()['line_content'][:(- 1)]
if ((filemode == Filemode.NEW) or (filemode == Filemode.DELETE)):
pre_index = 1
post_index = 1
if line_content:
line_type = ' '
pre_index -= 1
post_index -= 1
line_pre_index = None
line_post_index = None
category = LineCategory.empty
elif (line_type == '+'):
post_index += 1
line_post_index = post_index
line_content = line[1:]
category = LineCategory.addition
elif (line_type == '-'):
pre_index += 1
line_pre_index = pre_index
line_content = line[1:]
category = LineCategory.deletion
if (line_type and (line_content is not None)):
(yield Line(content=line_content, category=category, pre_index=line_pre_index, post_index=line_post_index)) | def get_lines_from_patch(content: str, filemode: Filemode) -> Iterable[Line]:
content += '\n'
pre_index = 0
post_index = 0
for line in content.split('\n'):
line_type = line[:1]
line_content =
line_pre_index = None
line_post_index = None
category = None
if (line_type == ' '):
line_content = line[1:]
pre_index += 1
post_index += 1
line_pre_index = pre_index
line_post_index = post_index
elif (line_type == '@'):
m = REGEX_PATCH_HEADER.search(line)
if (m is None):
continue
pre_index = int(m.groupdict()['pre_index'])
post_index = int(m.groupdict()['post_index'])
line_content = m.groupdict()['line_content'][:(- 1)]
if ((filemode == Filemode.NEW) or (filemode == Filemode.DELETE)):
pre_index = 1
post_index = 1
if line_content:
line_type = ' '
pre_index -= 1
post_index -= 1
line_pre_index = None
line_post_index = None
category = LineCategory.empty
elif (line_type == '+'):
post_index += 1
line_post_index = post_index
line_content = line[1:]
category = LineCategory.addition
elif (line_type == '-'):
pre_index += 1
line_pre_index = pre_index
line_content = line[1:]
category = LineCategory.deletion
if (line_type and (line_content is not None)):
(yield Line(content=line_content, category=category, pre_index=line_pre_index, post_index=line_post_index))<|docstring|>Return the lines with line number from a git patch.<|endoftext|> |
a86b6de68c3a6cfab3644e9a1109a837fdb1839349683aedcc879e10f4c2b0ac | def update_policy_break_matches(matches: List[Match], lines: List[Line], is_patch: bool, user_display: bool=False) -> None:
'\n Update secrets object with secret line and indexes in line.\n\n :param secrets: List of secrets sorted by start index\n :param lines: List of content lines with indexes (post_index and pre_index)\n :param is_patch: True if is patch from git, False if file\n :param user_display: Get line results as if treating the complete file\n '
index = 0
line_index = 0
for match in matches:
if (match.index_start is None):
continue
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
while (match.index_start >= (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
start_line = line_index
start_index = ((match.index_start - index) - int(is_patch))
while (match.index_end > (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
if user_display:
match.line_start = (lines[start_line].pre_index or lines[start_line].post_index)
match.line_end = (lines[line_index].pre_index or lines[line_index].post_index)
else:
match.line_start = start_line
match.line_end = line_index
match.index_start = start_index
match.index_end = (((match.index_end - index) - int(is_patch)) + 1) | Update secrets object with secret line and indexes in line.
:param secrets: List of secrets sorted by start index
:param lines: List of content lines with indexes (post_index and pre_index)
:param is_patch: True if is patch from git, False if file
:param user_display: Get line results as if treating the complete file | ggshield/utils.py | update_policy_break_matches | SofienM/ggtest-ci | 0 | python | def update_policy_break_matches(matches: List[Match], lines: List[Line], is_patch: bool, user_display: bool=False) -> None:
'\n Update secrets object with secret line and indexes in line.\n\n :param secrets: List of secrets sorted by start index\n :param lines: List of content lines with indexes (post_index and pre_index)\n :param is_patch: True if is patch from git, False if file\n :param user_display: Get line results as if treating the complete file\n '
index = 0
line_index = 0
for match in matches:
if (match.index_start is None):
continue
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
while (match.index_start >= (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
start_line = line_index
start_index = ((match.index_start - index) - int(is_patch))
while (match.index_end > (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
if user_display:
match.line_start = (lines[start_line].pre_index or lines[start_line].post_index)
match.line_end = (lines[line_index].pre_index or lines[line_index].post_index)
else:
match.line_start = start_line
match.line_end = line_index
match.index_start = start_index
match.index_end = (((match.index_end - index) - int(is_patch)) + 1) | def update_policy_break_matches(matches: List[Match], lines: List[Line], is_patch: bool, user_display: bool=False) -> None:
'\n Update secrets object with secret line and indexes in line.\n\n :param secrets: List of secrets sorted by start index\n :param lines: List of content lines with indexes (post_index and pre_index)\n :param is_patch: True if is patch from git, False if file\n :param user_display: Get line results as if treating the complete file\n '
index = 0
line_index = 0
for match in matches:
if (match.index_start is None):
continue
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
while (match.index_start >= (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
start_line = line_index
start_index = ((match.index_start - index) - int(is_patch))
while (match.index_end > (index + len_line)):
index += len_line
line_index += 1
len_line = ((len(lines[line_index].content) + 1) + int(is_patch))
if user_display:
match.line_start = (lines[start_line].pre_index or lines[start_line].post_index)
match.line_end = (lines[line_index].pre_index or lines[line_index].post_index)
else:
match.line_start = start_line
match.line_end = line_index
match.index_start = start_index
match.index_end = (((match.index_end - index) - int(is_patch)) + 1)<|docstring|>Update secrets object with secret line and indexes in line.
:param secrets: List of secrets sorted by start index
:param lines: List of content lines with indexes (post_index and pre_index)
:param is_patch: True if is patch from git, False if file
:param user_display: Get line results as if treating the complete file<|endoftext|> |
0104e65977415fb4d31516e19351bab4ded2ee7ee94bdcb2dca4463c69c8dc59 | def absorption(left, right):
"\n Let one of the two passed terms absorb the other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n .. NOTE::\n\n If neither of the terms can absorb the other, an\n :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.absorption(T(x^2), T(x^3))\n O(x^3)\n sage: atm.absorption(T(x^3), T(x^2))\n O(x^3)\n\n ::\n\n sage: T = atm.TermMonoid('exact', G, ZZ)\n sage: atm.absorption(T(x^2), T(x^3))\n Traceback (most recent call last):\n ...\n ArithmeticError: Absorption between x^2 and x^3 is not possible.\n "
try:
return left.absorb(right)
except ArithmeticError:
try:
return right.absorb(left)
except ArithmeticError:
raise ArithmeticError(('Absorption between %s and %s is not possible.' % (left, right))) | Let one of the two passed terms absorb the other.
Helper function used by
:class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.
.. NOTE::
If neither of the terms can absorb the other, an
:python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
INPUT:
- ``left`` -- an asymptotic term.
- ``right`` -- an asymptotic term.
OUTPUT:
An asymptotic term or ``None``.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermMonoid('O', G)
sage: atm.absorption(T(x^2), T(x^3))
O(x^3)
sage: atm.absorption(T(x^3), T(x^2))
O(x^3)
::
sage: T = atm.TermMonoid('exact', G, ZZ)
sage: atm.absorption(T(x^2), T(x^3))
Traceback (most recent call last):
...
ArithmeticError: Absorption between x^2 and x^3 is not possible. | src/sage/rings/asymptotic/term_monoid.py | absorption | Findstat/sage | 0 | python | def absorption(left, right):
"\n Let one of the two passed terms absorb the other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n .. NOTE::\n\n If neither of the terms can absorb the other, an\n :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.absorption(T(x^2), T(x^3))\n O(x^3)\n sage: atm.absorption(T(x^3), T(x^2))\n O(x^3)\n\n ::\n\n sage: T = atm.TermMonoid('exact', G, ZZ)\n sage: atm.absorption(T(x^2), T(x^3))\n Traceback (most recent call last):\n ...\n ArithmeticError: Absorption between x^2 and x^3 is not possible.\n "
try:
return left.absorb(right)
except ArithmeticError:
try:
return right.absorb(left)
except ArithmeticError:
raise ArithmeticError(('Absorption between %s and %s is not possible.' % (left, right))) | def absorption(left, right):
"\n Let one of the two passed terms absorb the other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n .. NOTE::\n\n If neither of the terms can absorb the other, an\n :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.absorption(T(x^2), T(x^3))\n O(x^3)\n sage: atm.absorption(T(x^3), T(x^2))\n O(x^3)\n\n ::\n\n sage: T = atm.TermMonoid('exact', G, ZZ)\n sage: atm.absorption(T(x^2), T(x^3))\n Traceback (most recent call last):\n ...\n ArithmeticError: Absorption between x^2 and x^3 is not possible.\n "
try:
return left.absorb(right)
except ArithmeticError:
try:
return right.absorb(left)
except ArithmeticError:
raise ArithmeticError(('Absorption between %s and %s is not possible.' % (left, right)))<|docstring|>Let one of the two passed terms absorb the other.
Helper function used by
:class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.
.. NOTE::
If neither of the terms can absorb the other, an
:python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
INPUT:
- ``left`` -- an asymptotic term.
- ``right`` -- an asymptotic term.
OUTPUT:
An asymptotic term or ``None``.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermMonoid('O', G)
sage: atm.absorption(T(x^2), T(x^3))
O(x^3)
sage: atm.absorption(T(x^3), T(x^2))
O(x^3)
::
sage: T = atm.TermMonoid('exact', G, ZZ)
sage: atm.absorption(T(x^2), T(x^3))
Traceback (most recent call last):
...
ArithmeticError: Absorption between x^2 and x^3 is not possible.<|endoftext|> |
1f47da307815c52f37b2f1ff3318b36f9937256973bf8c315f27e097e96a9e7b | def can_absorb(left, right):
"\n Return whether one of the two input terms is able to absorb the\n other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.can_absorb(T(x^2), T(x^3))\n True\n sage: atm.can_absorb(T(x^3), T(x^2))\n True\n "
return (left.can_absorb(right) or right.can_absorb(left)) | Return whether one of the two input terms is able to absorb the
other.
Helper function used by
:class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.
INPUT:
- ``left`` -- an asymptotic term.
- ``right`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermMonoid('O', G)
sage: atm.can_absorb(T(x^2), T(x^3))
True
sage: atm.can_absorb(T(x^3), T(x^2))
True | src/sage/rings/asymptotic/term_monoid.py | can_absorb | Findstat/sage | 0 | python | def can_absorb(left, right):
"\n Return whether one of the two input terms is able to absorb the\n other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.can_absorb(T(x^2), T(x^3))\n True\n sage: atm.can_absorb(T(x^3), T(x^2))\n True\n "
return (left.can_absorb(right) or right.can_absorb(left)) | def can_absorb(left, right):
"\n Return whether one of the two input terms is able to absorb the\n other.\n\n Helper function used by\n :class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.\n\n INPUT:\n\n - ``left`` -- an asymptotic term.\n\n - ``right`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermMonoid('O', G)\n sage: atm.can_absorb(T(x^2), T(x^3))\n True\n sage: atm.can_absorb(T(x^3), T(x^2))\n True\n "
return (left.can_absorb(right) or right.can_absorb(left))<|docstring|>Return whether one of the two input terms is able to absorb the
other.
Helper function used by
:class:`~sage.rings.asymptotic_ring.AsymptoticExpression`.
INPUT:
- ``left`` -- an asymptotic term.
- ``right`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermMonoid('O', G)
sage: atm.can_absorb(T(x^2), T(x^3))
True
sage: atm.can_absorb(T(x^3), T(x^2))
True<|endoftext|> |
572475a9c6429cb4b9e9258fb04f9c6e5f00da3a32851afaea8a5bf509a234f3 | def __init__(self, parent, growth):
"\n See :class:`GenericTerm` for more information.\n\n TESTS::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: T(x^2)\n Generic Term with growth x^2\n\n ::\n\n sage: atm.GenericTerm(parent=None, growth=x)\n Traceback (most recent call last):\n ...\n ValueError: The parent must be provided\n sage: atm.GenericTerm(T, agg.GrowthGroup('y^ZZ').gen())\n Traceback (most recent call last):\n ...\n ValueError: y is not in the parent's specified growth group\n "
from sage.rings.asymptotic.growth_group import GenericGrowthElement
if (parent is None):
raise ValueError('The parent must be provided')
if ((growth is None) or (not isinstance(growth, GenericGrowthElement))):
raise ValueError('The growth must be provided and must inherit from GenericGrowthElement')
elif (growth not in parent.growth_group):
raise ValueError(("%s is not in the parent's specified growth group" % growth))
self.growth = growth
super(GenericTerm, self).__init__(parent=parent) | See :class:`GenericTerm` for more information.
TESTS::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: T(x^2)
Generic Term with growth x^2
::
sage: atm.GenericTerm(parent=None, growth=x)
Traceback (most recent call last):
...
ValueError: The parent must be provided
sage: atm.GenericTerm(T, agg.GrowthGroup('y^ZZ').gen())
Traceback (most recent call last):
...
ValueError: y is not in the parent's specified growth group | src/sage/rings/asymptotic/term_monoid.py | __init__ | Findstat/sage | 0 | python | def __init__(self, parent, growth):
"\n See :class:`GenericTerm` for more information.\n\n TESTS::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: T(x^2)\n Generic Term with growth x^2\n\n ::\n\n sage: atm.GenericTerm(parent=None, growth=x)\n Traceback (most recent call last):\n ...\n ValueError: The parent must be provided\n sage: atm.GenericTerm(T, agg.GrowthGroup('y^ZZ').gen())\n Traceback (most recent call last):\n ...\n ValueError: y is not in the parent's specified growth group\n "
from sage.rings.asymptotic.growth_group import GenericGrowthElement
if (parent is None):
raise ValueError('The parent must be provided')
if ((growth is None) or (not isinstance(growth, GenericGrowthElement))):
raise ValueError('The growth must be provided and must inherit from GenericGrowthElement')
elif (growth not in parent.growth_group):
raise ValueError(("%s is not in the parent's specified growth group" % growth))
self.growth = growth
super(GenericTerm, self).__init__(parent=parent) | def __init__(self, parent, growth):
"\n See :class:`GenericTerm` for more information.\n\n TESTS::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: T(x^2)\n Generic Term with growth x^2\n\n ::\n\n sage: atm.GenericTerm(parent=None, growth=x)\n Traceback (most recent call last):\n ...\n ValueError: The parent must be provided\n sage: atm.GenericTerm(T, agg.GrowthGroup('y^ZZ').gen())\n Traceback (most recent call last):\n ...\n ValueError: y is not in the parent's specified growth group\n "
from sage.rings.asymptotic.growth_group import GenericGrowthElement
if (parent is None):
raise ValueError('The parent must be provided')
if ((growth is None) or (not isinstance(growth, GenericGrowthElement))):
raise ValueError('The growth must be provided and must inherit from GenericGrowthElement')
elif (growth not in parent.growth_group):
raise ValueError(("%s is not in the parent's specified growth group" % growth))
self.growth = growth
super(GenericTerm, self).__init__(parent=parent)<|docstring|>See :class:`GenericTerm` for more information.
TESTS::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: T(x^2)
Generic Term with growth x^2
::
sage: atm.GenericTerm(parent=None, growth=x)
Traceback (most recent call last):
...
ValueError: The parent must be provided
sage: atm.GenericTerm(T, agg.GrowthGroup('y^ZZ').gen())
Traceback (most recent call last):
...
ValueError: y is not in the parent's specified growth group<|endoftext|> |
2a08091aff3a13c3aac5e65f64ddbf4e8494366342873a8559f58c922c32fe4b | def _mul_(self, other):
"\n Abstract multiplication method for generic terms.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A :class:`GenericTerm` representing the product of ``self``\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from a common parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: t1, t2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: t1 * t2\n Generic Term with growth x^3\n "
return self.parent()((self.growth * other.growth)) | Abstract multiplication method for generic terms.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A :class:`GenericTerm` representing the product of ``self``
and ``other``.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element, as well as ``other``
are from a common parent.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x); t2 = T(x^2)
sage: t1, t2
(Generic Term with growth x, Generic Term with growth x^2)
sage: t1 * t2
Generic Term with growth x^3 | src/sage/rings/asymptotic/term_monoid.py | _mul_ | Findstat/sage | 0 | python | def _mul_(self, other):
"\n Abstract multiplication method for generic terms.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A :class:`GenericTerm` representing the product of ``self``\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from a common parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: t1, t2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: t1 * t2\n Generic Term with growth x^3\n "
return self.parent()((self.growth * other.growth)) | def _mul_(self, other):
"\n Abstract multiplication method for generic terms.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A :class:`GenericTerm` representing the product of ``self``\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from a common parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: t1, t2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: t1 * t2\n Generic Term with growth x^3\n "
return self.parent()((self.growth * other.growth))<|docstring|>Abstract multiplication method for generic terms.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A :class:`GenericTerm` representing the product of ``self``
and ``other``.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element, as well as ``other``
are from a common parent.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x); t2 = T(x^2)
sage: t1, t2
(Generic Term with growth x, Generic Term with growth x^2)
sage: t1 * t2
Generic Term with growth x^3<|endoftext|> |
f63715f60f293d2b366d51f1070e007ef85de7a5a44d92b7d9ed3bca9beae9d4 | def can_absorb(self, other):
'\n Check whether this asymptotic term is able to absorb\n the asymptotic term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n A :class:`GenericTerm` cannot absorb any other term.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: T = atm.GenericTermMonoid(G)\n sage: g1 = G(raw_element=21); g2 = G(raw_element=42)\n sage: t1 = T(g1); t2 = T(g2)\n sage: t1.can_absorb(t2) # indirect doctest\n False\n sage: t2.can_absorb(t1) # indirect doctest\n False\n '
return False | Check whether this asymptotic term is able to absorb
the asymptotic term ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
A :class:`GenericTerm` cannot absorb any other term.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GenericGrowthGroup(ZZ)
sage: T = atm.GenericTermMonoid(G)
sage: g1 = G(raw_element=21); g2 = G(raw_element=42)
sage: t1 = T(g1); t2 = T(g2)
sage: t1.can_absorb(t2) # indirect doctest
False
sage: t2.can_absorb(t1) # indirect doctest
False | src/sage/rings/asymptotic/term_monoid.py | can_absorb | Findstat/sage | 0 | python | def can_absorb(self, other):
'\n Check whether this asymptotic term is able to absorb\n the asymptotic term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n A :class:`GenericTerm` cannot absorb any other term.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: T = atm.GenericTermMonoid(G)\n sage: g1 = G(raw_element=21); g2 = G(raw_element=42)\n sage: t1 = T(g1); t2 = T(g2)\n sage: t1.can_absorb(t2) # indirect doctest\n False\n sage: t2.can_absorb(t1) # indirect doctest\n False\n '
return False | def can_absorb(self, other):
'\n Check whether this asymptotic term is able to absorb\n the asymptotic term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n A :class:`GenericTerm` cannot absorb any other term.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: T = atm.GenericTermMonoid(G)\n sage: g1 = G(raw_element=21); g2 = G(raw_element=42)\n sage: t1 = T(g1); t2 = T(g2)\n sage: t1.can_absorb(t2) # indirect doctest\n False\n sage: t2.can_absorb(t1) # indirect doctest\n False\n '
return False<|docstring|>Check whether this asymptotic term is able to absorb
the asymptotic term ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
A :class:`GenericTerm` cannot absorb any other term.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GenericGrowthGroup(ZZ)
sage: T = atm.GenericTermMonoid(G)
sage: g1 = G(raw_element=21); g2 = G(raw_element=42)
sage: t1 = T(g1); t2 = T(g2)
sage: t1.can_absorb(t2) # indirect doctest
False
sage: t2.can_absorb(t1) # indirect doctest
False<|endoftext|> |
ad4e8ba7a5d93686fbed9bf41bf75cbb26085fdfa3e02a1532bbecd7f8711881 | def absorb(self, other, check=True):
"\n Absorb the asymptotic term ``other`` and return the resulting\n asymptotic term.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n - ``check`` -- a boolean. If ``check`` is ``True`` (default),\n then ``can_absorb`` is called before absorption.\n\n OUTPUT:\n\n An asymptotic term or ``None`` if a cancellation occurs. If no\n absorption can be performed, an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n .. NOTE::\n\n Setting ``check`` to ``False`` is meant to be used in\n cases where the respective comparison is done externally\n (in order to avoid duplicate checking).\n\n For a more detailed explanation of the *absorption* of\n asymptotic terms see\n the :ref:`module description <term_absorption>`.\n\n EXAMPLES:\n\n We want to demonstrate in which cases an asymptotic term\n is able to absorb another term, as well as explain the output\n of this operation. We start by defining some parents and\n elements::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x = G_QQ.gen()\n sage: OT = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(growth_group=G_QQ, base_ring=QQ)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: et1 = ET(x, 100); et2 = ET(x^2, 2)\n sage: et3 = ET(x^2, 1); et4 = ET(x^2, -2)\n\n `O`-Terms are able to absorb other `O`-terms and exact terms\n with weaker or equal growth. ::\n\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot1.absorb(et1)\n O(x)\n sage: ot1.absorb(et1) is ot1\n True\n\n :class:`ExactTerm` is able to absorb another\n :class:`ExactTerm` if the terms have the same growth. In this\n case, *absorption* is nothing else than an addition of the\n respective coefficients::\n\n sage: et2.absorb(et3)\n 3*x^2\n sage: et3.absorb(et2)\n 3*x^2\n sage: et3.absorb(et4)\n -x^2\n\n Note that, for technical reasons, the coefficient `0` is not\n allowed, and thus ``None`` is returned if two exact terms\n cancel each other out::\n\n sage: et2.absorb(et4)\n sage: et4.absorb(et2) is None\n True\n\n TESTS:\n\n When disabling the ``check`` flag, absorb might produce\n wrong results::\n\n sage: et1.absorb(ot2, check=False)\n O(x)\n "
from sage.structure.element import have_same_parent
if check:
if (not self.can_absorb(other)):
raise ArithmeticError(('%s cannot absorb %s' % (self, other)))
if have_same_parent(self, other):
return self._absorb_(other)
from sage.structure.element import get_coercion_model
return get_coercion_model().bin_op(self, other, (lambda left, right: left._absorb_(right))) | Absorb the asymptotic term ``other`` and return the resulting
asymptotic term.
INPUT:
- ``other`` -- an asymptotic term.
- ``check`` -- a boolean. If ``check`` is ``True`` (default),
then ``can_absorb`` is called before absorption.
OUTPUT:
An asymptotic term or ``None`` if a cancellation occurs. If no
absorption can be performed, an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised.
.. NOTE::
Setting ``check`` to ``False`` is meant to be used in
cases where the respective comparison is done externally
(in order to avoid duplicate checking).
For a more detailed explanation of the *absorption* of
asymptotic terms see
the :ref:`module description <term_absorption>`.
EXAMPLES:
We want to demonstrate in which cases an asymptotic term
is able to absorb another term, as well as explain the output
of this operation. We start by defining some parents and
elements::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_QQ = agg.GrowthGroup('x^QQ'); x = G_QQ.gen()
sage: OT = atm.OTermMonoid(G_QQ)
sage: ET = atm.ExactTermMonoid(growth_group=G_QQ, base_ring=QQ)
sage: ot1 = OT(x); ot2 = OT(x^2)
sage: et1 = ET(x, 100); et2 = ET(x^2, 2)
sage: et3 = ET(x^2, 1); et4 = ET(x^2, -2)
`O`-Terms are able to absorb other `O`-terms and exact terms
with weaker or equal growth. ::
sage: ot1.absorb(ot1)
O(x)
sage: ot1.absorb(et1)
O(x)
sage: ot1.absorb(et1) is ot1
True
:class:`ExactTerm` is able to absorb another
:class:`ExactTerm` if the terms have the same growth. In this
case, *absorption* is nothing else than an addition of the
respective coefficients::
sage: et2.absorb(et3)
3*x^2
sage: et3.absorb(et2)
3*x^2
sage: et3.absorb(et4)
-x^2
Note that, for technical reasons, the coefficient `0` is not
allowed, and thus ``None`` is returned if two exact terms
cancel each other out::
sage: et2.absorb(et4)
sage: et4.absorb(et2) is None
True
TESTS:
When disabling the ``check`` flag, absorb might produce
wrong results::
sage: et1.absorb(ot2, check=False)
O(x) | src/sage/rings/asymptotic/term_monoid.py | absorb | Findstat/sage | 0 | python | def absorb(self, other, check=True):
"\n Absorb the asymptotic term ``other`` and return the resulting\n asymptotic term.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n - ``check`` -- a boolean. If ``check`` is ``True`` (default),\n then ``can_absorb`` is called before absorption.\n\n OUTPUT:\n\n An asymptotic term or ``None`` if a cancellation occurs. If no\n absorption can be performed, an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n .. NOTE::\n\n Setting ``check`` to ``False`` is meant to be used in\n cases where the respective comparison is done externally\n (in order to avoid duplicate checking).\n\n For a more detailed explanation of the *absorption* of\n asymptotic terms see\n the :ref:`module description <term_absorption>`.\n\n EXAMPLES:\n\n We want to demonstrate in which cases an asymptotic term\n is able to absorb another term, as well as explain the output\n of this operation. We start by defining some parents and\n elements::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x = G_QQ.gen()\n sage: OT = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(growth_group=G_QQ, base_ring=QQ)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: et1 = ET(x, 100); et2 = ET(x^2, 2)\n sage: et3 = ET(x^2, 1); et4 = ET(x^2, -2)\n\n `O`-Terms are able to absorb other `O`-terms and exact terms\n with weaker or equal growth. ::\n\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot1.absorb(et1)\n O(x)\n sage: ot1.absorb(et1) is ot1\n True\n\n :class:`ExactTerm` is able to absorb another\n :class:`ExactTerm` if the terms have the same growth. In this\n case, *absorption* is nothing else than an addition of the\n respective coefficients::\n\n sage: et2.absorb(et3)\n 3*x^2\n sage: et3.absorb(et2)\n 3*x^2\n sage: et3.absorb(et4)\n -x^2\n\n Note that, for technical reasons, the coefficient `0` is not\n allowed, and thus ``None`` is returned if two exact terms\n cancel each other out::\n\n sage: et2.absorb(et4)\n sage: et4.absorb(et2) is None\n True\n\n TESTS:\n\n When disabling the ``check`` flag, absorb might produce\n wrong results::\n\n sage: et1.absorb(ot2, check=False)\n O(x)\n "
from sage.structure.element import have_same_parent
if check:
if (not self.can_absorb(other)):
raise ArithmeticError(('%s cannot absorb %s' % (self, other)))
if have_same_parent(self, other):
return self._absorb_(other)
from sage.structure.element import get_coercion_model
return get_coercion_model().bin_op(self, other, (lambda left, right: left._absorb_(right))) | def absorb(self, other, check=True):
"\n Absorb the asymptotic term ``other`` and return the resulting\n asymptotic term.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n - ``check`` -- a boolean. If ``check`` is ``True`` (default),\n then ``can_absorb`` is called before absorption.\n\n OUTPUT:\n\n An asymptotic term or ``None`` if a cancellation occurs. If no\n absorption can be performed, an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised.\n\n .. NOTE::\n\n Setting ``check`` to ``False`` is meant to be used in\n cases where the respective comparison is done externally\n (in order to avoid duplicate checking).\n\n For a more detailed explanation of the *absorption* of\n asymptotic terms see\n the :ref:`module description <term_absorption>`.\n\n EXAMPLES:\n\n We want to demonstrate in which cases an asymptotic term\n is able to absorb another term, as well as explain the output\n of this operation. We start by defining some parents and\n elements::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x = G_QQ.gen()\n sage: OT = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(growth_group=G_QQ, base_ring=QQ)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: et1 = ET(x, 100); et2 = ET(x^2, 2)\n sage: et3 = ET(x^2, 1); et4 = ET(x^2, -2)\n\n `O`-Terms are able to absorb other `O`-terms and exact terms\n with weaker or equal growth. ::\n\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot1.absorb(et1)\n O(x)\n sage: ot1.absorb(et1) is ot1\n True\n\n :class:`ExactTerm` is able to absorb another\n :class:`ExactTerm` if the terms have the same growth. In this\n case, *absorption* is nothing else than an addition of the\n respective coefficients::\n\n sage: et2.absorb(et3)\n 3*x^2\n sage: et3.absorb(et2)\n 3*x^2\n sage: et3.absorb(et4)\n -x^2\n\n Note that, for technical reasons, the coefficient `0` is not\n allowed, and thus ``None`` is returned if two exact terms\n cancel each other out::\n\n sage: et2.absorb(et4)\n sage: et4.absorb(et2) is None\n True\n\n TESTS:\n\n When disabling the ``check`` flag, absorb might produce\n wrong results::\n\n sage: et1.absorb(ot2, check=False)\n O(x)\n "
from sage.structure.element import have_same_parent
if check:
if (not self.can_absorb(other)):
raise ArithmeticError(('%s cannot absorb %s' % (self, other)))
if have_same_parent(self, other):
return self._absorb_(other)
from sage.structure.element import get_coercion_model
return get_coercion_model().bin_op(self, other, (lambda left, right: left._absorb_(right)))<|docstring|>Absorb the asymptotic term ``other`` and return the resulting
asymptotic term.
INPUT:
- ``other`` -- an asymptotic term.
- ``check`` -- a boolean. If ``check`` is ``True`` (default),
then ``can_absorb`` is called before absorption.
OUTPUT:
An asymptotic term or ``None`` if a cancellation occurs. If no
absorption can be performed, an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised.
.. NOTE::
Setting ``check`` to ``False`` is meant to be used in
cases where the respective comparison is done externally
(in order to avoid duplicate checking).
For a more detailed explanation of the *absorption* of
asymptotic terms see
the :ref:`module description <term_absorption>`.
EXAMPLES:
We want to demonstrate in which cases an asymptotic term
is able to absorb another term, as well as explain the output
of this operation. We start by defining some parents and
elements::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_QQ = agg.GrowthGroup('x^QQ'); x = G_QQ.gen()
sage: OT = atm.OTermMonoid(G_QQ)
sage: ET = atm.ExactTermMonoid(growth_group=G_QQ, base_ring=QQ)
sage: ot1 = OT(x); ot2 = OT(x^2)
sage: et1 = ET(x, 100); et2 = ET(x^2, 2)
sage: et3 = ET(x^2, 1); et4 = ET(x^2, -2)
`O`-Terms are able to absorb other `O`-terms and exact terms
with weaker or equal growth. ::
sage: ot1.absorb(ot1)
O(x)
sage: ot1.absorb(et1)
O(x)
sage: ot1.absorb(et1) is ot1
True
:class:`ExactTerm` is able to absorb another
:class:`ExactTerm` if the terms have the same growth. In this
case, *absorption* is nothing else than an addition of the
respective coefficients::
sage: et2.absorb(et3)
3*x^2
sage: et3.absorb(et2)
3*x^2
sage: et3.absorb(et4)
-x^2
Note that, for technical reasons, the coefficient `0` is not
allowed, and thus ``None`` is returned if two exact terms
cancel each other out::
sage: et2.absorb(et4)
sage: et4.absorb(et2) is None
True
TESTS:
When disabling the ``check`` flag, absorb might produce
wrong results::
sage: et1.absorb(ot2, check=False)
O(x)<|endoftext|> |
a0a0abc9bd66c052504f1173f1e736005fe85d06e4a41a31a4168d1445512a59 | def _absorb_(self, other):
"\n Let this element absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term from the same parent as\n this element.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n .. NOTE::\n\n This is not implemented for abstract base classes. For\n concrete realizations see, for example, :meth:`OTerm._absorb_`\n or :meth:`ExactTerm._absorb_`.\n Override this in derived class.\n\n EXAMPLES:\n\n First, we define some asymptotic terms::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n\n When it comes to absorption, note that the method\n :meth:`can_absorb` (which is called before absorption takes\n place) does not allow the absorption of generic terms. Thus,\n an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised::\n\n sage: t2.absorb(t1)\n Traceback (most recent call last):\n ...\n ArithmeticError: Generic Term with growth x^2 cannot absorb Generic Term with growth x\n\n TESTS::\n\n sage: t2._absorb_(t1)\n Traceback (most recent call last):\n ...\n NotImplementedError: Not implemented in abstract base classes\n "
raise NotImplementedError('Not implemented in abstract base classes') | Let this element absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term from the same parent as
this element.
OUTPUT:
An asymptotic term or ``None``.
.. NOTE::
This is not implemented for abstract base classes. For
concrete realizations see, for example, :meth:`OTerm._absorb_`
or :meth:`ExactTerm._absorb_`.
Override this in derived class.
EXAMPLES:
First, we define some asymptotic terms::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x); t2 = T(x^2)
When it comes to absorption, note that the method
:meth:`can_absorb` (which is called before absorption takes
place) does not allow the absorption of generic terms. Thus,
an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised::
sage: t2.absorb(t1)
Traceback (most recent call last):
...
ArithmeticError: Generic Term with growth x^2 cannot absorb Generic Term with growth x
TESTS::
sage: t2._absorb_(t1)
Traceback (most recent call last):
...
NotImplementedError: Not implemented in abstract base classes | src/sage/rings/asymptotic/term_monoid.py | _absorb_ | Findstat/sage | 0 | python | def _absorb_(self, other):
"\n Let this element absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term from the same parent as\n this element.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n .. NOTE::\n\n This is not implemented for abstract base classes. For\n concrete realizations see, for example, :meth:`OTerm._absorb_`\n or :meth:`ExactTerm._absorb_`.\n Override this in derived class.\n\n EXAMPLES:\n\n First, we define some asymptotic terms::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n\n When it comes to absorption, note that the method\n :meth:`can_absorb` (which is called before absorption takes\n place) does not allow the absorption of generic terms. Thus,\n an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised::\n\n sage: t2.absorb(t1)\n Traceback (most recent call last):\n ...\n ArithmeticError: Generic Term with growth x^2 cannot absorb Generic Term with growth x\n\n TESTS::\n\n sage: t2._absorb_(t1)\n Traceback (most recent call last):\n ...\n NotImplementedError: Not implemented in abstract base classes\n "
raise NotImplementedError('Not implemented in abstract base classes') | def _absorb_(self, other):
"\n Let this element absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term from the same parent as\n this element.\n\n OUTPUT:\n\n An asymptotic term or ``None``.\n\n .. NOTE::\n\n This is not implemented for abstract base classes. For\n concrete realizations see, for example, :meth:`OTerm._absorb_`\n or :meth:`ExactTerm._absorb_`.\n Override this in derived class.\n\n EXAMPLES:\n\n First, we define some asymptotic terms::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x); t2 = T(x^2)\n\n When it comes to absorption, note that the method\n :meth:`can_absorb` (which is called before absorption takes\n place) does not allow the absorption of generic terms. Thus,\n an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`\n is raised::\n\n sage: t2.absorb(t1)\n Traceback (most recent call last):\n ...\n ArithmeticError: Generic Term with growth x^2 cannot absorb Generic Term with growth x\n\n TESTS::\n\n sage: t2._absorb_(t1)\n Traceback (most recent call last):\n ...\n NotImplementedError: Not implemented in abstract base classes\n "
raise NotImplementedError('Not implemented in abstract base classes')<|docstring|>Let this element absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term from the same parent as
this element.
OUTPUT:
An asymptotic term or ``None``.
.. NOTE::
This is not implemented for abstract base classes. For
concrete realizations see, for example, :meth:`OTerm._absorb_`
or :meth:`ExactTerm._absorb_`.
Override this in derived class.
EXAMPLES:
First, we define some asymptotic terms::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x); t2 = T(x^2)
When it comes to absorption, note that the method
:meth:`can_absorb` (which is called before absorption takes
place) does not allow the absorption of generic terms. Thus,
an :python:`ArithmeticError<library/exceptions.html#exceptions.ArithmeticError>`
is raised::
sage: t2.absorb(t1)
Traceback (most recent call last):
...
ArithmeticError: Generic Term with growth x^2 cannot absorb Generic Term with growth x
TESTS::
sage: t2._absorb_(t1)
Traceback (most recent call last):
...
NotImplementedError: Not implemented in abstract base classes<|endoftext|> |
c60bb0a17542eca5cc1381824c2a07ea17642b1da4b170f73f4f83c32fe4f268 | def __le__(self, other):
"\n Return whether the growth of this term is less than\n or equal to the growth of ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method **only** compares the growth of the input\n terms!\n\n EXAMPLES:\n\n First, we define some asymptotic terms (and their parents)::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: GT = atm.GenericTermMonoid(G)\n sage: OT = atm.OTermMonoid(G)\n sage: ET_ZZ = atm.ExactTermMonoid(G, ZZ)\n sage: ET_QQ = atm.ExactTermMonoid(G, QQ)\n sage: g1 = GT(x); g2 = GT(x^2); g1, g2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: o1 = OT(x^-1); o2 = OT(x^3); o1, o2\n (O(1/x), O(x^3))\n sage: t1 = ET_ZZ(x^2, 5); t2 = ET_QQ(x^3, 2/7); t1, t2\n (5*x^2, 2/7*x^3)\n\n In order for the comparison to work, the terms have come from\n or coerce into the same parent. In particular, comparing\n :class:`GenericTerm` to, for example, an :class:`OTerm`\n always yields ``False``::\n\n sage: g1 <= g2\n True\n sage: o1, g1\n (O(1/x), Generic Term with growth x)\n sage: o1 <= g1\n False\n\n If the elements of the common parent do not possess\n coefficients, then only the growth is compared::\n\n sage: o1 <= o1\n True\n sage: o1 <= o2\n True\n sage: o1 <= t1 and t1 <= o2\n True\n\n For terms with coefficient (like exact terms), comparison\n works similarly, with the sole exception that terms with\n equal growth are considered incomparable. Thus, `\\leq`\n only holds if the coefficients are equal as well::\n\n sage: t1 <= t2\n True\n sage: ET_ZZ(x, -5) <= ET_ZZ(x, 42)\n False\n sage: ET_ZZ(x, 5) <= ET_ZZ(x, 5)\n True\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._le_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.le)
except TypeError:
return False | Return whether the growth of this term is less than
or equal to the growth of ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method **only** compares the growth of the input
terms!
EXAMPLES:
First, we define some asymptotic terms (and their parents)::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: GT = atm.GenericTermMonoid(G)
sage: OT = atm.OTermMonoid(G)
sage: ET_ZZ = atm.ExactTermMonoid(G, ZZ)
sage: ET_QQ = atm.ExactTermMonoid(G, QQ)
sage: g1 = GT(x); g2 = GT(x^2); g1, g2
(Generic Term with growth x, Generic Term with growth x^2)
sage: o1 = OT(x^-1); o2 = OT(x^3); o1, o2
(O(1/x), O(x^3))
sage: t1 = ET_ZZ(x^2, 5); t2 = ET_QQ(x^3, 2/7); t1, t2
(5*x^2, 2/7*x^3)
In order for the comparison to work, the terms have come from
or coerce into the same parent. In particular, comparing
:class:`GenericTerm` to, for example, an :class:`OTerm`
always yields ``False``::
sage: g1 <= g2
True
sage: o1, g1
(O(1/x), Generic Term with growth x)
sage: o1 <= g1
False
If the elements of the common parent do not possess
coefficients, then only the growth is compared::
sage: o1 <= o1
True
sage: o1 <= o2
True
sage: o1 <= t1 and t1 <= o2
True
For terms with coefficient (like exact terms), comparison
works similarly, with the sole exception that terms with
equal growth are considered incomparable. Thus, `\leq`
only holds if the coefficients are equal as well::
sage: t1 <= t2
True
sage: ET_ZZ(x, -5) <= ET_ZZ(x, 42)
False
sage: ET_ZZ(x, 5) <= ET_ZZ(x, 5)
True | src/sage/rings/asymptotic/term_monoid.py | __le__ | Findstat/sage | 0 | python | def __le__(self, other):
"\n Return whether the growth of this term is less than\n or equal to the growth of ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method **only** compares the growth of the input\n terms!\n\n EXAMPLES:\n\n First, we define some asymptotic terms (and their parents)::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: GT = atm.GenericTermMonoid(G)\n sage: OT = atm.OTermMonoid(G)\n sage: ET_ZZ = atm.ExactTermMonoid(G, ZZ)\n sage: ET_QQ = atm.ExactTermMonoid(G, QQ)\n sage: g1 = GT(x); g2 = GT(x^2); g1, g2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: o1 = OT(x^-1); o2 = OT(x^3); o1, o2\n (O(1/x), O(x^3))\n sage: t1 = ET_ZZ(x^2, 5); t2 = ET_QQ(x^3, 2/7); t1, t2\n (5*x^2, 2/7*x^3)\n\n In order for the comparison to work, the terms have come from\n or coerce into the same parent. In particular, comparing\n :class:`GenericTerm` to, for example, an :class:`OTerm`\n always yields ``False``::\n\n sage: g1 <= g2\n True\n sage: o1, g1\n (O(1/x), Generic Term with growth x)\n sage: o1 <= g1\n False\n\n If the elements of the common parent do not possess\n coefficients, then only the growth is compared::\n\n sage: o1 <= o1\n True\n sage: o1 <= o2\n True\n sage: o1 <= t1 and t1 <= o2\n True\n\n For terms with coefficient (like exact terms), comparison\n works similarly, with the sole exception that terms with\n equal growth are considered incomparable. Thus, `\\leq`\n only holds if the coefficients are equal as well::\n\n sage: t1 <= t2\n True\n sage: ET_ZZ(x, -5) <= ET_ZZ(x, 42)\n False\n sage: ET_ZZ(x, 5) <= ET_ZZ(x, 5)\n True\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._le_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.le)
except TypeError:
return False | def __le__(self, other):
"\n Return whether the growth of this term is less than\n or equal to the growth of ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method **only** compares the growth of the input\n terms!\n\n EXAMPLES:\n\n First, we define some asymptotic terms (and their parents)::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: GT = atm.GenericTermMonoid(G)\n sage: OT = atm.OTermMonoid(G)\n sage: ET_ZZ = atm.ExactTermMonoid(G, ZZ)\n sage: ET_QQ = atm.ExactTermMonoid(G, QQ)\n sage: g1 = GT(x); g2 = GT(x^2); g1, g2\n (Generic Term with growth x, Generic Term with growth x^2)\n sage: o1 = OT(x^-1); o2 = OT(x^3); o1, o2\n (O(1/x), O(x^3))\n sage: t1 = ET_ZZ(x^2, 5); t2 = ET_QQ(x^3, 2/7); t1, t2\n (5*x^2, 2/7*x^3)\n\n In order for the comparison to work, the terms have come from\n or coerce into the same parent. In particular, comparing\n :class:`GenericTerm` to, for example, an :class:`OTerm`\n always yields ``False``::\n\n sage: g1 <= g2\n True\n sage: o1, g1\n (O(1/x), Generic Term with growth x)\n sage: o1 <= g1\n False\n\n If the elements of the common parent do not possess\n coefficients, then only the growth is compared::\n\n sage: o1 <= o1\n True\n sage: o1 <= o2\n True\n sage: o1 <= t1 and t1 <= o2\n True\n\n For terms with coefficient (like exact terms), comparison\n works similarly, with the sole exception that terms with\n equal growth are considered incomparable. Thus, `\\leq`\n only holds if the coefficients are equal as well::\n\n sage: t1 <= t2\n True\n sage: ET_ZZ(x, -5) <= ET_ZZ(x, 42)\n False\n sage: ET_ZZ(x, 5) <= ET_ZZ(x, 5)\n True\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._le_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.le)
except TypeError:
return False<|docstring|>Return whether the growth of this term is less than
or equal to the growth of ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method **only** compares the growth of the input
terms!
EXAMPLES:
First, we define some asymptotic terms (and their parents)::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: GT = atm.GenericTermMonoid(G)
sage: OT = atm.OTermMonoid(G)
sage: ET_ZZ = atm.ExactTermMonoid(G, ZZ)
sage: ET_QQ = atm.ExactTermMonoid(G, QQ)
sage: g1 = GT(x); g2 = GT(x^2); g1, g2
(Generic Term with growth x, Generic Term with growth x^2)
sage: o1 = OT(x^-1); o2 = OT(x^3); o1, o2
(O(1/x), O(x^3))
sage: t1 = ET_ZZ(x^2, 5); t2 = ET_QQ(x^3, 2/7); t1, t2
(5*x^2, 2/7*x^3)
In order for the comparison to work, the terms have come from
or coerce into the same parent. In particular, comparing
:class:`GenericTerm` to, for example, an :class:`OTerm`
always yields ``False``::
sage: g1 <= g2
True
sage: o1, g1
(O(1/x), Generic Term with growth x)
sage: o1 <= g1
False
If the elements of the common parent do not possess
coefficients, then only the growth is compared::
sage: o1 <= o1
True
sage: o1 <= o2
True
sage: o1 <= t1 and t1 <= o2
True
For terms with coefficient (like exact terms), comparison
works similarly, with the sole exception that terms with
equal growth are considered incomparable. Thus, `\leq`
only holds if the coefficients are equal as well::
sage: t1 <= t2
True
sage: ET_ZZ(x, -5) <= ET_ZZ(x, 42)
False
sage: ET_ZZ(x, 5) <= ET_ZZ(x, 5)
True<|endoftext|> |
7ff45c7212f4ef34d29aa41a6cabc7966492a19e86103c8c0ad158eab6e9def3 | def _le_(self, other):
"\n Return whether this generic term grows at most (i.e. less than\n or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from the same parent.\n\n Also, this method **only** compares the growth of the\n input terms!\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x^-2); t2 = T(x^5); t1, t2\n (Generic Term with growth x^(-2), Generic Term with growth x^5)\n sage: t1._le_(t2)\n True\n sage: t2._le_(t1)\n False\n "
return (self.growth <= other.growth) | Return whether this generic term grows at most (i.e. less than
or equal) like ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element, as well as ``other``
are from the same parent.
Also, this method **only** compares the growth of the
input terms!
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x^-2); t2 = T(x^5); t1, t2
(Generic Term with growth x^(-2), Generic Term with growth x^5)
sage: t1._le_(t2)
True
sage: t2._le_(t1)
False | src/sage/rings/asymptotic/term_monoid.py | _le_ | Findstat/sage | 0 | python | def _le_(self, other):
"\n Return whether this generic term grows at most (i.e. less than\n or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from the same parent.\n\n Also, this method **only** compares the growth of the\n input terms!\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x^-2); t2 = T(x^5); t1, t2\n (Generic Term with growth x^(-2), Generic Term with growth x^5)\n sage: t1._le_(t2)\n True\n sage: t2._le_(t1)\n False\n "
return (self.growth <= other.growth) | def _le_(self, other):
"\n Return whether this generic term grows at most (i.e. less than\n or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element, as well as ``other``\n are from the same parent.\n\n Also, this method **only** compares the growth of the\n input terms!\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(G)\n sage: t1 = T(x^-2); t2 = T(x^5); t1, t2\n (Generic Term with growth x^(-2), Generic Term with growth x^5)\n sage: t1._le_(t2)\n True\n sage: t2._le_(t1)\n False\n "
return (self.growth <= other.growth)<|docstring|>Return whether this generic term grows at most (i.e. less than
or equal) like ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element, as well as ``other``
are from the same parent.
Also, this method **only** compares the growth of the
input terms!
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(G)
sage: t1 = T(x^-2); t2 = T(x^5); t1, t2
(Generic Term with growth x^(-2), Generic Term with growth x^5)
sage: t1._le_(t2)
True
sage: t2._le_(t1)
False<|endoftext|> |
346991ad5563d376e788fb85815705e5e9c2e7da82fc0f9e0087dd4eed19d78b | def __eq__(self, other):
"\n Return whether this asymptotic term is equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an object.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This function uses the coercion model to find a common\n parent for the two operands.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import (GenericTermMonoid,\n ....: ExactTermMonoid, OTermMonoid)\n sage: GT = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: ET = ExactTermMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: g = GT.an_element(); e = ET.an_element(); o = OT.an_element()\n sage: g, e, o\n (Generic Term with growth x, x, O(x))\n sage: e == e^2 # indirect doctest\n False\n sage: e == ET(x,1) # indirect doctest\n True\n sage: o == OT(x^2) # indirect doctest\n False\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._eq_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.eq)
except TypeError:
return False | Return whether this asymptotic term is equal to ``other``.
INPUT:
- ``other`` -- an object.
OUTPUT:
A boolean.
.. NOTE::
This function uses the coercion model to find a common
parent for the two operands.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import (GenericTermMonoid,
....: ExactTermMonoid, OTermMonoid)
sage: GT = GenericTermMonoid(GrowthGroup('x^ZZ'))
sage: ET = ExactTermMonoid(GrowthGroup('x^ZZ'), ZZ)
sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))
sage: g = GT.an_element(); e = ET.an_element(); o = OT.an_element()
sage: g, e, o
(Generic Term with growth x, x, O(x))
sage: e == e^2 # indirect doctest
False
sage: e == ET(x,1) # indirect doctest
True
sage: o == OT(x^2) # indirect doctest
False | src/sage/rings/asymptotic/term_monoid.py | __eq__ | Findstat/sage | 0 | python | def __eq__(self, other):
"\n Return whether this asymptotic term is equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an object.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This function uses the coercion model to find a common\n parent for the two operands.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import (GenericTermMonoid,\n ....: ExactTermMonoid, OTermMonoid)\n sage: GT = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: ET = ExactTermMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: g = GT.an_element(); e = ET.an_element(); o = OT.an_element()\n sage: g, e, o\n (Generic Term with growth x, x, O(x))\n sage: e == e^2 # indirect doctest\n False\n sage: e == ET(x,1) # indirect doctest\n True\n sage: o == OT(x^2) # indirect doctest\n False\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._eq_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.eq)
except TypeError:
return False | def __eq__(self, other):
"\n Return whether this asymptotic term is equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an object.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This function uses the coercion model to find a common\n parent for the two operands.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import (GenericTermMonoid,\n ....: ExactTermMonoid, OTermMonoid)\n sage: GT = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: ET = ExactTermMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: g = GT.an_element(); e = ET.an_element(); o = OT.an_element()\n sage: g, e, o\n (Generic Term with growth x, x, O(x))\n sage: e == e^2 # indirect doctest\n False\n sage: e == ET(x,1) # indirect doctest\n True\n sage: o == OT(x^2) # indirect doctest\n False\n "
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._eq_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.eq)
except TypeError:
return False<|docstring|>Return whether this asymptotic term is equal to ``other``.
INPUT:
- ``other`` -- an object.
OUTPUT:
A boolean.
.. NOTE::
This function uses the coercion model to find a common
parent for the two operands.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import (GenericTermMonoid,
....: ExactTermMonoid, OTermMonoid)
sage: GT = GenericTermMonoid(GrowthGroup('x^ZZ'))
sage: ET = ExactTermMonoid(GrowthGroup('x^ZZ'), ZZ)
sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))
sage: g = GT.an_element(); e = ET.an_element(); o = OT.an_element()
sage: g, e, o
(Generic Term with growth x, x, O(x))
sage: e == e^2 # indirect doctest
False
sage: e == ET(x,1) # indirect doctest
True
sage: o == OT(x^2) # indirect doctest
False<|endoftext|> |
0e5790024fe24ed655b2ac779978a98261e79c8564008376d32048e0686684da | def _eq_(self, other):
"\n Return whether this asymptotic term is the same as ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion framework, so it\n can be assumed that this asymptotic term is from the\n same parent as ``other``.\n\n Only implemented in concrete realizations.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid\n sage: T = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = T.an_element()\n sage: t == t\n True\n\n ::\n\n sage: from sage.rings.asymptotic.term_monoid import OTermMonoid\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = OT.an_element(); t\n O(x)\n sage: t == OT(x) # indirect doctest\n True\n sage: t == OT(x^2) # indirect doctest\n False\n "
return (self.growth == other.growth) | Return whether this asymptotic term is the same as ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method gets called by the coercion framework, so it
can be assumed that this asymptotic term is from the
same parent as ``other``.
Only implemented in concrete realizations.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid
sage: T = GenericTermMonoid(GrowthGroup('x^ZZ'))
sage: t = T.an_element()
sage: t == t
True
::
sage: from sage.rings.asymptotic.term_monoid import OTermMonoid
sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))
sage: t = OT.an_element(); t
O(x)
sage: t == OT(x) # indirect doctest
True
sage: t == OT(x^2) # indirect doctest
False | src/sage/rings/asymptotic/term_monoid.py | _eq_ | Findstat/sage | 0 | python | def _eq_(self, other):
"\n Return whether this asymptotic term is the same as ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion framework, so it\n can be assumed that this asymptotic term is from the\n same parent as ``other``.\n\n Only implemented in concrete realizations.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid\n sage: T = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = T.an_element()\n sage: t == t\n True\n\n ::\n\n sage: from sage.rings.asymptotic.term_monoid import OTermMonoid\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = OT.an_element(); t\n O(x)\n sage: t == OT(x) # indirect doctest\n True\n sage: t == OT(x^2) # indirect doctest\n False\n "
return (self.growth == other.growth) | def _eq_(self, other):
"\n Return whether this asymptotic term is the same as ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion framework, so it\n can be assumed that this asymptotic term is from the\n same parent as ``other``.\n\n Only implemented in concrete realizations.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid\n sage: T = GenericTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = T.an_element()\n sage: t == t\n True\n\n ::\n\n sage: from sage.rings.asymptotic.term_monoid import OTermMonoid\n sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))\n sage: t = OT.an_element(); t\n O(x)\n sage: t == OT(x) # indirect doctest\n True\n sage: t == OT(x^2) # indirect doctest\n False\n "
return (self.growth == other.growth)<|docstring|>Return whether this asymptotic term is the same as ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
This method gets called by the coercion framework, so it
can be assumed that this asymptotic term is from the
same parent as ``other``.
Only implemented in concrete realizations.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid
sage: T = GenericTermMonoid(GrowthGroup('x^ZZ'))
sage: t = T.an_element()
sage: t == t
True
::
sage: from sage.rings.asymptotic.term_monoid import OTermMonoid
sage: OT = OTermMonoid(GrowthGroup('x^ZZ'))
sage: t = OT.an_element(); t
O(x)
sage: t == OT(x) # indirect doctest
True
sage: t == OT(x^2) # indirect doctest
False<|endoftext|> |
4caeccdd38b6533b9b324aad8675d3bfaf886c29859c1b351781fe45e91f5d6c | def _repr_(self):
"\n A representation string for this generic term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: T(x)._repr_()\n 'Generic Term with growth x'\n sage: T(x^7)._repr_()\n 'Generic Term with growth x^7'\n "
return ('Generic Term with growth ' + repr(self.growth)) | A representation string for this generic term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(growth_group=G)
sage: T(x)._repr_()
'Generic Term with growth x'
sage: T(x^7)._repr_()
'Generic Term with growth x^7' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this generic term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: T(x)._repr_()\n 'Generic Term with growth x'\n sage: T(x^7)._repr_()\n 'Generic Term with growth x^7'\n "
return ('Generic Term with growth ' + repr(self.growth)) | def _repr_(self):
"\n A representation string for this generic term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: T(x)._repr_()\n 'Generic Term with growth x'\n sage: T(x^7)._repr_()\n 'Generic Term with growth x^7'\n "
return ('Generic Term with growth ' + repr(self.growth))<|docstring|>A representation string for this generic term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(growth_group=G)
sage: T(x)._repr_()
'Generic Term with growth x'
sage: T(x^7)._repr_()
'Generic Term with growth x^7'<|endoftext|> |
0050b6caa45081006473bff77b2420900ccfae8b84b86b957f51c4bb7740f686 | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, category=None):
"\n See :class:`GenericTermMonoid` for more information.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_x = agg.GrowthGroup('x^ZZ')\n sage: T_x = atm.GenericTermMonoid(G_x); T_x\n Generic Term Monoid x^ZZ\n sage: T_x.growth_group\n Growth Group x^ZZ\n sage: G_y = agg.GrowthGroup('y^QQ')\n sage: T_y = atm.GenericTermMonoid(G_y); T_y\n Generic Term Monoid y^QQ\n sage: T_x is T_y\n False\n\n ::\n\n sage: atm.GenericTermMonoid(None)\n Traceback (most recent call last):\n ...\n ValueError: Growth Group has to be specified\n "
from sage.categories.monoids import Monoids
from sage.categories.posets import Posets
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (category is None):
category = (Monoids() & Posets())
else:
if (not isinstance(category, tuple)):
category = (category,)
if (not any((cat.is_subcategory((Monoids() & Posets())) for cat in category))):
raise ValueError(('%s is not a subcategory of %s' % (category, (Monoids() & Posets()))))
if (growth_group is None):
raise ValueError('Growth Group has to be specified')
elif (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s does not inherit from %s' % (growth_group, GenericGrowthGroup())))
self._growth_group_ = growth_group
super(GenericTermMonoid, self).__init__(category=category) | See :class:`GenericTermMonoid` for more information.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_x = agg.GrowthGroup('x^ZZ')
sage: T_x = atm.GenericTermMonoid(G_x); T_x
Generic Term Monoid x^ZZ
sage: T_x.growth_group
Growth Group x^ZZ
sage: G_y = agg.GrowthGroup('y^QQ')
sage: T_y = atm.GenericTermMonoid(G_y); T_y
Generic Term Monoid y^QQ
sage: T_x is T_y
False
::
sage: atm.GenericTermMonoid(None)
Traceback (most recent call last):
...
ValueError: Growth Group has to be specified | src/sage/rings/asymptotic/term_monoid.py | __init__ | Findstat/sage | 0 | python | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, category=None):
"\n See :class:`GenericTermMonoid` for more information.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_x = agg.GrowthGroup('x^ZZ')\n sage: T_x = atm.GenericTermMonoid(G_x); T_x\n Generic Term Monoid x^ZZ\n sage: T_x.growth_group\n Growth Group x^ZZ\n sage: G_y = agg.GrowthGroup('y^QQ')\n sage: T_y = atm.GenericTermMonoid(G_y); T_y\n Generic Term Monoid y^QQ\n sage: T_x is T_y\n False\n\n ::\n\n sage: atm.GenericTermMonoid(None)\n Traceback (most recent call last):\n ...\n ValueError: Growth Group has to be specified\n "
from sage.categories.monoids import Monoids
from sage.categories.posets import Posets
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (category is None):
category = (Monoids() & Posets())
else:
if (not isinstance(category, tuple)):
category = (category,)
if (not any((cat.is_subcategory((Monoids() & Posets())) for cat in category))):
raise ValueError(('%s is not a subcategory of %s' % (category, (Monoids() & Posets()))))
if (growth_group is None):
raise ValueError('Growth Group has to be specified')
elif (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s does not inherit from %s' % (growth_group, GenericGrowthGroup())))
self._growth_group_ = growth_group
super(GenericTermMonoid, self).__init__(category=category) | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, category=None):
"\n See :class:`GenericTermMonoid` for more information.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_x = agg.GrowthGroup('x^ZZ')\n sage: T_x = atm.GenericTermMonoid(G_x); T_x\n Generic Term Monoid x^ZZ\n sage: T_x.growth_group\n Growth Group x^ZZ\n sage: G_y = agg.GrowthGroup('y^QQ')\n sage: T_y = atm.GenericTermMonoid(G_y); T_y\n Generic Term Monoid y^QQ\n sage: T_x is T_y\n False\n\n ::\n\n sage: atm.GenericTermMonoid(None)\n Traceback (most recent call last):\n ...\n ValueError: Growth Group has to be specified\n "
from sage.categories.monoids import Monoids
from sage.categories.posets import Posets
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (category is None):
category = (Monoids() & Posets())
else:
if (not isinstance(category, tuple)):
category = (category,)
if (not any((cat.is_subcategory((Monoids() & Posets())) for cat in category))):
raise ValueError(('%s is not a subcategory of %s' % (category, (Monoids() & Posets()))))
if (growth_group is None):
raise ValueError('Growth Group has to be specified')
elif (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s does not inherit from %s' % (growth_group, GenericGrowthGroup())))
self._growth_group_ = growth_group
super(GenericTermMonoid, self).__init__(category=category)<|docstring|>See :class:`GenericTermMonoid` for more information.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_x = agg.GrowthGroup('x^ZZ')
sage: T_x = atm.GenericTermMonoid(G_x); T_x
Generic Term Monoid x^ZZ
sage: T_x.growth_group
Growth Group x^ZZ
sage: G_y = agg.GrowthGroup('y^QQ')
sage: T_y = atm.GenericTermMonoid(G_y); T_y
Generic Term Monoid y^QQ
sage: T_x is T_y
False
::
sage: atm.GenericTermMonoid(None)
Traceback (most recent call last):
...
ValueError: Growth Group has to be specified<|endoftext|> |
7629974176b934610314ad3ad6b70bf3ae0a73c2a23104109b2d97c2e9f1b381 | @property
def growth_group(self):
"\n The growth group underlying this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).growth_group\n Growth Group x^ZZ\n "
return self._growth_group_ | The growth group underlying this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.ExactTermMonoid(G, ZZ).growth_group
Growth Group x^ZZ | src/sage/rings/asymptotic/term_monoid.py | growth_group | Findstat/sage | 0 | python | @property
def growth_group(self):
"\n The growth group underlying this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).growth_group\n Growth Group x^ZZ\n "
return self._growth_group_ | @property
def growth_group(self):
"\n The growth group underlying this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).growth_group\n Growth Group x^ZZ\n "
return self._growth_group_<|docstring|>The growth group underlying this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.ExactTermMonoid(G, ZZ).growth_group
Growth Group x^ZZ<|endoftext|> |
51bb25dedb0dc7e27027b2c781c1232c9d1cb672f3cee910ec059277cc657628 | def _repr_(self):
"\n A representation string for this generic term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: atm.GenericTermMonoid(G)._repr_()\n 'Generic Term Monoid Generic(ZZ)'\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.GenericTermMonoid(growth_group=G)._repr_()\n 'Generic Term Monoid x^ZZ'\n "
return ('Generic Term Monoid %s' % (self.growth_group._repr_short_(),)) | A representation string for this generic term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GenericGrowthGroup(ZZ)
sage: atm.GenericTermMonoid(G)._repr_()
'Generic Term Monoid Generic(ZZ)'
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.GenericTermMonoid(growth_group=G)._repr_()
'Generic Term Monoid x^ZZ' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this generic term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: atm.GenericTermMonoid(G)._repr_()\n 'Generic Term Monoid Generic(ZZ)'\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.GenericTermMonoid(growth_group=G)._repr_()\n 'Generic Term Monoid x^ZZ'\n "
return ('Generic Term Monoid %s' % (self.growth_group._repr_short_(),)) | def _repr_(self):
"\n A representation string for this generic term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GenericGrowthGroup(ZZ)\n sage: atm.GenericTermMonoid(G)._repr_()\n 'Generic Term Monoid Generic(ZZ)'\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.GenericTermMonoid(growth_group=G)._repr_()\n 'Generic Term Monoid x^ZZ'\n "
return ('Generic Term Monoid %s' % (self.growth_group._repr_short_(),))<|docstring|>A representation string for this generic term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GenericGrowthGroup(ZZ)
sage: atm.GenericTermMonoid(G)._repr_()
'Generic Term Monoid Generic(ZZ)'
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.GenericTermMonoid(growth_group=G)._repr_()
'Generic Term Monoid x^ZZ'<|endoftext|> |
274a7723430d8a6fd78a856b5bf5d4e8476f0e63076a34e7b74e03b441345186 | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another generic term monoid ``S`` coerces into this term\n monoid if and only if the growth group of ``S`` coerces\n into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ); T_ZZ\n Generic Term Monoid x^ZZ\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ); T_QQ\n Generic Term Monoid x^QQ\n sage: T_QQ.has_coerce_map_from(T_ZZ) # indirect doctest\n True\n "
if isinstance(S, self.__class__):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True | Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
A boolean.
.. NOTE::
Another generic term monoid ``S`` coerces into this term
monoid if and only if the growth group of ``S`` coerces
into the growth group of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ); T_ZZ
Generic Term Monoid x^ZZ
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ); T_QQ
Generic Term Monoid x^QQ
sage: T_QQ.has_coerce_map_from(T_ZZ) # indirect doctest
True | src/sage/rings/asymptotic/term_monoid.py | _coerce_map_from_ | Findstat/sage | 0 | python | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another generic term monoid ``S`` coerces into this term\n monoid if and only if the growth group of ``S`` coerces\n into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ); T_ZZ\n Generic Term Monoid x^ZZ\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ); T_QQ\n Generic Term Monoid x^QQ\n sage: T_QQ.has_coerce_map_from(T_ZZ) # indirect doctest\n True\n "
if isinstance(S, self.__class__):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another generic term monoid ``S`` coerces into this term\n monoid if and only if the growth group of ``S`` coerces\n into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ); T_ZZ\n Generic Term Monoid x^ZZ\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ); T_QQ\n Generic Term Monoid x^QQ\n sage: T_QQ.has_coerce_map_from(T_ZZ) # indirect doctest\n True\n "
if isinstance(S, self.__class__):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True<|docstring|>Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
A boolean.
.. NOTE::
Another generic term monoid ``S`` coerces into this term
monoid if and only if the growth group of ``S`` coerces
into the growth group of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ); T_ZZ
Generic Term Monoid x^ZZ
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ); T_QQ
Generic Term Monoid x^QQ
sage: T_QQ.has_coerce_map_from(T_ZZ) # indirect doctest
True<|endoftext|> |
60c4394e21cff9caa9309371904e82e989302299cb60bc62600822f0771be710 | def _element_constructor_(self, data):
"\n Convert the given object to this term monoid.\n\n INPUT:\n\n - ``data`` -- an object representing the element to be\n initialized.\n\n OUTPUT:\n\n An element of this term monoid.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term that is\n to be coerced into this term monoid, or an asymptotic\n growth element that is used for creating an element\n of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ)\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ)\n sage: term1 = T_ZZ(G_ZZ.gen())\n sage: term2 = T_QQ(G_QQ.gen()^2)\n\n In order for two terms to be compared, a coercion into\n a common parent has to be found::\n\n sage: term1.parent()\n Generic Term Monoid x^ZZ\n sage: term2.parent()\n Generic Term Monoid x^QQ\n sage: term1 <= term2\n True\n\n In this case, this works because ``T_ZZ``, the parent of\n ``term1``, coerces into ``T_QQ``::\n\n sage: T_QQ.coerce(term1)\n Generic Term with growth x\n\n The conversion of growth elements also works for the creation\n of terms::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: T_ZZ(x^42)\n Generic Term with growth x^42\n sage: x = PolynomialRing(ZZ, 'x').gen(); x.parent()\n Univariate Polynomial Ring in x over Integer Ring\n sage: T_ZZ(x^10)\n Generic Term with growth x^10\n sage: T_ZZ(10 * x^2)\n Traceback (most recent call last):\n ...\n ValueError: Input is ambiguous: cannot convert 10*x^2 to a generic term.\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, GenericTerm):
return self.element_class(self, data.growth)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
else:
try:
data = self.growth_group(data)
return self.element_class(self, data)
except:
raise ValueError(('Input is ambiguous: cannot convert %s to a generic term.' % (data,))) | Convert the given object to this term monoid.
INPUT:
- ``data`` -- an object representing the element to be
initialized.
OUTPUT:
An element of this term monoid.
.. NOTE::
The object ``data`` is either an asymptotic term that is
to be coerced into this term monoid, or an asymptotic
growth element that is used for creating an element
of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ)
sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ)
sage: term1 = T_ZZ(G_ZZ.gen())
sage: term2 = T_QQ(G_QQ.gen()^2)
In order for two terms to be compared, a coercion into
a common parent has to be found::
sage: term1.parent()
Generic Term Monoid x^ZZ
sage: term2.parent()
Generic Term Monoid x^QQ
sage: term1 <= term2
True
In this case, this works because ``T_ZZ``, the parent of
``term1``, coerces into ``T_QQ``::
sage: T_QQ.coerce(term1)
Generic Term with growth x
The conversion of growth elements also works for the creation
of terms::
sage: x = SR('x'); x.parent()
Symbolic Ring
sage: T_ZZ(x^42)
Generic Term with growth x^42
sage: x = PolynomialRing(ZZ, 'x').gen(); x.parent()
Univariate Polynomial Ring in x over Integer Ring
sage: T_ZZ(x^10)
Generic Term with growth x^10
sage: T_ZZ(10 * x^2)
Traceback (most recent call last):
...
ValueError: Input is ambiguous: cannot convert 10*x^2 to a generic term. | src/sage/rings/asymptotic/term_monoid.py | _element_constructor_ | Findstat/sage | 0 | python | def _element_constructor_(self, data):
"\n Convert the given object to this term monoid.\n\n INPUT:\n\n - ``data`` -- an object representing the element to be\n initialized.\n\n OUTPUT:\n\n An element of this term monoid.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term that is\n to be coerced into this term monoid, or an asymptotic\n growth element that is used for creating an element\n of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ)\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ)\n sage: term1 = T_ZZ(G_ZZ.gen())\n sage: term2 = T_QQ(G_QQ.gen()^2)\n\n In order for two terms to be compared, a coercion into\n a common parent has to be found::\n\n sage: term1.parent()\n Generic Term Monoid x^ZZ\n sage: term2.parent()\n Generic Term Monoid x^QQ\n sage: term1 <= term2\n True\n\n In this case, this works because ``T_ZZ``, the parent of\n ``term1``, coerces into ``T_QQ``::\n\n sage: T_QQ.coerce(term1)\n Generic Term with growth x\n\n The conversion of growth elements also works for the creation\n of terms::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: T_ZZ(x^42)\n Generic Term with growth x^42\n sage: x = PolynomialRing(ZZ, 'x').gen(); x.parent()\n Univariate Polynomial Ring in x over Integer Ring\n sage: T_ZZ(x^10)\n Generic Term with growth x^10\n sage: T_ZZ(10 * x^2)\n Traceback (most recent call last):\n ...\n ValueError: Input is ambiguous: cannot convert 10*x^2 to a generic term.\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, GenericTerm):
return self.element_class(self, data.growth)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
else:
try:
data = self.growth_group(data)
return self.element_class(self, data)
except:
raise ValueError(('Input is ambiguous: cannot convert %s to a generic term.' % (data,))) | def _element_constructor_(self, data):
"\n Convert the given object to this term monoid.\n\n INPUT:\n\n - ``data`` -- an object representing the element to be\n initialized.\n\n OUTPUT:\n\n An element of this term monoid.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term that is\n to be coerced into this term monoid, or an asymptotic\n growth element that is used for creating an element\n of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ)\n sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ)\n sage: term1 = T_ZZ(G_ZZ.gen())\n sage: term2 = T_QQ(G_QQ.gen()^2)\n\n In order for two terms to be compared, a coercion into\n a common parent has to be found::\n\n sage: term1.parent()\n Generic Term Monoid x^ZZ\n sage: term2.parent()\n Generic Term Monoid x^QQ\n sage: term1 <= term2\n True\n\n In this case, this works because ``T_ZZ``, the parent of\n ``term1``, coerces into ``T_QQ``::\n\n sage: T_QQ.coerce(term1)\n Generic Term with growth x\n\n The conversion of growth elements also works for the creation\n of terms::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: T_ZZ(x^42)\n Generic Term with growth x^42\n sage: x = PolynomialRing(ZZ, 'x').gen(); x.parent()\n Univariate Polynomial Ring in x over Integer Ring\n sage: T_ZZ(x^10)\n Generic Term with growth x^10\n sage: T_ZZ(10 * x^2)\n Traceback (most recent call last):\n ...\n ValueError: Input is ambiguous: cannot convert 10*x^2 to a generic term.\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, GenericTerm):
return self.element_class(self, data.growth)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
else:
try:
data = self.growth_group(data)
return self.element_class(self, data)
except:
raise ValueError(('Input is ambiguous: cannot convert %s to a generic term.' % (data,)))<|docstring|>Convert the given object to this term monoid.
INPUT:
- ``data`` -- an object representing the element to be
initialized.
OUTPUT:
An element of this term monoid.
.. NOTE::
The object ``data`` is either an asymptotic term that is
to be coerced into this term monoid, or an asymptotic
growth element that is used for creating an element
of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: T_ZZ = atm.GenericTermMonoid(growth_group=G_ZZ)
sage: T_QQ = atm.GenericTermMonoid(growth_group=G_QQ)
sage: term1 = T_ZZ(G_ZZ.gen())
sage: term2 = T_QQ(G_QQ.gen()^2)
In order for two terms to be compared, a coercion into
a common parent has to be found::
sage: term1.parent()
Generic Term Monoid x^ZZ
sage: term2.parent()
Generic Term Monoid x^QQ
sage: term1 <= term2
True
In this case, this works because ``T_ZZ``, the parent of
``term1``, coerces into ``T_QQ``::
sage: T_QQ.coerce(term1)
Generic Term with growth x
The conversion of growth elements also works for the creation
of terms::
sage: x = SR('x'); x.parent()
Symbolic Ring
sage: T_ZZ(x^42)
Generic Term with growth x^42
sage: x = PolynomialRing(ZZ, 'x').gen(); x.parent()
Univariate Polynomial Ring in x over Integer Ring
sage: T_ZZ(x^10)
Generic Term with growth x^10
sage: T_ZZ(10 * x^2)
Traceback (most recent call last):
...
ValueError: Input is ambiguous: cannot convert 10*x^2 to a generic term.<|endoftext|> |
92d7c9f5b8258666c27df13534cadc841b8f985230cd673c7c5b8a3e426b2768 | def _an_element_(self):
"\n Return an element of this term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.OTermMonoid(G).an_element() # indirect doctest\n O(x)\n sage: atm.GenericTermMonoid(G).an_element() # indirect doctest\n Generic Term with growth x\n "
return self(self.growth_group.an_element()) | Return an element of this term monoid.
INPUT:
Nothing.
OUTPUT:
An element of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.OTermMonoid(G).an_element() # indirect doctest
O(x)
sage: atm.GenericTermMonoid(G).an_element() # indirect doctest
Generic Term with growth x | src/sage/rings/asymptotic/term_monoid.py | _an_element_ | Findstat/sage | 0 | python | def _an_element_(self):
"\n Return an element of this term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.OTermMonoid(G).an_element() # indirect doctest\n O(x)\n sage: atm.GenericTermMonoid(G).an_element() # indirect doctest\n Generic Term with growth x\n "
return self(self.growth_group.an_element()) | def _an_element_(self):
"\n Return an element of this term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.OTermMonoid(G).an_element() # indirect doctest\n O(x)\n sage: atm.GenericTermMonoid(G).an_element() # indirect doctest\n Generic Term with growth x\n "
return self(self.growth_group.an_element())<|docstring|>Return an element of this term monoid.
INPUT:
Nothing.
OUTPUT:
An element of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.OTermMonoid(G).an_element() # indirect doctest
O(x)
sage: atm.GenericTermMonoid(G).an_element() # indirect doctest
Generic Term with growth x<|endoftext|> |
f777835566b415daf4f6de8e496d407bfd53b27cdf3746fb02f01f6d08e071c3 | def le(self, left, right):
"\n Return whether the term ``left`` is at most (less than or equal\n to) the term ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: T.le(t1, t2)\n True\n "
return (self(left) <= self(right)) | Return whether the term ``left`` is at most (less than or equal
to) the term ``right``.
INPUT:
- ``left`` -- an element.
- ``right`` -- an element.
OUTPUT:
A boolean.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(growth_group=G)
sage: t1 = T(x); t2 = T(x^2)
sage: T.le(t1, t2)
True | src/sage/rings/asymptotic/term_monoid.py | le | Findstat/sage | 0 | python | def le(self, left, right):
"\n Return whether the term ``left`` is at most (less than or equal\n to) the term ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: T.le(t1, t2)\n True\n "
return (self(left) <= self(right)) | def le(self, left, right):
"\n Return whether the term ``left`` is at most (less than or equal\n to) the term ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.GenericTermMonoid(growth_group=G)\n sage: t1 = T(x); t2 = T(x^2)\n sage: T.le(t1, t2)\n True\n "
return (self(left) <= self(right))<|docstring|>Return whether the term ``left`` is at most (less than or equal
to) the term ``right``.
INPUT:
- ``left`` -- an element.
- ``right`` -- an element.
OUTPUT:
A boolean.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.GenericTermMonoid(growth_group=G)
sage: t1 = T(x); t2 = T(x^2)
sage: T.le(t1, t2)
True<|endoftext|> |
2e9504871fe45d1288a4bace6d2adbe59878b04205fb0ac671b66454eb74123d | def _repr_(self):
"\n A representation string for this `O`-term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: OT = atm.OTermMonoid(G)\n sage: t1 = OT(x); t2 = OT(x^2); t3 = OT(x^3)\n sage: t1._repr_(), t2._repr_()\n ('O(x)', 'O(x^2)')\n sage: t3\n O(x^3)\n "
return ('O(%s)' % self.growth) | A representation string for this `O`-term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: OT = atm.OTermMonoid(G)
sage: t1 = OT(x); t2 = OT(x^2); t3 = OT(x^3)
sage: t1._repr_(), t2._repr_()
('O(x)', 'O(x^2)')
sage: t3
O(x^3) | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this `O`-term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: OT = atm.OTermMonoid(G)\n sage: t1 = OT(x); t2 = OT(x^2); t3 = OT(x^3)\n sage: t1._repr_(), t2._repr_()\n ('O(x)', 'O(x^2)')\n sage: t3\n O(x^3)\n "
return ('O(%s)' % self.growth) | def _repr_(self):
"\n A representation string for this `O`-term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: OT = atm.OTermMonoid(G)\n sage: t1 = OT(x); t2 = OT(x^2); t3 = OT(x^3)\n sage: t1._repr_(), t2._repr_()\n ('O(x)', 'O(x^2)')\n sage: t3\n O(x^3)\n "
return ('O(%s)' % self.growth)<|docstring|>A representation string for this `O`-term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: OT = atm.OTermMonoid(G)
sage: t1 = OT(x); t2 = OT(x^2); t3 = OT(x^3)
sage: t1._repr_(), t2._repr_()
('O(x)', 'O(x^2)')
sage: t3
O(x^3)<|endoftext|> |
4f49193b387ea7a4e6eb79647c22e6f31a0ccc656f9de84a0d4e408f6ee8b98c | def can_absorb(self, other):
"\n Check whether this `O`-term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n An :class:`OTerm` can absorb any other asymptotic term\n with weaker or equal growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: OT = atm.TermMonoid('O', agg.GrowthGroup('x^ZZ'))\n sage: t1 = OT(x^21); t2 = OT(x^42)\n sage: t1.can_absorb(t2)\n False\n sage: t2.can_absorb(t1)\n True\n "
return (other <= self) | Check whether this `O`-term can absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
An :class:`OTerm` can absorb any other asymptotic term
with weaker or equal growth.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: OT = atm.TermMonoid('O', agg.GrowthGroup('x^ZZ'))
sage: t1 = OT(x^21); t2 = OT(x^42)
sage: t1.can_absorb(t2)
False
sage: t2.can_absorb(t1)
True | src/sage/rings/asymptotic/term_monoid.py | can_absorb | Findstat/sage | 0 | python | def can_absorb(self, other):
"\n Check whether this `O`-term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n An :class:`OTerm` can absorb any other asymptotic term\n with weaker or equal growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: OT = atm.TermMonoid('O', agg.GrowthGroup('x^ZZ'))\n sage: t1 = OT(x^21); t2 = OT(x^42)\n sage: t1.can_absorb(t2)\n False\n sage: t2.can_absorb(t1)\n True\n "
return (other <= self) | def can_absorb(self, other):
"\n Check whether this `O`-term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n An :class:`OTerm` can absorb any other asymptotic term\n with weaker or equal growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: OT = atm.TermMonoid('O', agg.GrowthGroup('x^ZZ'))\n sage: t1 = OT(x^21); t2 = OT(x^42)\n sage: t1.can_absorb(t2)\n False\n sage: t2.can_absorb(t1)\n True\n "
return (other <= self)<|docstring|>Check whether this `O`-term can absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
An :class:`OTerm` can absorb any other asymptotic term
with weaker or equal growth.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: OT = atm.TermMonoid('O', agg.GrowthGroup('x^ZZ'))
sage: t1 = OT(x^21); t2 = OT(x^42)
sage: t1.can_absorb(t2)
False
sage: t2.can_absorb(t1)
True<|endoftext|> |
40936f505fef90d9858f0e0ff0dc5a950000ccf5fc999618e3e75a310df12c94 | def _absorb_(self, other):
'\n Let this `O`-term absorb another `O`-term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic `O`-term.\n\n OUTPUT:\n\n An asymptotic `O`-term.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other``\n have the same parent.\n\n Also, observe that the result of a "dominant" `O`-term\n absorbing another `O`-term always is the "dominant"\n `O`-term again.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup(\'x^ZZ\'); x = G.gen()\n sage: OT = atm.OTermMonoid(growth_group=G)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot2.absorb(ot1)\n O(x^2)\n sage: ot1.absorb(ot2)\n Traceback (most recent call last):\n ...\n ArithmeticError: O(x) cannot absorb O(x^2)\n '
return self | Let this `O`-term absorb another `O`-term ``other``.
INPUT:
- ``other`` -- an asymptotic `O`-term.
OUTPUT:
An asymptotic `O`-term.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other``
have the same parent.
Also, observe that the result of a "dominant" `O`-term
absorbing another `O`-term always is the "dominant"
`O`-term again.
See the :ref:`module description <term_absorption>` for a
detailed explanation on absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: OT = atm.OTermMonoid(growth_group=G)
sage: ot1 = OT(x); ot2 = OT(x^2)
sage: ot1.absorb(ot1)
O(x)
sage: ot2.absorb(ot1)
O(x^2)
sage: ot1.absorb(ot2)
Traceback (most recent call last):
...
ArithmeticError: O(x) cannot absorb O(x^2) | src/sage/rings/asymptotic/term_monoid.py | _absorb_ | Findstat/sage | 0 | python | def _absorb_(self, other):
'\n Let this `O`-term absorb another `O`-term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic `O`-term.\n\n OUTPUT:\n\n An asymptotic `O`-term.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other``\n have the same parent.\n\n Also, observe that the result of a "dominant" `O`-term\n absorbing another `O`-term always is the "dominant"\n `O`-term again.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup(\'x^ZZ\'); x = G.gen()\n sage: OT = atm.OTermMonoid(growth_group=G)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot2.absorb(ot1)\n O(x^2)\n sage: ot1.absorb(ot2)\n Traceback (most recent call last):\n ...\n ArithmeticError: O(x) cannot absorb O(x^2)\n '
return self | def _absorb_(self, other):
'\n Let this `O`-term absorb another `O`-term ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic `O`-term.\n\n OUTPUT:\n\n An asymptotic `O`-term.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other``\n have the same parent.\n\n Also, observe that the result of a "dominant" `O`-term\n absorbing another `O`-term always is the "dominant"\n `O`-term again.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup(\'x^ZZ\'); x = G.gen()\n sage: OT = atm.OTermMonoid(growth_group=G)\n sage: ot1 = OT(x); ot2 = OT(x^2)\n sage: ot1.absorb(ot1)\n O(x)\n sage: ot2.absorb(ot1)\n O(x^2)\n sage: ot1.absorb(ot2)\n Traceback (most recent call last):\n ...\n ArithmeticError: O(x) cannot absorb O(x^2)\n '
return self<|docstring|>Let this `O`-term absorb another `O`-term ``other``.
INPUT:
- ``other`` -- an asymptotic `O`-term.
OUTPUT:
An asymptotic `O`-term.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other``
have the same parent.
Also, observe that the result of a "dominant" `O`-term
absorbing another `O`-term always is the "dominant"
`O`-term again.
See the :ref:`module description <term_absorption>` for a
detailed explanation on absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: OT = atm.OTermMonoid(growth_group=G)
sage: ot1 = OT(x); ot2 = OT(x^2)
sage: ot1.absorb(ot1)
O(x)
sage: ot2.absorb(ot1)
O(x^2)
sage: ot1.absorb(ot2)
Traceback (most recent call last):
...
ArithmeticError: O(x) cannot absorb O(x^2)<|endoftext|> |
04a0a3ccff4ec043b570162bec66a388a6bc0b353f48a4e864263509214078b1 | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n ``True`` or ``None``.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this term monoid\n if ``S`` is an instance of one of the following classes:\n\n - :class:`OTermMonoid`\n\n - :class:`ExactTermMonoid`\n\n Additionally, the growth group underlying ``S`` has to\n coerce into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ'); x_ZZ = G_ZZ.gen()\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x_QQ = G_QQ.gen()\n sage: OT_ZZ = atm.OTermMonoid(G_ZZ)\n sage: OT_QQ = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(G_ZZ, ZZ)\n\n Now, the :class:`OTermMonoid` whose growth group is over the\n integer ring has to coerce into the :class:`OTermMonoid` with\n the growth group over the rational field, and the\n :class:`ExactTermMonoid` also has to coerce in each of the\n given :class:`OTermMonoid`::\n\n sage: OT_QQ.has_coerce_map_from(OT_ZZ) # indirect doctest\n True\n sage: OT_QQ.has_coerce_map_from(ET) # indirect doctest\n True\n sage: ET.has_coerce_map_from(OT_ZZ) # indirect doctest\n False\n "
if isinstance(S, (ExactTermMonoid,)):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True
else:
return super(OTermMonoid, self)._coerce_map_from_(S) | Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
``True`` or ``None``.
.. NOTE::
Another term monoid ``S`` coerces into this term monoid
if ``S`` is an instance of one of the following classes:
- :class:`OTermMonoid`
- :class:`ExactTermMonoid`
Additionally, the growth group underlying ``S`` has to
coerce into the growth group of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ'); x_ZZ = G_ZZ.gen()
sage: G_QQ = agg.GrowthGroup('x^QQ'); x_QQ = G_QQ.gen()
sage: OT_ZZ = atm.OTermMonoid(G_ZZ)
sage: OT_QQ = atm.OTermMonoid(G_QQ)
sage: ET = atm.ExactTermMonoid(G_ZZ, ZZ)
Now, the :class:`OTermMonoid` whose growth group is over the
integer ring has to coerce into the :class:`OTermMonoid` with
the growth group over the rational field, and the
:class:`ExactTermMonoid` also has to coerce in each of the
given :class:`OTermMonoid`::
sage: OT_QQ.has_coerce_map_from(OT_ZZ) # indirect doctest
True
sage: OT_QQ.has_coerce_map_from(ET) # indirect doctest
True
sage: ET.has_coerce_map_from(OT_ZZ) # indirect doctest
False | src/sage/rings/asymptotic/term_monoid.py | _coerce_map_from_ | Findstat/sage | 0 | python | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n ``True`` or ``None``.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this term monoid\n if ``S`` is an instance of one of the following classes:\n\n - :class:`OTermMonoid`\n\n - :class:`ExactTermMonoid`\n\n Additionally, the growth group underlying ``S`` has to\n coerce into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ'); x_ZZ = G_ZZ.gen()\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x_QQ = G_QQ.gen()\n sage: OT_ZZ = atm.OTermMonoid(G_ZZ)\n sage: OT_QQ = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(G_ZZ, ZZ)\n\n Now, the :class:`OTermMonoid` whose growth group is over the\n integer ring has to coerce into the :class:`OTermMonoid` with\n the growth group over the rational field, and the\n :class:`ExactTermMonoid` also has to coerce in each of the\n given :class:`OTermMonoid`::\n\n sage: OT_QQ.has_coerce_map_from(OT_ZZ) # indirect doctest\n True\n sage: OT_QQ.has_coerce_map_from(ET) # indirect doctest\n True\n sage: ET.has_coerce_map_from(OT_ZZ) # indirect doctest\n False\n "
if isinstance(S, (ExactTermMonoid,)):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True
else:
return super(OTermMonoid, self)._coerce_map_from_(S) | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n ``True`` or ``None``.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this term monoid\n if ``S`` is an instance of one of the following classes:\n\n - :class:`OTermMonoid`\n\n - :class:`ExactTermMonoid`\n\n Additionally, the growth group underlying ``S`` has to\n coerce into the growth group of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ'); x_ZZ = G_ZZ.gen()\n sage: G_QQ = agg.GrowthGroup('x^QQ'); x_QQ = G_QQ.gen()\n sage: OT_ZZ = atm.OTermMonoid(G_ZZ)\n sage: OT_QQ = atm.OTermMonoid(G_QQ)\n sage: ET = atm.ExactTermMonoid(G_ZZ, ZZ)\n\n Now, the :class:`OTermMonoid` whose growth group is over the\n integer ring has to coerce into the :class:`OTermMonoid` with\n the growth group over the rational field, and the\n :class:`ExactTermMonoid` also has to coerce in each of the\n given :class:`OTermMonoid`::\n\n sage: OT_QQ.has_coerce_map_from(OT_ZZ) # indirect doctest\n True\n sage: OT_QQ.has_coerce_map_from(ET) # indirect doctest\n True\n sage: ET.has_coerce_map_from(OT_ZZ) # indirect doctest\n False\n "
if isinstance(S, (ExactTermMonoid,)):
if self.growth_group.has_coerce_map_from(S.growth_group):
return True
else:
return super(OTermMonoid, self)._coerce_map_from_(S)<|docstring|>Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
``True`` or ``None``.
.. NOTE::
Another term monoid ``S`` coerces into this term monoid
if ``S`` is an instance of one of the following classes:
- :class:`OTermMonoid`
- :class:`ExactTermMonoid`
Additionally, the growth group underlying ``S`` has to
coerce into the growth group of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ'); x_ZZ = G_ZZ.gen()
sage: G_QQ = agg.GrowthGroup('x^QQ'); x_QQ = G_QQ.gen()
sage: OT_ZZ = atm.OTermMonoid(G_ZZ)
sage: OT_QQ = atm.OTermMonoid(G_QQ)
sage: ET = atm.ExactTermMonoid(G_ZZ, ZZ)
Now, the :class:`OTermMonoid` whose growth group is over the
integer ring has to coerce into the :class:`OTermMonoid` with
the growth group over the rational field, and the
:class:`ExactTermMonoid` also has to coerce in each of the
given :class:`OTermMonoid`::
sage: OT_QQ.has_coerce_map_from(OT_ZZ) # indirect doctest
True
sage: OT_QQ.has_coerce_map_from(ET) # indirect doctest
True
sage: ET.has_coerce_map_from(OT_ZZ) # indirect doctest
False<|endoftext|> |
80ede091b7058bb6d46bdf5e285e71dcdabc24cc50a9e465173159becc2e00d9 | def _repr_(self):
"\n A representation string for this `O`-term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.OTermMonoid(G)._repr_()\n 'Asymptotic O-Term Monoid x^ZZ'\n "
return ('Asymptotic O-Term Monoid %s' % (self.growth_group._repr_short_(),)) | A representation string for this `O`-term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: atm.OTermMonoid(G)._repr_()
'Asymptotic O-Term Monoid x^ZZ' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this `O`-term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.OTermMonoid(G)._repr_()\n 'Asymptotic O-Term Monoid x^ZZ'\n "
return ('Asymptotic O-Term Monoid %s' % (self.growth_group._repr_short_(),)) | def _repr_(self):
"\n A representation string for this `O`-term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.OTermMonoid(G)._repr_()\n 'Asymptotic O-Term Monoid x^ZZ'\n "
return ('Asymptotic O-Term Monoid %s' % (self.growth_group._repr_short_(),))<|docstring|>A representation string for this `O`-term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: atm.OTermMonoid(G)._repr_()
'Asymptotic O-Term Monoid x^ZZ'<|endoftext|> |
9f867070675b60abae39e8010f9e59787e1f633fa852655e6045468b52843e14 | def __init__(self, parent, growth, coefficient):
"\n See :class:`TermWithCoefficient` for more information.\n\n EXAMPLES:\n\n First, we define some monoids::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT_ZZ = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: CT_QQ = atm.TermWithCoefficientMonoid(G, QQ)\n\n The coefficients have to be from the given base ring::\n\n sage: t = CT_ZZ(x, 1/2)\n Traceback (most recent call last):\n ...\n ValueError: 1/2 is not in Integer Ring\n sage: t = CT_QQ(x, 1/2); t\n Asymptotic Term with coefficient 1/2 and growth x\n\n For technical reasons, the coefficient 0 is not allowed::\n\n sage: t = CT_ZZ(x^42, 0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not a valid coefficient.\n\n The conversion of growth elements also works for the creation\n of terms with coefficient::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: CT_ZZ(x^42, 42)\n Asymptotic Term with coefficient 42 and growth x^42\n "
if (coefficient not in parent.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, parent.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient')
self.coefficient = parent.base_ring()(coefficient)
super(TermWithCoefficient, self).__init__(parent=parent, growth=growth) | See :class:`TermWithCoefficient` for more information.
EXAMPLES:
First, we define some monoids::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: CT_ZZ = atm.TermWithCoefficientMonoid(G, ZZ)
sage: CT_QQ = atm.TermWithCoefficientMonoid(G, QQ)
The coefficients have to be from the given base ring::
sage: t = CT_ZZ(x, 1/2)
Traceback (most recent call last):
...
ValueError: 1/2 is not in Integer Ring
sage: t = CT_QQ(x, 1/2); t
Asymptotic Term with coefficient 1/2 and growth x
For technical reasons, the coefficient 0 is not allowed::
sage: t = CT_ZZ(x^42, 0)
Traceback (most recent call last):
...
ValueError: 0 is not a valid coefficient.
The conversion of growth elements also works for the creation
of terms with coefficient::
sage: x = SR('x'); x.parent()
Symbolic Ring
sage: CT_ZZ(x^42, 42)
Asymptotic Term with coefficient 42 and growth x^42 | src/sage/rings/asymptotic/term_monoid.py | __init__ | Findstat/sage | 0 | python | def __init__(self, parent, growth, coefficient):
"\n See :class:`TermWithCoefficient` for more information.\n\n EXAMPLES:\n\n First, we define some monoids::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT_ZZ = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: CT_QQ = atm.TermWithCoefficientMonoid(G, QQ)\n\n The coefficients have to be from the given base ring::\n\n sage: t = CT_ZZ(x, 1/2)\n Traceback (most recent call last):\n ...\n ValueError: 1/2 is not in Integer Ring\n sage: t = CT_QQ(x, 1/2); t\n Asymptotic Term with coefficient 1/2 and growth x\n\n For technical reasons, the coefficient 0 is not allowed::\n\n sage: t = CT_ZZ(x^42, 0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not a valid coefficient.\n\n The conversion of growth elements also works for the creation\n of terms with coefficient::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: CT_ZZ(x^42, 42)\n Asymptotic Term with coefficient 42 and growth x^42\n "
if (coefficient not in parent.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, parent.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient')
self.coefficient = parent.base_ring()(coefficient)
super(TermWithCoefficient, self).__init__(parent=parent, growth=growth) | def __init__(self, parent, growth, coefficient):
"\n See :class:`TermWithCoefficient` for more information.\n\n EXAMPLES:\n\n First, we define some monoids::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT_ZZ = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: CT_QQ = atm.TermWithCoefficientMonoid(G, QQ)\n\n The coefficients have to be from the given base ring::\n\n sage: t = CT_ZZ(x, 1/2)\n Traceback (most recent call last):\n ...\n ValueError: 1/2 is not in Integer Ring\n sage: t = CT_QQ(x, 1/2); t\n Asymptotic Term with coefficient 1/2 and growth x\n\n For technical reasons, the coefficient 0 is not allowed::\n\n sage: t = CT_ZZ(x^42, 0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not a valid coefficient.\n\n The conversion of growth elements also works for the creation\n of terms with coefficient::\n\n sage: x = SR('x'); x.parent()\n Symbolic Ring\n sage: CT_ZZ(x^42, 42)\n Asymptotic Term with coefficient 42 and growth x^42\n "
if (coefficient not in parent.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, parent.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient')
self.coefficient = parent.base_ring()(coefficient)
super(TermWithCoefficient, self).__init__(parent=parent, growth=growth)<|docstring|>See :class:`TermWithCoefficient` for more information.
EXAMPLES:
First, we define some monoids::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: CT_ZZ = atm.TermWithCoefficientMonoid(G, ZZ)
sage: CT_QQ = atm.TermWithCoefficientMonoid(G, QQ)
The coefficients have to be from the given base ring::
sage: t = CT_ZZ(x, 1/2)
Traceback (most recent call last):
...
ValueError: 1/2 is not in Integer Ring
sage: t = CT_QQ(x, 1/2); t
Asymptotic Term with coefficient 1/2 and growth x
For technical reasons, the coefficient 0 is not allowed::
sage: t = CT_ZZ(x^42, 0)
Traceback (most recent call last):
...
ValueError: 0 is not a valid coefficient.
The conversion of growth elements also works for the creation
of terms with coefficient::
sage: x = SR('x'); x.parent()
Symbolic Ring
sage: CT_ZZ(x^42, 42)
Asymptotic Term with coefficient 42 and growth x^42<|endoftext|> |
307d4a6afc3b0e9340fc0a39f729fa6a6ade7eee3f6264b580796a0c7d299abe | def _repr_(self):
"\n A representation string for this term with coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: T(x^2, 5)._repr_()\n 'Asymptotic Term with coefficient 5 and growth x^2'\n "
return ('Asymptotic Term with coefficient %s and growth %s' % (self.coefficient, self.growth)) | A representation string for this term with coefficient.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.TermWithCoefficientMonoid(G, ZZ)
sage: T(x^2, 5)._repr_()
'Asymptotic Term with coefficient 5 and growth x^2' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this term with coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: T(x^2, 5)._repr_()\n 'Asymptotic Term with coefficient 5 and growth x^2'\n "
return ('Asymptotic Term with coefficient %s and growth %s' % (self.coefficient, self.growth)) | def _repr_(self):
"\n A representation string for this term with coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: T(x^2, 5)._repr_()\n 'Asymptotic Term with coefficient 5 and growth x^2'\n "
return ('Asymptotic Term with coefficient %s and growth %s' % (self.coefficient, self.growth))<|docstring|>A representation string for this term with coefficient.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T = atm.TermWithCoefficientMonoid(G, ZZ)
sage: T(x^2, 5)._repr_()
'Asymptotic Term with coefficient 5 and growth x^2'<|endoftext|> |
85807279eda203ab9505e6654b23c56292fbdf2c73f72cb2c770bd89af2f2e3c | def _mul_(self, other):
"\n Multiplication method for asymptotic terms with coefficients.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term representing the product of this element\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` have\n the same parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n\n This method handles the multiplication of abstract terms\n with coefficient (i.e. :class:`TermWithCoefficient`) and\n exact terms (i.e. :class:`ExactTerm`). First, an example\n for abstract terms::\n\n sage: t1 = CT(x^2, 2); t2 = CT(x^3, 3)\n sage: t1 * t2\n Asymptotic Term with coefficient 6 and growth x^5\n\n And now, an example for exact terms::\n\n sage: t1 = ET(x^2, 2); t2 = ET(x^3, 3)\n sage: t1 * t2\n 6*x^5\n "
return self.parent()((self.growth * other.growth), (self.coefficient * other.coefficient)) | Multiplication method for asymptotic terms with coefficients.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
An asymptotic term representing the product of this element
and ``other``.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other`` have
the same parent.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: CT = atm.TermWithCoefficientMonoid(G, ZZ)
sage: ET = atm.ExactTermMonoid(G, ZZ)
This method handles the multiplication of abstract terms
with coefficient (i.e. :class:`TermWithCoefficient`) and
exact terms (i.e. :class:`ExactTerm`). First, an example
for abstract terms::
sage: t1 = CT(x^2, 2); t2 = CT(x^3, 3)
sage: t1 * t2
Asymptotic Term with coefficient 6 and growth x^5
And now, an example for exact terms::
sage: t1 = ET(x^2, 2); t2 = ET(x^3, 3)
sage: t1 * t2
6*x^5 | src/sage/rings/asymptotic/term_monoid.py | _mul_ | Findstat/sage | 0 | python | def _mul_(self, other):
"\n Multiplication method for asymptotic terms with coefficients.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term representing the product of this element\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` have\n the same parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n\n This method handles the multiplication of abstract terms\n with coefficient (i.e. :class:`TermWithCoefficient`) and\n exact terms (i.e. :class:`ExactTerm`). First, an example\n for abstract terms::\n\n sage: t1 = CT(x^2, 2); t2 = CT(x^3, 3)\n sage: t1 * t2\n Asymptotic Term with coefficient 6 and growth x^5\n\n And now, an example for exact terms::\n\n sage: t1 = ET(x^2, 2); t2 = ET(x^3, 3)\n sage: t1 * t2\n 6*x^5\n "
return self.parent()((self.growth * other.growth), (self.coefficient * other.coefficient)) | def _mul_(self, other):
"\n Multiplication method for asymptotic terms with coefficients.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n An asymptotic term representing the product of this element\n and ``other``.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` have\n the same parent.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: CT = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n\n This method handles the multiplication of abstract terms\n with coefficient (i.e. :class:`TermWithCoefficient`) and\n exact terms (i.e. :class:`ExactTerm`). First, an example\n for abstract terms::\n\n sage: t1 = CT(x^2, 2); t2 = CT(x^3, 3)\n sage: t1 * t2\n Asymptotic Term with coefficient 6 and growth x^5\n\n And now, an example for exact terms::\n\n sage: t1 = ET(x^2, 2); t2 = ET(x^3, 3)\n sage: t1 * t2\n 6*x^5\n "
return self.parent()((self.growth * other.growth), (self.coefficient * other.coefficient))<|docstring|>Multiplication method for asymptotic terms with coefficients.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
An asymptotic term representing the product of this element
and ``other``.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other`` have
the same parent.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: CT = atm.TermWithCoefficientMonoid(G, ZZ)
sage: ET = atm.ExactTermMonoid(G, ZZ)
This method handles the multiplication of abstract terms
with coefficient (i.e. :class:`TermWithCoefficient`) and
exact terms (i.e. :class:`ExactTerm`). First, an example
for abstract terms::
sage: t1 = CT(x^2, 2); t2 = CT(x^3, 3)
sage: t1 * t2
Asymptotic Term with coefficient 6 and growth x^5
And now, an example for exact terms::
sage: t1 = ET(x^2, 2); t2 = ET(x^3, 3)
sage: t1 * t2
6*x^5<|endoftext|> |
8aa26cfaf3c3d9247b51e9364490dd1eea74369b9281995c798895272a168d8f | def _le_(self, other):
"\n Return whether this asymptotic term with coefficient grows\n at most (less than or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term with coefficient.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` are\n from the same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermMonoid\n sage: G = GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = TermMonoid('exact', G, QQ)\n sage: t1 = ET(x, 5); t2 = ET(x^2, 3); t3 = ET(x^2, 42)\n sage: t1 <= t2\n True\n sage: t2 <= t1\n False\n sage: t2 <= t3\n False\n sage: t3 <= t2\n False\n sage: t2 <= t2\n True\n\n TESTS::\n\n sage: ET(x, -2) <= ET(x, 1)\n False\n "
if (self.growth == other.growth):
return (self.coefficient == other.coefficient)
else:
return super(TermWithCoefficient, self)._le_(other) | Return whether this asymptotic term with coefficient grows
at most (less than or equal) like ``other``.
INPUT:
- ``other`` -- an asymptotic term with coefficient.
OUTPUT:
A boolean.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other`` are
from the same parent.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import TermMonoid
sage: G = GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = TermMonoid('exact', G, QQ)
sage: t1 = ET(x, 5); t2 = ET(x^2, 3); t3 = ET(x^2, 42)
sage: t1 <= t2
True
sage: t2 <= t1
False
sage: t2 <= t3
False
sage: t3 <= t2
False
sage: t2 <= t2
True
TESTS::
sage: ET(x, -2) <= ET(x, 1)
False | src/sage/rings/asymptotic/term_monoid.py | _le_ | Findstat/sage | 0 | python | def _le_(self, other):
"\n Return whether this asymptotic term with coefficient grows\n at most (less than or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term with coefficient.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` are\n from the same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermMonoid\n sage: G = GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = TermMonoid('exact', G, QQ)\n sage: t1 = ET(x, 5); t2 = ET(x^2, 3); t3 = ET(x^2, 42)\n sage: t1 <= t2\n True\n sage: t2 <= t1\n False\n sage: t2 <= t3\n False\n sage: t3 <= t2\n False\n sage: t2 <= t2\n True\n\n TESTS::\n\n sage: ET(x, -2) <= ET(x, 1)\n False\n "
if (self.growth == other.growth):
return (self.coefficient == other.coefficient)
else:
return super(TermWithCoefficient, self)._le_(other) | def _le_(self, other):
"\n Return whether this asymptotic term with coefficient grows\n at most (less than or equal) like ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term with coefficient.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method is called by the coercion framework, thus,\n it can be assumed that this element and ``other`` are\n from the same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermMonoid\n sage: G = GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = TermMonoid('exact', G, QQ)\n sage: t1 = ET(x, 5); t2 = ET(x^2, 3); t3 = ET(x^2, 42)\n sage: t1 <= t2\n True\n sage: t2 <= t1\n False\n sage: t2 <= t3\n False\n sage: t3 <= t2\n False\n sage: t2 <= t2\n True\n\n TESTS::\n\n sage: ET(x, -2) <= ET(x, 1)\n False\n "
if (self.growth == other.growth):
return (self.coefficient == other.coefficient)
else:
return super(TermWithCoefficient, self)._le_(other)<|docstring|>Return whether this asymptotic term with coefficient grows
at most (less than or equal) like ``other``.
INPUT:
- ``other`` -- an asymptotic term with coefficient.
OUTPUT:
A boolean.
.. NOTE::
This method is called by the coercion framework, thus,
it can be assumed that this element and ``other`` are
from the same parent.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import TermMonoid
sage: G = GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = TermMonoid('exact', G, QQ)
sage: t1 = ET(x, 5); t2 = ET(x^2, 3); t3 = ET(x^2, 42)
sage: t1 <= t2
True
sage: t2 <= t1
False
sage: t2 <= t3
False
sage: t3 <= t2
False
sage: t2 <= t2
True
TESTS::
sage: ET(x, -2) <= ET(x, 1)
False<|endoftext|> |
ceba154315bf0d1004877f27b0430f53543135a7d61a2052508375222c522493 | def _eq_(self, other):
"\n Return whether this :class:`TermWithCoefficient` is the same as\n ``other``.\n\n INPUT:\n\n - ``other`` -- an :class:`TermWithCoefficient`.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion model, so it can\n be assumed that this term and ``other`` come from the\n same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermWithCoefficientMonoid\n sage: T = TermWithCoefficientMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: t = T.an_element(); t\n Asymptotic Term with coefficient 1 and growth x\n sage: t == T(x, 1)\n True\n sage: t == T(x, 2)\n False\n sage: t == T(x^2, 1)\n False\n "
return (super(TermWithCoefficient, self)._eq_(other) and (self.coefficient == other.coefficient)) | Return whether this :class:`TermWithCoefficient` is the same as
``other``.
INPUT:
- ``other`` -- an :class:`TermWithCoefficient`.
OUTPUT:
A boolean.
.. NOTE::
This method gets called by the coercion model, so it can
be assumed that this term and ``other`` come from the
same parent.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import TermWithCoefficientMonoid
sage: T = TermWithCoefficientMonoid(GrowthGroup('x^ZZ'), ZZ)
sage: t = T.an_element(); t
Asymptotic Term with coefficient 1 and growth x
sage: t == T(x, 1)
True
sage: t == T(x, 2)
False
sage: t == T(x^2, 1)
False | src/sage/rings/asymptotic/term_monoid.py | _eq_ | Findstat/sage | 0 | python | def _eq_(self, other):
"\n Return whether this :class:`TermWithCoefficient` is the same as\n ``other``.\n\n INPUT:\n\n - ``other`` -- an :class:`TermWithCoefficient`.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion model, so it can\n be assumed that this term and ``other`` come from the\n same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermWithCoefficientMonoid\n sage: T = TermWithCoefficientMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: t = T.an_element(); t\n Asymptotic Term with coefficient 1 and growth x\n sage: t == T(x, 1)\n True\n sage: t == T(x, 2)\n False\n sage: t == T(x^2, 1)\n False\n "
return (super(TermWithCoefficient, self)._eq_(other) and (self.coefficient == other.coefficient)) | def _eq_(self, other):
"\n Return whether this :class:`TermWithCoefficient` is the same as\n ``other``.\n\n INPUT:\n\n - ``other`` -- an :class:`TermWithCoefficient`.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method gets called by the coercion model, so it can\n be assumed that this term and ``other`` come from the\n same parent.\n\n EXAMPLES::\n\n sage: from sage.rings.asymptotic.growth_group import GrowthGroup\n sage: from sage.rings.asymptotic.term_monoid import TermWithCoefficientMonoid\n sage: T = TermWithCoefficientMonoid(GrowthGroup('x^ZZ'), ZZ)\n sage: t = T.an_element(); t\n Asymptotic Term with coefficient 1 and growth x\n sage: t == T(x, 1)\n True\n sage: t == T(x, 2)\n False\n sage: t == T(x^2, 1)\n False\n "
return (super(TermWithCoefficient, self)._eq_(other) and (self.coefficient == other.coefficient))<|docstring|>Return whether this :class:`TermWithCoefficient` is the same as
``other``.
INPUT:
- ``other`` -- an :class:`TermWithCoefficient`.
OUTPUT:
A boolean.
.. NOTE::
This method gets called by the coercion model, so it can
be assumed that this term and ``other`` come from the
same parent.
EXAMPLES::
sage: from sage.rings.asymptotic.growth_group import GrowthGroup
sage: from sage.rings.asymptotic.term_monoid import TermWithCoefficientMonoid
sage: T = TermWithCoefficientMonoid(GrowthGroup('x^ZZ'), ZZ)
sage: t = T.an_element(); t
Asymptotic Term with coefficient 1 and growth x
sage: t == T(x, 1)
True
sage: t == T(x, 2)
False
sage: t == T(x^2, 1)
False<|endoftext|> |
dacd064625521180a2928234abc6a4f168b93bb58dceabe88907e777df156f20 | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, base_ring, category=None):
"\n For more information see :class:`TermWithCoefficientMonoid`.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T_ZZ = atm.TermWithCoefficientMonoid(G, ZZ); T_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: T_QQ = atm.TermWithCoefficientMonoid(G, QQ); T_QQ\n Term Monoid x^ZZ with coefficients from Rational Field\n sage: T_QQ.category()\n Join of Category of monoids and Category of posets\n\n TESTS::\n\n sage: T = atm.TermWithCoefficientMonoid(G, None)\n Traceback (most recent call last):\n ...\n ValueError: None is not a valid base ring.\n "
from sage.categories.rings import Rings
if (base_ring not in Rings()):
raise ValueError(('%s is not a valid base ring.' % (base_ring,)))
self._base_ring_ = base_ring
super(TermWithCoefficientMonoid, self).__init__(growth_group=growth_group, category=category) | For more information see :class:`TermWithCoefficientMonoid`.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T_ZZ = atm.TermWithCoefficientMonoid(G, ZZ); T_ZZ
Term Monoid x^ZZ with coefficients from Integer Ring
sage: T_QQ = atm.TermWithCoefficientMonoid(G, QQ); T_QQ
Term Monoid x^ZZ with coefficients from Rational Field
sage: T_QQ.category()
Join of Category of monoids and Category of posets
TESTS::
sage: T = atm.TermWithCoefficientMonoid(G, None)
Traceback (most recent call last):
...
ValueError: None is not a valid base ring. | src/sage/rings/asymptotic/term_monoid.py | __init__ | Findstat/sage | 0 | python | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, base_ring, category=None):
"\n For more information see :class:`TermWithCoefficientMonoid`.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T_ZZ = atm.TermWithCoefficientMonoid(G, ZZ); T_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: T_QQ = atm.TermWithCoefficientMonoid(G, QQ); T_QQ\n Term Monoid x^ZZ with coefficients from Rational Field\n sage: T_QQ.category()\n Join of Category of monoids and Category of posets\n\n TESTS::\n\n sage: T = atm.TermWithCoefficientMonoid(G, None)\n Traceback (most recent call last):\n ...\n ValueError: None is not a valid base ring.\n "
from sage.categories.rings import Rings
if (base_ring not in Rings()):
raise ValueError(('%s is not a valid base ring.' % (base_ring,)))
self._base_ring_ = base_ring
super(TermWithCoefficientMonoid, self).__init__(growth_group=growth_group, category=category) | @sage.misc.superseded.experimental(trac_number=17601)
def __init__(self, growth_group, base_ring, category=None):
"\n For more information see :class:`TermWithCoefficientMonoid`.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: T_ZZ = atm.TermWithCoefficientMonoid(G, ZZ); T_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: T_QQ = atm.TermWithCoefficientMonoid(G, QQ); T_QQ\n Term Monoid x^ZZ with coefficients from Rational Field\n sage: T_QQ.category()\n Join of Category of monoids and Category of posets\n\n TESTS::\n\n sage: T = atm.TermWithCoefficientMonoid(G, None)\n Traceback (most recent call last):\n ...\n ValueError: None is not a valid base ring.\n "
from sage.categories.rings import Rings
if (base_ring not in Rings()):
raise ValueError(('%s is not a valid base ring.' % (base_ring,)))
self._base_ring_ = base_ring
super(TermWithCoefficientMonoid, self).__init__(growth_group=growth_group, category=category)<|docstring|>For more information see :class:`TermWithCoefficientMonoid`.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: T_ZZ = atm.TermWithCoefficientMonoid(G, ZZ); T_ZZ
Term Monoid x^ZZ with coefficients from Integer Ring
sage: T_QQ = atm.TermWithCoefficientMonoid(G, QQ); T_QQ
Term Monoid x^ZZ with coefficients from Rational Field
sage: T_QQ.category()
Join of Category of monoids and Category of posets
TESTS::
sage: T = atm.TermWithCoefficientMonoid(G, None)
Traceback (most recent call last):
...
ValueError: None is not a valid base ring.<|endoftext|> |
7f25a3b99b57df2f98f412792452b75d34b7c49983b3452569460b3aa77c61e1 | def base_ring(self):
"\n The base ring of this term monoid, i.e. the ring where\n the coefficients are from.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).base_ring()\n Integer Ring\n "
return self._base_ring_ | The base ring of this term monoid, i.e. the ring where
the coefficients are from.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.ExactTermMonoid(G, ZZ).base_ring()
Integer Ring | src/sage/rings/asymptotic/term_monoid.py | base_ring | Findstat/sage | 0 | python | def base_ring(self):
"\n The base ring of this term monoid, i.e. the ring where\n the coefficients are from.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).base_ring()\n Integer Ring\n "
return self._base_ring_ | def base_ring(self):
"\n The base ring of this term monoid, i.e. the ring where\n the coefficients are from.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.ExactTermMonoid(G, ZZ).base_ring()\n Integer Ring\n "
return self._base_ring_<|docstring|>The base ring of this term monoid, i.e. the ring where
the coefficients are from.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.ExactTermMonoid(G, ZZ).base_ring()
Integer Ring<|endoftext|> |
0578b0077da9a87aeaadea5ce4c29459a9276b5266c3e838b71056ef9db087ef | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this\n :class:`TermWithCoefficientMonoid`\n if both, the base ring as well as the growth\n group underlying ``S`` coerce into the base ring and the\n growth group underlying this term monoid, respectively.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: TC_ZZ = atm.TermWithCoefficientMonoid(G_ZZ, ZZ); TC_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: TC_QQ = atm.TermWithCoefficientMonoid(G_QQ, QQ); TC_QQ\n Term Monoid x^QQ with coefficients from Rational Field\n sage: TC_QQ.has_coerce_map_from(TC_ZZ) # indirect doctest\n True\n sage: TC_ZZ.has_coerce_map_from(TC_QQ) # indirect doctest\n False\n "
if isinstance(S, TermWithCoefficientMonoid):
return (super(TermWithCoefficientMonoid, self)._coerce_map_from_(S) and self.base_ring().has_coerce_map_from(S.base_ring())) | Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
A boolean.
.. NOTE::
Another term monoid ``S`` coerces into this
:class:`TermWithCoefficientMonoid`
if both, the base ring as well as the growth
group underlying ``S`` coerce into the base ring and the
growth group underlying this term monoid, respectively.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: TC_ZZ = atm.TermWithCoefficientMonoid(G_ZZ, ZZ); TC_ZZ
Term Monoid x^ZZ with coefficients from Integer Ring
sage: TC_QQ = atm.TermWithCoefficientMonoid(G_QQ, QQ); TC_QQ
Term Monoid x^QQ with coefficients from Rational Field
sage: TC_QQ.has_coerce_map_from(TC_ZZ) # indirect doctest
True
sage: TC_ZZ.has_coerce_map_from(TC_QQ) # indirect doctest
False | src/sage/rings/asymptotic/term_monoid.py | _coerce_map_from_ | Findstat/sage | 0 | python | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this\n :class:`TermWithCoefficientMonoid`\n if both, the base ring as well as the growth\n group underlying ``S`` coerce into the base ring and the\n growth group underlying this term monoid, respectively.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: TC_ZZ = atm.TermWithCoefficientMonoid(G_ZZ, ZZ); TC_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: TC_QQ = atm.TermWithCoefficientMonoid(G_QQ, QQ); TC_QQ\n Term Monoid x^QQ with coefficients from Rational Field\n sage: TC_QQ.has_coerce_map_from(TC_ZZ) # indirect doctest\n True\n sage: TC_ZZ.has_coerce_map_from(TC_QQ) # indirect doctest\n False\n "
if isinstance(S, TermWithCoefficientMonoid):
return (super(TermWithCoefficientMonoid, self)._coerce_map_from_(S) and self.base_ring().has_coerce_map_from(S.base_ring())) | def _coerce_map_from_(self, S):
"\n Return whether ``S`` coerces into this term monoid.\n\n INPUT:\n\n - ``S`` -- a parent.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n Another term monoid ``S`` coerces into this\n :class:`TermWithCoefficientMonoid`\n if both, the base ring as well as the growth\n group underlying ``S`` coerce into the base ring and the\n growth group underlying this term monoid, respectively.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G_ZZ = agg.GrowthGroup('x^ZZ')\n sage: G_QQ = agg.GrowthGroup('x^QQ')\n sage: TC_ZZ = atm.TermWithCoefficientMonoid(G_ZZ, ZZ); TC_ZZ\n Term Monoid x^ZZ with coefficients from Integer Ring\n sage: TC_QQ = atm.TermWithCoefficientMonoid(G_QQ, QQ); TC_QQ\n Term Monoid x^QQ with coefficients from Rational Field\n sage: TC_QQ.has_coerce_map_from(TC_ZZ) # indirect doctest\n True\n sage: TC_ZZ.has_coerce_map_from(TC_QQ) # indirect doctest\n False\n "
if isinstance(S, TermWithCoefficientMonoid):
return (super(TermWithCoefficientMonoid, self)._coerce_map_from_(S) and self.base_ring().has_coerce_map_from(S.base_ring()))<|docstring|>Return whether ``S`` coerces into this term monoid.
INPUT:
- ``S`` -- a parent.
OUTPUT:
A boolean.
.. NOTE::
Another term monoid ``S`` coerces into this
:class:`TermWithCoefficientMonoid`
if both, the base ring as well as the growth
group underlying ``S`` coerce into the base ring and the
growth group underlying this term monoid, respectively.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G_ZZ = agg.GrowthGroup('x^ZZ')
sage: G_QQ = agg.GrowthGroup('x^QQ')
sage: TC_ZZ = atm.TermWithCoefficientMonoid(G_ZZ, ZZ); TC_ZZ
Term Monoid x^ZZ with coefficients from Integer Ring
sage: TC_QQ = atm.TermWithCoefficientMonoid(G_QQ, QQ); TC_QQ
Term Monoid x^QQ with coefficients from Rational Field
sage: TC_QQ.has_coerce_map_from(TC_ZZ) # indirect doctest
True
sage: TC_ZZ.has_coerce_map_from(TC_QQ) # indirect doctest
False<|endoftext|> |
8c478194510eeb682ff1a48a1a1ff8d9b4942ba62ca7e2ccf904ea14c9f67ab6 | def _element_constructor_(self, data, coefficient=None):
"\n Construct an asymptotic term with coefficient or convert\n the given object ``data`` to this term monoid.\n\n INPUT:\n\n - ``data`` -- a growth element or an object representing the\n element to be initialized.\n\n - ``coefficient`` -- an element of the base ring.\n\n OUTPUT:\n\n An asymptotic term.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term with\n coefficient that is to be coerced into this term monoid,\n or an asymptotic growth element that is used together\n with ``coefficient`` in order to create an element of\n this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: x.parent() == SR\n True\n sage: t1 = T(x^2, 5); t1 # indirect doctest\n Asymptotic Term with coefficient 5 and growth x^2\n\n TESTS::\n\n sage: T(5 * x^5)\n Asymptotic Term with coefficient 5 and growth x^5\n sage: T(G.gen()^10)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient is not specified. Cannot continue.\n sage: T(G.gen()^10, coefficient=10)\n Asymptotic Term with coefficient 10 and growth x^10\n sage: T(x^123)\n Asymptotic Term with coefficient 1 and growth x^123\n\n ::\n\n sage: T(x)\n Asymptotic Term with coefficient 1 and growth x\n\n ::\n\n sage: G_log = agg.GrowthGroup('log(x)^ZZ')\n sage: T_log = atm.TermWithCoefficientMonoid(G_log, ZZ)\n sage: T_log(log(x))\n Asymptotic Term with coefficient 1 and growth log(x)\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, TermWithCoefficient):
return self.element_class(self, data.growth, data.coefficient)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
try:
if (coefficient is not None):
data = self.growth_group(data)
return self.element_class(self, data, coefficient)
else:
P = data.parent()
from sage.symbolic.ring import SR
import operator
from sage.symbolic.operators import mul_vararg
if (P is SR):
op = data.operator()
if (op == mul_vararg):
(data, coef_tmp) = data.operands()
data = self.growth_group(data)
elif ((op in (operator.pow, None)) or isinstance(op, sage.functions.log.Function_log)):
coef_tmp = 1
data = self.growth_group(data)
else:
coeffs = data.coefficients()
if (type(coeffs) == list):
coef_tmp = coeffs[0]
data = self.growth_group((data / coef_tmp))
elif (type(coeffs) == dict):
coef_tmp = coeffs.values()[0]
data = self.growth_group((data / coef_tmp))
return self.element_class(self, data, coef_tmp)
except (ValueError, AttributeError):
if (coefficient is None):
raise ValueError('Coefficient is not specified. Cannot continue.')
elif (coefficient not in self.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, self.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient.')
raise ValueError(('Input is ambiguous: cannot convert %s with coefficient %s to a term with coefficient.' % (data, coefficient))) | Construct an asymptotic term with coefficient or convert
the given object ``data`` to this term monoid.
INPUT:
- ``data`` -- a growth element or an object representing the
element to be initialized.
- ``coefficient`` -- an element of the base ring.
OUTPUT:
An asymptotic term.
.. NOTE::
The object ``data`` is either an asymptotic term with
coefficient that is to be coerced into this term monoid,
or an asymptotic growth element that is used together
with ``coefficient`` in order to create an element of
this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermWithCoefficientMonoid(G, ZZ)
sage: x.parent() == SR
True
sage: t1 = T(x^2, 5); t1 # indirect doctest
Asymptotic Term with coefficient 5 and growth x^2
TESTS::
sage: T(5 * x^5)
Asymptotic Term with coefficient 5 and growth x^5
sage: T(G.gen()^10)
Traceback (most recent call last):
...
ValueError: Coefficient is not specified. Cannot continue.
sage: T(G.gen()^10, coefficient=10)
Asymptotic Term with coefficient 10 and growth x^10
sage: T(x^123)
Asymptotic Term with coefficient 1 and growth x^123
::
sage: T(x)
Asymptotic Term with coefficient 1 and growth x
::
sage: G_log = agg.GrowthGroup('log(x)^ZZ')
sage: T_log = atm.TermWithCoefficientMonoid(G_log, ZZ)
sage: T_log(log(x))
Asymptotic Term with coefficient 1 and growth log(x) | src/sage/rings/asymptotic/term_monoid.py | _element_constructor_ | Findstat/sage | 0 | python | def _element_constructor_(self, data, coefficient=None):
"\n Construct an asymptotic term with coefficient or convert\n the given object ``data`` to this term monoid.\n\n INPUT:\n\n - ``data`` -- a growth element or an object representing the\n element to be initialized.\n\n - ``coefficient`` -- an element of the base ring.\n\n OUTPUT:\n\n An asymptotic term.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term with\n coefficient that is to be coerced into this term monoid,\n or an asymptotic growth element that is used together\n with ``coefficient`` in order to create an element of\n this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: x.parent() == SR\n True\n sage: t1 = T(x^2, 5); t1 # indirect doctest\n Asymptotic Term with coefficient 5 and growth x^2\n\n TESTS::\n\n sage: T(5 * x^5)\n Asymptotic Term with coefficient 5 and growth x^5\n sage: T(G.gen()^10)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient is not specified. Cannot continue.\n sage: T(G.gen()^10, coefficient=10)\n Asymptotic Term with coefficient 10 and growth x^10\n sage: T(x^123)\n Asymptotic Term with coefficient 1 and growth x^123\n\n ::\n\n sage: T(x)\n Asymptotic Term with coefficient 1 and growth x\n\n ::\n\n sage: G_log = agg.GrowthGroup('log(x)^ZZ')\n sage: T_log = atm.TermWithCoefficientMonoid(G_log, ZZ)\n sage: T_log(log(x))\n Asymptotic Term with coefficient 1 and growth log(x)\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, TermWithCoefficient):
return self.element_class(self, data.growth, data.coefficient)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
try:
if (coefficient is not None):
data = self.growth_group(data)
return self.element_class(self, data, coefficient)
else:
P = data.parent()
from sage.symbolic.ring import SR
import operator
from sage.symbolic.operators import mul_vararg
if (P is SR):
op = data.operator()
if (op == mul_vararg):
(data, coef_tmp) = data.operands()
data = self.growth_group(data)
elif ((op in (operator.pow, None)) or isinstance(op, sage.functions.log.Function_log)):
coef_tmp = 1
data = self.growth_group(data)
else:
coeffs = data.coefficients()
if (type(coeffs) == list):
coef_tmp = coeffs[0]
data = self.growth_group((data / coef_tmp))
elif (type(coeffs) == dict):
coef_tmp = coeffs.values()[0]
data = self.growth_group((data / coef_tmp))
return self.element_class(self, data, coef_tmp)
except (ValueError, AttributeError):
if (coefficient is None):
raise ValueError('Coefficient is not specified. Cannot continue.')
elif (coefficient not in self.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, self.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient.')
raise ValueError(('Input is ambiguous: cannot convert %s with coefficient %s to a term with coefficient.' % (data, coefficient))) | def _element_constructor_(self, data, coefficient=None):
"\n Construct an asymptotic term with coefficient or convert\n the given object ``data`` to this term monoid.\n\n INPUT:\n\n - ``data`` -- a growth element or an object representing the\n element to be initialized.\n\n - ``coefficient`` -- an element of the base ring.\n\n OUTPUT:\n\n An asymptotic term.\n\n .. NOTE::\n\n The object ``data`` is either an asymptotic term with\n coefficient that is to be coerced into this term monoid,\n or an asymptotic growth element that is used together\n with ``coefficient`` in order to create an element of\n this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: T = atm.TermWithCoefficientMonoid(G, ZZ)\n sage: x.parent() == SR\n True\n sage: t1 = T(x^2, 5); t1 # indirect doctest\n Asymptotic Term with coefficient 5 and growth x^2\n\n TESTS::\n\n sage: T(5 * x^5)\n Asymptotic Term with coefficient 5 and growth x^5\n sage: T(G.gen()^10)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient is not specified. Cannot continue.\n sage: T(G.gen()^10, coefficient=10)\n Asymptotic Term with coefficient 10 and growth x^10\n sage: T(x^123)\n Asymptotic Term with coefficient 1 and growth x^123\n\n ::\n\n sage: T(x)\n Asymptotic Term with coefficient 1 and growth x\n\n ::\n\n sage: G_log = agg.GrowthGroup('log(x)^ZZ')\n sage: T_log = atm.TermWithCoefficientMonoid(G_log, ZZ)\n sage: T_log(log(x))\n Asymptotic Term with coefficient 1 and growth log(x)\n "
if (isinstance(data, self.element_class) and (data.parent() == self)):
return data
elif isinstance(data, TermWithCoefficient):
return self.element_class(self, data.growth, data.coefficient)
elif (isinstance(data, int) and (data == 0)):
raise ValueError('No input specified. Cannot continue.')
try:
if (coefficient is not None):
data = self.growth_group(data)
return self.element_class(self, data, coefficient)
else:
P = data.parent()
from sage.symbolic.ring import SR
import operator
from sage.symbolic.operators import mul_vararg
if (P is SR):
op = data.operator()
if (op == mul_vararg):
(data, coef_tmp) = data.operands()
data = self.growth_group(data)
elif ((op in (operator.pow, None)) or isinstance(op, sage.functions.log.Function_log)):
coef_tmp = 1
data = self.growth_group(data)
else:
coeffs = data.coefficients()
if (type(coeffs) == list):
coef_tmp = coeffs[0]
data = self.growth_group((data / coef_tmp))
elif (type(coeffs) == dict):
coef_tmp = coeffs.values()[0]
data = self.growth_group((data / coef_tmp))
return self.element_class(self, data, coef_tmp)
except (ValueError, AttributeError):
if (coefficient is None):
raise ValueError('Coefficient is not specified. Cannot continue.')
elif (coefficient not in self.base_ring()):
raise ValueError(('%s is not in %s' % (coefficient, self.base_ring())))
elif (coefficient == 0):
raise ValueError('0 is not a valid coefficient.')
raise ValueError(('Input is ambiguous: cannot convert %s with coefficient %s to a term with coefficient.' % (data, coefficient)))<|docstring|>Construct an asymptotic term with coefficient or convert
the given object ``data`` to this term monoid.
INPUT:
- ``data`` -- a growth element or an object representing the
element to be initialized.
- ``coefficient`` -- an element of the base ring.
OUTPUT:
An asymptotic term.
.. NOTE::
The object ``data`` is either an asymptotic term with
coefficient that is to be coerced into this term monoid,
or an asymptotic growth element that is used together
with ``coefficient`` in order to create an element of
this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ')
sage: T = atm.TermWithCoefficientMonoid(G, ZZ)
sage: x.parent() == SR
True
sage: t1 = T(x^2, 5); t1 # indirect doctest
Asymptotic Term with coefficient 5 and growth x^2
TESTS::
sage: T(5 * x^5)
Asymptotic Term with coefficient 5 and growth x^5
sage: T(G.gen()^10)
Traceback (most recent call last):
...
ValueError: Coefficient is not specified. Cannot continue.
sage: T(G.gen()^10, coefficient=10)
Asymptotic Term with coefficient 10 and growth x^10
sage: T(x^123)
Asymptotic Term with coefficient 1 and growth x^123
::
sage: T(x)
Asymptotic Term with coefficient 1 and growth x
::
sage: G_log = agg.GrowthGroup('log(x)^ZZ')
sage: T_log = atm.TermWithCoefficientMonoid(G_log, ZZ)
sage: T_log(log(x))
Asymptotic Term with coefficient 1 and growth log(x)<|endoftext|> |
31a745c4d9961c32397b6fae82010ffae85ce3ea3bc4ff4cb2d78dbb19d09703 | def _repr_(self):
"\n A representation string for this monoid of terms with\n coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ)._repr_()\n 'Term Monoid x^ZZ with coefficients from Integer Ring'\n "
return ('Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring())) | A representation string for this monoid of terms with
coefficient.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermWithCoefficientMonoid(G, ZZ)._repr_()
'Term Monoid x^ZZ with coefficients from Integer Ring' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this monoid of terms with\n coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ)._repr_()\n 'Term Monoid x^ZZ with coefficients from Integer Ring'\n "
return ('Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring())) | def _repr_(self):
"\n A representation string for this monoid of terms with\n coefficient.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ)._repr_()\n 'Term Monoid x^ZZ with coefficients from Integer Ring'\n "
return ('Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring()))<|docstring|>A representation string for this monoid of terms with
coefficient.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermWithCoefficientMonoid(G, ZZ)._repr_()
'Term Monoid x^ZZ with coefficients from Integer Ring'<|endoftext|> |
df75b2ebe728cc03d3b517409b98ba99f13cc8bd6db9f1cd028af05635371d4c | def _an_element_(self):
"\n Return an element of this term with coefficient monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ).an_element() # indirect doctest\n Asymptotic Term with coefficient 1 and growth x\n sage: atm.ExactTermMonoid(G, ZZ).an_element() # indirect doctest\n x\n "
return self(self.growth_group.an_element(), self.base_ring().an_element()) | Return an element of this term with coefficient monoid.
INPUT:
Nothing.
OUTPUT:
An element of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermWithCoefficientMonoid(G, ZZ).an_element() # indirect doctest
Asymptotic Term with coefficient 1 and growth x
sage: atm.ExactTermMonoid(G, ZZ).an_element() # indirect doctest
x | src/sage/rings/asymptotic/term_monoid.py | _an_element_ | Findstat/sage | 0 | python | def _an_element_(self):
"\n Return an element of this term with coefficient monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ).an_element() # indirect doctest\n Asymptotic Term with coefficient 1 and growth x\n sage: atm.ExactTermMonoid(G, ZZ).an_element() # indirect doctest\n x\n "
return self(self.growth_group.an_element(), self.base_ring().an_element()) | def _an_element_(self):
"\n Return an element of this term with coefficient monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n An element of this term monoid.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermWithCoefficientMonoid(G, ZZ).an_element() # indirect doctest\n Asymptotic Term with coefficient 1 and growth x\n sage: atm.ExactTermMonoid(G, ZZ).an_element() # indirect doctest\n x\n "
return self(self.growth_group.an_element(), self.base_ring().an_element())<|docstring|>Return an element of this term with coefficient monoid.
INPUT:
Nothing.
OUTPUT:
An element of this term monoid.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermWithCoefficientMonoid(G, ZZ).an_element() # indirect doctest
Asymptotic Term with coefficient 1 and growth x
sage: atm.ExactTermMonoid(G, ZZ).an_element() # indirect doctest
x<|endoftext|> |
871343d6da92c3b0925e58b83667517231b73f1892dba0b4db7d634da73e4e4e | def _repr_(self):
"\n A representation string for this exact term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n sage: et1 = ET(x^2, 2); et1\n 2*x^2\n\n TESTS::\n\n sage: ET(x^2, 1)\n x^2\n sage: ET(x^2, -1)\n -x^2\n sage: ET(x^0, 42)\n 42\n "
if (self.growth._raw_element_ == 0):
return ('%s' % self.coefficient)
elif (self.coefficient == 1):
return ('%s' % self.growth)
elif (self.coefficient == (- 1)):
return ('-%s' % self.growth)
else:
return ('%s*%s' % (self.coefficient, self.growth)) | A representation string for this exact term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = atm.ExactTermMonoid(G, ZZ)
sage: et1 = ET(x^2, 2); et1
2*x^2
TESTS::
sage: ET(x^2, 1)
x^2
sage: ET(x^2, -1)
-x^2
sage: ET(x^0, 42)
42 | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this exact term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n sage: et1 = ET(x^2, 2); et1\n 2*x^2\n\n TESTS::\n\n sage: ET(x^2, 1)\n x^2\n sage: ET(x^2, -1)\n -x^2\n sage: ET(x^0, 42)\n 42\n "
if (self.growth._raw_element_ == 0):
return ('%s' % self.coefficient)
elif (self.coefficient == 1):
return ('%s' % self.growth)
elif (self.coefficient == (- 1)):
return ('-%s' % self.growth)
else:
return ('%s*%s' % (self.coefficient, self.growth)) | def _repr_(self):
"\n A representation string for this exact term.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, ZZ)\n sage: et1 = ET(x^2, 2); et1\n 2*x^2\n\n TESTS::\n\n sage: ET(x^2, 1)\n x^2\n sage: ET(x^2, -1)\n -x^2\n sage: ET(x^0, 42)\n 42\n "
if (self.growth._raw_element_ == 0):
return ('%s' % self.coefficient)
elif (self.coefficient == 1):
return ('%s' % self.growth)
elif (self.coefficient == (- 1)):
return ('-%s' % self.growth)
else:
return ('%s*%s' % (self.coefficient, self.growth))<|docstring|>A representation string for this exact term.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = atm.ExactTermMonoid(G, ZZ)
sage: et1 = ET(x^2, 2); et1
2*x^2
TESTS::
sage: ET(x^2, 1)
x^2
sage: ET(x^2, -1)
-x^2
sage: ET(x^0, 42)
42<|endoftext|> |
7caeeca85d15bbd28bbc4c24cc715c4f299565e2c53a9c3b13f6f53a7cd5daeb | def can_absorb(self, other):
"\n Check whether this exact term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n For :class:`ExactTerm`, absorption corresponds to\n addition. This means that an exact term can absorb\n only other exact terms with the same growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: ET = atm.TermMonoid('exact', agg.GrowthGroup('x^ZZ'), ZZ)\n sage: t1 = ET(x^21, 1); t2 = ET(x^21, 2); t3 = ET(x^42, 1)\n sage: t1.can_absorb(t2)\n True\n sage: t2.can_absorb(t1)\n True\n sage: t1.can_absorb(t3) or t3.can_absorb(t1)\n False\n "
return (isinstance(other, ExactTerm) and (self.growth == other.growth)) | Check whether this exact term can absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
For :class:`ExactTerm`, absorption corresponds to
addition. This means that an exact term can absorb
only other exact terms with the same growth.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: ET = atm.TermMonoid('exact', agg.GrowthGroup('x^ZZ'), ZZ)
sage: t1 = ET(x^21, 1); t2 = ET(x^21, 2); t3 = ET(x^42, 1)
sage: t1.can_absorb(t2)
True
sage: t2.can_absorb(t1)
True
sage: t1.can_absorb(t3) or t3.can_absorb(t1)
False | src/sage/rings/asymptotic/term_monoid.py | can_absorb | Findstat/sage | 0 | python | def can_absorb(self, other):
"\n Check whether this exact term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n For :class:`ExactTerm`, absorption corresponds to\n addition. This means that an exact term can absorb\n only other exact terms with the same growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: ET = atm.TermMonoid('exact', agg.GrowthGroup('x^ZZ'), ZZ)\n sage: t1 = ET(x^21, 1); t2 = ET(x^21, 2); t3 = ET(x^42, 1)\n sage: t1.can_absorb(t2)\n True\n sage: t2.can_absorb(t1)\n True\n sage: t1.can_absorb(t3) or t3.can_absorb(t1)\n False\n "
return (isinstance(other, ExactTerm) and (self.growth == other.growth)) | def can_absorb(self, other):
"\n Check whether this exact term can absorb ``other``.\n\n INPUT:\n\n - ``other`` -- an asymptotic term.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n For :class:`ExactTerm`, absorption corresponds to\n addition. This means that an exact term can absorb\n only other exact terms with the same growth.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation of absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: ET = atm.TermMonoid('exact', agg.GrowthGroup('x^ZZ'), ZZ)\n sage: t1 = ET(x^21, 1); t2 = ET(x^21, 2); t3 = ET(x^42, 1)\n sage: t1.can_absorb(t2)\n True\n sage: t2.can_absorb(t1)\n True\n sage: t1.can_absorb(t3) or t3.can_absorb(t1)\n False\n "
return (isinstance(other, ExactTerm) and (self.growth == other.growth))<|docstring|>Check whether this exact term can absorb ``other``.
INPUT:
- ``other`` -- an asymptotic term.
OUTPUT:
A boolean.
.. NOTE::
For :class:`ExactTerm`, absorption corresponds to
addition. This means that an exact term can absorb
only other exact terms with the same growth.
See the :ref:`module description <term_absorption>` for a
detailed explanation of absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: ET = atm.TermMonoid('exact', agg.GrowthGroup('x^ZZ'), ZZ)
sage: t1 = ET(x^21, 1); t2 = ET(x^21, 2); t3 = ET(x^42, 1)
sage: t1.can_absorb(t2)
True
sage: t2.can_absorb(t1)
True
sage: t1.can_absorb(t3) or t3.can_absorb(t1)
False<|endoftext|> |
934eaad5016ef1d77c6943a09236585f93e3bfb8d2190ccd9ba2b2151e1a0409 | def _absorb_(self, other):
"\n Let this exact term absorb another exact term ``other``.\n\n INPUT:\n\n - ``other`` -- an exact term.\n\n OUTPUT:\n\n An exact term or ``None``.\n\n .. NOTE::\n\n In the context of exact terms, absorption translates\n to addition. As the coefficient `0` is not allowed,\n ``None`` is returned instead if the terms cancel out.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, QQ)\n\n Asymptotic exact terms can absorb other asymptotic exact\n terms with the same growth::\n\n sage: et1 = ET(x^2, 2); et2 = ET(x^2, -2)\n sage: et1.absorb(et1)\n 4*x^2\n sage: et1.absorb(et2) is None\n True\n\n If the growth differs, an ``ArithmeticException`` is raised::\n\n sage: ET(x^5, 1).absorb(et1)\n Traceback (most recent call last):\n ...\n ArithmeticError: x^5 cannot absorb 2*x^2\n "
coeff_new = (self.coefficient + other.coefficient)
if (coeff_new == 0):
return None
else:
return self.parent()(self.growth, coeff_new) | Let this exact term absorb another exact term ``other``.
INPUT:
- ``other`` -- an exact term.
OUTPUT:
An exact term or ``None``.
.. NOTE::
In the context of exact terms, absorption translates
to addition. As the coefficient `0` is not allowed,
``None`` is returned instead if the terms cancel out.
See the :ref:`module description <term_absorption>` for a
detailed explanation on absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = atm.ExactTermMonoid(G, QQ)
Asymptotic exact terms can absorb other asymptotic exact
terms with the same growth::
sage: et1 = ET(x^2, 2); et2 = ET(x^2, -2)
sage: et1.absorb(et1)
4*x^2
sage: et1.absorb(et2) is None
True
If the growth differs, an ``ArithmeticException`` is raised::
sage: ET(x^5, 1).absorb(et1)
Traceback (most recent call last):
...
ArithmeticError: x^5 cannot absorb 2*x^2 | src/sage/rings/asymptotic/term_monoid.py | _absorb_ | Findstat/sage | 0 | python | def _absorb_(self, other):
"\n Let this exact term absorb another exact term ``other``.\n\n INPUT:\n\n - ``other`` -- an exact term.\n\n OUTPUT:\n\n An exact term or ``None``.\n\n .. NOTE::\n\n In the context of exact terms, absorption translates\n to addition. As the coefficient `0` is not allowed,\n ``None`` is returned instead if the terms cancel out.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, QQ)\n\n Asymptotic exact terms can absorb other asymptotic exact\n terms with the same growth::\n\n sage: et1 = ET(x^2, 2); et2 = ET(x^2, -2)\n sage: et1.absorb(et1)\n 4*x^2\n sage: et1.absorb(et2) is None\n True\n\n If the growth differs, an ``ArithmeticException`` is raised::\n\n sage: ET(x^5, 1).absorb(et1)\n Traceback (most recent call last):\n ...\n ArithmeticError: x^5 cannot absorb 2*x^2\n "
coeff_new = (self.coefficient + other.coefficient)
if (coeff_new == 0):
return None
else:
return self.parent()(self.growth, coeff_new) | def _absorb_(self, other):
"\n Let this exact term absorb another exact term ``other``.\n\n INPUT:\n\n - ``other`` -- an exact term.\n\n OUTPUT:\n\n An exact term or ``None``.\n\n .. NOTE::\n\n In the context of exact terms, absorption translates\n to addition. As the coefficient `0` is not allowed,\n ``None`` is returned instead if the terms cancel out.\n\n See the :ref:`module description <term_absorption>` for a\n detailed explanation on absorption.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: ET = atm.ExactTermMonoid(G, QQ)\n\n Asymptotic exact terms can absorb other asymptotic exact\n terms with the same growth::\n\n sage: et1 = ET(x^2, 2); et2 = ET(x^2, -2)\n sage: et1.absorb(et1)\n 4*x^2\n sage: et1.absorb(et2) is None\n True\n\n If the growth differs, an ``ArithmeticException`` is raised::\n\n sage: ET(x^5, 1).absorb(et1)\n Traceback (most recent call last):\n ...\n ArithmeticError: x^5 cannot absorb 2*x^2\n "
coeff_new = (self.coefficient + other.coefficient)
if (coeff_new == 0):
return None
else:
return self.parent()(self.growth, coeff_new)<|docstring|>Let this exact term absorb another exact term ``other``.
INPUT:
- ``other`` -- an exact term.
OUTPUT:
An exact term or ``None``.
.. NOTE::
In the context of exact terms, absorption translates
to addition. As the coefficient `0` is not allowed,
``None`` is returned instead if the terms cancel out.
See the :ref:`module description <term_absorption>` for a
detailed explanation on absorption.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: ET = atm.ExactTermMonoid(G, QQ)
Asymptotic exact terms can absorb other asymptotic exact
terms with the same growth::
sage: et1 = ET(x^2, 2); et2 = ET(x^2, -2)
sage: et1.absorb(et1)
4*x^2
sage: et1.absorb(et2) is None
True
If the growth differs, an ``ArithmeticException`` is raised::
sage: ET(x^5, 1).absorb(et1)
Traceback (most recent call last):
...
ArithmeticError: x^5 cannot absorb 2*x^2<|endoftext|> |
be5c1407b98dad307b2173418c534f76d04a565e77a510e5af102ea4f153b2b9 | def _repr_(self):
"\n A representation string for this exact term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.ExactTermMonoid(G, QQ)._repr_()\n 'Exact Term Monoid x^ZZ with coefficients from Rational Field'\n "
return ('Exact Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring())) | A representation string for this exact term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: atm.ExactTermMonoid(G, QQ)._repr_()
'Exact Term Monoid x^ZZ with coefficients from Rational Field' | src/sage/rings/asymptotic/term_monoid.py | _repr_ | Findstat/sage | 0 | python | def _repr_(self):
"\n A representation string for this exact term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.ExactTermMonoid(G, QQ)._repr_()\n 'Exact Term Monoid x^ZZ with coefficients from Rational Field'\n "
return ('Exact Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring())) | def _repr_(self):
"\n A representation string for this exact term monoid.\n\n INPUT:\n\n Nothing.\n\n OUTPUT:\n\n A string.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()\n sage: atm.ExactTermMonoid(G, QQ)._repr_()\n 'Exact Term Monoid x^ZZ with coefficients from Rational Field'\n "
return ('Exact Term Monoid %s with coefficients from %s' % (self.growth_group._repr_short_(), self.base_ring()))<|docstring|>A representation string for this exact term monoid.
INPUT:
Nothing.
OUTPUT:
A string.
EXAMPLES::
sage: import sage.rings.asymptotic.term_monoid as atm
sage: import sage.rings.asymptotic.growth_group as agg
sage: G = agg.GrowthGroup('x^ZZ'); x = G.gen()
sage: atm.ExactTermMonoid(G, QQ)._repr_()
'Exact Term Monoid x^ZZ with coefficients from Rational Field'<|endoftext|> |
7444dc44a88d8ca8942d294a4ce3530c5349d7e222cb830a9679906c0acc8309 | def create_key_and_extra_args(self, term, growth_group, base_ring=None, **kwds):
"\n Given the arguments and keyword, create a key that uniquely\n determines this object.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid.create_key_and_extra_args('O', G)\n (('O', Growth Group x^ZZ, None), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G, ZZ)\n (('exact', Growth Group x^ZZ, Integer Ring), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G)\n Traceback (most recent call last):\n ...\n ValueError: A base ring has to be specified\n\n TESTS::\n\n sage: atm.TermMonoid.create_key_and_extra_args('icecream', G)\n Traceback (most recent call last):\n ...\n ValueError: icecream has to be either 'exact' or 'O'\n sage: atm.TermMonoid.create_key_and_extra_args('O', ZZ)\n Traceback (most recent call last):\n ...\n ValueError: Integer Ring has to be an asymptotic growth group\n "
if (term not in ['O', 'exact']):
raise ValueError(("%s has to be either 'exact' or 'O'" % term))
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s has to be an asymptotic growth group' % growth_group))
if ((term == 'exact') and (base_ring is None)):
raise ValueError('A base ring has to be specified')
elif (term == 'O'):
base_ring = None
return ((term, growth_group, base_ring), kwds) | Given the arguments and keyword, create a key that uniquely
determines this object.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermMonoid.create_key_and_extra_args('O', G)
(('O', Growth Group x^ZZ, None), {})
sage: atm.TermMonoid.create_key_and_extra_args('exact', G, ZZ)
(('exact', Growth Group x^ZZ, Integer Ring), {})
sage: atm.TermMonoid.create_key_and_extra_args('exact', G)
Traceback (most recent call last):
...
ValueError: A base ring has to be specified
TESTS::
sage: atm.TermMonoid.create_key_and_extra_args('icecream', G)
Traceback (most recent call last):
...
ValueError: icecream has to be either 'exact' or 'O'
sage: atm.TermMonoid.create_key_and_extra_args('O', ZZ)
Traceback (most recent call last):
...
ValueError: Integer Ring has to be an asymptotic growth group | src/sage/rings/asymptotic/term_monoid.py | create_key_and_extra_args | Findstat/sage | 0 | python | def create_key_and_extra_args(self, term, growth_group, base_ring=None, **kwds):
"\n Given the arguments and keyword, create a key that uniquely\n determines this object.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid.create_key_and_extra_args('O', G)\n (('O', Growth Group x^ZZ, None), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G, ZZ)\n (('exact', Growth Group x^ZZ, Integer Ring), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G)\n Traceback (most recent call last):\n ...\n ValueError: A base ring has to be specified\n\n TESTS::\n\n sage: atm.TermMonoid.create_key_and_extra_args('icecream', G)\n Traceback (most recent call last):\n ...\n ValueError: icecream has to be either 'exact' or 'O'\n sage: atm.TermMonoid.create_key_and_extra_args('O', ZZ)\n Traceback (most recent call last):\n ...\n ValueError: Integer Ring has to be an asymptotic growth group\n "
if (term not in ['O', 'exact']):
raise ValueError(("%s has to be either 'exact' or 'O'" % term))
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s has to be an asymptotic growth group' % growth_group))
if ((term == 'exact') and (base_ring is None)):
raise ValueError('A base ring has to be specified')
elif (term == 'O'):
base_ring = None
return ((term, growth_group, base_ring), kwds) | def create_key_and_extra_args(self, term, growth_group, base_ring=None, **kwds):
"\n Given the arguments and keyword, create a key that uniquely\n determines this object.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid.create_key_and_extra_args('O', G)\n (('O', Growth Group x^ZZ, None), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G, ZZ)\n (('exact', Growth Group x^ZZ, Integer Ring), {})\n sage: atm.TermMonoid.create_key_and_extra_args('exact', G)\n Traceback (most recent call last):\n ...\n ValueError: A base ring has to be specified\n\n TESTS::\n\n sage: atm.TermMonoid.create_key_and_extra_args('icecream', G)\n Traceback (most recent call last):\n ...\n ValueError: icecream has to be either 'exact' or 'O'\n sage: atm.TermMonoid.create_key_and_extra_args('O', ZZ)\n Traceback (most recent call last):\n ...\n ValueError: Integer Ring has to be an asymptotic growth group\n "
if (term not in ['O', 'exact']):
raise ValueError(("%s has to be either 'exact' or 'O'" % term))
from sage.rings.asymptotic.growth_group import GenericGrowthGroup
if (not isinstance(growth_group, GenericGrowthGroup)):
raise ValueError(('%s has to be an asymptotic growth group' % growth_group))
if ((term == 'exact') and (base_ring is None)):
raise ValueError('A base ring has to be specified')
elif (term == 'O'):
base_ring = None
return ((term, growth_group, base_ring), kwds)<|docstring|>Given the arguments and keyword, create a key that uniquely
determines this object.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermMonoid.create_key_and_extra_args('O', G)
(('O', Growth Group x^ZZ, None), {})
sage: atm.TermMonoid.create_key_and_extra_args('exact', G, ZZ)
(('exact', Growth Group x^ZZ, Integer Ring), {})
sage: atm.TermMonoid.create_key_and_extra_args('exact', G)
Traceback (most recent call last):
...
ValueError: A base ring has to be specified
TESTS::
sage: atm.TermMonoid.create_key_and_extra_args('icecream', G)
Traceback (most recent call last):
...
ValueError: icecream has to be either 'exact' or 'O'
sage: atm.TermMonoid.create_key_and_extra_args('O', ZZ)
Traceback (most recent call last):
...
ValueError: Integer Ring has to be an asymptotic growth group<|endoftext|> |
a88641294a5a6801cc49dc5a42264f14e66b8aa36b3e5e28ed010a5fa43c84d0 | def create_object(self, version, key, **kwds):
"\n Create a object from the given arguments.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid('O', G) # indirect doctest\n Asymptotic O-Term Monoid x^ZZ\n sage: atm.TermMonoid('exact', G, ZZ) # indirect doctest\n Exact Term Monoid x^ZZ with coefficients from Integer Ring\n "
(term, growth_group, base_ring) = key
if (term == 'O'):
return OTermMonoid(growth_group, **kwds)
else:
return ExactTermMonoid(growth_group, base_ring, **kwds) | Create a object from the given arguments.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermMonoid('O', G) # indirect doctest
Asymptotic O-Term Monoid x^ZZ
sage: atm.TermMonoid('exact', G, ZZ) # indirect doctest
Exact Term Monoid x^ZZ with coefficients from Integer Ring | src/sage/rings/asymptotic/term_monoid.py | create_object | Findstat/sage | 0 | python | def create_object(self, version, key, **kwds):
"\n Create a object from the given arguments.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid('O', G) # indirect doctest\n Asymptotic O-Term Monoid x^ZZ\n sage: atm.TermMonoid('exact', G, ZZ) # indirect doctest\n Exact Term Monoid x^ZZ with coefficients from Integer Ring\n "
(term, growth_group, base_ring) = key
if (term == 'O'):
return OTermMonoid(growth_group, **kwds)
else:
return ExactTermMonoid(growth_group, base_ring, **kwds) | def create_object(self, version, key, **kwds):
"\n Create a object from the given arguments.\n\n EXAMPLES::\n\n sage: import sage.rings.asymptotic.growth_group as agg\n sage: import sage.rings.asymptotic.term_monoid as atm\n sage: G = agg.GrowthGroup('x^ZZ')\n sage: atm.TermMonoid('O', G) # indirect doctest\n Asymptotic O-Term Monoid x^ZZ\n sage: atm.TermMonoid('exact', G, ZZ) # indirect doctest\n Exact Term Monoid x^ZZ with coefficients from Integer Ring\n "
(term, growth_group, base_ring) = key
if (term == 'O'):
return OTermMonoid(growth_group, **kwds)
else:
return ExactTermMonoid(growth_group, base_ring, **kwds)<|docstring|>Create a object from the given arguments.
EXAMPLES::
sage: import sage.rings.asymptotic.growth_group as agg
sage: import sage.rings.asymptotic.term_monoid as atm
sage: G = agg.GrowthGroup('x^ZZ')
sage: atm.TermMonoid('O', G) # indirect doctest
Asymptotic O-Term Monoid x^ZZ
sage: atm.TermMonoid('exact', G, ZZ) # indirect doctest
Exact Term Monoid x^ZZ with coefficients from Integer Ring<|endoftext|> |
0c988779ede9fc2da2fb35cea0816d0cb158461a2fd8b666ea4971ba2e7e755a | def run_create_hyper_file_from_csv():
'\n An example demonstrating loading data from a csv into a new Hyper file\n '
if args.preprocessed:
print('running on {} + {} columns'.format(5, 4))
else:
print('running on {} + {} columns'.format(16, 9))
load_time = (- 1)
query_time = (- 1)
tstart = time.time()
path_to_database = Path('tpchq19.hyper')
process_parameters = {'soft_concurrent_query_thread_limit': '16', 'hard_concurrent_query_thread_limit': '16', 'memory_limit': '100g'}
if args.single_threaded:
process_parameters['soft_concurrent_query_thread_limit'] = '1'
process_parameters['hard_concurrent_query_thread_limit'] = '1'
result = None
with HyperProcess(telemetry=Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU, parameters=process_parameters) as hyper:
connection_parameters = {'lc_time': 'en_US'}
with Connection(endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE, parameters=connection_parameters) as connection:
lineitem_table_name = ''
part_table_name = ''
if args.preprocessed:
connection.catalog.create_table(table_definition=lineitem_table_preprocessed)
lineitem_table_name = lineitem_table_preprocessed.table_name
connection.catalog.create_table(table_definition=part_table_preprocessed)
part_table_name = part_table_preprocessed.table_name
else:
connection.catalog.create_table(table_definition=lineitem_table)
lineitem_table_name = lineitem_table.table_name
connection.catalog.create_table(table_definition=part_table)
part_table_name = part_table.table_name
lineitem_csv_path = args.lineitem_path
part_csv_path = args.part_path
count_in_lineitem_table = connection.execute_command(command=f"COPY {lineitem_table_name} from {escape_string_literal(lineitem_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
count_in_part_table = connection.execute_command(command=f"COPY {part_table_name} from {escape_string_literal(part_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
print(f'The number of rows in table {lineitem_table.table_name} is {count_in_lineitem_table}.')
print(f'The number of rows in table {part_table.table_name} is {count_in_part_table}.')
load_time = (time.time() - tstart)
print('Loading CSV to Hyper took {}s'.format(load_time))
tstart = time.time()
q = ''
if args.weld_mode:
q = f'''select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 12
and p_container in (18, 31, 25, 4)
and l_quantity >= 1 and l_quantity <= 1 + 10
and p_size between 1 and 5
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 23
and p_container in (5, 38, 19, 13)
and l_quantity >= 10 and l_quantity <= 10 + 10
and p_size between 1 and 10
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 34
and p_container in (1, 14, 29, 21)
and l_quantity >= 20 and l_quantity <= 20 + 10
and p_size between 1 and 15
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
)'''
else:
q = f'''select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 'Brand#12'
and p_container in ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG')
and l_quantity >= 1 and l_quantity <= 11
and p_size between 1 and 5
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#23'
and p_container in ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK')
and l_quantity >= 10 and l_quantity <= 20
and p_size between 1 and 10
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#34'
and p_container in ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG')
and l_quantity >= 20 and l_quantity <= 30
and p_size between 1 and 15
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
)'''
result = connection.execute_list_query(query=q)
query_time = (time.time() - tstart)
print('Query took {}s'.format(query_time))
print('Result::')
print(result)
print('The connection to the Hyper file has been closed.')
print('The Hyper process has been shut down.')
print('framework,version,load,query,result\n{},{},{},{},{}'.format('hyper', hyperversion, load_time, query_time, str(result[0][0]))) | An example demonstrating loading data from a csv into a new Hyper file | benchmarks/tpch/Q19/runhyper.py | run_create_hyper_file_from_csv | yash-browncs/tuplex | 778 | python | def run_create_hyper_file_from_csv():
'\n \n '
if args.preprocessed:
print('running on {} + {} columns'.format(5, 4))
else:
print('running on {} + {} columns'.format(16, 9))
load_time = (- 1)
query_time = (- 1)
tstart = time.time()
path_to_database = Path('tpchq19.hyper')
process_parameters = {'soft_concurrent_query_thread_limit': '16', 'hard_concurrent_query_thread_limit': '16', 'memory_limit': '100g'}
if args.single_threaded:
process_parameters['soft_concurrent_query_thread_limit'] = '1'
process_parameters['hard_concurrent_query_thread_limit'] = '1'
result = None
with HyperProcess(telemetry=Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU, parameters=process_parameters) as hyper:
connection_parameters = {'lc_time': 'en_US'}
with Connection(endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE, parameters=connection_parameters) as connection:
lineitem_table_name =
part_table_name =
if args.preprocessed:
connection.catalog.create_table(table_definition=lineitem_table_preprocessed)
lineitem_table_name = lineitem_table_preprocessed.table_name
connection.catalog.create_table(table_definition=part_table_preprocessed)
part_table_name = part_table_preprocessed.table_name
else:
connection.catalog.create_table(table_definition=lineitem_table)
lineitem_table_name = lineitem_table.table_name
connection.catalog.create_table(table_definition=part_table)
part_table_name = part_table.table_name
lineitem_csv_path = args.lineitem_path
part_csv_path = args.part_path
count_in_lineitem_table = connection.execute_command(command=f"COPY {lineitem_table_name} from {escape_string_literal(lineitem_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
count_in_part_table = connection.execute_command(command=f"COPY {part_table_name} from {escape_string_literal(part_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
print(f'The number of rows in table {lineitem_table.table_name} is {count_in_lineitem_table}.')
print(f'The number of rows in table {part_table.table_name} is {count_in_part_table}.')
load_time = (time.time() - tstart)
print('Loading CSV to Hyper took {}s'.format(load_time))
tstart = time.time()
q =
if args.weld_mode:
q = f'select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 12
and p_container in (18, 31, 25, 4)
and l_quantity >= 1 and l_quantity <= 1 + 10
and p_size between 1 and 5
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 23
and p_container in (5, 38, 19, 13)
and l_quantity >= 10 and l_quantity <= 10 + 10
and p_size between 1 and 10
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 34
and p_container in (1, 14, 29, 21)
and l_quantity >= 20 and l_quantity <= 20 + 10
and p_size between 1 and 15
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
)'
else:
q = f'select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 'Brand#12'
and p_container in ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG')
and l_quantity >= 1 and l_quantity <= 11
and p_size between 1 and 5
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#23'
and p_container in ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK')
and l_quantity >= 10 and l_quantity <= 20
and p_size between 1 and 10
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#34'
and p_container in ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG')
and l_quantity >= 20 and l_quantity <= 30
and p_size between 1 and 15
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
)'
result = connection.execute_list_query(query=q)
query_time = (time.time() - tstart)
print('Query took {}s'.format(query_time))
print('Result::')
print(result)
print('The connection to the Hyper file has been closed.')
print('The Hyper process has been shut down.')
print('framework,version,load,query,result\n{},{},{},{},{}'.format('hyper', hyperversion, load_time, query_time, str(result[0][0]))) | def run_create_hyper_file_from_csv():
'\n \n '
if args.preprocessed:
print('running on {} + {} columns'.format(5, 4))
else:
print('running on {} + {} columns'.format(16, 9))
load_time = (- 1)
query_time = (- 1)
tstart = time.time()
path_to_database = Path('tpchq19.hyper')
process_parameters = {'soft_concurrent_query_thread_limit': '16', 'hard_concurrent_query_thread_limit': '16', 'memory_limit': '100g'}
if args.single_threaded:
process_parameters['soft_concurrent_query_thread_limit'] = '1'
process_parameters['hard_concurrent_query_thread_limit'] = '1'
result = None
with HyperProcess(telemetry=Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU, parameters=process_parameters) as hyper:
connection_parameters = {'lc_time': 'en_US'}
with Connection(endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE, parameters=connection_parameters) as connection:
lineitem_table_name =
part_table_name =
if args.preprocessed:
connection.catalog.create_table(table_definition=lineitem_table_preprocessed)
lineitem_table_name = lineitem_table_preprocessed.table_name
connection.catalog.create_table(table_definition=part_table_preprocessed)
part_table_name = part_table_preprocessed.table_name
else:
connection.catalog.create_table(table_definition=lineitem_table)
lineitem_table_name = lineitem_table.table_name
connection.catalog.create_table(table_definition=part_table)
part_table_name = part_table.table_name
lineitem_csv_path = args.lineitem_path
part_csv_path = args.part_path
count_in_lineitem_table = connection.execute_command(command=f"COPY {lineitem_table_name} from {escape_string_literal(lineitem_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
count_in_part_table = connection.execute_command(command=f"COPY {part_table_name} from {escape_string_literal(part_csv_path)} with (format csv, NULL 'NULL', delimiter '|')")
print(f'The number of rows in table {lineitem_table.table_name} is {count_in_lineitem_table}.')
print(f'The number of rows in table {part_table.table_name} is {count_in_part_table}.')
load_time = (time.time() - tstart)
print('Loading CSV to Hyper took {}s'.format(load_time))
tstart = time.time()
q =
if args.weld_mode:
q = f'select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 12
and p_container in (18, 31, 25, 4)
and l_quantity >= 1 and l_quantity <= 1 + 10
and p_size between 1 and 5
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 23
and p_container in (5, 38, 19, 13)
and l_quantity >= 10 and l_quantity <= 10 + 10
and p_size between 1 and 10
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
or
(
p_brand = 34
and p_container in (1, 14, 29, 21)
and l_quantity >= 20 and l_quantity <= 20 + 10
and p_size between 1 and 15
and l_shipmode in (3, 7)
and l_shipinstruct = 0
)
)'
else:
q = f'select
sum(l_extendedprice * (1 - l_discount)) as revenue
from
{lineitem_table_name},
{part_table_name}
where
p_partkey = l_partkey
and (
(
p_brand = 'Brand#12'
and p_container in ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG')
and l_quantity >= 1 and l_quantity <= 11
and p_size between 1 and 5
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#23'
and p_container in ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK')
and l_quantity >= 10 and l_quantity <= 20
and p_size between 1 and 10
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
or
(
p_brand = 'Brand#34'
and p_container in ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG')
and l_quantity >= 20 and l_quantity <= 30
and p_size between 1 and 15
and l_shipmode in ('AIR', 'AIR REG')
and l_shipinstruct = 'DELIVER IN PERSON'
)
)'
result = connection.execute_list_query(query=q)
query_time = (time.time() - tstart)
print('Query took {}s'.format(query_time))
print('Result::')
print(result)
print('The connection to the Hyper file has been closed.')
print('The Hyper process has been shut down.')
print('framework,version,load,query,result\n{},{},{},{},{}'.format('hyper', hyperversion, load_time, query_time, str(result[0][0])))<|docstring|>An example demonstrating loading data from a csv into a new Hyper file<|endoftext|> |
135ff8bb9b828211a540226d8da965a336620629d67103f912c77331f906256f | def __init__(self, champion_level: int, chest_granted: bool, champion_points: int, champion_points_since_last_level: int, champion_points_until_next_level: int, summoner_id: str, tokens_earned: int, champion_id: int, last_play_time: int):
'\n :param champion_level:\n :param chest_granted:\n :param champion_points:\n :param champion_points_since_last_level:\n :param champion_points_until_next_level:\n :param summoner_id:\n :param tokens_earned:\n :param champion_id:\n :param last_play_time:\n '
self.championLevel: int = champion_level
self.chestGranted: bool = chest_granted
self.championPoints: int = champion_points
self.championPointsSinceLastLevel: int = champion_points_since_last_level
self.championPointsUntilNextLevel: int = champion_points_until_next_level
self.summonerId: str = summoner_id
self.tokensEarned: int = tokens_earned
self.championId: int = champion_id
self.lastPlayTime: int = last_play_time | :param champion_level:
:param chest_granted:
:param champion_points:
:param champion_points_since_last_level:
:param champion_points_until_next_level:
:param summoner_id:
:param tokens_earned:
:param champion_id:
:param last_play_time: | RiotGames/API/ChampionMastery.py | __init__ | Timohiho/RiotGames | 2 | python | def __init__(self, champion_level: int, chest_granted: bool, champion_points: int, champion_points_since_last_level: int, champion_points_until_next_level: int, summoner_id: str, tokens_earned: int, champion_id: int, last_play_time: int):
'\n :param champion_level:\n :param chest_granted:\n :param champion_points:\n :param champion_points_since_last_level:\n :param champion_points_until_next_level:\n :param summoner_id:\n :param tokens_earned:\n :param champion_id:\n :param last_play_time:\n '
self.championLevel: int = champion_level
self.chestGranted: bool = chest_granted
self.championPoints: int = champion_points
self.championPointsSinceLastLevel: int = champion_points_since_last_level
self.championPointsUntilNextLevel: int = champion_points_until_next_level
self.summonerId: str = summoner_id
self.tokensEarned: int = tokens_earned
self.championId: int = champion_id
self.lastPlayTime: int = last_play_time | def __init__(self, champion_level: int, chest_granted: bool, champion_points: int, champion_points_since_last_level: int, champion_points_until_next_level: int, summoner_id: str, tokens_earned: int, champion_id: int, last_play_time: int):
'\n :param champion_level:\n :param chest_granted:\n :param champion_points:\n :param champion_points_since_last_level:\n :param champion_points_until_next_level:\n :param summoner_id:\n :param tokens_earned:\n :param champion_id:\n :param last_play_time:\n '
self.championLevel: int = champion_level
self.chestGranted: bool = chest_granted
self.championPoints: int = champion_points
self.championPointsSinceLastLevel: int = champion_points_since_last_level
self.championPointsUntilNextLevel: int = champion_points_until_next_level
self.summonerId: str = summoner_id
self.tokensEarned: int = tokens_earned
self.championId: int = champion_id
self.lastPlayTime: int = last_play_time<|docstring|>:param champion_level:
:param chest_granted:
:param champion_points:
:param champion_points_since_last_level:
:param champion_points_until_next_level:
:param summoner_id:
:param tokens_earned:
:param champion_id:
:param last_play_time:<|endoftext|> |
a00b6075db82dbd6def7f6c1210945ca9c6e4940a205c4c2676ddb45a7ded730 | def __init__(self, apikey: str):
'\n :param apikey:\n '
super().__init__(apikey)
self.__super = super() | :param apikey: | RiotGames/API/ChampionMastery.py | __init__ | Timohiho/RiotGames | 2 | python | def __init__(self, apikey: str):
'\n \n '
super().__init__(apikey)
self.__super = super() | def __init__(self, apikey: str):
'\n \n '
super().__init__(apikey)
self.__super = super()<|docstring|>:param apikey:<|endoftext|> |
a490942a7315ca9da88001685154089eaab5d5b9224df197ee6ef05af1a4c80b | def summoner_masteries(self, summoner: SummonerAccount, region: str) -> [ChampionMasteries]:
'\n :param summoner:\n :param region:\n :return:\n '
summoner_masteries: [ChampionMasteries] = []
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
for champion_data in data:
summoner_masteries.append(ChampionMasteries(champion_data['championLevel'], champion_data['chestGranted'], champion_data['championPoints'], champion_data['championPointsSinceLastLevel'], champion_data['championPointsUntilNextLevel'], champion_data['summonerId'], champion_data['tokensEarned'], champion_data['championId'], champion_data['lastPlayTime']))
return summoner_masteries | :param summoner:
:param region:
:return: | RiotGames/API/ChampionMastery.py | summoner_masteries | Timohiho/RiotGames | 2 | python | def summoner_masteries(self, summoner: SummonerAccount, region: str) -> [ChampionMasteries]:
'\n :param summoner:\n :param region:\n :return:\n '
summoner_masteries: [ChampionMasteries] = []
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
for champion_data in data:
summoner_masteries.append(ChampionMasteries(champion_data['championLevel'], champion_data['chestGranted'], champion_data['championPoints'], champion_data['championPointsSinceLastLevel'], champion_data['championPointsUntilNextLevel'], champion_data['summonerId'], champion_data['tokensEarned'], champion_data['championId'], champion_data['lastPlayTime']))
return summoner_masteries | def summoner_masteries(self, summoner: SummonerAccount, region: str) -> [ChampionMasteries]:
'\n :param summoner:\n :param region:\n :return:\n '
summoner_masteries: [ChampionMasteries] = []
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
for champion_data in data:
summoner_masteries.append(ChampionMasteries(champion_data['championLevel'], champion_data['chestGranted'], champion_data['championPoints'], champion_data['championPointsSinceLastLevel'], champion_data['championPointsUntilNextLevel'], champion_data['summonerId'], champion_data['tokensEarned'], champion_data['championId'], champion_data['lastPlayTime']))
return summoner_masteries<|docstring|>:param summoner:
:param region:
:return:<|endoftext|> |
ebac0ef639460c85b0ee40a4c62b0bbe61239842f6d129a2b0a23903a2860eb8 | def champion_masteries(self, summoner: SummonerAccount, champion_id: int, region: str) -> ChampionMasteries:
'\n :param summoner:\n :param champion_id:\n :param region:\n :return:\n '
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, champion_id, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
return ChampionMasteries(data['championLevel'], data['chestGranted'], data['championPoints'], data['championPointsSinceLastLevel'], data['championPointsUntilNextLevel'], data['summonerId'], data['tokensEarned'], data['championId'], data['lastPlayTime']) | :param summoner:
:param champion_id:
:param region:
:return: | RiotGames/API/ChampionMastery.py | champion_masteries | Timohiho/RiotGames | 2 | python | def champion_masteries(self, summoner: SummonerAccount, champion_id: int, region: str) -> ChampionMasteries:
'\n :param summoner:\n :param champion_id:\n :param region:\n :return:\n '
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, champion_id, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
return ChampionMasteries(data['championLevel'], data['chestGranted'], data['championPoints'], data['championPointsSinceLastLevel'], data['championPointsUntilNextLevel'], data['summonerId'], data['tokensEarned'], data['championId'], data['lastPlayTime']) | def champion_masteries(self, summoner: SummonerAccount, champion_id: int, region: str) -> ChampionMasteries:
'\n :param summoner:\n :param champion_id:\n :param region:\n :return:\n '
data: dict = eval(bytes(urllib.request.urlopen(self.__summoner_masteries_url.format(region, summoner.summonerId, champion_id, super()._get_key())).read()).decode().replace('true', 'True').replace('false', 'False'))
return ChampionMasteries(data['championLevel'], data['chestGranted'], data['championPoints'], data['championPointsSinceLastLevel'], data['championPointsUntilNextLevel'], data['summonerId'], data['tokensEarned'], data['championId'], data['lastPlayTime'])<|docstring|>:param summoner:
:param champion_id:
:param region:
:return:<|endoftext|> |
3677d42d9d6c9003d9e66291465ef09495c5b608519c07c8909e5018dec1d7d1 | def scores(self, summoner: SummonerAccount, region: str):
'\n :param summoner:\n :param region:\n :return:\n '
return eval(bytes(urllib.request.urlopen(self.__score_url.format(region, summoner.summonerId, super()._get_key())).read()).decode()) | :param summoner:
:param region:
:return: | RiotGames/API/ChampionMastery.py | scores | Timohiho/RiotGames | 2 | python | def scores(self, summoner: SummonerAccount, region: str):
'\n :param summoner:\n :param region:\n :return:\n '
return eval(bytes(urllib.request.urlopen(self.__score_url.format(region, summoner.summonerId, super()._get_key())).read()).decode()) | def scores(self, summoner: SummonerAccount, region: str):
'\n :param summoner:\n :param region:\n :return:\n '
return eval(bytes(urllib.request.urlopen(self.__score_url.format(region, summoner.summonerId, super()._get_key())).read()).decode())<|docstring|>:param summoner:
:param region:
:return:<|endoftext|> |
0e3dd2e898f449fd1b47d1707668cd45266377e95077b5163ed09c7c419280fe | @staticmethod
def _mul2(a, b):
'\n Calculate __mul__ for matrixes of size 2\n :return: A Mat9 - product of a and b\n '
a11 = a.m[0][0]
a12 = a.m[0][1]
a21 = a.m[1][0]
a22 = a.m[1][1]
b11 = b.m[0][0]
b12 = b.m[0][1]
b21 = b.m[1][0]
b22 = b.m[1][1]
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
return Mat9([[c11, c12], [c21, c22]]) | Calculate __mul__ for matrixes of size 2
:return: A Mat9 - product of a and b | task3_strassen_multiplication.py | _mul2 | leskin-in/mipt-dmalgo | 0 | python | @staticmethod
def _mul2(a, b):
'\n Calculate __mul__ for matrixes of size 2\n :return: A Mat9 - product of a and b\n '
a11 = a.m[0][0]
a12 = a.m[0][1]
a21 = a.m[1][0]
a22 = a.m[1][1]
b11 = b.m[0][0]
b12 = b.m[0][1]
b21 = b.m[1][0]
b22 = b.m[1][1]
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
return Mat9([[c11, c12], [c21, c22]]) | @staticmethod
def _mul2(a, b):
'\n Calculate __mul__ for matrixes of size 2\n :return: A Mat9 - product of a and b\n '
a11 = a.m[0][0]
a12 = a.m[0][1]
a21 = a.m[1][0]
a22 = a.m[1][1]
b11 = b.m[0][0]
b12 = b.m[0][1]
b21 = b.m[1][0]
b22 = b.m[1][1]
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
return Mat9([[c11, c12], [c21, c22]])<|docstring|>Calculate __mul__ for matrixes of size 2
:return: A Mat9 - product of a and b<|endoftext|> |
efbd882c02c71179517d757f85096ac023b0418f15017b22a5bab15516c8a725 | @staticmethod
def _mul(a, b):
'\n Calculate __mul__ using Strassen algorithm\n :return: A Mat9 - product of a and b\n '
l_div = (a.L // 2)
a11 = Mat9([a.m[i][:l_div] for i in range(0, l_div)])
a12 = Mat9([a.m[i][l_div:] for i in range(0, l_div)])
a21 = Mat9([a.m[i][:l_div] for i in range(l_div, a.L)])
a22 = Mat9([a.m[i][l_div:] for i in range(l_div, a.L)])
b11 = Mat9([b.m[i][:l_div] for i in range(0, l_div)])
b12 = Mat9([b.m[i][l_div:] for i in range(0, l_div)])
b21 = Mat9([b.m[i][:l_div] for i in range(l_div, b.L)])
b22 = Mat9([b.m[i][l_div:] for i in range(l_div, b.L)])
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
for i in range(l_div):
c11.m[i].extend(c12.m[i])
c21.m[i].extend(c22.m[i])
c11.m.extend(c21.m)
c11.L = (c11.L * 2)
return c11 | Calculate __mul__ using Strassen algorithm
:return: A Mat9 - product of a and b | task3_strassen_multiplication.py | _mul | leskin-in/mipt-dmalgo | 0 | python | @staticmethod
def _mul(a, b):
'\n Calculate __mul__ using Strassen algorithm\n :return: A Mat9 - product of a and b\n '
l_div = (a.L // 2)
a11 = Mat9([a.m[i][:l_div] for i in range(0, l_div)])
a12 = Mat9([a.m[i][l_div:] for i in range(0, l_div)])
a21 = Mat9([a.m[i][:l_div] for i in range(l_div, a.L)])
a22 = Mat9([a.m[i][l_div:] for i in range(l_div, a.L)])
b11 = Mat9([b.m[i][:l_div] for i in range(0, l_div)])
b12 = Mat9([b.m[i][l_div:] for i in range(0, l_div)])
b21 = Mat9([b.m[i][:l_div] for i in range(l_div, b.L)])
b22 = Mat9([b.m[i][l_div:] for i in range(l_div, b.L)])
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
for i in range(l_div):
c11.m[i].extend(c12.m[i])
c21.m[i].extend(c22.m[i])
c11.m.extend(c21.m)
c11.L = (c11.L * 2)
return c11 | @staticmethod
def _mul(a, b):
'\n Calculate __mul__ using Strassen algorithm\n :return: A Mat9 - product of a and b\n '
l_div = (a.L // 2)
a11 = Mat9([a.m[i][:l_div] for i in range(0, l_div)])
a12 = Mat9([a.m[i][l_div:] for i in range(0, l_div)])
a21 = Mat9([a.m[i][:l_div] for i in range(l_div, a.L)])
a22 = Mat9([a.m[i][l_div:] for i in range(l_div, a.L)])
b11 = Mat9([b.m[i][:l_div] for i in range(0, l_div)])
b12 = Mat9([b.m[i][l_div:] for i in range(0, l_div)])
b21 = Mat9([b.m[i][:l_div] for i in range(l_div, b.L)])
b22 = Mat9([b.m[i][l_div:] for i in range(l_div, b.L)])
m1 = ((a11 + a22) * (b11 + b22))
m2 = ((a21 + a22) * b11)
m3 = (a11 * (b12 - b22))
m4 = (a22 * (b21 - b11))
m5 = ((a11 + a12) * b22)
m6 = ((a21 - a11) * (b11 + b12))
m7 = ((a12 - a22) * (b21 + b22))
c11 = (((m1 + m4) - m5) + m7)
c12 = (m3 + m5)
c21 = (m2 + m4)
c22 = (((m1 - m2) + m3) + m6)
for i in range(l_div):
c11.m[i].extend(c12.m[i])
c21.m[i].extend(c22.m[i])
c11.m.extend(c21.m)
c11.L = (c11.L * 2)
return c11<|docstring|>Calculate __mul__ using Strassen algorithm
:return: A Mat9 - product of a and b<|endoftext|> |
889cd72f718fc4da63def19e8786399153b054cc46dce2c122c17fac8cbf6513 | def generateOneTestHeader(self, incomeLevel, testExplain):
'\n this used to be complex enough to warrant its own method...\n '
header = (('<h2>' + testExplain) + '</h2>\n')
return header | this used to be complex enough to warrant its own method... | generateData.py | generateOneTestHeader | cuthbertLab/collegeCosts | 2 | python | def generateOneTestHeader(self, incomeLevel, testExplain):
'\n \n '
header = (('<h2>' + testExplain) + '</h2>\n')
return header | def generateOneTestHeader(self, incomeLevel, testExplain):
'\n \n '
header = (('<h2>' + testExplain) + '</h2>\n')
return header<|docstring|>this used to be complex enough to warrant its own method...<|endoftext|> |
da1f881ece5ecc3d322ba544ebe5ac617a428726094cedc42a4eb5b7a15ad2c1 | def disable_job_watcher():
'Disables the job watcher.\n '
_JOB_WATCHER.stop_viewer() | Disables the job watcher. | qiskit/tools/jupyter/__init__.py | disable_job_watcher | chowington/qiskit-terra | 0 | python | def disable_job_watcher():
'\n '
_JOB_WATCHER.stop_viewer() | def disable_job_watcher():
'\n '
_JOB_WATCHER.stop_viewer()<|docstring|>Disables the job watcher.<|endoftext|> |
da9f50c6fde978e149e1305f368e1912f70d0c9045b971891acc5229d96d59d2 | def enable_job_watcher():
'Enables the job watcher.\n '
_JOB_WATCHER.start_viewer() | Enables the job watcher. | qiskit/tools/jupyter/__init__.py | enable_job_watcher | chowington/qiskit-terra | 0 | python | def enable_job_watcher():
'\n '
_JOB_WATCHER.start_viewer() | def enable_job_watcher():
'\n '
_JOB_WATCHER.start_viewer()<|docstring|>Enables the job watcher.<|endoftext|> |
b36e19d293f95b291ad314f7f1d578c9343a3d6922c8b34d0a84deb742379610 | def save_pic(form_picture):
'\n function that saves the picture uploaded, gives it a rondom hex number and also resizes it\n '
random_hex = secrets.token_hex(8)
(_, f_ext) = os.path.splitext(form_picture.filename)
picture_fn = (random_hex + f_ext)
pic_path = os.path.join(current_app.root_path, 'static/images', picture_fn)
output_size = (125, 125)
form_picture.save(pic_path)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(pic_path)
return picture_fn | function that saves the picture uploaded, gives it a rondom hex number and also resizes it | blog/users/utils.py | save_pic | DerrickOdhiambo/Personal-Blog | 0 | python | def save_pic(form_picture):
'\n \n '
random_hex = secrets.token_hex(8)
(_, f_ext) = os.path.splitext(form_picture.filename)
picture_fn = (random_hex + f_ext)
pic_path = os.path.join(current_app.root_path, 'static/images', picture_fn)
output_size = (125, 125)
form_picture.save(pic_path)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(pic_path)
return picture_fn | def save_pic(form_picture):
'\n \n '
random_hex = secrets.token_hex(8)
(_, f_ext) = os.path.splitext(form_picture.filename)
picture_fn = (random_hex + f_ext)
pic_path = os.path.join(current_app.root_path, 'static/images', picture_fn)
output_size = (125, 125)
form_picture.save(pic_path)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(pic_path)
return picture_fn<|docstring|>function that saves the picture uploaded, gives it a rondom hex number and also resizes it<|endoftext|> |
6ce9ef724f00cadb2b84293d513fd55555f08b8c829c81e9a1383b8b8baeb987 | @torch.no_grad()
def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
grad_values = grad._values()
size = grad.size()
x = p.data[grad_indices[0]]
grad_values = (grad_values + (x * group['weight_decay']))
def make_sparse(values):
constructor = grad.new
if ((grad_indices.dim() == 0) or (values.dim() == 0)):
return constructor().resize_as_(grad)
return constructor(grad_indices, values, size)
state['sum'].add_(make_sparse(grad_values.pow(2)))
std = state['sum'].sparse_mask(grad)
std_values = std._values().sqrt_().add_(group['eps'])
x_n = F.relu((x - ((clr * grad_values) / std_values)))
x_u = (x_n - x)
p.add_(make_sparse(x_u))
else:
x = p.data
grad = (grad + (x * group['weight_decay']))
state['sum'].addcmul_(grad, grad, value=1)
std = state['sum'].sqrt().add_(group['eps'])
x_n = F.relu((x - ((clr * grad) / std)))
x_u = (x_n - x)
p.add_(x_u)
return loss | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. | Python version/optim.py | step | harrycrow/RDM | 0 | python | @torch.no_grad()
def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
grad_values = grad._values()
size = grad.size()
x = p.data[grad_indices[0]]
grad_values = (grad_values + (x * group['weight_decay']))
def make_sparse(values):
constructor = grad.new
if ((grad_indices.dim() == 0) or (values.dim() == 0)):
return constructor().resize_as_(grad)
return constructor(grad_indices, values, size)
state['sum'].add_(make_sparse(grad_values.pow(2)))
std = state['sum'].sparse_mask(grad)
std_values = std._values().sqrt_().add_(group['eps'])
x_n = F.relu((x - ((clr * grad_values) / std_values)))
x_u = (x_n - x)
p.add_(make_sparse(x_u))
else:
x = p.data
grad = (grad + (x * group['weight_decay']))
state['sum'].addcmul_(grad, grad, value=1)
std = state['sum'].sqrt().add_(group['eps'])
x_n = F.relu((x - ((clr * grad) / std)))
x_u = (x_n - x)
p.add_(x_u)
return loss | @torch.no_grad()
def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
grad_values = grad._values()
size = grad.size()
x = p.data[grad_indices[0]]
grad_values = (grad_values + (x * group['weight_decay']))
def make_sparse(values):
constructor = grad.new
if ((grad_indices.dim() == 0) or (values.dim() == 0)):
return constructor().resize_as_(grad)
return constructor(grad_indices, values, size)
state['sum'].add_(make_sparse(grad_values.pow(2)))
std = state['sum'].sparse_mask(grad)
std_values = std._values().sqrt_().add_(group['eps'])
x_n = F.relu((x - ((clr * grad_values) / std_values)))
x_u = (x_n - x)
p.add_(make_sparse(x_u))
else:
x = p.data
grad = (grad + (x * group['weight_decay']))
state['sum'].addcmul_(grad, grad, value=1)
std = state['sum'].sqrt().add_(group['eps'])
x_n = F.relu((x - ((clr * grad) / std)))
x_u = (x_n - x)
p.add_(x_u)
return loss<|docstring|>Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.<|endoftext|> |
c545441f22b5f39d460eb81d1ae4f480d8b8ca0d39be7a4b5581b8fc36f8d030 | def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
dim = group['dim']
beta = group['beta']
eye = group['eye']
eps = group['eps']
lap_reg = group['lap_reg']
square_avg = state['square_avg']
with torch.no_grad():
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
g = grad._values().view((- 1), dim, dim)
x = p.data[grad_indices[0]].view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.matmul(torch.matmul(x, torch.transpose(g, 1, 2)), x))
sa = square_avg[grad_indices[0]].view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(grad.new(grad_indices, x_u.reshape((- 1), (dim * dim)), grad.size()))
square_avg.add_(grad.new(grad_indices, sa_u.view((- 1), 1), square_avg.size()))
else:
g = grad.view((- 1), dim, dim)
x = p.data.view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.bmm(torch.bmm(x, torch.transpose(g, 1, 2)), x))
sa = square_avg.view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(x_u.reshape((- 1), (dim * dim)))
square_avg.add_(sa_u.view((- 1), 1))
return loss | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. | Python version/optim.py | step | harrycrow/RDM | 0 | python | def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
dim = group['dim']
beta = group['beta']
eye = group['eye']
eps = group['eps']
lap_reg = group['lap_reg']
square_avg = state['square_avg']
with torch.no_grad():
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
g = grad._values().view((- 1), dim, dim)
x = p.data[grad_indices[0]].view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.matmul(torch.matmul(x, torch.transpose(g, 1, 2)), x))
sa = square_avg[grad_indices[0]].view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(grad.new(grad_indices, x_u.reshape((- 1), (dim * dim)), grad.size()))
square_avg.add_(grad.new(grad_indices, sa_u.view((- 1), 1), square_avg.size()))
else:
g = grad.view((- 1), dim, dim)
x = p.data.view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.bmm(torch.bmm(x, torch.transpose(g, 1, 2)), x))
sa = square_avg.view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(x_u.reshape((- 1), (dim * dim)))
square_avg.add_(sa_u.view((- 1), 1))
return loss | def step(self, closure=None):
'Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n '
loss = None
if (closure is not None):
loss = closure()
for group in self.param_groups:
for p in group['params']:
if (p.grad is None):
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
clr = (group['lr'] / (1 + ((state['step'] - 1) * group['lr_decay'])))
dim = group['dim']
beta = group['beta']
eye = group['eye']
eps = group['eps']
lap_reg = group['lap_reg']
square_avg = state['square_avg']
with torch.no_grad():
if grad.is_sparse:
grad = grad.coalesce()
grad_indices = grad._indices()
g = grad._values().view((- 1), dim, dim)
x = p.data[grad_indices[0]].view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.matmul(torch.matmul(x, torch.transpose(g, 1, 2)), x))
sa = square_avg[grad_indices[0]].view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(grad.new(grad_indices, x_u.reshape((- 1), (dim * dim)), grad.size()))
square_avg.add_(grad.new(grad_indices, sa_u.view((- 1), 1), square_avg.size()))
else:
g = grad.view((- 1), dim, dim)
x = p.data.view((- 1), dim, dim)
g = (g + (lap_reg * torch.sign((x - eye))))
g = (g - torch.bmm(torch.bmm(x, torch.transpose(g, 1, 2)), x))
sa = square_avg.view((- 1))
sa_u = g.pow(2).sum(dim=(1, 2))
sa = sa.add_(sa_u).sqrt_().add_(eps).view((- 1), 1, 1)
x_n = _qr_retraction((x - ((clr * g) / sa)))
x_u = (x_n - x)
p.data.add_(x_u.reshape((- 1), (dim * dim)))
square_avg.add_(sa_u.view((- 1), 1))
return loss<|docstring|>Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.<|endoftext|> |
c72ce156d5e91250e287436b78ba294ba8c964c7d09c6070a376192d935b2958 | def test_direct_dep(self):
'Test that we can import the module directly.'
from test.python_rules import data_dep
self.assertEqual(42, data_dep.the_answer()) | Test that we can import the module directly. | test/python_rules/data_dep_test.py | test_direct_dep | chronicc/please | 1,992 | python | def test_direct_dep(self):
from test.python_rules import data_dep
self.assertEqual(42, data_dep.the_answer()) | def test_direct_dep(self):
from test.python_rules import data_dep
self.assertEqual(42, data_dep.the_answer())<|docstring|>Test that we can import the module directly.<|endoftext|> |
2820f3d0f9a58a56e46263c30dd945395b0596a083f6ecdd054cd12da6e61c26 | def test_data_dep(self):
'Test that we can also invoke the .pex directly as a data dependency.'
output = subprocess.check_output(['test/python_rules/data_dep.pex'])
self.assertEqual('42', output.strip().decode('utf-8')) | Test that we can also invoke the .pex directly as a data dependency. | test/python_rules/data_dep_test.py | test_data_dep | chronicc/please | 1,992 | python | def test_data_dep(self):
output = subprocess.check_output(['test/python_rules/data_dep.pex'])
self.assertEqual('42', output.strip().decode('utf-8')) | def test_data_dep(self):
output = subprocess.check_output(['test/python_rules/data_dep.pex'])
self.assertEqual('42', output.strip().decode('utf-8'))<|docstring|>Test that we can also invoke the .pex directly as a data dependency.<|endoftext|> |
8bd788c23fb82296ec2db050b5d9a7b4d3ba00bf2d2a26d0f51b8efa71a0efcf | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text, module_file: Text, serving_model_dir: Text, metadata_path: Text, beam_pipeline_args: List[Text]) -> pipeline.Pipeline:
'Implements an example pipeline with the sampling component witin TFX.'
example_gen = CsvExampleGen(input_base=data_root)
statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
schema_gen = SchemaGen(statistics=statistics_gen.outputs['statistics'], infer_feature_shape=False)
example_validator = ExampleValidator(statistics=statistics_gen.outputs['statistics'], schema=schema_gen.outputs['schema'])
sample = Sampler(input_data=example_gen.outputs['examples'], splits=['train'], label='Class', shards=10)
transform = Transform(examples=sample.outputs['output_data'], schema=schema_gen.outputs['schema'], module_file=module_file)
latest_model_resolver = resolver.Resolver(strategy_class=latest_artifacts_resolver.LatestArtifactsResolver, latest_model=Channel(type=Model)).with_id('latest_model_resolver')
trainer = Trainer(module_file=module_file, custom_executor_spec=executor_spec.ExecutorClassSpec(Executor), transformed_examples=transform.outputs['transformed_examples'], schema=schema_gen.outputs['schema'], base_model=latest_model_resolver.outputs['latest_model'], transform_graph=transform.outputs['transform_graph'], train_args=trainer_pb2.TrainArgs(num_steps=10000), eval_args=trainer_pb2.EvalArgs(num_steps=5000))
model_resolver = resolver.Resolver(strategy_class=latest_blessed_model_resolver.LatestBlessedModelResolver, model=Channel(type=Model), model_blessing=Channel(type=ModelBlessing)).with_id('latest_blessed_model_resolver')
eval_config = tfma.EvalConfig(model_specs=[tfma.ModelSpec(signature_name='eval')], slicing_specs=[tfma.SlicingSpec(), tfma.SlicingSpec(feature_keys=['trip_start_hour'])], metrics_specs=[tfma.MetricsSpec(thresholds={'accuracy': tfma.config.MetricThreshold(value_threshold=tfma.GenericValueThreshold(lower_bound={'value': 0.6}), change_threshold=tfma.GenericChangeThreshold(direction=tfma.MetricDirection.HIGHER_IS_BETTER, absolute={'value': (- 1e-10)}))})])
evaluator = Evaluator(examples=example_gen.outputs['examples'], model=trainer.outputs['model'], baseline_model=model_resolver.outputs['model'], eval_config=eval_config)
pusher = Pusher(model=trainer.outputs['model'], model_blessing=evaluator.outputs['blessing'], push_destination=pusher_pb2.PushDestination(filesystem=pusher_pb2.PushDestination.Filesystem(base_directory=serving_model_dir)))
return pipeline.Pipeline(pipeline_name=pipeline_name, pipeline_root=pipeline_root, components=[example_gen, statistics_gen, schema_gen, example_validator, sample, transform, latest_model_resolver, trainer, model_resolver, evaluator, pusher], enable_cache=False, metadata_connection_config=metadata.sqlite_metadata_connection_config(metadata_path), beam_pipeline_args=beam_pipeline_args) | Implements an example pipeline with the sampling component witin TFX. | tfx_addons/sampling/example/sampler_pipeline_local.py | _create_pipeline | vulkomilev/tfx-addons | 70 | python | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text, module_file: Text, serving_model_dir: Text, metadata_path: Text, beam_pipeline_args: List[Text]) -> pipeline.Pipeline:
example_gen = CsvExampleGen(input_base=data_root)
statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
schema_gen = SchemaGen(statistics=statistics_gen.outputs['statistics'], infer_feature_shape=False)
example_validator = ExampleValidator(statistics=statistics_gen.outputs['statistics'], schema=schema_gen.outputs['schema'])
sample = Sampler(input_data=example_gen.outputs['examples'], splits=['train'], label='Class', shards=10)
transform = Transform(examples=sample.outputs['output_data'], schema=schema_gen.outputs['schema'], module_file=module_file)
latest_model_resolver = resolver.Resolver(strategy_class=latest_artifacts_resolver.LatestArtifactsResolver, latest_model=Channel(type=Model)).with_id('latest_model_resolver')
trainer = Trainer(module_file=module_file, custom_executor_spec=executor_spec.ExecutorClassSpec(Executor), transformed_examples=transform.outputs['transformed_examples'], schema=schema_gen.outputs['schema'], base_model=latest_model_resolver.outputs['latest_model'], transform_graph=transform.outputs['transform_graph'], train_args=trainer_pb2.TrainArgs(num_steps=10000), eval_args=trainer_pb2.EvalArgs(num_steps=5000))
model_resolver = resolver.Resolver(strategy_class=latest_blessed_model_resolver.LatestBlessedModelResolver, model=Channel(type=Model), model_blessing=Channel(type=ModelBlessing)).with_id('latest_blessed_model_resolver')
eval_config = tfma.EvalConfig(model_specs=[tfma.ModelSpec(signature_name='eval')], slicing_specs=[tfma.SlicingSpec(), tfma.SlicingSpec(feature_keys=['trip_start_hour'])], metrics_specs=[tfma.MetricsSpec(thresholds={'accuracy': tfma.config.MetricThreshold(value_threshold=tfma.GenericValueThreshold(lower_bound={'value': 0.6}), change_threshold=tfma.GenericChangeThreshold(direction=tfma.MetricDirection.HIGHER_IS_BETTER, absolute={'value': (- 1e-10)}))})])
evaluator = Evaluator(examples=example_gen.outputs['examples'], model=trainer.outputs['model'], baseline_model=model_resolver.outputs['model'], eval_config=eval_config)
pusher = Pusher(model=trainer.outputs['model'], model_blessing=evaluator.outputs['blessing'], push_destination=pusher_pb2.PushDestination(filesystem=pusher_pb2.PushDestination.Filesystem(base_directory=serving_model_dir)))
return pipeline.Pipeline(pipeline_name=pipeline_name, pipeline_root=pipeline_root, components=[example_gen, statistics_gen, schema_gen, example_validator, sample, transform, latest_model_resolver, trainer, model_resolver, evaluator, pusher], enable_cache=False, metadata_connection_config=metadata.sqlite_metadata_connection_config(metadata_path), beam_pipeline_args=beam_pipeline_args) | def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text, module_file: Text, serving_model_dir: Text, metadata_path: Text, beam_pipeline_args: List[Text]) -> pipeline.Pipeline:
example_gen = CsvExampleGen(input_base=data_root)
statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
schema_gen = SchemaGen(statistics=statistics_gen.outputs['statistics'], infer_feature_shape=False)
example_validator = ExampleValidator(statistics=statistics_gen.outputs['statistics'], schema=schema_gen.outputs['schema'])
sample = Sampler(input_data=example_gen.outputs['examples'], splits=['train'], label='Class', shards=10)
transform = Transform(examples=sample.outputs['output_data'], schema=schema_gen.outputs['schema'], module_file=module_file)
latest_model_resolver = resolver.Resolver(strategy_class=latest_artifacts_resolver.LatestArtifactsResolver, latest_model=Channel(type=Model)).with_id('latest_model_resolver')
trainer = Trainer(module_file=module_file, custom_executor_spec=executor_spec.ExecutorClassSpec(Executor), transformed_examples=transform.outputs['transformed_examples'], schema=schema_gen.outputs['schema'], base_model=latest_model_resolver.outputs['latest_model'], transform_graph=transform.outputs['transform_graph'], train_args=trainer_pb2.TrainArgs(num_steps=10000), eval_args=trainer_pb2.EvalArgs(num_steps=5000))
model_resolver = resolver.Resolver(strategy_class=latest_blessed_model_resolver.LatestBlessedModelResolver, model=Channel(type=Model), model_blessing=Channel(type=ModelBlessing)).with_id('latest_blessed_model_resolver')
eval_config = tfma.EvalConfig(model_specs=[tfma.ModelSpec(signature_name='eval')], slicing_specs=[tfma.SlicingSpec(), tfma.SlicingSpec(feature_keys=['trip_start_hour'])], metrics_specs=[tfma.MetricsSpec(thresholds={'accuracy': tfma.config.MetricThreshold(value_threshold=tfma.GenericValueThreshold(lower_bound={'value': 0.6}), change_threshold=tfma.GenericChangeThreshold(direction=tfma.MetricDirection.HIGHER_IS_BETTER, absolute={'value': (- 1e-10)}))})])
evaluator = Evaluator(examples=example_gen.outputs['examples'], model=trainer.outputs['model'], baseline_model=model_resolver.outputs['model'], eval_config=eval_config)
pusher = Pusher(model=trainer.outputs['model'], model_blessing=evaluator.outputs['blessing'], push_destination=pusher_pb2.PushDestination(filesystem=pusher_pb2.PushDestination.Filesystem(base_directory=serving_model_dir)))
return pipeline.Pipeline(pipeline_name=pipeline_name, pipeline_root=pipeline_root, components=[example_gen, statistics_gen, schema_gen, example_validator, sample, transform, latest_model_resolver, trainer, model_resolver, evaluator, pusher], enable_cache=False, metadata_connection_config=metadata.sqlite_metadata_connection_config(metadata_path), beam_pipeline_args=beam_pipeline_args)<|docstring|>Implements an example pipeline with the sampling component witin TFX.<|endoftext|> |
828f65e7bb8fb09801832425dc94fed67a6b735f581aed2a57073cd4d32240d6 | @cupy.fuse
def func_wo_paren(x):
'Fuse without parentheses'
return (x + x) | Fuse without parentheses | tests/cupy_tests/core_tests/fusion_tests/test_misc.py | func_wo_paren | saswatpp/cupy | 6,180 | python | @cupy.fuse
def func_wo_paren(x):
return (x + x) | @cupy.fuse
def func_wo_paren(x):
return (x + x)<|docstring|>Fuse without parentheses<|endoftext|> |
2f5ec322b3583367fcf4d998b00e37b3377648576157b01a982fed74dbff45d6 | @cupy.fuse()
def func_w_paren(x):
'Fuse with parentheses'
return (x + x) | Fuse with parentheses | tests/cupy_tests/core_tests/fusion_tests/test_misc.py | func_w_paren | saswatpp/cupy | 6,180 | python | @cupy.fuse()
def func_w_paren(x):
return (x + x) | @cupy.fuse()
def func_w_paren(x):
return (x + x)<|docstring|>Fuse with parentheses<|endoftext|> |
3f6d96d76f09e78c6d60834bc8b52c8af44007385c8887ef3d792d706c07ce0d | def init():
'Return True if the plugin has loaded successfully.'
g.registerHandler('select1', onSelect)
g.plugin_signon(__name__)
return True | Return True if the plugin has loaded successfully. | leo/plugins/at_folder.py | init | thomasbuttler/leo-editor | 1,550 | python | def init():
g.registerHandler('select1', onSelect)
g.plugin_signon(__name__)
return True | def init():
g.registerHandler('select1', onSelect)
g.plugin_signon(__name__)
return True<|docstring|>Return True if the plugin has loaded successfully.<|endoftext|> |
8fc8c3dfa028cd6cfc596bec0062672cab6c5249f3a9cac77536772221394e8e | def timediff_from_now_for_where(oper='-', units=None):
"\n timediff_from_now_for_where takes in variables and returns string of representation of the difference\n between now and the units operator and amount passed in\n\n :param oper: operator (minus or plus), defaults to '-'\n :type oper: str, optional\n :param units: Expects dictionary, for ex: {'weeks': 12}, defaults to None\n :type units: dictionary, optional\n :return: representation of date figured out to use in where statement\n :rtype: str\n "
units = ({'days': 1} if (units is None) else units)
now = datetime.now(tz=tz.tzlocal())
if (oper == '-'):
new_date = str((now - timedelta(**units)))
else:
new_date = str((now + timedelta(**units)))
return new_date | timediff_from_now_for_where takes in variables and returns string of representation of the difference
between now and the units operator and amount passed in
:param oper: operator (minus or plus), defaults to '-'
:type oper: str, optional
:param units: Expects dictionary, for ex: {'weeks': 12}, defaults to None
:type units: dictionary, optional
:return: representation of date figured out to use in where statement
:rtype: str | utilities/date_time.py | timediff_from_now_for_where | lizschley/number_six | 1 | python | def timediff_from_now_for_where(oper='-', units=None):
"\n timediff_from_now_for_where takes in variables and returns string of representation of the difference\n between now and the units operator and amount passed in\n\n :param oper: operator (minus or plus), defaults to '-'\n :type oper: str, optional\n :param units: Expects dictionary, for ex: {'weeks': 12}, defaults to None\n :type units: dictionary, optional\n :return: representation of date figured out to use in where statement\n :rtype: str\n "
units = ({'days': 1} if (units is None) else units)
now = datetime.now(tz=tz.tzlocal())
if (oper == '-'):
new_date = str((now - timedelta(**units)))
else:
new_date = str((now + timedelta(**units)))
return new_date | def timediff_from_now_for_where(oper='-', units=None):
"\n timediff_from_now_for_where takes in variables and returns string of representation of the difference\n between now and the units operator and amount passed in\n\n :param oper: operator (minus or plus), defaults to '-'\n :type oper: str, optional\n :param units: Expects dictionary, for ex: {'weeks': 12}, defaults to None\n :type units: dictionary, optional\n :return: representation of date figured out to use in where statement\n :rtype: str\n "
units = ({'days': 1} if (units is None) else units)
now = datetime.now(tz=tz.tzlocal())
if (oper == '-'):
new_date = str((now - timedelta(**units)))
else:
new_date = str((now + timedelta(**units)))
return new_date<|docstring|>timediff_from_now_for_where takes in variables and returns string of representation of the difference
between now and the units operator and amount passed in
:param oper: operator (minus or plus), defaults to '-'
:type oper: str, optional
:param units: Expects dictionary, for ex: {'weeks': 12}, defaults to None
:type units: dictionary, optional
:return: representation of date figured out to use in where statement
:rtype: str<|endoftext|> |
00f08420a88f51ab9f63b27f1bf03bebd68667a390dac3f6e5e2331bca082bbf | def current_timestamp_with_timezone():
'\n current_timestamp_with_timezone returns the current time in the format to update a\n postgres timestamp with time zone field\n\n :return: current time with time zone\n :rtype: str\n '
now = datetime.now(tz=tz.tzlocal())
return str(now) | current_timestamp_with_timezone returns the current time in the format to update a
postgres timestamp with time zone field
:return: current time with time zone
:rtype: str | utilities/date_time.py | current_timestamp_with_timezone | lizschley/number_six | 1 | python | def current_timestamp_with_timezone():
'\n current_timestamp_with_timezone returns the current time in the format to update a\n postgres timestamp with time zone field\n\n :return: current time with time zone\n :rtype: str\n '
now = datetime.now(tz=tz.tzlocal())
return str(now) | def current_timestamp_with_timezone():
'\n current_timestamp_with_timezone returns the current time in the format to update a\n postgres timestamp with time zone field\n\n :return: current time with time zone\n :rtype: str\n '
now = datetime.now(tz=tz.tzlocal())
return str(now)<|docstring|>current_timestamp_with_timezone returns the current time in the format to update a
postgres timestamp with time zone field
:return: current time with time zone
:rtype: str<|endoftext|> |
3813effbab99b91b908a69f1e626b43d57da4163f83157250597508565c2c32c | def postgres_friendly_datetime(datetime_obj):
'\n postgres_friendly_datetime takes a datetime object and writes it to a string\n in a format that can be used to update postgres\n :param datetime_obj: passed in datetime obj\n :type datetime_obj: datetime.datetime\n :return: string representaion of the object that postgres understands\n :rtype: str\n '
string_dt = str(datetime_obj)
temp = string_dt.split('.')
return (temp[0] + '+00') | postgres_friendly_datetime takes a datetime object and writes it to a string
in a format that can be used to update postgres
:param datetime_obj: passed in datetime obj
:type datetime_obj: datetime.datetime
:return: string representaion of the object that postgres understands
:rtype: str | utilities/date_time.py | postgres_friendly_datetime | lizschley/number_six | 1 | python | def postgres_friendly_datetime(datetime_obj):
'\n postgres_friendly_datetime takes a datetime object and writes it to a string\n in a format that can be used to update postgres\n :param datetime_obj: passed in datetime obj\n :type datetime_obj: datetime.datetime\n :return: string representaion of the object that postgres understands\n :rtype: str\n '
string_dt = str(datetime_obj)
temp = string_dt.split('.')
return (temp[0] + '+00') | def postgres_friendly_datetime(datetime_obj):
'\n postgres_friendly_datetime takes a datetime object and writes it to a string\n in a format that can be used to update postgres\n :param datetime_obj: passed in datetime obj\n :type datetime_obj: datetime.datetime\n :return: string representaion of the object that postgres understands\n :rtype: str\n '
string_dt = str(datetime_obj)
temp = string_dt.split('.')
return (temp[0] + '+00')<|docstring|>postgres_friendly_datetime takes a datetime object and writes it to a string
in a format that can be used to update postgres
:param datetime_obj: passed in datetime obj
:type datetime_obj: datetime.datetime
:return: string representaion of the object that postgres understands
:rtype: str<|endoftext|> |
e7523af29059266d086180fb304c8b251eb963527b2dc97e45073bfb4aec2902 | def get_current_epoch_date():
'\n get_current_epoch_date returns current date in seconds from 1/1/1970 to use for versioning on S3\n\n :return: epoch date in seconds\n :rtype: int\n '
epoch = int(datetime.now().timestamp())
return epoch | get_current_epoch_date returns current date in seconds from 1/1/1970 to use for versioning on S3
:return: epoch date in seconds
:rtype: int | utilities/date_time.py | get_current_epoch_date | lizschley/number_six | 1 | python | def get_current_epoch_date():
'\n get_current_epoch_date returns current date in seconds from 1/1/1970 to use for versioning on S3\n\n :return: epoch date in seconds\n :rtype: int\n '
epoch = int(datetime.now().timestamp())
return epoch | def get_current_epoch_date():
'\n get_current_epoch_date returns current date in seconds from 1/1/1970 to use for versioning on S3\n\n :return: epoch date in seconds\n :rtype: int\n '
epoch = int(datetime.now().timestamp())
return epoch<|docstring|>get_current_epoch_date returns current date in seconds from 1/1/1970 to use for versioning on S3
:return: epoch date in seconds
:rtype: int<|endoftext|> |
289a99123261e177525bce7cec5c09de0e7bef306d31a497f9c585f974e5c54f | def join():
'\n\tBlocks the current thread until the user interface has stopped.\n\t'
pass | Blocks the current thread until the user interface has stopped. | plugins/userinterface/automatic/automatic.py | join | Ghostkeeper/Luna | 0 | python | def join():
'\n\t\n\t'
pass | def join():
'\n\t\n\t'
pass<|docstring|>Blocks the current thread until the user interface has stopped.<|endoftext|> |
9be859c804658243338623b4986e4f9dc5c8dd11cb8c74c470ed7f96c8b7ec98 | def start():
'\n\tStarts the user interface.\n\n\tFor this automatic user interface, this runs the entire program automatically.\n\t'
Automatic.instance = Automatic()
Automatic.instance.start() | Starts the user interface.
For this automatic user interface, this runs the entire program automatically. | plugins/userinterface/automatic/automatic.py | start | Ghostkeeper/Luna | 0 | python | def start():
'\n\tStarts the user interface.\n\n\tFor this automatic user interface, this runs the entire program automatically.\n\t'
Automatic.instance = Automatic()
Automatic.instance.start() | def start():
'\n\tStarts the user interface.\n\n\tFor this automatic user interface, this runs the entire program automatically.\n\t'
Automatic.instance = Automatic()
Automatic.instance.start()<|docstring|>Starts the user interface.
For this automatic user interface, this runs the entire program automatically.<|endoftext|> |
8c798ee3645001dbec90b907ee918ce978efaaa2c50991f45c1f69121edef0c3 | def stop():
'\n\tStops the user interface.\n\t'
pass | Stops the user interface. | plugins/userinterface/automatic/automatic.py | stop | Ghostkeeper/Luna | 0 | python | def stop():
'\n\t\n\t'
pass | def stop():
'\n\t\n\t'
pass<|docstring|>Stops the user interface.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.