index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
47,701 | dfana01/pbx-dashboard | refs/heads/master | /run.py | from app import create_app, sk
if __name__ == '__main__':
app = create_app()
sk.run(app, debug=False, host="0.0.0.0", port=8080)
| {"/app/__init__.py": ["/app/extensions.py"], "/run.py": ["/app/__init__.py"]} |
47,712 | Fati3521/Mpredicve | refs/heads/main | /fonction.py | import pandas as pd
#from tensorflow.keras.utils import to_categorical
#from keras.models import load_model
import seaborn as sns
from scipy.stats import iqr
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from os.path import join
from os import listdir
import os
from sklearn.model_selection import train_test_split
from scipy.signal import welch
from scipy.fftpack import fft
from matplotlib.collections import LineCollection
#import tensorflow as tf
#from tensorflow import keras
from pylab import rcParams
#from fonction import *
from scipy import stats
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
"""Plot results of the detect_peaks function, see its help."""
try:
import matplotlib.pyplot as plt
except ImportError:
print('matplotlib is not available.')
else:
if ax is None:
_, ax = plt.subplots(1, 1, figsize=(8, 4))
no_ax = True
else:
no_ax = False
ax.plot(x, 'b', lw=1)
if ind.size:
label = 'valley' if valley else 'peak'
label = label + 's' if ind.size > 1 else label
ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
label='%d %s' % (ind.size, label))
ax.legend(loc='best', framealpha=.5, numpoints=1)
ax.set_xlim(-.02*x.size, x.size*1.02-1)
ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
yrange = ymax - ymin if ymax > ymin else 1
ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
ax.set_xlabel('Data #', fontsize=14)
ax.set_ylabel('Amplitude', fontsize=14)
if no_ax:
plt.show()
def create_dataset(X, y, time_steps=1, step=1):
Xs, ys = [], []
for i in range(0, len(X) - time_steps, step):
v = X.iloc[i:(i + time_steps)].values
labels = y.iloc[i: i + time_steps]
Xs.append(v)
ys.append(stats.mode(labels)[0][0])
return np.array(Xs), np.array(ys).reshape(-1, 1)
def extrac_features(data):
liste=[]
i=data.index.min()
while i <= data.index.max()-200:
liste1=[]
columns_names=[]
liste2=[]
for j in data.columns:
liste2.append(np.mean(data.loc[i:i+200][j]))
liste2.append(np.std(data.loc[i:i+200][j]))
liste2.append(np.median(data.loc[i:i+200][j]))
liste2.append(min(data.loc[i:i+200][j]))
#liste2.append(max(data.loc[i:i+200][j]))
liste2.append(np.var(data.loc[i:i+200][j]))
liste2.append(iqr(data.loc[i:i+200][j]))
liste2.append(max(data.loc[i:i+200][j])-min(data.loc[i:i+200][j]))
#liste2.append(np.sma(data.loc[i:i+200][j]))
#liste2.append(np.energy(data.loc[i:i+200][j]))
#liste2.append(np.iqr(data.loc[i:i+200][j]))
#print(data.loc[i:200][j])
columns_names.append("mean"+str(j))
columns_names.append("std"+str(j))
columns_names.append("mad"+str(j))
columns_names.append("min"+str(j))
#columns_names.append("max"+str(j))
columns_names.append("var"+str(j))
columns_names.append("iqr"+str(j))
columns_names.append("ecart"+str(j))
#print(len (columns_names))
liste1.append(liste2)
df = pd.DataFrame(liste1,columns = columns_names)
liste.append(df)
#print(liste1)
#columns_names.append("sma"+str(j))
#columns_names.append("energy"+str(j))
#columns_names.append("iqr"+str(j))
i=i+200
data_final= pd.concat(liste,ignore_index=True)
return data_final
def feat(data):
data_final=[]
for i in set(data['angle']):
for j in set(data['obs']):
data1=data[(data['angle']==i) & (data['obs']==j)]
data2i=extrac_features(data1[['acc_x','acc_y']])
data2i["defaut"]=data1["defaut"].tolist()[0]
#data2i["numero ouverture"]=data1["numero ouverture"].tolist()[0]
data_final.append(data2i)
data22=pd.concat(data_final, ignore_index=True)
return data22
def create_dataset_kmean(X, y,angle, obs, time_steps=1, step=1):
Xs, ys, Angle, Obs = [], [], [], []
for i in range(0, len(X) - time_steps, step):
v = X.iloc[i:(i + time_steps)].values
labels = y.iloc[i: i + time_steps]
labels_a = angle.iloc[i: i + time_steps]
labels_o = obs.iloc[i: i + time_steps]
Xs.append(v)
ys.append(stats.mode(labels)[0][0])
Angle.append(stats.mode(labels_a)[0][0])
Obs.append(stats.mode(labels_o)[0][0])
return np.array(Xs), np.array(ys).reshape(-1, 1), np.array(Angle).reshape(-1, 1), np.array(Obs).reshape(-1, 1)
def get_fft_values(y_values, T, N, f_s):
f_values = np.linspace(0.0, 1.0/(2.0*T), N//2)
fft_values_ = fft(y_values)
fft_values = 2.0/N * np.abs(fft_values_[0:N//2])
return f_values, fft_values
def get_psd_values(y_values, T, N, f_s):
f_values, psd_values = welch(y_values, fs=f_s)
return f_values, psd_values
def autocorr(x):
result = np.correlate(x, x, mode='full')
return result[len(result)//2:]
def get_autocorr_values(y_values, T, N, f_s):
autocorr_values = autocorr(y_values)
x_values = np.array([T * jj for jj in range(0, N)])
return x_values, autocorr_values
def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising',
kpsh=False, valley=False, show=False, ax=None):
"""Detect peaks in data based on their amplitude and other features.
Parameters
----------
x : 1D array_like
data.
mph : {None, number}, optional (default = None)
detect peaks that are greater than minimum peak height.
mpd : positive integer, optional (default = 1)
detect peaks that are at least separated by minimum peak distance (in
number of data).
threshold : positive number, optional (default = 0)
detect peaks (valleys) that are greater (smaller) than `threshold`
in relation to their immediate neighbors.
edge : {None, 'rising', 'falling', 'both'}, optional (default = 'rising')
for a flat peak, keep only the rising edge ('rising'), only the
falling edge ('falling'), both edges ('both'), or don't detect a
flat peak (None).
kpsh : bool, optional (default = False)
keep peaks with same height even if they are closer than `mpd`.
valley : bool, optional (default = False)
if True (1), detect valleys (local minima) instead of peaks.
show : bool, optional (default = False)
if True (1), plot data in matplotlib figure.
ax : a matplotlib.axes.Axes instance, optional (default = None).
Returns
-------
ind : 1D array_like
indeces of the peaks in `x`.
Notes
-----
The detection of valleys instead of peaks is performed internally by simply
negating the data: `ind_valleys = detect_peaks(-x)`
The function can handle NaN's
See this IPython Notebook [1]_.
References
----------
.. [1] http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DetectPeaks.ipynb
"""
x = np.atleast_1d(x).astype('float64')
if x.size < 3:
return np.array([], dtype=int)
if valley:
x = -x
# find indices of all peaks
dx = x[1:] - x[:-1]
# handle NaN's
indnan = np.where(np.isnan(x))[0]
if indnan.size:
x[indnan] = np.inf
dx[np.where(np.isnan(dx))[0]] = np.inf
ine, ire, ife = np.array([[], [], []], dtype=int)
if not edge:
ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0]
else:
if edge.lower() in ['rising', 'both']:
ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0]
if edge.lower() in ['falling', 'both']:
ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0]
ind = np.unique(np.hstack((ine, ire, ife)))
# handle NaN's
if ind.size and indnan.size:
# NaN's and values close to NaN's cannot be peaks
ind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)]
# first and last values of x cannot be peaks
if ind.size and ind[0] == 0:
ind = ind[1:]
if ind.size and ind[-1] == x.size-1:
ind = ind[:-1]
# remove peaks < minimum peak height
if ind.size and mph is not None:
ind = ind[x[ind] >= mph]
# remove peaks - neighbors < threshold
if ind.size and threshold > 0:
dx = np.min(np.vstack([x[ind]-x[ind-1], x[ind]-x[ind+1]]), axis=0)
ind = np.delete(ind, np.where(dx < threshold)[0])
# detect small peaks closer than minimum peak distance
if ind.size and mpd > 1:
ind = ind[np.argsort(x[ind])][::-1] # sort ind by peak height
idel = np.zeros(ind.size, dtype=bool)
for i in range(ind.size):
if not idel[i]:
# keep peaks with the same height if kpsh is True
idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \
& (x[ind[i]] > x[ind] if kpsh else True)
idel[i] = 0 # Keep current peak
# remove the small peaks and sort back the indices by their occurrence
ind = np.sort(ind[~idel])
if show:
if indnan.size:
x[indnan] = np.nan
if valley:
x = -x
_plot(x, mph, mpd, threshold, edge, valley, ax, ind)
return ind
def get_first_n_peaks(x,y,no_peaks=10):
x_, y_ = list(x), list(y)
if len(x_) >= no_peaks:
return x_[:no_peaks], y_[:no_peaks]
else:
missing_no_peaks = no_peaks-len(x_)
return x_ + [0]*missing_no_peaks, y_ + [0]*missing_no_peaks
def get_features(x_values, y_values, mph, booll):
indices_peaks = detect_peaks(y_values, mph=mph, valley=booll)
peaks_x, peaks_y = get_first_n_peaks(x_values[indices_peaks], y_values[indices_peaks])
return peaks_x + peaks_y
def extract_features_labels(dataset, labels, T, N, f_s, denominator):
percentile = 5
list_of_features = []
list_of_labels = []
for signal_no in range(0, len(dataset)):
features = []
list_of_labels.append(labels[signal_no])
for signal_comp in range(0,dataset.shape[2]):
signl = dataset[signal_no, :, signal_comp]
signal_min = np.nanpercentile(signl, percentile)
signal_max = np.nanpercentile(signl, 100-percentile)
#ijk = (100 - 2*percentile)/10
mph = signal_min + (signal_max - signal_min)/denominator
#print(len(get_features(*get_psd_values(signl, T, N, f_s), mph)))
#print(len(get_features(*get_fft_values(signl, T, N, f_s), mph)))
#print(len(get_features(*get_autocorr_values(signl, T, N, f_s), mph)))
#features += get_features(signl, mph, True)
#features += get_features(signl, mph, False)
features += get_features(*get_psd_values(signl, T, N, f_s), mph, False)
features += get_features(*get_psd_values(signl, T, N, f_s), mph, True)
features += get_features(*get_fft_values(signl, T, N, f_s), mph, False)
features += get_features(*get_fft_values(signl, T, N, f_s), mph, True)
features += get_features(*get_autocorr_values(signl, T, N, f_s), mph, False)
features += get_features(*get_autocorr_values(signl, T, N, f_s), mph, True)
list_of_features.append(features)
return np.array(list_of_features), np.array(list_of_labels)
"""def extract_features_kmean(dataset, labels,angle, obs, T, N, f_s, denominator):
percentile = 5
list_of_features = []
list_of_labels = []
list_of_angle = []
list_of_obs = []
for signal_no in range(0, len(dataset)):
features = []
list_of_labels.append(labels[signal_no])
list_of_angle.append(angle[signal_no])
list_of_obs.append(obs[signal_no])
for signal_comp in range(0,dataset.shape[2]):
signl = dataset[signal_no, :, signal_comp]
signal_min = np.nanpercentile(signl, percentile)
signal_max = np.nanpercentile(signl, 100-percentile)
#ijk = (100 - 2*percentile)/10
mph = signal_min + (signal_max - signal_min)/denominator
#print(len(get_features(*get_psd_values(signl, T, N, f_s), mph)))
#print(len(get_features(*get_fft_values(signl, T, N, f_s), mph)))
#print(len(get_features(*get_autocorr_values(signl, T, N, f_s), mph)))
features += get_features(*get_psd_values(signl, T, N, f_s), mph, False)
features += get_features(*get_psd_values(signl, T, N, f_s), mph, True)
features += get_features(*get_fft_values(signl, T, N, f_s), mph, False)
features += get_features(*get_fft_values(signl, T, N, f_s), mph, True)
features += get_features(*get_autocorr_values(signl, T, N, f_s), mph, False)
features += get_features(*get_autocorr_values(signl, T, N, f_s), mph, True)
list_of_features.append(features)
return np.array(list_of_features), np.array(list_of_labels), np.array(list_of_angle), np.array(obs)"""
def display_circles(pcs, n_comp, pca, axis_ranks, labels=None, label_rotation=0, lims=None):
for d1, d2 in axis_ranks: # On affiche les 3 premiers plans factoriels, donc les 6 premières composantes
if d2 < n_comp:
# initialisation de la figure
fig, ax = plt.subplots(figsize=(7,6))
# détermination des limites du graphique
if lims is not None :
xmin, xmax, ymin, ymax = lims
elif pcs.shape[1] < 30 :
xmin, xmax, ymin, ymax = -1, 1, -1, 1
else :
xmin, xmax, ymin, ymax = min(pcs[d1,:]), max(pcs[d1,:]), min(pcs[d2,:]), max(pcs[d2,:])
# affichage des flèches
# s'il y a plus de 30 flèches, on n'affiche pas le triangle à leur extrémité
if pcs.shape[1] < 30 :
plt.quiver(np.zeros(pcs.shape[1]), np.zeros(pcs.shape[1]),
pcs[d1,:], pcs[d2,:],
angles='xy', scale_units='xy', scale=1, color="grey")
# (voir la doc : https://matplotlib.org/api/_as_gen/matplotlib.pyplot.quiver.html)
else:
lines = [[[0,0],[x,y]] for x,y in pcs[[d1,d2]].T]
ax.add_collection(LineCollection(lines, axes=ax, alpha=.1, color='black'))
# affichage des noms des variables
if labels is not None:
for i,(x, y) in enumerate(pcs[[d1,d2]].T):
if x >= xmin and x <= xmax and y >= ymin and y <= ymax :
plt.text(x, y, labels[i], fontsize='14', ha='center', va='center', rotation=label_rotation, color="blue", alpha=0.5)
# affichage du cercle
circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')
plt.gca().add_artist(circle)
# définition des limites du graphique
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
# affichage des lignes horizontales et verticales
plt.plot([-1, 1], [0, 0], color='grey', ls='--')
plt.plot([0, 0], [-1, 1], color='grey', ls='--')
# nom des axes, avec le pourcentage d'inertie expliqué
plt.xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))
plt.ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))
plt.title("Cercle des corrélations (F{} et F{})".format(d1+1, d2+1))
plt.show(block=False)
def display_factorial_planes(X_projected, n_comp, pca, axis_ranks, labels=None, alpha=1, illustrative_var=None):
for d1,d2 in axis_ranks:
if d2 < n_comp:
# initialisation de la figure
fig = plt.figure(figsize=(7,6))
# affichage des points
if illustrative_var is None:
plt.scatter(X_projected[:, d1], X_projected[:, d2], alpha=alpha)
else:
illustrative_var = np.array(illustrative_var)
for value in np.unique(illustrative_var):
selected = np.where(illustrative_var == value)
plt.scatter(X_projected[selected, d1], X_projected[selected, d2], alpha=alpha, label=value)
plt.legend()
# affichage des labels des points
if labels is not None:
for i,(x,y) in enumerate(X_projected[:,[d1,d2]]):
plt.text(x, y, labels[i],
fontsize='14', ha='center',va='center')
# détermination des limites du graphique
boundary = np.max(np.abs(X_projected[:, [d1,d2]])) * 1.1
plt.xlim([-boundary,boundary])
plt.ylim([-boundary,boundary])
# affichage des lignes horizontales et verticales
plt.plot([-100, 100], [0, 0], color='grey', ls='--')
plt.plot([0, 0], [-100, 100], color='grey', ls='--')
# nom des axes, avec le pourcentage d'inertie expliqué
plt.xlabel('F{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))
plt.ylabel('F{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))
plt.title("Projection des individus (sur F{} et F{})".format(d1+1, d2+1))
plt.show(block=False)
def display_scree_plot(pca):
scree = pca.explained_variance_ratio_*100
plt.bar(np.arange(len(scree))+1, scree)
plt.plot(np.arange(len(scree))+1, scree.cumsum(),c="red",marker='o')
plt.xlabel("rang de l'axe d'inertie")
plt.ylabel("pourcentage d'inertie")
plt.title("Eboulis des valeurs propres")
plt.show(block=False)
| {"/app.py": ["/fonction.py"]} |
47,713 | Fati3521/Mpredicve | refs/heads/main | /app.py | import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
import shap
from fonction import *
import plotly.express as px
from umap import UMAP
plt.style.use('fivethirtyeight')
#sns.set_style('darkgrid')scaler1
def main() :
#@st.cache
def load_data_app():
data=pd.read_csv(r"data_app_brute.csv", sep=";")
return data
#@st.cache
def load_data_test():
data=pd.read_csv(r"data_test_brute.csv", sep=";")
Num_ouverture=set(data["numero ouverture"])
return data, Num_ouverture
@st.cache
def data_brute():
data=pd.read_csv(r"data8.csv", sep=";")
scaler1=load_scaler()
data[['acc_x','acc_y']] = scaler1.transform(data[['acc_x','acc_y']])
data.loc[data["defaut"]==0,"defaut"]="normal"
data.loc[data["defaut"]==1,"defaut"]="anormal"
return data
#@st.cache
def load_model():
model=joblib.load(r"strealit_model.sav")
return model
@st.cache
def load_scaler():
scaler1 = joblib.load(r"strealit_scaler.sav")
return scaler1
#@st.cache
def pretraitement(sample, id):
sample=sample[sample["numero ouverture"] == id]
scaler1=load_scaler()
sample[['acc_x','acc_y']] = scaler1.transform(sample[['acc_x','acc_y']])
sample1=extrac_features(sample[['acc_x','acc_y']].reset_index(drop = True))
return sample1
#@st.cache
def load_prediction(sample,id, clf):
data=pretraitement(sample, id)
score = clf.predict(data)[0]
comp="normal" if score==0 else "anormal"
return comp
#@st.cache
def load_umap(train, sample, id):
sample=sample[sample["numero ouverture"] == id]
scaler1=load_scaler()
sample[['acc_x','acc_y']] = scaler1.transform(sample[['acc_x','acc_y']])
sample1=extrac_features(sample[['acc_x','acc_y']].reset_index(drop = True))
train[['acc_x','acc_y']] = scaler1.transform(train[['acc_x','acc_y']])
train1=feat(train.reset_index(drop = True))
#train1=extrac_features(train[['acc_x','acc_y']].reset_index(drop = True))
umap_2d = UMAP(n_components=2, init='random', random_state=0)
proj_2d = pd.DataFrame(umap_2d.fit_transform(train1.iloc[:,:-1]))
proj_1d = pd.DataFrame(umap_2d.transform(sample1))
proj_2d['defaut']=train1['defaut']
return proj_2d, proj_1d
#@st.cache
def box_plotly(brute_app, data_test, chk_id):
brute_test=data_test[data_test["numero ouverture"] == chk_id]
scaler1=load_scaler()
brute_test[['acc_x','acc_y']] = scaler1.transform(brute_test[['acc_x','acc_y']])
brute_test["defaut"]="nouvelle prediction"
data_fusion=pd.concat([brute_app, brute_test.iloc[:,:-1]])
fig = px.box(data_fusion, x="defaut", y=feat_id, points="all")
st.plotly_chart(fig)
data_app = load_data_app()
data_test, numero_ouverture = load_data_test()
targets = data_app.defaut.value_counts()
brute_app=data_brute()
feature=['acc_x', 'acc_y', 'acc_z', 'gyr_x', 'gyr_y', 'gyr_z','temp']
#print(type(numero_ouverture))
#######################################
# SIDEBAR
#######################################
#Title display
html_temp = """
<div style="background-color: tomato; padding:10px; border-radius:10px">
<h1 style="color: white; text-align:center">MAINTENANCE PREDICTIVE</h1>
</div>
<p style="font-size: 20px; font-weight: bold; text-align:center">INTERPRETATION MODELE PREDICTIF</p>
"""
st.markdown(html_temp, unsafe_allow_html=True)
#Loading data……
clf = load_model()
#Customer ID selection
st.sidebar.header("**JEU DE DONNEES**")
#Loading select-box
#st.sidebar.markdown("<u>Average loan amount (USD) :</u>", unsafe_allow_html=True)
#fig = px.pie(values=targets.values, names=targets.index)
#st.sidebar.plotly_chart(fig)
fig, ax = plt.subplots(figsize=(5,5))
plt.pie(targets, explode=[0, 0.1], labels=['No default', 'Default'], autopct='%1.1f%%', startangle=90)
st.sidebar.pyplot(fig)
chk_id = st.sidebar.selectbox("Numero Ouverture", numero_ouverture)
#######################################
# HOME PAGE - MAIN CONTENT
#######################################
#Display Customer ID from Sidebar
#Customer solvability display
st.header("**ANALYSE DES PREDICTIONS**")
if st.button('Prediction'):
#if st.checkbox("Show customer information ?"):
prediction = load_prediction(data_test, chk_id, clf)
st.write("**Comportement:**",prediction)
data_app1, data_test1=load_umap(data_app, data_test,chk_id)
data_app1["taille"]=1
data_test1["defaut"]=2
data_test1["taille"]=5
XX=pd.concat([data_test1,data_app1])
fig_2d = px.scatter(XX, x=0, y=1, color=XX["defaut"], labels={'color': 'lable'}, size="taille")
#fig_2d.update_layout(showlegend=False)
st.plotly_chart(fig_2d)
#Feature importance / description
if st.checkbox("Interpretation niveau global ?"):
shap.initjs()
X=pretraitement(data_test, chk_id)
#number = st.slider("Pick a number of features…", 0, 20, 5)
fig, ax = plt.subplots(figsize=(10, 10))
explainer = shap.TreeExplainer(load_model())
shap_values = explainer.shap_values(X)
# Plot summary_plot
shap.summary_plot(shap_values, X)
st.pyplot(fig)
else:
st.markdown("<i>…</i>", unsafe_allow_html=True)
X=pretraitement(data_test, chk_id)
if st.checkbox("Interpretation niveau local Niveau 1"):
fig, ax = plt.subplots()
explainer = shap.TreeExplainer(load_model())
shap_values = explainer.shap_values(X)
# Plot summary_plot
shap.initjs()
force_plot=shap.force_plot(explainer.expected_value[1], shap_values[1], X, matplotlib=True,
show=False)
st.pyplot(force_plot)
else:
st.markdown("<i>…</i>", unsafe_allow_html=True)
if st.checkbox("Interpretation niveau local Niveau 2"):
fig, ax = plt.subplots()
explainer = shap.TreeExplainer(load_model())
shap_values = explainer.shap_values(X)
fig, ax = plt.subplots(figsize=(10, 10))
# Plot summary_plot
shap.initjs()
shap.decision_plot(explainer.expected_value[1], shap_values[1], X)
st.pyplot(fig)
else:
st.markdown("<i>…</i>", unsafe_allow_html=True)
if st.checkbox("Distribution des données"):
feat_id = st.selectbox("feature", feature)
box_plotly(brute_app, data_test, chk_id)
else:
st.markdown("<i>…</i>", unsafe_allow_html=True)
if __name__ == '__main__':
main()
| {"/app.py": ["/fonction.py"]} |
47,747 | PetarPeychev/automatagen | refs/heads/master | /automatagen/__init__.py | from automatagen.automatagen import TerrainGenerator
| {"/automatagen/__init__.py": ["/automatagen/automatagen.py"]} |
47,748 | PetarPeychev/automatagen | refs/heads/master | /automatagen/automatagen.py | import random
class TerrainGenerator:
def __init__(self,
initial_density = 0.48,
steps = 5,
loneliness_limit = 4):
self.initial_density = initial_density
self.steps = steps
self.loneliness_limit = loneliness_limit
def _randomize(self):
# seed random function
random.seed(a = self.seed)
# change cell to true if random float is under initial_density
for y in range(0, self.height):
for x in range(0, self.width):
if random.random() < self.initial_density:
self._cells[y][x] = False
def _step_simulation(self):
# initialize a new 2d cell array
new_cells = [[True for x in range(self.width)] for y in range(self.height)]
# iterate over cells
for y in range(0, self.height):
for x in range(0, self.width):
neighbours = self._count_living_neighbours(x, y)
if neighbours > self.loneliness_limit:
new_cells[y][x] = True
else:
new_cells[y][x] = False
self._cells = new_cells
def _count_living_neighbours(self, x, y):
count = 0
# iterate over the 3x3 neighbourhood
for i in range(-1, 2):
for j in range(-1, 2):
neighbour_x = x + i
neighbour_y = y + j
# if neighbour is outside of map, count it
if neighbour_x < 0 or neighbour_y < 0 or neighbour_y >= len(self._cells) or neighbour_x >= len(self._cells[0]):
count += 1
# if neighbour is alive, count it
elif self._cells[neighbour_y][neighbour_x]:
count += 1
return count
def generate(self, width, height, seed = None):
self.width = width
self.height = height
# create 2d bool array, all true (walls)
self._cells = [[True for x in range(self.width)] for y in range(self.height)]
# generate random seed or use provided
if not seed:
seed = random.randrange(2147483648)
self.seed = seed
self._randomize()
for step in range(self.steps):
self._step_simulation()
return self._cells
| {"/automatagen/__init__.py": ["/automatagen/automatagen.py"]} |
47,750 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /model/MLP.py | import torch
import torch.nn as nn
class Mlp(nn.Module):
def __init__(self, in_channel, hidden_channel, out_channel, hidden_num):
super(Mlp, self).__init__()
self.layer1 = nn.Sequential(nn.Linear(in_channel, hidden_channel, bias=True), nn.ReLU())
self.hidden_num = hidden_num
if hidden_num >= 2:
self.hidden = nn.ModuleList([
nn.Sequential(nn.Linear(hidden_channel, hidden_channel, bias=True), nn.ReLU())
for i in range(hidden_num-1)])
self.out_layer = nn.Linear(hidden_channel, out_channel, bias=True)
def forward(self, x):
x = self.layer1(x)
if self.hidden_num >= 2:
for blk in self.hidden:
x = blk(x)
out = nn.functional.softmax(self.out_layer(x), dim=1)
return out | {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,751 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /MLP_Cifar10.py | import torch
import torch.nn as nn
import torchvision
from torch.utils.data import Dataset,DataLoader,TensorDataset
from torch.autograd import Variable
import os
import numpy as np
from sklearn.metrics import classification_report
from utils.util import dim_redu, get_kfold_data, WriteExcelRow
from model.MLP import Mlp
def fit_one_train(epoch, train_loader, model, criterion, X_test, y_test, cuda):
train_losses = []
print("Start training")
for e in range(epoch):
train_loss = 0
model.train()
for X, y in train_loader:
if cuda:
X = X.cuda()
y = y.cuda()
X_data = Variable(X)
out = model(X_data)
loss = criterion(out, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
print("Epoch", e+1, " loss:", train_loss / len(train_data))
if (e + 1) % 5 == 0:
#每训练5次迭代进行一次精确度评估
model.eval()
if cuda:
X_test = X_test.cuda()
y_test = y_test.cuda()
y_pred = model(X_test)
acc = np.mean((torch.argmax(y_pred, 1).cpu().numpy() == y_test.cpu().numpy()))
print("Epoch", e+1, " acc:", acc)
# torch.save(model.state_dict(), "logs/Epoch" + str(e+1) + ".pth")
train_losses.append(train_loss / len(train_data))
model.eval()
if cuda:
X_test = X_test.cuda()
y_test = y_test.cuda()
y_pred = model(X_test)
acc = np.mean((torch.argmax(y_pred, 1).cpu().numpy() == y_test.cpu().numpy()))
return acc, model
if __name__ == "__main__":
# -----------------------------------------------参数都在这里修改-----------------------------------------------#
#是否使用GPU训练
cuda = True
#分类数量
class_num = 10
# 训练迭代数
epoch = 50
#batch_size
batch_size = 16
#学习率
learning_rate = 0.001
# 降维比例和是否灰度处理,pca_ratio设置为1为不降维,灰度处理后特征数量为3072/3*pca_ratio
pca_ratio = 1
gray = False
#隐藏层大小,设置为-1时为输入层大小除2
hidden_c = -1
#隐藏层数量,每一层隐藏层通道数固定
hidden_num = 2
#是否使用10折交叉验证,不使用时即计算F1值并将结果储存在表格中
k_fold_10 = False
#储存结果数据的表格路径
path = "./result/result.xlsx"
# -----------------------------------------------参数都在这里修改-----------------------------------------------#
data_path = "./cifar10/"
#读取训练数据
train_data = torchvision.datasets.CIFAR10(
root=data_path,
train=True,
transform=torchvision.transforms.ToTensor(),
download=False,
)
#读取测试数据
test_data = torchvision.datasets.CIFAR10(
root=data_path,
train=False,
transform=torchvision.transforms.ToTensor(),
download=False,
)
#对图片降维
train_X = dim_redu(train_data.data, gray, pca_ratio)
test_X = dim_redu(test_data.data, gray, pca_ratio)
#将数据由numpy格式转变为torch的张量模式
X_train = torch.from_numpy(train_X).type(torch.FloatTensor)
y_train = torch.tensor(train_data.targets, dtype=torch.long)
X_test = torch.from_numpy(test_X).type(torch.FloatTensor)
y_test = torch.tensor(test_data.targets, dtype=torch.long)
#选择GPU训练
device = torch.device("cuda:0")
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
if k_fold_10:
acc_mean = 0
for i in range(10):
X_train, y_train, X_valid, y_valid = get_kfold_data(10, i, X_test, y_test)
print("10折交叉验证,第", i+1, "次:")
train_dataset = TensorDataset(X_train, y_train)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
input_size = X_test.shape[-1]
#建立模型
if hidden_c == -1:
model = Mlp(input_size, input_size//2, class_num, hidden_num)
else:
model = Mlp(input_size, hidden_c, class_num, hidden_num)
if cuda:
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) #优化器
acc, model = fit_one_train(epoch, train_loader, model, criterion, X_valid, y_valid, cuda) #训练
if gray:
dim_reduce_ratio = 3072/3*pca_ratio
else:
dim_reduce_ratio = 3072*pca_ratio
# torch.save(model.state_dict(), 'logs/dim%.2f-kfold%d-weight.pth'%(dim_reduce_ratio, i+1))
print("第", i+1, "折模型正确率为", acc)
acc_mean += acc
print("十折交叉验证结束,平均正确率为:", acc_mean / 10)
else:
train_dataset = TensorDataset(X_train, y_train)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=32, shuffle=True)
input_size = X_test.shape[-1]
# 建立模型
if hidden_c == -1:
model = Mlp(input_size, input_size // 2, class_num, hidden_num)
else:
model = Mlp(input_size, hidden_c, class_num, hidden_num)
if cuda:
model.to(device)
criterion = nn.CrossEntropyLoss() #损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) #优化器
acc, model = fit_one_train(epoch, train_loader, model, criterion, X_test, y_test, cuda) #训练
if gray:
dim_reduce_ratio = pca_ratio / 3
else:
dim_reduce_ratio = pca_ratio
torch.save(model.state_dict(), 'logs/dim%.2f-weight.pth' % (dim_reduce_ratio))
# 利用测试数据测试模型
if cuda:
X_test = X_test.cuda()
y_pred = model(X_test)
res = classification_report(torch.argmax(y_pred, 1).cpu(), y_test.cpu(), output_dict=True)
print(classification_report(torch.argmax(y_pred, 1).cpu(), y_test.cpu()))
f1_score = []
for i in range(10):
f1_score.append(res[str(i)]['f1-score'])
print("每个类的F1值如下:", f1_score)
f1_score_mean = res['macro avg']["f1-score"]
#将降维后的特征数和最终平均f1指数写入表格
WriteExcelRow([dim_reduce_ratio, f1_score_mean], path, -1, "features")
| {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,752 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /utils/util.py | import torch
from PIL import Image
import numpy as np
import openpyxl
from sklearn.decomposition import PCA
def dim_redu(data, gray, dim_ratio):
"""
将三通道图片灰度处理后进行PCA降维
cifar10图片原大小为32*32*3,展开为3072,总共包含3072个特征值,如果做灰度处理会减少为1024,然后按pca设定的比例进行降维
Args:
data:输入数据为四维[batch,H,W,C]
gray:是否进行灰度处理
dim_ratio:降维比率
"""
cifar_train = data
# 灰度处理
if gray:
print("灰度处理...")
batch_size = len(cifar_train)
cifar_gray = []
for i in range(len(cifar_train)):
gray_item = np.array(Image.fromarray(cifar_train[i]).convert('L'))
cifar_gray.append(gray_item)
cifar_train = np.array(cifar_gray).reshape(batch_size, -1)
print("灰度处理完成")
if dim_ratio == 1:
cifar_train = cifar_train.reshape(len(cifar_train), -1)
else:
cifar_train = cifar_train.reshape(len(cifar_train), -1)
# PCA降维
print("开始PCA降维,降维比率为", dim_ratio, "...")
pca_model = PCA(n_components=int(cifar_train.shape[-1] * dim_ratio))
pca_model.fit(cifar_train)
cifar_train = pca_model.transform(cifar_train)
print("PCA降维完成")
return cifar_train
def get_kfold_data(k, i, X, y):
"""
K折验证
Args:
k:将原数据分为几份(原题目为10)
i:当前所划分的验证数据为第几份
X:数据集
y:数据标签
"""
fold_size = X.shape[0] // k # 每份的个数:数据总条数/折数(组数)
val_start = i * fold_size
if i != k - 1:
val_end = (i + 1) * fold_size
X_valid, y_valid = X[val_start:val_end], y[val_start:val_end]
X_train = torch.cat((X[0:val_start], X[val_end:]), dim=0)
y_train = torch.cat((y[0:val_start], y[val_end:]), dim=0)
else: # 若是最后一折交叉验证
X_valid, y_valid = X[val_start:], y[val_start:] # 若不能整除,将多的case放在最后一折里
X_train = X[0:val_start]
y_train = y[0:val_start]
return X_train, y_train, X_valid, y_valid
def WriteExcelRow(data, path, colIndex, sheet):
wb = openpyxl.load_workbook(path)
ws = wb[sheet]
if colIndex == -1:
colIndex = ws.max_row + 1
for i in range(len(data)):
ws.cell(row=colIndex, column=i+1).value = data[i]
wb.save(path)
| {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,753 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /model/CNN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Mish(nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
return x * torch.tanh(F.softplus(x))
class CBL(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1):
super(CBL, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size // 2, bias=False)
self.bn = nn.BatchNorm2d(out_channels)
self.activation = nn.LeakyReLU(0.1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activation(x)
return x
class CNNnet(nn.Module):
def __init__(self, num_class):
super(CNNnet, self).__init__()
# 32*32*3 -> 16*16*16
self.conv1 = CBL(3, 16, kernel_size=3, stride=1)
# 16*16*16 -> 8*8*32
self.conv2 = CBL(16, 32, kernel_size=3, stride=1)
self.pool = nn.MaxPool2d(2, 2)
# 第一层全连接(32 * 8 * 8 -> 500)
self.fc1 = nn.Linear(32 * 8 * 8, 500)
# 第二层全连接 (500 -> 10)
self.fc2 = nn.Linear(500, num_class)
# dropout层
self.dropout = nn.Dropout(0.3)
def forward(self, x):
x = self.pool(self.conv1(x))
x = self.pool(self.conv2(x))
# 将特征层展平
x = self.dropout(x.view(-1, 32 * 8 * 8))
x = self.dropout(F.relu(self.fc1(x)))
out = self.fc2(x)
return out | {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,754 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /draw.py | r"""
训练完成后平均F1值会存在result文件夹下的表格里,
运行task2_draw可以画出折线图(储存结果数据可以自己改,也可以画出来)
不知道为什么降维以后效果会很差,可能本来就这样吧、、、
"""
import pandas as pd
import matplotlib.pyplot as plt
sheet = "features"
df = pd.read_excel("./result/result.xlsx", names=None, sheet_name=sheet)
df = df.sort_values("ratio")
plt.plot(df['ratio'], df["mean F1"])
plt.show()
| {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,755 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /CNN_Cifar.py | import torch
import torch.nn as nn
import torchvision
from torch.utils.data import Dataset,DataLoader,TensorDataset
from torch.autograd import Variable
import os
import numpy as np
from sklearn.metrics import classification_report
from model.CNN import CNNnet
def fit_one_train(epoch, train_loader, model, criterion, X_test, y_test, cuda):
train_losses = []
print("Start training")
for e in range(epoch):
train_loss = 0
model.train()
for X, y in train_loader:
if cuda:
X = X.cuda()
y = y.cuda()
X_data = Variable(X)
out = model(X_data)
loss = criterion(out, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
print("Epoch", e+1, " loss:", train_loss / len(train_data))
if (e+1) == epoch:
model.eval()
if cuda:
X_test = X_test.cuda()
y_pred = model(X_test)
acc = np.mean((torch.argmax(y_pred, 1).cpu().numpy() == y_test.cpu().numpy()))
print("Epoch", e + 1, " acc:", acc)
# torch.save(model.state_dict(), "logs/Epoch" + str(e+1) + ".pth")
res = classification_report(torch.argmax(y_pred, 1).cpu(), y_test.cpu(), output_dict=True)
f1_score = []
for i in range(10):
f1_score.append(res[str(i)]['f1-score'])
print("每个类的F1值如下:", f1_score)
f1_score_mean = res['macro avg']["f1-score"]
print("F1平均值:", f1_score_mean)
print(classification_report(torch.argmax(y_pred, 1).cpu(), y_test.cpu()))
train_losses.append(train_loss / len(train_data))
return acc, f1_score, f1_score_mean, model
if __name__ == "__main__":
# -----------------------------------------------参数都在这里修改-----------------------------------------------#
#是否使用GPU训练
cuda = True
#分类数量
class_num = 10
# 训练迭代数
epoch = 50
# batch_size
batch_size = 16
#学习率
learning_rate = 0.001
# -----------------------------------------------参数都在这里修改-----------------------------------------------#
data_path = "./cifar10/"
train_data = torchvision.datasets.CIFAR10(
root=data_path,
train=True,
transform=torchvision.transforms.ToTensor(),
download=False,
)
test_data = torchvision.datasets.CIFAR10(
root=data_path,
train=False,
transform=torchvision.transforms.ToTensor(),
download=False,
)
X_train = torch.from_numpy(train_data.data).type(torch.FloatTensor).permute(0, 3, 1, 2).contiguous()
y_train = torch.tensor(train_data.targets, dtype=torch.long)
X_test = torch.from_numpy(test_data.data).type(torch.FloatTensor).permute(0, 3, 1, 2).contiguous()
y_test = torch.tensor(test_data.targets, dtype=torch.long)
device = torch.device("cuda:0")
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
train_dataset = TensorDataset(X_train, y_train)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = TensorDataset(X_test, y_test)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
input_size = X_test.shape[-1]
model = CNNnet(class_num)
if cuda:
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
acc, f1_score, f1_score_mean, model = fit_one_train(epoch, train_loader, model, criterion, X_test, y_test, cuda)
print("精度为:", acc)
print("每个类的F1值如下:", f1_score)
print("平均F1值为:", f1_score_mean)
| {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,756 | carryg1998/Cifar10_Mlp_CNN | refs/heads/main | /PCA.py | r"""
降维的函数详见utils.util.dim_redu函数
"""
import torch
import torchvision
import numpy as np
from PIL import Image
from utils.util import dim_redu
data_path = "./cifar10/"
train_data = torchvision.datasets.CIFAR10(
root=data_path,
train=True,
transform=torchvision.transforms.ToTensor(),
download=False,
)
test_data = torchvision.datasets.CIFAR10(
root=data_path,
train=False,
transform=torchvision.transforms.ToTensor(),
download=False,
)
res = dim_redu(train_data.data, True, 0.5)
print(res.shape)
| {"/MLP_Cifar10.py": ["/utils/util.py", "/model/MLP.py"], "/CNN_Cifar.py": ["/model/CNN.py"], "/PCA.py": ["/utils/util.py"]} |
47,758 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__sr.py | import phunspell
import inspect
import unittest
# TODO
class TestSR(unittest.TestCase):
pspell = phunspell.Phunspell('sr')
def test_true(self):
self.assertTrue(True)
# def test_word_found(self):
# self.assertTrue(self.pspell.lookup("фекетић"))
# def test_word_not_found(self):
# self.assertFalse(self.pspell.lookup("phunspell"))
# def test_lookup_list_return_not_found(self):
# words = "Pričinovi otpuhnut Oprikić Miltenović фекетић borken"
# self.assertListEqual(
# self.pspell.lookup_list(words.split(" ")), ["borken"]
# )
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,759 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test_multi_load_no_cache.py | import phunspell
import inspect
import unittest
dicts_words = {
"af_ZA": "voortgewoed",
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
"br_FR": "c'huñvderioù",
"de_DE": "schilffrei",
"en_GB": "indict",
"es_MX": "pianista",
"fr_FR": "zoomorphe",
}
dicts_words_cached = {
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
}
# TODO:
# fix this upstream
# re: reloading dictionaries is not handled upstream
# ResourceWarning: Enable tracemalloc to get the object allocation traceback
# /Users/dwright/Dev/python/misc/dw/lib/python3.8/site-packages/spylls/hunspell/dictionary.py:141: ResourceWarning: unclosed file <_io.TextIOWrapper name='/Users/dwright/Dev/python/Phunspell/phunspell/data/dictionary/de/de_DE.aff' mode='r' encoding='ISO8859-1'>
# aff, context = readers.read_aff(FileReader(path + '.aff'))
# ResourceWarning: Enable tracemalloc to get the object allocation traceback
class TestMultiLoadNoCache(unittest.TestCase):
def test_multi_load_no_cache(self):
for loc in dicts_words.keys():
# slower performance
pspell = phunspell.Phunspell(loc)
self.assertTrue(pspell.lookup(dicts_words[loc], loc=loc))
for loc in dicts_words_cached.keys():
# slower performance
pspell = phunspell.Phunspell(loc)
self.assertTrue(pspell.lookup(dicts_words[loc], loc=loc))
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,760 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test_phunspell.py | import phunspell
import inspect
import unittest
class TestPhunspell(unittest.TestCase):
pspell = phunspell.Phunspell('en_US')
def setUp(self):
pass
def tearDown(self):
pass
def test_package(self):
self.assertTrue(inspect.ismodule(phunspell))
def test_exception_if_not_dictionary(self):
with self.assertRaises(phunspell.phunspell.PhunspellError):
phunspell.Phunspell('no-lang')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("about"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_sentance_to_list_cleaned(self):
self.assertListEqual(
self.pspell.to_list(
"This !\"#$%&'()*+, -./:;<=>?@[]^_`{|}~ IS, A lISt? OF words!?, $%^( right here*"
),
['this', 'is', 'a', 'list', 'of', 'words', 'right', 'here'],
)
def test_lookup_list_return_not_found(self):
self.assertListEqual(
self.pspell.lookup_list("Bill's TV is borken".split(" ")),
["borken"],
)
def test_suggest(self):
suggestions = [x for x in self.pspell.suggest('phunspell')]
self.assertListEqual(
suggestions,
["Hunspell"],
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,761 | dvwright/phunspell | refs/heads/main | /phunspell/__init__.py | import os
import sys
__name__ = "phunspell"
__author__ = "David Wright"
__email__ = "dvwright@cpan.org"
__version__ = "0.1.6"
# For relative imports to work in Python 3.6
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from .phunspell import Phunspell, PhunspellError # noqa F401
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,762 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__gug.py | import phunspell
import inspect
import unittest
class TestGug(unittest.TestCase):
pspell = phunspell.Phunspell('gug_PY')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("mba'erepy"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "formula hetyma ytororõ apysa mba'erepy borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,763 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__ca.py | import phunspell
import inspect
import unittest
class TestCaPY(unittest.TestCase):
pspell = phunspell.Phunspell('ca')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("Ogooué-Ivindo"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "redifonga Ogooué-Ivindo seriositat borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,764 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__no.py | import phunspell
import inspect
import unittest
class TestNO(unittest.TestCase):
pspell = phunspell.Phunspell('nb_NO')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("sjøfarende"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "kompetansebegrep kvalitetskontroller lovreguler datamaterial sjøfarende notword"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["notword"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,765 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test_multi_load_cache.py | import phunspell
import inspect
import unittest
dicts_words = {
"af_ZA": "voortgewoed",
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
"br_FR": "c'huñvderioù",
"de_DE": "schilffrei",
"en_GB": "indict",
"es_MX": "pianista",
"fr_FR": "zoomorphe",
}
# use cache if already seen
dicts_words_cached = {
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
}
class TestMultiLoadCache(unittest.TestCase):
pspell = phunspell.Phunspell()
def test_multi_load_cache(self):
for loc in dicts_words.keys():
self.assertTrue(self.pspell.lookup(dicts_words[loc], loc=loc))
for loc in dicts_words_cached.keys():
self.assertTrue(self.pspell.lookup(dicts_words[loc], loc=loc))
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,766 | dvwright/phunspell | refs/heads/main | /setup.py | from setuptools import setup
from setuptools import find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='phunspell',
version='0.1.6',
url='https://github.com/dvwright/phunspell',
download_url='https://github.com/dvwright/phunspell/archive/v0.1.6.tar.gz',
license='MIT',
description='Pure Python spell checker, utilizing Spylls a port of Hunspell',
long_description=long_description,
long_description_content_type="text/markdown",
author='David Wright',
author_email='dvwright@cpan.org',
include_package_data=True,
packages=find_packages(
exclude=[
'tests',
'pyproject.toml',
'create_test_data.sh',
'obtain_dicts.rb',
'obtain_dicts.sh',
'test_data.txt',
]
),
install_requires=['spylls'],
keywords=['Spelling', 'Hunspell', 'Spylls', 'Python'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,767 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test_object_store_not_exist.py | import os
import time
import phunspell
import inspect
import unittest
import tempfile
TEMPDIR = tempfile.gettempdir()
class TestPhunspellObjectStoreNotExist(unittest.TestCase):
pspell = phunspell.Phunspell(object_storage=TEMPDIR)
def setUp(self):
self._rm_locale("ru_RU")
def tearDown(self):
self._rm_locale("ru_RU")
def _rm_locale(self, loc):
try:
os.remove(os.path.join(TEMPDIR, loc))
except FileNotFoundError as error:
print(error)
def test_dict_obj_expected_not_exist(self):
"""local object expected but not exist,
fallback to dist included dictionary then dump to local storage
so it's there next time
NOTE: feature is ONLY if user set storage_path is set
"""
pass
# debug
# pass standlone
# fails when run as suite
# loc = "ru_RU"
# # not exist
# filepath = os.path.join(TEMPDIR, loc)
# self.assertFalse(os.path.exists(filepath))
# self.assertTrue(self.pspell.lookup("наденутся", loc=loc))
# # was created
# self.assertTrue(os.path.exists(filepath))
# self.assertFalse(self.pspell.lookup("phunspell", loc=loc))
# # still exist
# self.assertTrue(os.path.exists(filepath))
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,768 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__ar.py | import phunspell
import inspect
import unittest
class TestArPy(unittest.TestCase):
pspell = phunspell.Phunspell('ar')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("يقرحان"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "يقرحان هن انشقوا borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,769 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__ne_NP.py | import phunspell
import inspect
import unittest
class TestNeNP(unittest.TestCase):
pspell = phunspell.Phunspell('ne_NP')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("डम्फु"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "डम्फु दोस्त मगज शिक्षाविद दिशानिर्देश borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
def test_to_list(self):
words = "!\"#$%&'()*+, -./:;<=>?@[]^_`{|}~ बछेडा-बछेडी सह-सेनानी हास्य-व्यङ्ग्य $%^(*"
self.assertListEqual(
self.pspell.to_list(words),
["बछेडा-बछेडी", "सह-सेनानी", "हास्य-व्यङ्ग्य"],
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,770 | dvwright/phunspell | refs/heads/main | /phunspell/phunspell.py | # Copyright (c) 2021 David Wright
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Phunspell - A pure Python spell checker, utilizing Spylls a port of Hunspell
Typical usage:
import phunspell
pspell = phunspell.Phunspell("en_US")
print(pspell.lookup("phunspell")) # False
print(pspell.lookup("about")) # True
mispelled = pspell.lookup_list("Bill's TV is borken".split(" "))
print(mispelled) # ["bill", "tv", "borken"]
pspell = phunspell.Phunspell("cs_CZ")
"""
import os
import string
import pickle
from spylls.hunspell import Dictionary
DICTIONARIES = {
# lang-loc # dir # language
"af_ZA": ["af_ZA", "Afrikaans"],
"an_ES": ["an_ES", "Aragonese"],
"ar": ["ar", "Arabic"],
"be_BY": ["be_BY", "Belarusian"],
"bg_BG": ["bg_BG", "Bulgarian"],
"bn_BD": ["bn_BD", "?"],
"bo": ["bo", "?"],
"br_FR": ["br_FR", "Breton"],
"bs_BA": ["bs_BA", "?"],
# "ca-valencia": ["ca", "?"], # a dialect? used?
"ca": ["ca", "Catalan ?"],
"ca_ES": ["ca", "Catalan"], # guessing that ca should be ca_ES
"cs_CZ": ["cs_CZ", "Czech"],
"da_DK": ["da_DK", "Danish"],
"de_AT": ["de", "German"],
"de_CH": ["de", "German"],
"de_DE": ["de", "German"],
"el_GR": ["el_GR", "Greek"],
"en_AU": ["en", "English (Australian)"],
"en_CA": ["en", "English (Canada)"],
"en_GB": ["en", "English (Great Britain)"],
"en_US": ["en", "English (US)"],
"en_ZA": ["en", "English (South African)"],
"es": ["es", "Spanish"],
"es_AR": ["es", "Spanish"],
"es_BO": ["es", "Spanish"],
"es_CL": ["es", "Spanish"],
"es_CO": ["es", "Spanish"],
"es_CR": ["es", "Spanish"],
"es_CU": ["es", "Spanish"],
"es_DO": ["es", "Spanish"],
"es_EC": ["es", "Spanish"],
"es_ES": ["es", "Spanish"],
"es_GQ": ["es", "Spanish"],
"es_GT": ["es", "Spanish"],
"es_HN": ["es", "Spanish"],
"es_MX": ["es", "Spanish"],
"es_NI": ["es", "Spanish"],
"es_PA": ["es", "Spanish"],
"es_PE": ["es", "Spanish"],
"es_PH": ["es", "Spanish"],
"es_PR": ["es", "Spanish"],
"es_PY": ["es", "Spanish"],
"es_SV": ["es", "Spanish"],
"es_US": ["es", "Spanish"],
"es_UY": ["es", "Spanish"],
"es_VE": ["es", "Spanish"],
"et_EE": ["et_EE", "Estonian"],
"fr_FR": ["fr_FR", "French"],
"gd_GB": ["gd_GB", "Scottish Gaelic"],
"gl_ES": ["gl", "?"],
"gu_IN": ["gu_IN", "Gujarati"],
"gug_PY": ["gug", "Guarani"],
"he_IL": ["he_IL", "Hebrew"],
"hi_IN": ["hi_IN", "Hindi"],
"hr_HR": ["hr_HR", "Croatian"],
"hu_HU": ["hu_HU", "Hungarian"],
"id_ID": ["id", "Indonesian"],
"is": ["is", "Icelandic"],
"it_IT": ["it_IT", "Italian"],
# Kurdish (Turkey) ku_TR ?
"kmr_Latn": ["kmr_Latn", "?"],
"ko_KR": ["ko_KR", "?"],
"lo_LA": ["lo_LA", "?"],
"lt_LT": ["lt_LT", "Lithuanian"],
"lv_LV": ["lv_LV", "Latvian"],
# Mapudüngun md (arn) ?
"ne_NP": ["ne_NP", "?"],
"nl_NL": ["nl_NL", "Netherlands"],
"nb_NO": ["no", "Norwegian"],
"nn_NO": ["no", "Norwegian"],
"oc_FR": ["oc_FR", "Occitan"],
"pl_PL": ["pl_PL", "Polish"],
"pt_BR": ["pt_BR", "Brazilian Portuguese"],
"pt_PT": ["pt_PT", "Portuguese"],
"ro_RO": ["ro", "Romanian"],
"ru_RU": ["ru_RU", "Russian"],
"si_LK": ["si_LK", "Sinhala"],
"sk_SK": ["sk_SK", "Slovak"],
"sl_SI": ["sl_SI", "Slovenian"],
"sq_AL": ["sq_AL", "?"],
"sr-Latn": ["sr", "?"],
"sr": ["sr", "Serbian (Cyrillic and Latin)"],
"sv_FI": ["sv_SE", "Swedish"],
"sv_SE": ["sv_SE", "Swedish"],
"sw_TZ": ["sw_TZ", "Swahili"],
"te_IN": ["te_IN", "?"],
"th_TH": ["th_TH", "Thai"],
"tr_TR": ["tr_TR", "Turkish"],
"uk_UA": ["uk_UA", "Ukrainian"],
"vi_VN": ["vi", "Vietnamese"],
# "hyph_zu_ZA" : ["zu_ZA", "LANG"],
}
# memoize - only if using object_storage feature
DICTIONARIES_LOADED = {}
class PhunspellError(Exception):
def __init__(self, message):
Exception.__init__(self, "%s" % (message))
class PhunspellObjectStore:
"""Create local object stores of all dictionaries
meant to only be run once.
NOTE: Will need to be rerun anytime a dictionary is updated
"""
def __init__(self, path):
"""NOTE: meant to be run once to
create/store local pickled dictionary objects
"""
try:
pspell = Phunspell(object_storage=path)
pspell.dictionary_loader(pspell.dictionaries_all())
# pspell.dictionary_loader(['ca', 'ru_RU'])
except (
FileNotFoundError,
KeyError,
TypeError,
ValueError,
PhunspellError,
) as error:
raise PhunspellError(
"phunspell object store, dictionary not found {}".format(error)
)
class Phunspell:
"""pure Python spell checker, utilizing Spylls a port of Hunspell"""
def __init__(self, loc_lang="en_US", loc_list=[], object_storage=None):
"""Load passed dictionary (loc_lang) on init
dictionary must be of the form Locale_Langage
e.g. "en_US"
Can specify a local directory path to dictionary objects
params:
loc_list : ["en_US", "de_AT", "de_DE", "el_GR", etc]
object_storage : "/home/dwright/python/phunspell/pickled_data/"
See README for all supported languages
"""
try:
self.object_storage = object_storage
if len(loc_list) > 0:
# if locales passed, load specified dictionaries on init
self.dictionary_loader(loc_list)
else:
# load single loc dictionary on init
self.dict_dirpath(loc_lang)
# use local dictionaries
self.dictionary = Dictionary.from_files(self.dict_path)
except (
FileNotFoundError,
KeyError,
TypeError,
ValueError,
PhunspellError,
) as error:
raise PhunspellError(
"phunspell, dictionary not found {}".format(error)
)
def dictionaries_all(self):
"""Return included dictionary locales names"""
return [n for n in DICTIONARIES.keys() if n.find('_') != -1]
def dictionary_load(self, loc):
"""load stored dictionary object for locale"""
try:
if loc in DICTIONARIES_LOADED:
self.dictionary = DICTIONARIES_LOADED[loc]
return
if self.object_storage:
filepath = os.path.join(self.object_storage, loc)
if os.path.exists(filepath):
pfile = open(filepath, 'rb')
stored_dic = pickle.load(pfile)
self.dictionary = stored_dic
pfile.close()
# memoize
DICTIONARIES_LOADED[loc] = stored_dic
else:
# not found it object_storage, create it
self.dictionary_store(loc)
else:
# not using object store
# open dist included dictionary directly
self.dict_dirpath(loc)
self.dictionary = Dictionary.from_files(self.dict_path)
except (TypeError, OSError) as error:
raise PhunspellError("Cannot load dictionary {}".format(error))
def dictionary_store(self, loc):
"""iterate locale dump dictionary to object
pickle the dictionary
"""
try:
if self.object_storage:
filepath = os.path.join(self.object_storage, loc)
self.dict_dirpath(loc)
# read dictionaries from distrubtion path
data = Dictionary.from_files(self.dict_path)
# open object_storage local path to dump object to
pfile = open(filepath, 'wb')
pickle.dump(data, pfile)
pfile.close()
self.dictionary = data
# memoize it
DICTIONARIES_LOADED[loc] = data
except (KeyError, TypeError, OSError) as error:
raise PhunspellError("Cannot write file {}".format(error))
def dictionary_loader(self, loc_list):
"""iterate locale list load dictionary for locale
meant to load dictionaries on init, not return them
from this call
"""
for loc in loc_list:
# XXX skip for now
# re.error: bad character range ű-ø at position 12
if loc in ["hu_HU"]:
continue
self.dictionary_store(loc)
def find_dict_dirpath(self, dictdir, loc_lang):
"""find directory for dictionary `loc_lang`
if found sets:
self.dict_path = dictionary directory
self.loc_lang = language locale
"""
# expecting "underscore" format. e.g. "en_US"
if os.path.isdir(dictdir):
aff_file = os.path.join(dictdir, "{}.aff".format(loc_lang))
# expecting "underscore" format. e.g. "en_US.aff"
if os.path.exists(aff_file):
self.dict_path = os.path.join(dictdir, loc_lang)
self.loc_lang = loc_lang
return True
else:
# underscore format ("en_US") not found
# fallback try lang dir "en"
loc_lang = loc_lang[0:2]
dictdir = os.path.join(dictdir, loc_lang)
aff_file = os.path.join(dictdir, "{}.aff".format(loc_lang))
if os.path.exists(aff_file):
self.dict_path = dictdir
self.loc_lang = loc_lang
return True
raise PhunspellError("phunspell, dictionary path not found")
def dict_dirpath(self, loc_lang):
"""find directory to dictionary for locale"""
try:
dirpath = os.path.dirname(os.path.realpath(__file__))
dictdir = os.path.join(
dirpath,
"data",
"dictionary",
DICTIONARIES[loc_lang.strip()][0],
)
self.find_dict_dirpath(dictdir, loc_lang)
except ValueError as error:
raise PhunspellError("phunspell, to list failed {}".format(error))
def to_list(self, sentance, lcase=True, filter_all=False):
"""takes string of words and
splits it into list removing punctuation
returns list of words
args: lcase : convert all chars to lower case (the default)
filter_all : strip all punctuation (set True)
strips all punctuation except hyphen and dash ['-]
(set False) [the default]
string.punctuation => !"#$%&'()*+, -./:;<=>?@[]^_`{|}~
en_* based languages only?
TODO: punctuation for other languages?
TODO:
remove non-breaking unicode char from string: \xa0
"The New\xa0Movie" => ['The', 'New\xa0Movie']
i.e. update to: "NFKD"?
return [unicodedata.normalize("NFKC", x.strip()) for x in words if len(x) and x not in ["'", '-']] # noqa E501
"""
try:
if lcase:
sentance = sentance.lower()
# allow hyphen and dash ['-]
punctuation = r"""!"#$%&()*+,./:;<=>?@[\]^_`{|}~"""
if filter_all:
punctuation = string.punctuation
words = sentance.translate(
str.maketrans('', '', punctuation)
).split(" ")
return [x.strip() for x in words if len(x) and x not in ["'", '-']]
except (FileNotFoundError, TypeError, ValueError) as error:
raise PhunspellError("phunspell, to list failed {}".format(error))
def lookup(self, word, loc=None):
"""takes word (string)
removes beginning and trailing whitespace
returns true if found in dictionary, false otherwise
"""
try:
if loc:
self.dictionary_load(loc)
return self.dictionary.lookup(word.strip())
except ValueError as error:
raise PhunspellError(
"phunspell, dictionary lookup failed {}".format(error)
)
def lookup_list(self, wordlist, loc=None):
"""takes list of words, returns list words not found
in dictionary
In: ["word", "another", "more", "programming"]
Out: ["programing"]
"""
try:
if loc:
self.dictionary_load(loc)
flagged = []
for word in wordlist:
if not self.dictionary.lookup(word.strip()):
flagged.append(word)
return flagged
except ValueError as error:
raise PhunspellError(
"phunspell, dictionary lookup_list failed {}".format(error)
)
def suggest(self, word, loc=None):
"""takes word (string)
removes beginning and trailing whitespace
returns suggested spelling if not found in dictionary
returns nothing if found in dictionary
"""
try:
if loc:
self.dictionary_load(loc)
return self.dictionary.suggest(word.strip())
except ValueError as error:
raise PhunspellError(
"phunspell, dictionary suggest failed {}".format(error)
)
def languages(self):
# ["Afrikaans", "Aragonese"...
return [x[1] for x in DICTIONARIES.values()]
def dictionaries(self):
# ["af_ZA", "an_ES", "ar"...
return [x for x in DICTIONARIES.keys()]
if __name__ == "__main__":
import sys
# TEST - local object expected but not exist,
# will be read from dictionary and dumped to local storage
# so it's there next time
# NOTE: feature is ONLY if user set storage_path is set
# pspell = Phunspell(object_storage="/tmp/d")
# # should load default en_US dictionary
# print(pspell.lookup("phunspell")) # False
# print(pspell.lookup("about")) # True
# # load russian dictionary - should create a dump file in /tmp/d
# print(pspell.lookup("phunspell", loc='ru_RU')) # False
# print(pspell.lookup("about", loc='ru_RU')) # False
# sys.exit()
pspell = Phunspell()
# should load default en_US dictionary
print(pspell.lookup("phunspell")) # False
print(pspell.lookup("about")) # True
# load russian dictionary - should NOTE create a dump file in /tmp/d
print(pspell.lookup("phunspell", loc='ru_RU')) # False
print(pspell.lookup("about", loc='ru_RU')) # False
sys.exit()
# create pickled dictionaries for all dictionaries
# import tempfile
# TEMPDIR = tempfile.gettempdir()
# storage_path = "/var/folders/vd/n_l9hxb57msdcc_33myhkqmw0000gn/T"
storage_path = "/tmp/foo"
# run once:
# pspell = PhunspellObjectStore(path=storage_path)
# import sys
# sys.exit()
dicts_words = {
"af_ZA": "voortgewoed",
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
"br_FR": "c'huñvderioù",
"de_DE": "schilffrei",
"en_GB": "indict",
"es_MX": "pianista",
"fr_FR": "zoomorphe",
}
# use cache if already seen
dicts_words_cached = {
"an_ES": "vengar",
"be_BY": "ідалапаклонніцкі",
"bg_BG": "удържехме",
}
# 16.41s user 0.48s system 99% cpu 16.986 total
pspell = Phunspell(object_storage=storage_path)
for loc in dicts_words.keys():
# 36.08s user 0.65s system 99% cpu 36.788 total
# pspell = Phunspell(loc)
print(pspell.lookup(dicts_words[loc], loc=loc))
for loc in dicts_words_cached.keys():
# 36.08s user 0.65s system 99% cpu 36.788 total
# pspell = Phunspell(loc)
print(pspell.lookup(dicts_words[loc], loc=loc))
# import sys
# sys.exit()
pspell = Phunspell(loc_lang="en_US")
print(pspell.lookup_list("Wonder Woman 1984"))
print(pspell.lookup_list(pspell.to_list("Wonder Woman 1984")))
pspell = Phunspell() # default "en_US"
# pspell = Phunspell("af_ZA")
print(pspell.lookup("phunspell")) # False
print(pspell.lookup("about")) # True
mispelled = pspell.lookup_list("Bill's TV is borken".split(" "))
print(mispelled) # ["borken"]
for suggestion in pspell.suggest("phunspell"):
print(suggestion)
# Hunspell
# spellbound
# unshapely
# speller
# principle
# principal
# exception
# pspell = Phunspell("cs_CZ")
# ["this", "is", "a", "list", "of", "words", "right", "here"]
print(
pspell.to_list(
"This !\"#$%&'()*+, -./:;<=>?@[]^_`{|}~ IS, A lISt? OF words!?, $%^( right here*"
)
)
print(pspell.languages())
print(pspell.dictionaries())
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,771 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__cs_CZ.py | import phunspell
import inspect
import unittest
# TODO
class TestCsCZ(unittest.TestCase):
pass
# pspell = phunspell.Phunspell('cs_CZ')
# def test_word_found(self):
# self.assertTrue(true)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,772 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__is.py | import phunspell
import inspect
import unittest
class TestIS(unittest.TestCase):
pspell = phunspell.Phunspell('is')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("vonbiðilsins"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = (
"freðfiski vonbiðilsins ráðherraráðs jafnsnart skólafélagi borken"
)
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,773 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__uk_UA.py | import phunspell
import inspect
import unittest
class TestUkUA(unittest.TestCase):
pspell = phunspell.Phunspell('uk_UA')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("фосфоричність"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = (
"фосфоричність провіщати практикуючи піретрум застібування borken"
)
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
def test_to_list(self):
words = "!\"#$%&'()*+, -./:;<=>?@[]^_`{|}~ бас-гітара бас-кларнет безособово-предикативний безумовно-рефлекторний $%^(*" # noqa E501
self.assertListEqual(
self.pspell.to_list(words),
[
"бас-гітара",
"бас-кларнет",
"безособово-предикативний",
"безумовно-рефлекторний",
],
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,774 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__te_IN.py | import phunspell
import inspect
import unittest
class TestTeIN(unittest.TestCase):
pspell = phunspell.Phunspell('te_IN')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("గుర్రుమని"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "గుర్రుమని స్యాట్ ప్రాజాపత్యము ప్రస్తుతి నూ borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,775 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__pl_PL.py | import phunspell
import inspect
import unittest
# TODO:
class TestPhunspellLangs(unittest.TestCase):
pass
# pspell = phunspell.Phunspell('pl_PL')
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,776 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__zu_ZA.py | import phunspell
import inspect
import unittest
# TODO
class TestZuAZ(unittest.TestCase):
pass
# pspell = phunspell.Phunspell('zu_ZA')
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,777 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test_object_store_expected.py | import os
import phunspell
import inspect
import unittest
import tempfile
TEMPDIR = tempfile.gettempdir()
class TestPhunspellObjectStoreExpected(unittest.TestCase):
loc = "ru_RU"
# use object path
pspell = phunspell.Phunspell(object_storage=TEMPDIR)
pspell.dictionary_loader([loc])
def tearDown(self):
try:
os.remove(os.path.join(TEMPDIR, self.loc))
except FileNotFoundError as error:
print(error)
def test_dict_obj_expected(self):
"""local object expected and used"""
# exists
filepath = os.path.join(TEMPDIR, self.loc)
self.assertTrue(os.path.exists(filepath))
self.assertTrue(self.pspell.lookup("наденутся", loc=self.loc))
self.assertFalse(self.pspell.lookup("phunspell", loc=self.loc))
# still exist
self.assertTrue(os.path.exists(filepath))
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,778 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__ro.py | import phunspell
import inspect
import unittest
class TestRO(unittest.TestCase):
pspell = phunspell.Phunspell('ro_RO')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("nesesizată"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "rezeflemisindu cvasiumanelor nesesizată Democrată borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,779 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__kmr_Latn.py | import phunspell
import inspect
import unittest
class TestKmrLatn(unittest.TestCase):
pspell = phunspell.Phunspell('kmr_Latn')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("dîrok"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "koletî kûr Botan dîrok hemû borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,780 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__el_GR.py | import phunspell
import inspect
import unittest
# TODO
class TestElGR(unittest.TestCase):
pspell = phunspell.Phunspell('el_GR')
def test_true(self):
self.assertTrue(True)
# def test_word_found(self):
# # self.assertTrue(self.pspell.lookup("åðéóðåýóáíôá"))
# self.assertTrue(self.pspell.lookup("Êëåñìüí"))
# def test_word_not_found(self):
# self.assertFalse(self.pspell.lookup("phunspell"))
# def test_lookup_list_return_not_found(self):
# words = "åðéóðåýóáíôá ðáñáäáñìÝíçò øçëïýôóéêïé áðïëõìÜíåé íïóïöïâßåò borken"
# self.assertListEqual(
# self.pspell.lookup_list(words.split(" ")), ["borken"]
# )
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,781 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__bn_BD.py | import phunspell
import inspect
import unittest
class TestBnBD(unittest.TestCase):
pspell = phunspell.Phunspell('bn_BD')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("জিয়ান"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "জিয়ান কপ্চাইয়াছিলেন ফাঁপছি হাসাইতে সাপ্টাইয়াছি borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,782 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__hi_IN.py | import phunspell
import inspect
import unittest
class TestHiIN(unittest.TestCase):
pspell = phunspell.Phunspell('hi_IN')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("एनटीटीडोकोमो"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "एनटीटीडोकोमो शिविरों यूपी भागता पहियों borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,783 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__sk_SK.py | import phunspell
import inspect
import unittest
class TestSkSK(unittest.TestCase):
pspell = phunspell.Phunspell('sk_SK')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("nezbožštite"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = (
"neodňateľne nezbožštite najtorzovitejších éra zaváňajúci borken"
)
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
def test_to_list(self):
words = "!\"#$%&'()*+, -./:;<=>?@[]^_`{|}~ Alma-ata bielo-červený bielo-čierny cyrilo-metodovský červeno-biely Česko-slovensko, $%^(*" # noqa E501
self.assertListEqual(
self.pspell.to_list(words),
[
"alma-ata",
"bielo-červený",
"bielo-čierny",
"cyrilo-metodovský",
"červeno-biely",
"česko-slovensko",
],
)
self.assertListEqual(
self.pspell.to_list(words, lcase=False),
[
"Alma-ata",
"bielo-červený",
"bielo-čierny",
"cyrilo-metodovský",
"červeno-biely",
"Česko-slovensko",
],
)
self.assertListEqual(
self.pspell.to_list(words, lcase=False, filter_all=True),
[
"Almaata",
"bieločervený",
"bieločierny",
"cyrilometodovský",
"červenobiely",
"Československo",
],
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,784 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__th_TH.py | import phunspell
import inspect
import unittest
class TestThTH(unittest.TestCase):
pspell = phunspell.Phunspell('th_TH')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("พริ้มเพรา"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "ประเทศชาติ พริ้มเพรา เปิดช่อง จำราญ อาร์เอสเอส borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,785 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__bg_BG.py | import phunspell
import inspect
import unittest
class TestBgBG(unittest.TestCase):
pspell = phunspell.Phunspell('bg_BG')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("удържехме"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "удържехме премляхме непретрупан пладнуване ралица borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,786 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__br_FR.py | import phunspell
import inspect
import unittest
class TestBrFR(unittest.TestCase):
pspell = phunspell.Phunspell('br_FR')
def test_word_found(self):
self.assertTrue(self.pspell.lookup("c'huñvderioù"))
def test_word_not_found(self):
self.assertFalse(self.pspell.lookup("phunspell"))
def test_lookup_list_return_not_found(self):
words = "biziataior c'huñvderioù fikerien farlotetoc'h simud borken"
self.assertListEqual(
self.pspell.lookup_list(words.split(" ")), ["borken"]
)
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,787 | dvwright/phunspell | refs/heads/main | /phunspell/tests/test__sl_SI.py | import phunspell
import inspect
import unittest
# TODO
class TestSlSL(unittest.TestCase):
pspell = phunspell.Phunspell('sl_SI')
def test_true(self):
self.assertTrue(True)
# def test_word_found(self):
# self.assertTrue(self.pspell.lookup("Podvr¹ièe"))
# def test_word_not_found(self):
# self.assertFalse(self.pspell.lookup("phunspell"))
# def test_lookup_list_return_not_found(self):
# words = "Bala¾ice Podvr¹ièe Mlaèevkah omikanosti napakicam borken"
# self.assertListEqual(
# self.pspell.lookup_list(words.split(" ")), ["borken"]
# )
if __name__ == "__main__":
unittest.main()
| {"/phunspell/tests/test__sr.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_no_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_phunspell.py": ["/phunspell/__init__.py"], "/phunspell/__init__.py": ["/phunspell/phunspell.py"], "/phunspell/tests/test__gug.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ca.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__no.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_multi_load_cache.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_not_exist.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ar.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ne_NP.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__cs_CZ.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__is.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__uk_UA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__te_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__pl_PL.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__zu_ZA.py": ["/phunspell/__init__.py"], "/phunspell/tests/test_object_store_expected.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__ro.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__kmr_Latn.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__el_GR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bn_BD.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__hi_IN.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sk_SK.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__th_TH.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__bg_BG.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__br_FR.py": ["/phunspell/__init__.py"], "/phunspell/tests/test__sl_SI.py": ["/phunspell/__init__.py"]} |
47,792 | bdomars/mortar-py | refs/heads/master | /mortarlib/gridref.py | import numpy as np
import re
from .errors import GridError, ParseError
BASE_GRID = 300.0
class GridRef(object):
'''
GridRef is a class to contain grid references in a meaningful way for calculations.
A GridRef is usually constructed using the classmethod GridRef.from_string().
'''
def __init__(self, letter, major, keypads=None):
'''Initializing a GridRef requires two paramaters with an optional thrid parameter.
Params:
* letter - A letter A-Z representing the x coordinate of a major grid cell
* major - An integer representing the y coordinate of a major grid cell
* keypads (optional) - A list of integers (1-9) for specifying sub grid cells
'''
self.letter = letter.upper()
self.major = int(major)
self._verify_major()
if keypads:
self.keypads = keypads
self._verify_keypads()
else:
self.keypads = []
self._vector = None
def __str__(self):
return "{}{}K{}".format(self.letter, self.major, ''.join([str(x) for x in self.keypads]))
def __repr__(self):
return "<GridRef: {}>".format(self)
def _verify_keypads(self):
for k in self.keypads:
if k < 1 or k > 9:
raise GridError("Keypads must be in the range 1-9")
def _verify_major(self):
if self.major < 1:
raise GridError("major coordinate cannot be < 1")
@property
def vector(self):
'''
A numpy vector from the origin to the center of the referenced grid cell.
'''
if not self._vector:
self._calculate()
return self._vector
def _kp_to_pos(self, kp):
x = (kp - 1) % 3 - 1
y = 1 - (kp - 1) / 3
return np.array([x, y], dtype='float64')
def _letter_num(self):
num = ord(self.letter) - 64
assert(num >= 1 and num <= 26)
return num
def _calculate(self):
base_x = self._letter_num() - 0.5
base_y = self.major - 0.5
basecoord = np.array([base_x, base_y]) * BASE_GRID
for n, kp in enumerate(self.keypads):
subcoord = self._kp_to_pos(kp)
subcoord *= BASE_GRID / (3**(n + 1))
basecoord = basecoord + subcoord
self._vector = basecoord
@classmethod
def from_string(cls, gridstr):
'''
Method for constructing GridRef's from strings.
Strings are at least on letter followed by one or two integers,
optionally one might specify any number of keypads and subkeypads
following the letter K. Like so:
* A1
* A12
* A1K12
* A10K12
'''
m = re.match(r'^(\w)(\d{1,2})(?:K(\d+))?$', gridstr)
if m:
letter = str(m.group(1))
major = int(m.group(2))
if m.group(3):
keypads = [int(x) for x in m.group(3) if x > 0]
else:
keypads = None
return cls(letter, major, keypads)
raise ParseError("Bad grid string")
| {"/mortarlib/__init__.py": ["/mortarlib/gridref.py"]} |
47,793 | bdomars/mortar-py | refs/heads/master | /grid.py | #!/usr/bin/env python2
import argparse
import math
import numpy as np
import numpy.linalg as la
from scipy import interpolate
from mortarlib import GridRef
from mortarlib.errors import Error
NORTH = np.array([0, -100])
ranges = np.arange(50, 1251, 50)
mils = np.array([
1579,
1558,
1538,
1517,
1496,
1475,
1453,
1431,
1409,
1387,
1364,
1341,
1317,
1292,
1267,
1240,
1212,
1183,
1152,
1118,
1081,
1039,
988,
918,
800
])
interp_mils = interpolate.interp1d(ranges, mils)
mils_spline = interpolate.splrep(ranges, mils)
def get_angle(to_target):
angle = math.degrees(np.arctan2(to_target[0], -to_target[1]))
if angle < 0:
return 360 + angle
else:
return angle
def get_elevation_lerp(dist):
return float(interp_mils(dist))
def get_elevation_spline(dist):
reachable = dist >= 50 and dist <= 1250
return reachable, float(interpolate.splev(dist, mils_spline))
def get_range(to_target):
return la.norm(to_target)
def calculate(base, target):
to_target = target - base
angle = get_angle(to_target)
distance = get_range(to_target)
reachable, elev = get_elevation_spline(distance)
print
print "Targeting solution"
print "-------------------------------"
print "Angle : {:>10.1f} degrees".format(angle)
print "Distance : {:>10.1f} meters".format(distance)
if reachable:
print "Elevation : {:>10.1f} mils".format(elev)
else:
print "Elevation : N/A"
print
print "Ready to fire!"
print
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('base')
parser.add_argument('target')
args = parser.parse_args()
try:
base = GridRef.from_string(args.base)
target = GridRef.from_string(args.target)
calculate(base.vector, target.vector)
except Error as e:
print "Something went wrong: {}".format(e)
| {"/mortarlib/__init__.py": ["/mortarlib/gridref.py"]} |
47,794 | bdomars/mortar-py | refs/heads/master | /mortarlib/__init__.py | from .gridref import GridRef # NOQA
| {"/mortarlib/__init__.py": ["/mortarlib/gridref.py"]} |
47,804 | Nuzhny007/clcommons | refs/heads/master | /tests/kernels.py | import pyopencl as cl
import pyopencl.array as clarray
from time import time
import numpy as np
import os
from median_of_medians import base_path
from common import *
from numpy import uint32, int32
common_lib_path = base_path
#ctx = cl.create_some_context()
platform = cl.get_platforms()[0]
devices = [device for device in platform.get_devices() if device.type == cl.device_type.GPU]
device = [devices[0]]
queue_properties = cl.command_queue_properties.PROFILING_ENABLE | cl.command_queue_properties.OUT_OF_ORDER_EXEC_MODE_ENABLE
ctx = cl.Context(devices)
queues = [cl.CommandQueue(ctx, device, properties=queue_properties) for device in devices]
#multicontext
#ctxs = [cl.Context(device) for device in devices]
#queues = [cl.CommandQueue(ctx, device, properties=queue_properties) for ctx, device in zip(ctxs, devices)]
queue = queues[0]
computeUnits = device.max_compute_units
device_wg_size = min([wavefront_wg_size(device) for device in devices])
default_wg_size = device_wg_size
is_amd_platform = all([is_device_amd(device) for device in devices])
is_nvidia_platform = all([is_device_nvidia(device) for device in devices])
def cl_opt_decorate(kop, CL_FLAGS, max_wg_size_used = None):
if is_amd_platform:
CL_FLAGS2 = '-D AMD_ARCH -D DEVICE_WAVEFRONT_SIZE={wavefront_size} '.format(wavefront_size=device_wg_size)
if max_wg_size_used is not None and np.prod(max_wg_size_used, dtype=np.uint32) <= device_wg_size:
CL_FLAGS2 = CL_FLAGS2 + '-D PROMISE_WG_IS_WAVEFRONT '
CL_FLAGS = CL_FLAGS2 + CL_FLAGS
elif is_nvidia_platform:
CL_FLAGS2 = '-D NVIDIA_ARCH -D DEVICE_WAVEFRONT_SIZE={wavefront_size} '.format(wavefront_size=device_wg_size)
#if max_wg_size_used is not None and np.prod(max_wg_size_used, dtype=np.uint32) <= device_wg_size:
# CL_FLAGS2 = CL_FLAGS2 + '-D PROMISE_WG_IS_WAVEFRONT '
#causes segfault in NvCliCompileBitcode - seems like internal compiler error
CL_FLAGS = CL_FLAGS2 + CL_FLAGS
if kop.debug == 2:
CL_FLAGS = '-D DEBUG -g -cl-opt-disable '+CL_FLAGS
elif kop.debug:
CL_FLAGS = '-D DEBUG '+CL_FLAGS
return CL_FLAGS
def green(image):
return image[:, :, 1].copy()
| {"/tests/platform.py": ["/tests/common.py"]} |
47,805 | Nuzhny007/clcommons | refs/heads/master | /tests/platform.py | from .common import *
platform = cl.get_platforms()[0]
devices = [device for device in platform.get_devices() if device.type == cl.device_type.GPU]
device = [devices[0]]
queue_properties = cl.command_queue_properties.PROFILING_ENABLE
ctx = cl.Context(devices)
queues = [cl.CommandQueue(ctx, device, properties=queue_properties) for device in devices]
queue = queues[0]
computeUnits = device.max_compute_units
device_wg_size = min([wavefront_wg_size(device) for device in devices])
default_wg_size = device_wg_size
is_amd_platform = all([is_device_amd(device) for device in devices])
is_nvidia_platform = all([is_device_nvidia(device) for device in devices])
def cl_opt_decorate(debug, CL_FLAGS, max_wg_size_used = None):
if is_amd_platform:
CL_FLAGS2 = '-D AMD_ARCH -D DEVICE_WAVEFRONT_SIZE={wavefront_size} '.format(wavefront_size=device_wg_size)
if max_wg_size_used is not None and np.prod(max_wg_size_used, dtype=np.uint32) <= device_wg_size:
CL_FLAGS2 = CL_FLAGS2 + '-D PROMISE_WG_IS_WAVEFRONT '
CL_FLAGS = CL_FLAGS2 + CL_FLAGS
if debug == 2:
CL_FLAGS = '-D DEBUG -g -cl-opt-disable '+CL_FLAGS
elif debug:
CL_FLAGS = '-D DEBUG '+CL_FLAGS
return CL_FLAGS
| {"/tests/platform.py": ["/tests/common.py"]} |
47,806 | Nuzhny007/clcommons | refs/heads/master | /tests/unit_tests.py | import unittest
from .common import *
from .platform import *
def prefix_sum_test(input_data, kernel, dtype, exclusive):
#print 'wg_size: %r'%(wg_size,)
wg_size = len(input_data)
ref_result = prefix_sum(input_data, exclusive, dtype=dtype)
src_buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, wg_size*dtype.itemsize)
dst_buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, wg_size*dtype.itemsize)
cl_result = np.zeros(wg_size, dtype = dtype)
cl.enqueue_copy(queue, src_buf, input_data, is_blocking = True)
event = kernel(queue, (1,), (wg_size,), src_buf, dst_buf, g_times_l=True)
event.wait()
cl.enqueue_copy(queue, cl_result, dst_buf, is_blocking = True)
diffs = np.where(cl_result != ref_result)[0]
if len(diffs) > 0:
print 'reference:'
print ref_result
print 'cl_result:'
print cl_result
from IPython import embed; embed()
#print 'wg_size %d different starting at %d, span of %d'%(wg_size, diffs[0], len(tdata) - diffs[0] - 1)
return (wg_size, diffs[0], len(cl_result) - diffs[0])
else:
return (wg_size, 0, 0)
def reduce_test(input_data, kernel, reduction_fun, dtype):
#print 'wg_size: %r'%(wg_size,)
wg_size = len(input_data)
ref_result = None
if reduction_fun is np.sum:
ref_result = reduction_fun(input_data, dtype=dtype)
else:
ref_result = reduction_fun(input_data)
src_buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, wg_size*dtype.itemsize)
dst_buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE, wg_size*dtype.itemsize)
cl_result = np.zeros(1, dtype = dtype)
cl.enqueue_copy(queue, src_buf, input_data, is_blocking = True)
event = kernel(queue, (1,), (wg_size,), src_buf, dst_buf, g_times_l=True)
event.wait()
cl.enqueue_copy(queue, cl_result, dst_buf, is_blocking = True)
return (wg_size, ref_result != cl_result, ref_result, cl_result)
def load_tests(loader, tests, pattern):
class WorkGroupTestCases(unittest.TestCase):
def __init__(self, method, dtype, program, debug = False):
self.dtype = dtype
self.debug = debug
self.program = program
self.method = method
unittest.TestCase.__init__(self, method)
def gen_input_random(self, wg_size):
np.random.seed(24)
input_data = np.array([np.random.randint(0, 1+1) for x in range(wg_size)], self.dtype)
return input_data
def gen_input_zeros(self, wg_size):
return np.zeros(wg_size, self.dtype)
def gen_input_ones(self, wg_size):
return np.ones(wg_size, self.dtype)
def gen_reduction_input(self, wg_size, reduction_fun):
dtype = self.dtype
np.random.seed(24)
denom = (1<<(dtype.itemsize*8 - 1))
min_value, max_value = np.iinfo(dtype).min/denom, (np.iinfo(dtype).max+1)/denom
input_data = None
if reduction_fun is np.sum and dtype==np.uint8:
input_data = np.array([np.random.randint(0, 2) for x in range(wg_size)], dtype)
if reduction_fun is np.sum and dtype==np.int8:
input_data = np.array([np.random.randint(-2, 3) for x in range(wg_size)], dtype)
else:
input_data = np.array([np.random.randint(min_value, max_value) for x in range(wg_size)], dtype)
return input_data
def test_inclusive_prefix_sum(self):
kernel = self.program.wg_inclusive_sum
sum_tests_rand = np.array([prefix_sum_test(self.gen_input_random(x), kernel, self.dtype, 0) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_rand[:, 2] == 0))
sum_tests_zeros = np.array([prefix_sum_test(self.gen_input_zeros(x), kernel, self.dtype, 0) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_zeros[:, 2] == 0))
sum_tests_ones = np.array([prefix_sum_test(self.gen_input_ones(x), kernel, self.dtype, 0) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_ones[:, 2] == 0))
def test_exclusive_prefix_sum(self):
kernel = self.program.wg_exclusive_sum
sum_tests_rand = np.array([prefix_sum_test(self.gen_input_random(x), kernel, self.dtype, 1) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_rand[:, 2] == 0))
sum_tests_zeros = np.array([prefix_sum_test(self.gen_input_zeros(x), kernel, self.dtype, 1) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_zeros[:, 2] == 0))
sum_tests_ones = np.array([prefix_sum_test(self.gen_input_ones(x), kernel, self.dtype, 1) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(sum_tests_ones[:, 2] == 0))
def test_reduce_min(self):
kernel = self.program.wg_reduce_min
reduce_tests_rand = np.array([reduce_test(self.gen_reduction_input(x, np.min), kernel, np.min, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_rand[:, 1] == 0))
reduce_tests_zeros = np.array([reduce_test(self.gen_input_zeros(x), kernel, np.min, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_zeros[:, 1] == 0))
reduce_tests_ones = np.array([reduce_test(self.gen_input_ones(x), kernel, np.min, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_ones[:, 1] == 0))
def test_reduce_max(self):
kernel = self.program.wg_reduce_max
reduce_tests_rand = np.array([reduce_test(self.gen_reduction_input(x, np.max), kernel, np.max, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_rand[:, 1] == 0))
reduce_tests_zeros = np.array([reduce_test(self.gen_input_zeros(x), kernel, np.max, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_zeros[:, 1] == 0))
reduce_tests_ones = np.array([reduce_test(self.gen_input_ones(x), kernel, np.max, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_ones[:, 1] == 0))
def test_reduce_sum(self):
kernel = self.program.wg_reduce_sum
reduce_tests_rand = np.array([reduce_test(self.gen_input_random(x), kernel, np.sum, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_rand[:, 1] == 0))
reduce_tests_zeros = np.array([reduce_test(self.gen_input_zeros(x), kernel, np.sum, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_zeros[:, 1] == 0))
reduce_tests_ones = np.array([reduce_test(self.gen_input_ones(x), kernel, np.sum, self.dtype) for x in range(1, 257)], self.dtype)
self.assertTrue(np.all(reduce_tests_ones[:, 1] == 0))
def __str__(self):
return 'WorkGroup %r dtype: %r'%(self.method, self.dtype)
suite = unittest.TestSuite()
dtypes = [np.uint8, np.int8, np.int16, np.uint16, np.int32, np.uint32]
methods = ['test_inclusive_prefix_sum', 'test_exclusive_prefix_sum', 'test_reduce_min', 'test_reduce_max', 'test_reduce_sum']
debug = True
for dtype in map(np.dtype, dtypes):
ItemT = type_mapper(dtype)
LDSItemT = 'uint'
if ItemT[0] != 'u':
LDSItemT = 'int'
iinfo = np.iinfo(dtype)
KERNEL_FLAGS = "-D ITEMT={ItemT} -D LDSITEMT={LDSItemT} -D TMIN={TMIN} -D TMAX={TMAX}".format(ItemT=ItemT, LDSItemT=LDSItemT, TMIN=iinfo.min, TMAX=iinfo.max)
CL_FLAGS = "-I %s -cl-std=CL1.2 %s" %(common_lib_path, KERNEL_FLAGS)
CL_FLAGS = cl_opt_decorate(debug, CL_FLAGS)
print '%r compile flags: %s'%(ItemT, CL_FLAGS)
CL_SOURCE = file(os.path.join(base_path, 'test_work_group_kernels.cl'), 'r').read()
program = cl.Program(ctx, CL_SOURCE).build(options=CL_FLAGS)
for method in methods:
suite.addTest(WorkGroupTestCases(method, dtype, program))
return suite
| {"/tests/platform.py": ["/tests/common.py"]} |
47,807 | Nuzhny007/clcommons | refs/heads/master | /tests/common.py | import unittest
import os
from os.path import join as pjoin
import pyopencl as cl
import pyopencl.array as clarray
import numpy as np
from numpy import uint32, int32
common_lib_path = os.path.normpath(pjoin(os.path.dirname(os.path.realpath(__file__)), '..', 'include'))
base_path = os.path.dirname(os.path.realpath(__file__))
def prefix_sum(counts, inclusive_or_exclusive = 0, dtype=None):
counts = np.asarray(counts, dtype=dtype)
sums = np.cumsum(counts, dtype=dtype)
if inclusive_or_exclusive == 1:
_sums = np.empty_like(sums)
_sums[0] = 0
_sums[1:] = sums[0:-1]
sums = _sums
return sums
def inclusive_prefix_sum(counts, dtype=None):
return prefix_sum(counts, 0, dtype=dtype)
def exclusive_prefix_sum(counts, dtype=None):
return prefix_sum(counts, 1, dtype=dtype)
def prefix_product(counts, inclusive_or_exclusive = 0, dtype=None):
counts = np.asarray(counts, dtype=dtype)
products = np.cumprod(counts, dtype=dtype)
if inclusive_or_exclusive == 1:
_products = np.empty_like(products)
_products[0] = 1
_products[1:] = products[0:-1]
products = _products
return products
def inclusive_prefix_product(counts, dtype=None):
return prefix_product(counts, 0, dtype=dtype)
def exclusive_prefix_product(counts, dtype=None):
return prefix_product(counts, 1, dtype=dtype)
def type_mapper(x):
if x == np.int32:
return 'int'
if x == np.uint32:
return 'uint'
if x == np.int8:
return 'char'
if x == np.uint8:
return 'uchar'
if x == np.int16:
return 'short'
if x == np.uint16:
return 'ushort'
if x == np.int64:
return 'long'
if x == np.uint64:
return 'ulong'
if x == np.float32:
return 'float'
if x == np.float64:
return 'double'
return None
def dtype_of(x):
if type(x) is type:
x = np.dtype(x)
return x
def is_platform_amd(platform):
return platform.vendor == 'Advanced Micro Devices, Inc.'
def is_platform_nvidia(platform):
return platform.vendor == 'NVIDIA Corporation'
def is_device_amd(device):
return device.vendor == 'Advanced Micro Devices, Inc.'
def is_device_nvidia(device):
return device.vendor == 'NVIDIA Corporation'
def is_device_intel(device):
return device.vendor == 'GenuineIntel'
def wavefront_wg_size(device):
if is_device_amd(device) and device.type == cl.device_type.GPU:
return device.wavefront_width_amd
elif is_device_nvidia(device) and device.type == cl.device_type.GPU:
return device.warp_size_nv
else:
return device.max_work_group_size
def device_workgroups(device):
if is_device_amd(device):
return device.simd_per_compute_unit_amd * device.max_compute_units
else:
return device.max_compute_units
| {"/tests/platform.py": ["/tests/common.py"]} |
47,809 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /estoque/__init__.py | # arquivo obrigatorio para um package
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,810 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /estoque/produto.py | def cadastrar_produto(produto):
nome = produto['nome']
print(f'Produto: {nome} cadastrado')
def remover_produto():
print('produto removido')
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,811 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /main.py | """
Um módulo é um arquivo contendo definições
e instruções Python que podem ser importados para
utilização de seus recursos.
https://docs.python.org/pt-br/3/tutorial/modules.html
"""
# from operacoes import *
# import operacoes from operacoes import * desaconselhavel utilizar importe apenas o que for utilizar pois se
# importar tudo sera rodado todo código importado from operacoes import somar, subtrair, multiplicar, nome_empresa
#
# print(multiplicar(1, 3))
# print(somar(1, 3))
# print(subtrair(1, 3))
# print(nome_empresa)
# print(__name__)
# # import estoque.produto
# from estoque.produto import cadastrar_produto
# produto = {'nome': 'Notebook', 'preco': 1200}
# cadastrar_produto(produto)
# from estoque.inventario import atualizar_quantidade_produto
# produto = {'nome': 'Notebook', 'quantidade': 100}
# atualizar_quantidade_produto(produto)
from estoque.utilidades.moeda import formatar_real
lista_produtos = [
{'nome': 'Notebook', 'preco': 1200},
{'nome': 'Xbox', 'preco': 3500.80},
{'nome': 'Fone de Ouvido', 'preco': 99.90}
]
for produto in lista_produtos:
nome = produto['nome']
preco = formatar_real(produto['preco'])
print(f'produto: {nome}, preco:{preco}')
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,812 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /estoque/inventario.py | def atualizar_quantidade_produto(produto):
nome = produto['nome']
qtd = produto['quantidade']
print(f'produto: {nome}, unidades: {qtd}')
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,813 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /estoque/utilidades/moeda.py | def formatar_real(preco):
return f'R$ {preco:.2f}'.replace('.',',')
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,814 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /modulos-padroes.py | """
Um módulo é im arquivo contendo definições
e instruções Python que podem ser importados para
utilização de seus recursos
Permitem expandir as funcionalidades
da linguagem além dos recursos padrões
1) É possível utilizar módulos padrões do Python
2) É possível instalar módulos
https://docs.python.org/pt-br/3/py-modindex.html
"""
# import random
from random import randint # ctrl + space mostra todos itens dentro do import do random
# Caso clique com o botão direiro no random selecionat go to e implementação
# voce cnseguirá ver a implementação do modulo random
# print(random.randint(1, 10))
print(randint(1, 10))
# from functools import reduce
# from datetime import datetime as date #date é um apelido
# print(date.now())
# from math import sqrt
# print(sqrt(64))
"""
PIP
pip é um sistema de gerenciamento de pacotes em python
pip3 install --upgrade pip
pip install nome-pacote
pip uninstall nome-pacote
"""
import pymysql
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
47,815 | GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes | refs/heads/main | /operacoes.py | nome_empresa = 'mirror-sistemas'
def somar(n1, n2):
return n1 + n2
def multiplicar(n1, n2):
return n1 * n2
def subtrair(n1, n2):
return n1 - n2
print(__name__) # Caso rode este codigo aqui aparecerá __main__ pois esse quando executado diretamente é o arquivo
# principal!
if __name__ == '__main__':
print('Executando como módulo principal')
print('Módulos operacoes executado')
| {"/main.py": ["/estoque/utilidades/moeda.py"]} |
48,035 | DeanDro/Battleship | refs/heads/main | /player.py |
class Player:
"""This class represents a player in the game"""
def __init__(self, name):
"""The class creates a Player for the game. It takes the username for the player."""
self._username = name
def get_username(self):
"""Returns the name of the player"""
return self._username
| {"/game.py": ["/game_logic.py"], "/main.py": ["/game.py"], "/game_logic.py": ["/player.py"]} |
48,036 | DeanDro/Battleship | refs/heads/main | /game.py | """This class starts the battleship game and works as presentation layer"""
import pygame
import sys
from game_logic import GameLogic
class BattleShip:
"""Represents a battleship game"""
def __init__(self, username):
"""Initiates the game and takes as a parameter the users name"""
pygame.init()
self._screen = pygame.display.set_mode((1380, 800))
self._screen.fill((54, 48, 33))
self._username = username
self._board_font = pygame.font.SysFont('Arial', 15, bold=pygame.font.Font.bold)
# What stage of the game we are
self._game_status = 'PRE-SETUP'
# Board setup files
self._running = True
# Creates map and board graphics
self._create_sea_map()
self._vertical_horizontal_lines()
self._game_logic = GameLogic(self._username)
self.mark_active_boats([1100, 30])
self.mark_active_boats([1100, 200], 'human')
self._game_logic.setup_game()
while self._running:
for event in pygame.event.get():
# Populate ai boat dictionary
self._event_handler(event)
pygame.display.update()
def _event_handler(self, event):
"""Manages game events"""
if event.type == pygame.QUIT:
self._running = False
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self._game_status == 'PRE-SETUP':
self._setup_button('Rotate')
self._game_status = 'SETUP'
if self._game_status == 'SETUP':
self._setup_button('Rotate')
self._listen_for_clicks(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
elif self._game_status == 'START':
self._create_sea_map()
self._vertical_horizontal_lines()
self._game_status = 'PLAY'
pygame.draw.rect(self._screen, (54, 48, 33), pygame.Rect(1100, 550, 100, 50))
self._setup_button(str(self._game_logic.get_current_player()), 100, 50, (54, 48, 33))
pygame.display.update()
elif self._game_status == 'PLAY':
self.mark_active_boats([1100, 30])
self.mark_active_boats([1100, 200], 'human')
self._setup_button(str(self._game_logic.get_current_player()), 100, 50, (54, 48, 33))
if self._game_logic.get_current_player() == 'human':
self._listen_for_clicks(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
self._load_shots_on_map('human')
else:
self._game_logic.get_ai_response()
self._check_for_winner()
elif self._game_status == 'END':
self._show_winner()
def _create_sea_map(self):
"""It creates the sea map for the ships"""
pygame.draw.rect(self._screen, (126, 5, 247), pygame.Rect(50, 50, 1000, 600))
pygame.display.flip()
def _vertical_horizontal_lines(self):
"""Draws vertical and horizontal white lines on sea board"""
for i in range(1, 21):
pygame.draw.rect(self._screen, (255, 255, 255), pygame.Rect(i*50, 50, 1, 600))
for j in range(1, 13):
pygame.draw.rect(self._screen, (255, 255, 255), pygame.Rect(50, j*50, 1000, 1))
def _setup_button(self, message, x_size=100, y_size=50, color=(235, 94, 52)):
"""Adding the rotation button on the board"""
pygame.draw.rect(self._screen, color, pygame.Rect(1100, 550, x_size, y_size))
text = self._add_text_on_screen(message, 25)
self._screen.blit(text, (1110, 560))
pygame.display.update()
def _add_text_on_screen(self, text, font_size, color=(255, 255, 255)):
"""Takes as a parameter a text and returns the text ready to attach on screen"""
font = pygame.font.Font('freesansbold.ttf', font_size)
text = font.render(text, True, color)
return text
def mark_active_boats(self, start_pos, player='ai'):
"""It marks active or inactive an enemy vessel if it gets destroyed"""
vessels = self._game_logic.get_vessels_location()[player]
boats_list = self._add_text_on_screen(player+' Boats', 20, (235, 0, 0))
self._screen.blit(boats_list, (start_pos[0], start_pos[1]))
coord_x_y = [start_pos[0], start_pos[1]+30]
for vessel in vessels:
text = self._add_text_on_screen(vessel, 15)
if vessels[vessel] == ['destroyed']:
pygame.draw.rect(self._screen, (54, 48, 33), pygame.Rect(coord_x_y[0]+60, coord_x_y[1], 100, 20))
boat_status = self._add_text_on_screen('Destroyed', 15, (235, 0, 0))
else:
boat_status = self._add_text_on_screen('Active', 15, (15, 184, 68))
self._screen.blit(text, (coord_x_y[0], coord_x_y[1]))
self._screen.blit(boat_status, (coord_x_y[0]+70, coord_x_y[1]))
coord_x_y[1] += 30
def _convert_click_to_box(self, coordx, coordy):
"""This is a helper method. Takes coords from click and returns the actual box coordinates on map"""
if 50 < coordx < 1050 and 50 < coordy < 650:
x_pos = (coordx//50) * 50
y_pos = (coordy//50) * 50
return x_pos, y_pos
else:
return None
def _draw_color_box(self, x, y, color, boat_size=1):
"""It draws a color box to represent a ship or shot on the map. Takes the color and coordinates as parameter"""
if boat_size != 1 and self._game_logic.get_direction() == 'horizontal':
pygame.draw.rect(self._screen, color, pygame.Rect(x, y, 50*boat_size, 50))
elif boat_size != 1 and self._game_logic.get_direction() != 'horizontal':
pygame.draw.rect(self._screen, color, pygame.Rect(x, y, 50, 50*boat_size))
else:
pygame.draw.rect(self._screen, color, pygame.Rect(x, y, 50, 50))
def _draw_ship_on_map(self, coordx, coordy, ship_type, ship_size):
"""
It draws the ship on the map. Takes coordinates x, y, ship type and ship size
"""
# Convert coordinates to specific box
pos = self._convert_click_to_box(coordx, coordy)
if self._game_logic.get_direction() == 'horizontal' and 50<=pos[0]+(ship_size * 50)<=1050 and 50<=pos[1]<=650:
# Add coordinates in dictionary for players
self._game_logic._populate_vessel_dictionary(pos[0], pos[1], ship_type, 'human')
# Add box on the map
self._draw_color_box(pos[0], pos[1], (109, 117, 112), ship_size)
elif self._game_logic.get_direction() == 'vertical' and 50<=pos[0]<=1050 and 50<=pos[1]+(ship_size*50)<=650:
# Add coordinates in dictionary for players
self._game_logic._populate_vessel_dictionary(pos[0], pos[1], ship_type, 'human')
# Add box on the map
self._draw_color_box(pos[0], pos[1], (109, 117, 112), ship_size)
def _add_ships_on_map(self, coordx, coordy):
"""This method puts each boat on the map and populates the players dictionary for human"""
boat_size = {'vessel': 5, 'frigate': 4, 'galleon': 3, 'brig': 2}
if self._game_logic.get_vessels_location()['human']['vessel'] == []:
self._draw_ship_on_map(coordx, coordy, 'vessel', 5)
elif self._game_logic.get_vessels_location()['human']['frigate'] == []:
self._draw_ship_on_map(coordx, coordy, 'frigate', 4)
elif self._game_logic.get_vessels_location()['human']['galleon'] == []:
self._draw_ship_on_map(coordx, coordy, 'galleon', 3)
else:
self._draw_ship_on_map(coordx, coordy, 'brig', 2)
self._game_status = 'START'
def _listen_for_clicks(self, coordx, coordy):
"""
It takes two parameters coordinates x and y and activates the proper function
"""
if 50 < coordx < 1050 and 50 < coordy < 650 and (self._game_status == 'SETUP' or self._game_status == 'PRE-SETUP'):
self._add_ships_on_map(coordx, coordy)
elif 1100 < coordx < 1200 and 550 < coordy < 600 and (self._game_status == 'SETUP' or self._game_status == 'PRE-SETUP'):
self._game_logic.set_direction()
elif 50 < coordx < 1050 and 50 < coordy < 650 and self._game_status == 'PLAY':
self._load_shots_on_map() # Load previous shots for current player
# It doesn't capture players in the right order!!!
self._draw_shots_on_map(coordx, coordy) # Player automatically changes
self._load_shots_on_map('opponent') # Reload map for the same player to show new shot
self._load_shots_on_map() # Load next players shots so he can make a new
def _draw_shots_on_map(self, coordx, coordy):
"""
It marks hit or miss shots on enemy map. It checks if shot has already been fired.
"""
result = self._game_logic.get_cannon_shots(coordx, coordy)
boxes = self._convert_click_to_box(result[1], result[2])
shots = self._game_logic.get_shots_fired()[self._game_logic.get_current_player()]
shot_fired = False
for shot in shots:
if shots[shot][0] == (boxes[0], boxes[1]):
shot_fired = True
if not shot_fired:
if result[0]:
self._draw_color_box(boxes[0], boxes[1], (255, 0, 0))
else:
self._draw_color_box(boxes[0], boxes[1], (182, 191, 207))
def _show_game_icon(self, message):
"""
Shows a message in the middle of the screen
"""
pygame.display.set_caption(message)
font = pygame.font.Font(pygame.font.get_default_font(), 35)
text = font.render(message, True, (255, 255, 255), (255, 0, 0))
self._screen.blit(text, (450, 700))
def _load_shots_on_map(self, player='current'):
"""
Loads all shots fired from current player on the map
"""
if player == 'current':
shots_dict = self._game_logic.get_shots_fired()[self._game_logic.get_current_player()]
else:
shots_dict = self._game_logic.get_shots_fired()[self._game_logic.get_opponent()]
self._create_sea_map()
self._vertical_horizontal_lines()
for key in shots_dict:
box_x = shots_dict[key][0][0]
box_y = shots_dict[key][0][1]
self._draw_color_box(box_x, box_y, shots_dict[key][1])
def _check_for_winner(self):
"""
If some already won, no more clicks available and game status changes to END
"""
winner = self._game_logic.get_winner()
if winner[0]:
self._game_status = 'END'
def _show_winner(self):
"""Shows on screen the winner"""
winner = self._game_logic.get_winner()
winner = self._add_text_on_screen(winner[1]+' WON!', 50, (102, 204, 0))
self._screen.blit(winner, (400, 300))
| {"/game.py": ["/game_logic.py"], "/main.py": ["/game.py"], "/game_logic.py": ["/player.py"]} |
48,037 | DeanDro/Battleship | refs/heads/main | /main.py | # Author: Konstantinos Drosos
# Date: 5/15/2021
# Description: A battleship game
import tkinter as tk
from tkinter import *
from game import BattleShip
import os
class Application(tk.Frame):
"""This class represents the starting page of the game"""
def __init__(self, master, image):
"""Initializes application and gets tk.root as parameter"""
super().__init__(master)
self._master = master
self._background_image = image
self._username = tk.StringVar()
self._create_widget()
def _create_widget(self):
"""Creates an input for username"""
name_label = tk.Label(self._master, text="Username", font=('Arial', 20), fg='#ffffff')
name_label.configure(bg="#524A35")
input_box = tk.Entry(self._master, textvariable=self._username, font=('Arial', 10))
name_label.grid(column=0, row=0, pady=20)
input_box.grid(column=1, row=0, pady=20)
# Buttons
game_button = tk.Button(self._master, text='Start Game', font=('Arial', 15), command=self._start_game)
cancel_button = tk.Button(self._master, text='Cancel', font=('Arial', 15), command=self._cancel_game)
game_button.grid(column=0, row=1, padx=40, pady=40)
cancel_button.grid(column=1, row=1, padx=40, pady=40)
def _start_game(self):
"""It starts the game"""
user = self._username.get()
battleship_game = BattleShip(user)
def _cancel_game(self):
"""Cancels game"""
self.master.quit()
def _add_background_image(self):
"""
Returns a photo image file for the background image
"""
base_folder = os.path.dirname(__file__)
image_path = os.path.join(base_folder, self._background_image)
photo = tk.PhotoImage(file=image_path)
photo_label = tk.Label(self._master, image=photo)
photo_label.place(x=0, y=0, relwidth=1, relheight=1)
root = tk.Tk()
root.geometry('400x400')
root.configure(bg='#524A35')
battleship = Application(root, 'boat_background.png')
battleship.mainloop()
| {"/game.py": ["/game_logic.py"], "/main.py": ["/game.py"], "/game_logic.py": ["/player.py"]} |
48,038 | DeanDro/Battleship | refs/heads/main | /game_logic.py | # In this class we will hold all decisions made for AI in the game as well as respond to user moves
import random
from player import Player
class GameLogic:
"""
This class manages all decisions made by AI and response to user interaction.
"""
def __init__(self, human_name):
"""This class will initialize a battleship game. Takes as an argument the username given"""
# We add some dam data for testing the app
self._vessels_location = {'human': {'vessel': [],
'frigate': [],
'galleon': [],
'brig': []
},
'ai': {'vessel': [],
'frigate': [],
'galleon': [],
'brig': []
}
}
self._shots_fired = {'human': {}, 'ai': {}}
self._human = Player(human_name)
self.direction = 'horizontal'
self._ai = Player('ai')
self._number_of_shoots = 0
self._current_player = 'human'
# Variable to store the size of each boat
self._ai_targets = {'vessel': 5, 'frigate': 4, 'galleon': 3, 'brig': 2}
# Variable to store if there is an active target for ai
self._active_target = {'active': False, 'coord': None}
def get_vessels_location(self):
"""Method to return the dictionary with the vessels locations."""
return self._vessels_location
def get_shots_fired(self):
"""Method to return the dictionary with the shots fired"""
return self._shots_fired
def get_direction(self):
"""It returns the direction for placing the boat"""
return self.direction
def set_direction(self):
"""Changes direction from vertical to horizontal and vice versa"""
if self.direction == 'horizontal':
self.direction = 'vertical'
else:
self.direction = 'horizontal'
def get_number_shots(self):
"""Returns the number of shots fired"""
return self._number_of_shoots
def _update_player(self):
"""Updates players turn"""
if self._current_player == 'human':
self._current_player = 'ai'
else:
self._current_player = 'human'
def get_current_player(self):
"""Return players turn"""
return self._current_player
def get_opponent(self):
"""Get the opponent player"""
if self._current_player == 'human':
return 'ai'
return 'human'
def get_winner(self):
"""
Returns tuple with true and winner's name if there is a winner already otherwise returns False, None
"""
return self._winner()
def get_cannon_shots(self, coordx, coordy):
"""
This method takes as parameters the target player, the player that shot, the x and y coordinates and returns
a list with true if it hit an enemy boat or false if it was a miss and the x, y coordinates
"""
# Each box in the board is 50x50. By dividing coordx with 50 we will get the box before the one the user
# clicked on. Multiplying by 50 will give us the starting point x of the box the user clicked. Adding
# 50 will give us the end point of that box. Similar for y. Also we add the color of the box in the
# list that goes in the dictionary with shots fired to indicated if it was hit or miss.
if not self._winner()[0]:
box_x = (coordx // 50) * 50 + 1
box_y = (coordy // 50) * 50 + 1
# Check if the player has already shot this box
if (box_x, box_y) not in self._shots_fired[self._current_player]:
target_player = self.get_opponent()
for value in self._vessels_location[target_player]:
for loc in self._vessels_location[target_player][value]:
# Check shot hit vessel
if loc == (box_x, box_y):
self._shots_fired[self._current_player][(box_x, box_y)] = [(box_x, box_y), (255, 0, 0)]
self._update_vessels(box_x, box_y, target_player, value)
# Check boat destroyed
if self._check_boat_destroyed(target_player, value):
self._vessels_location[target_player][value] = ['destroyed']
self._update_player()
return [True, box_x, box_y]
# The player didn't hit an enemy boat
self._shots_fired[self._current_player][(box_x, box_y)] = [(box_x, box_y), (182, 191, 207)]
self._update_player()
return [False, box_x, box_y]
return [False, box_x, box_y]
def _check_boat_destroyed(self, target_player, vessel):
"""
Helper method to check if a boat has been destroyed. Takes as parameters target player and vessel and returns
True if the vessel was destroyed
"""
destroyed = True
for coord in self._vessels_location[target_player][vessel]:
if not coord == ['hit']:
destroyed = False
return destroyed
def _populate_vessel_dictionary(self, x_point, y_point, ship_type, players_turn):
"""
This method takes from the user where the boats are placed in the map and populates the dictionary with their
coordinates
"""
# length for each boat
vessel_size = {'vessel': 5, 'frigate': 4, 'galleon': 3, 'brig': 2}
# Adjust x, y coord for boat
x_coord = (x_point // 50) * 50 + 1
y_coord = (y_point // 50) * 50 + 1
if self.direction == 'horizontal':
end_point = x_coord + vessel_size[ship_type] * 50
for i in range(x_coord, end_point, 50):
self._vessels_location[players_turn][ship_type].append((i, y_coord))
else:
end_point = y_coord + vessel_size[ship_type] * 50
for i in range(y_coord, end_point, 50):
self._vessels_location[players_turn][ship_type].append((x_coord, i))
def _winner(self):
"""Checks if someone won the game. Returns a tuple with boolean and winner's name"""
for player in self._vessels_location:
end_of_game = True
for ship_type in self._vessels_location[player]:
if self._vessels_location[player][ship_type] != ['destroyed']:
end_of_game = False
if end_of_game:
return end_of_game, player
return False, None
def _fill_coordinates_tracker(self, coord, list_coordinates, ship_size):
"""Adds poxes to the coordinates tracker to avoid overlap"""
for i in range(0, ship_size):
point = coord + (50 * i)
list_coordinates.append(point)
def _possible_coordinates(self):
"""Return a set of all possible coordinates"""
set_values = set()
# Because we count coordinates from 51 growing by 50, we will start possible options from 51
for i in range(51, 1050, 50):
for j in range(51, 650, 50):
set_values.add((i, j))
return set_values
def _ai_battle_ships(self):
"""Populates battle ships for ai in random locations"""
vessel_size = {'vessel': 5, 'frigate': 4, 'galleon': 3, 'brig': 2}
available_coord = self._possible_coordinates()
for ship in self._vessels_location['ai']:
orientation = random.randint(1, 2)
if orientation == 1:
x_max = 1050 - (vessel_size[ship] * 50)
incomplete = True
while incomplete:
pos = []
x_pos = (random.randint(50, x_max) // 50) * 50 + 1
y_pos = (random.randint(50, 600) // 50) * 50 + 1
for i in range(0, vessel_size[ship]):
pos.append((x_pos + i * 50, y_pos))
check_coord = True
# Check if a ship already in that location
for j in pos:
if j not in available_coord:
check_coord = False
if check_coord:
self._vessels_location['ai'][ship] = pos
incomplete = False
else:
y_max = 650 - (vessel_size[ship] * 50)
incomplete = True
while incomplete:
pos = []
x_pos = (random.randint(50, 1000) // 50) * 50 + 1
y_pos = (random.randint(50, y_max) // 50) * 50 + 1
for i in range(0, vessel_size[ship]):
pos.append((x_pos, y_pos + i * 50))
check_coord = True
for j in pos:
if j not in available_coord:
check_coord = False
if check_coord:
self._vessels_location['ai'][ship] = pos
incomplete = False
# For testing print ai positions
# print(self._vessels_location['ai'])
def setup_game(self):
"""Starts necessary private methods"""
self._ai_battle_ships()
def _coord_converter(self, x, y):
"""Takes coordinates and converts them to specific box coordinates"""
point_x = (x // 50) * 50 + 1
point_y = (y // 50) * 50 + 1
return point_x, point_y
def _update_active_targets(self, x, y):
if self._shots_fired['ai'][(x, y)][1] == (255, 0, 0):
self._active_target = {'active': True, 'coord': (x, y)}
def get_ai_response(self):
"""
A method for all the moves that the AI will do in the game
"""
if self._active_target['active']:
x = self._active_target['coord'][0]
y = self._active_target['coord'][1]
if x < 1000 and (x+50, y) not in self._shots_fired['ai'].keys():
self.get_cannon_shots(x+50, y)
self._update_active_targets(x+50, y)
elif x > 100 and (x-50, y) not in self._shots_fired['ai'].keys():
self.get_cannon_shots(x-50, y)
self._update_active_targets(x-50, y)
elif y > 100 and (x, y-50) not in self._shots_fired['ai']:
self.get_cannon_shots(x, y-50)
self._update_active_targets(x, y-50)
elif y < 550 and (x, y-50) not in self._shots_fired['ai'].keys():
self.get_cannon_shots(x, y+50)
self._update_active_targets(x, y+50)
self._update_player()
else:
rand_x = random.randint(50, 1050)
rand_y = random.randint(50, 650)
miss = True
points = self._coord_converter(rand_x, rand_y)
for boat in self._vessels_location['human']:
for loc in self._vessels_location['human'][boat]:
if loc == (points[0], points[1]):
miss = False
self._shots_fired['ai'][(points[0], points[1])] = [(points[0], points[1]), (255, 0, 0)]
self._active_target = {'active': True, 'coord': (points[0], points[1])}
if miss:
self._shots_fired['ai'][(points[0], points[1])] = [(points[0], points[1]), (182, 191, 207)]
self._update_player()
def _update_vessels(self, coordx, coordy, target_player, ship):
"""
Takes the coordinates, target player and ship to update vessels dictionary when a vessel is hit. Coordinates
are in tuples, target_player and ship a string
"""
for i in range(len(self._vessels_location[target_player][ship])):
if self._vessels_location[target_player][ship][i] == (coordx, coordy):
self._vessels_location[target_player][ship][i] = ['hit']
def _check_neighboring_boxes(self, coordx, coordy, neighboring_box):
"""
Checks if neighboring box has already been selected. Takes parameters coord x and y and neighboring box.
"""
if (coordx+50, coordy) not in self._shots_fired['ai'].keys():
print('Not selected')
print(coordx+50)
# Testing Code
if __name__ == '__main__':
test = GameLogic('Test')
test._check_neighboring_boxes(101, 51, 'test')
| {"/game.py": ["/game_logic.py"], "/main.py": ["/game.py"], "/game_logic.py": ["/player.py"]} |
48,039 | kirillvh/Robotism | refs/heads/master | /kalmanAccVel.py | import numpy as np
import matplotlib.pyplot as plt
import math
from numpy.linalg import inv
class kalmanKinematic2:
def __init__(self, encoder_sampl_period, encResolution,uncertaintyGain):
self.T = encoder_sampl_period
self.encResolution = encResolution
self.x = np.zeros((2,1))
self.P = np.zeros((2,2))
self.A = np.zeros((2,2))
self.A[0][0] = 1
self.A[0][1] = self.T
self.A[1][0] = 0
self.A[1][1] = 1
self.B = np.zeros((2,1))
self.C = np.zeros((1,2))
self.C[0][0] = 1.0
self.C[0][1] = 0.0
self.B[0] = 0.5*self.T*self.T
self.B[1] = self.T
self.R = self.encResolution*self.encResolution/12.0
self.Q = np.zeros((2,2))
self.Q[0][0] = (1.0/3.0)*self.T*self.T*self.T
self.Q[0][1] = (1.0/2.0)*self.T*self.T
self.Q[1][0] = (1.0/2.0)*self.T*self.T
self.Q[1][1] = self.T
self.Q = self.Q*uncertaintyGain
def update(self,thetaMeasured, ddthetaModel):
#A-priori update
self.x = self.A.dot(self.x) + self.B*ddthetaModel;
self.P = self.A.dot(self.P).dot(self.A.T) + self.Q;
#A-posteriori update
y = np.identity(1)*thetaMeasured - self.C.dot(self.x);
S = self.C.dot(self.P).dot(self.C.T) + self.R;
K = self.P.dot(np.transpose(self.C)).dot(inv(S));
self.x = self.x + K.dot(y);
self.P = (np.identity(2) - K.dot(self.C)).dot(self.P);
return self.x
class kalmanKinematic3:
#this class only needs the encoder data
def __init__(self, encoder_sampl_period, encResolution,uncertaintyGain):
self.T = encoder_sampl_period
self.encResolution = encResolution
self.x = np.zeros((3,1))
self.P = np.zeros((3,3))
self.A = np.zeros((3,3))
self.A[0][0] = 1.0
self.A[0][1] = self.T
self.A[0][2] = 0.5*self.T*self.T
self.A[1][0] = 0
self.A[1][1] = 1.0
self.A[1][2] = self.T
self.A[2][0] = 0
self.A[2][1] = 0
self.A[2][2] = 1.0
self.B = np.zeros((3,1))
self.C = np.zeros((1,3))
self.C[0][0] = 1.0 #position sense
self.C[0][1] = 0.0
self.C[0][2] = 0.0
self.B[0] = 0.5*self.T*self.T
self.B[1] = self.T
self.B[2] = 1.0
self.R = self.encResolution*self.encResolution/12.0
self.Q = np.zeros((3,3))
self.Q[0][0] = (1.0/20.0)*self.T*self.T*self.T*self.T*self.T
self.Q[0][1] = (1.0/8.0)*self.T*self.T*self.T*self.T
self.Q[0][2] = (1.0/6.0)*self.T*self.T*self.T
self.Q[1][0] = (1.0/8.0)*self.T*self.T*self.T*self.T
self.Q[1][1] = (1.0/3.0)*self.T*self.T*self.T
self.Q[1][2] = (1.0/2.0)*self.T*self.T
self.Q[2][0] = (1.0/6.0)*self.T*self.T*self.T
self.Q[2][1] = (1.0/2.0)*self.T*self.T
self.Q[2][2] = self.T
#self.Q[0][0] = (1.0/3.0)*self.T*self.T*self.T
#self.Q[0][1] = (1.0/2.0)*self.T*self.T
#self.Q[1][0] = (1.0/2.0)*self.T*self.T
#self.Q[1][1] = self.T
self.Q = self.Q*uncertaintyGain
def update(self,thetaMeasured):
#A-priori update
self.x = self.A.dot(self.x) + self.B*ddthetaModel;
self.P = self.A.dot(self.P).dot(self.A.T) + self.Q;
#A-posteriori update
y = np.identity(1)*thetaMeasured - self.C.dot(self.x);
S = self.C.dot(self.P).dot(self.C.T) + self.R;
K = self.P.dot(self.C.T).dot(inv(S));
#print(K)
self.x = self.x + K*y;
self.P = (np.identity(3) - K.dot(self.C)).dot(self.P);
return self.x
class kalmanKinematic3B:
#this class can use both encoder data and dynamic model acceleration
#if no dynamic model is availible, then you MUST substitute the previous acceleration result instead of the dynamic model
def __init__(self, encoder_sampl_period, encResolution,uncertaintyGain):
self.T = encoder_sampl_period
self.encResolution = encResolution
self.x = np.zeros((3,1))
self.P = np.zeros((3,3))
self.A = np.zeros((3,3))
self.A[0][0] = 1.0
self.A[0][1] = self.T
self.A[0][2] = 0.5*self.T*self.T
self.A[1][0] = 0
self.A[1][1] = 1.0
self.A[1][2] = self.T
self.A[2][0] = 0
self.A[2][1] = 0
self.A[2][2] = 1.0
self.A2 = np.zeros((3,3))
self.A2[0][0] = 1.0
self.A2[0][1] = self.T
self.A2[0][2] = 0#0.5*self.T*self.T
self.A2[1][0] = 0
self.A2[1][1] = 1.0
self.A2[1][2] = 0#self.T
self.A2[2][0] = 0
self.A2[2][1] = 0
self.A2[2][2] = 0#1.0
self.B = np.zeros((3,1))
self.C = np.zeros((1,3))
self.C[0][0] = 1.0 #position sense
self.C[0][1] = 0.0
self.C[0][2] = 0.0
self.B[0] = 0.5*self.T*self.T
self.B[1] = self.T
self.B[2] = 1.0
self.R = self.encResolution*self.encResolution/12.0
self.Q = np.zeros((3,3))
self.Q[0][0] = (1.0/20.0)*self.T*self.T*self.T*self.T*self.T
self.Q[0][1] = (1.0/8.0)*self.T*self.T*self.T*self.T
self.Q[0][2] = (1.0/6.0)*self.T*self.T*self.T
self.Q[1][0] = (1.0/8.0)*self.T*self.T*self.T*self.T
self.Q[1][1] = (1.0/3.0)*self.T*self.T*self.T
self.Q[1][2] = (1.0/2.0)*self.T*self.T
self.Q[2][0] = (1.0/6.0)*self.T*self.T*self.T
self.Q[2][1] = (1.0/2.0)*self.T*self.T
self.Q[2][2] = self.T
#self.Q[0][0] = (1.0/3.0)*self.T*self.T*self.T
#self.Q[0][1] = (1.0/2.0)*self.T*self.T
#self.Q[1][0] = (1.0/2.0)*self.T*self.T
#self.Q[1][1] = self.T
self.Q = self.Q*uncertaintyGain
def update(self,thetaMeasured, ddthetaModel):
#A-priori update
self.x = self.A2.dot(self.x) + self.B*ddthetaModel;
self.P = self.A.dot(self.P).dot(self.A.T) + self.Q;
#A-posteriori update
y = np.identity(1)*thetaMeasured - self.C.dot(self.x);
S = self.C.dot(self.P).dot(self.C.T) + self.R;
K = self.P.dot(self.C.T).dot(inv(S));
#print(K)
self.x = self.x + K*y;
self.P = (np.identity(3) - K.dot(self.C)).dot(self.P);
return self.x
def main():
#generate data
print("Generating data")
w1 = 10
w2 = 1
dt = 0.001 #100us
encoder_sampl_period = 0.001
encResolution = 2.0*3.141592/(1024)
t_period = 5# 10 seconds
#print(jerks)
pos = np.zeros((t_period/dt,1))
vel = np.zeros((t_period/dt,1))
velM = np.zeros((t_period/dt,1))
accM = np.zeros((t_period/dt,1))
acc = np.zeros((t_period/dt,1))
jerk = np.zeros((t_period/dt,1))
for i in range(1,int(t_period/dt)):
pos[i] = math.sin(w1*i*dt) - 2.0*math.cos(w2*i*dt)
vel[i] = w1*math.cos(w1*i*dt) + 2.0*w2*math.sin(w2*i*dt)
acc[i] = -w1*w1*math.sin(w1*i*dt) + 2.0*w2*w2*math.cos(w2*i*dt)
jerk[i] = -w1*w1*w1*math.cos(w1*i*dt) - 2.0*w2*w2*w2*math.sin(w2*i*dt)
#calculate discretized position signals and vel,acc by finite difference method
enc = np.zeros((t_period/encoder_sampl_period,1))
for i in range(1,int(t_period/encoder_sampl_period)):
enc[i] = pos[i*encoder_sampl_period/dt]
#discretize
enc[i] = int(enc[i]/encResolution)*encResolution
velM[i] = (enc[i]-enc[i-1])/encoder_sampl_period
accM[i] = (velM[i]-velM[i-1])/encoder_sampl_period
#use kalman filter
x = np.zeros((2,1))
vel_kalman = np.zeros((t_period/dt,1))
acc_kalman = np.zeros((t_period/dt,1))
w_filtered = 0
#P = 0#encoder_sampl_period
P = np.zeros((2,2))
kal1 = kalmanKinematic3B(encoder_sampl_period,encResolution,1.0);
for i in range(1,int(t_period/encoder_sampl_period)):
noise = np.random.uniform(low=-1.0, high=1.0, size=1)
#use acceleration model
x = kal1.update(enc[i],acc[i]+noise)
#no model acceleration, feedback kalman state
#x = kal1.update(enc[i],acc_kalman[i-1])
#print(x)
vel_kalman[i] = x[1]
acc_kalman[i] = x[2]
#plot comparision
ax=plt.subplot(131)
plt.plot(enc, label="encoder pos.")
plt.plot(pos,label="kalman pos.")
plt.ylabel('rad')
plt.xlabel('time')
legend = ax.legend(loc='lower right', shadow=True, prop={'size':10})
ax=plt.subplot(132)
plt.plot(vel, label="real vel")
plt.plot(velM,label="finite diff. vel")
plt.plot(vel_kalman, label="kalman vel.")
plt.ylabel('rad/sec')
plt.xlabel('time')
legend2 = ax.legend(loc='lower right', shadow=True, prop={'size':10})
ax.set_ylim([-15,15])
ax=plt.subplot(133)
plt.plot(accM,label="finite diff. acc")
plt.plot(acc, label="real acc.")
plt.plot(acc_kalman,label="kalman acc.")
plt.ylabel('rad/sec^2')
plt.xlabel('time')
legend2 = ax.legend(loc='lower right', shadow=True, prop={'size':10})
ax.set_ylim([-10000,10000])
plt.show()
###
def kalman_velModel(x, P, thetaMeasured, ddthetaModel, T, thetaM, q):
#do kalman stuff
A = np.zeros((2,2))
A[0][0] = 1
A[0][1] = T
A[1][0] = 0
A[1][1] = 1
B = np.zeros((2,1))
C = np.zeros((2,1))
C[0] = 1.0
B[0] = 0.5*T*T
B[1] = T
#R = np.zeros((1,1))
R = thetaM*thetaM/12.0
Q = np.zeros((2,2))
Q[0][0] = (1.0/3.0)*T*T*T
Q[0][1] = (1.0/2.0)*T*T
Q[1][0] = (1.0/2.0)*T*T
Q[1][1] = T
S = np.zeros((1,1))
#A-priori update
x = A*x + B*ddthetaModel;
P = A*P*A.transpose() + Q;
#A-posteriori update
y = np.identity(1)*thetaMeasured - C*x;
S = C*P*np.transpose(C) + R;
K = P*np.transpose(C)*inv(S);
x = x + K*y;
P = (np.identity(2) - K*C)*P;
print(P)
return x
if __name__ == "__main__":
main()
| {"/QPtrajectory.py": ["/QP.py"]} |
48,040 | kirillvh/Robotism | refs/heads/master | /QP.py | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 13 21:42:37 2016
@author: Kirill Van Heerden
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import math
import quadprog
# x.T*Q*x + q.T*x + r = 0
class Quadratic(object):
def __init__(self, Q=None, q=None, r=0.0):
assert Q is None or type(Q) is np.ndarray
assert q is None or type(q) is np.ndarray
self.n = 0 if q is None else max(q.shape)
self.Q = Q if Q is not None else np.zeros((self.n, self.n))
self.q = q if q is not None else np.zeros((self.n))
self.r = r
def evalQuad(self, x):
""" Evaluates x^T Q x + q^T*x + r
"""
return (x.T.dot(self.Q.dot(x))) + (self.q.dot(x)) + self.r
def __add__(self, other):
return Quadratic(Q=self.Q+other.Q, q=self.q+other.q, r=self.r+other.r)
def __sub__(self, other):
return Quadratic(Q=self.Q-other.Q, q=self.q-other.q, r=self.r-other.r)
def __neg__(self):
return Quadratic(Q=-self.Q, q=-self.q, r=-self.r)
def __pos__(self):
return self
def __str__(self):
return "Q:"+os.linesep+str(self.Q)+os.linesep+"q: "+str(self.q)+os.linesep+"r: "+str(self.r)
def __call__(self, x):
return self.evalQuad(x)
class QP(object):
""" Quadratic Program
min : x'*Q*x + q'*x + r
st : p'*x + r = 0 , i=[0,...,ne] equality constraints
: h'*x + r < 0 , i=[0,...,ni] inequality constraints
"""
def __init__(self, goal=None, constraintsEq=None, constraintsIq=None):
assert constraintsEq == None or type(constraintsEq) == list
assert constraintsIq == None or type(constraintsIq) == list
assert goal == None or type(goal) == Quadratic
self.goal = Quadratic() if goal is None else goal
#equality constraints
self.constraintsEq = [] if constraintsEq is None else constraintsEq
#inequality constraints
self.constraintsIq = [] if constraintsIq is None else constraintsIq
self.n = 0 if goal is None else goal.n
def setGoal(self,Q,q):
self.goal.Q=Q
self.goal.q=q
self.n=len(q)
def evalGoal(self, x):
assert type(x) == np.matrix
return goal.evalQuad(x)
def __str__(self):
s = "QCQP, goal eq:"+os.linesep
s += str(self.goal)+os.linesep
s += str(len(self.constraintsEq))+" equality constraints: "+os.linesep
for c in self.constraintsEq: s += str(c)+os.linesep
s += os.linesep
s += str(len(self.constraintsIq))+" inequality constraints: "
for c in self.constraintsIq: s += str(c)+os.linesep
return s
def CeqMat(self):
if len(self.constraintsEq)<=0: return []
ret = None
for c in self.constraintsEq:
if ret is None:
ret = c.q
else: ret = np.vstack([ret, c.q])
return ret
def DeqVec(self):
if len(self.constraintsEq)<=0: return []
ret = None
for c in self.constraintsEq:
if ret is None:
ret = c.r
else: ret = np.hstack([ret, c.r])
return ret
def CiqMat(self):
if len(self.constraintsIq)<=0: return []
ret = None
for c in self.constraintsIq:
if ret is None:
ret = c.q
else: ret = np.vstack([ret, c.q])
return ret
def DiqVec(self):
if len(self.constraintsIq)<=0: return []
ret = None
for c in self.constraintsIq:
if ret is None:
ret = c.r
else: ret = np.hstack([ret, c.r])
return ret
def solve(self, solver="quadprog"):
if solver=="quadprog":
#==============================================================================
# quadprog format
# min: 0.5*x'*G*X - aT*x
# s.t: C'*X >= b
#==============================================================================
assert self.goal.Q != []
assert self.goal.q != []
Q = 2.0*self.goal.Q
q = -self.goal.q
Ceq = self.CeqMat()
deq = self.DeqVec()
Ciq = self.CiqMat()
diq = self.DiqVec()
C = []
d = []
if Ceq != []:
C = np.vstack([Ceq, -Ceq])
d = -np.vstack([-deq, deq])
if Ciq != [] and C != []:
C = np.vstack([C, -Ciq])
d = np.vstack([d, diq])
elif Ciq != [] and C == []:
C = -Ciq
d = diq
if C==[]: # unconstrained path
x,f,xu,i,lagr,iact= quadprog.solve_qp(Q, q)
return x
else: # constrained path
x,f,xu,i,lagr,iact= quadprog.solve_qp(Q, q, C.T, d.T)
print("constrained::::::::::")
return x
def test():
G = Quadratic(Q=np.array([[1.0, 0.0], [0.0, 1.0]]), q=2*np.array([-2.0, -2.0]), r=4.0)
C = Quadratic(q=np.array([[1.0], [0.0]]), r=-1.0)
y = np.array([10.0, 10.0])
prob = QP(goal=G, constraintsEq = [C])
print(prob)
print("Solution")
print(prob.solve())
if __name__ == "__main__":
test() | {"/QPtrajectory.py": ["/QP.py"]} |
48,041 | kirillvh/Robotism | refs/heads/master | /QPtrajectory.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 3 17:43:39 2017
@author: Kirill Van Heerden
"""
from QP import *
import numpy as np
import matplotlib.pyplot as plt
class QPTrajectory(object):
def __init__(self, initalState=[0.,0.,0.],samplingTime=0.1, COMHeight=0.5,numtrjPoints=16):
self.initalState = np.array(initalState)
self.samplingTime = samplingTime
self.COMHight=0.5
self.numtrjPoints = numtrjPoints
self.A = np.array([[1.0, samplingTime, 0.5*samplingTime*samplingTime],\
[0.,1.,samplingTime], [0.,0.,1.]])
self.B = np.array([[(1./6.)*samplingTime*samplingTime*samplingTime],\
[0.5*samplingTime*samplingTime],[samplingTime]])
# ZMP/COP selection vector
self.Cz = np.array([1.,0.,-COMHeight/9.81])
# Acceleration selection vector
self.Ca = np.array([0.,0.,1.])
# Velocity selection vector
self.Cv = np.array([0.,1.,0.])
# Position selection vector
self.Cp = np.array([1.,0.,0.])
self.Pzs = self.constructPSmat(self.Cz)
self.Pzu = self.constructPUmat(self.Cz)
self.Pas = self.constructPSmat(self.Ca)
self.Pau = self.constructPUmat(self.Ca)
self.Pvs = self.constructPSmat(self.Cv)
self.Pvu = self.constructPUmat(self.Cv)
self.Pps = self.constructPSmat(self.Cp)
self.Ppu = self.constructPUmat(self.Cp)
self.qp=QP()
def constructPSmat(self,C, dbg=False):
ps = np.zeros((self.numtrjPoints,3))
for i in range(self.numtrjPoints):
temp=C.dot(np.linalg.matrix_power(self.A,i+1))
for j in range(3):
ps[i][j] = temp[j]
return ps
def constructPUmat(self,C,dbg=False):
pu = np.zeros((self.numtrjPoints, self.numtrjPoints))
for i in range(self.numtrjPoints): # 0,1,...,numtrjPoints-1
for j in range(self.numtrjPoints): # 0,1,...,numtrjPoints-1
#this can be optimized...
pu[i][j]=C.dot(np.linalg.matrix_power(self.A,i-j).dot(self.B))
if j>=i: break
return pu
def generateGoalFunction(self,comTrj,alpha=0.5,beta=10.0,gamma=1.0, R=1E-3):
Q = 0.5*R*np.identity(self.numtrjPoints)+\
0.5*alpha*self.Pvu.T.dot(self.Pvu)+\
0.5*beta*self.Ppu.T.dot(self.Ppu)
q = alpha*self.Pvu.T.dot(self.Pvs.dot(self.initalState))+\
beta*self.Ppu.T.dot(self.Pps.dot(self.initalState))+\
-beta*self.Ppu.T.dot(comTrj)
self.qp.setGoal(Q,q)
def generateCOPconstraints(self,cop_max,cop_min):
constraintUp = Quadratic(q=self.Pzu,r=-(-self.Pzs.dot(self.initalState)+cop_max))
self.qp.constraintsIq.append(constraintUp)
constraintDown = Quadratic(q=self.Pzu,r=-(-self.Pzs.dot(self.initalState)+cop_min))
self.qp.constraintsIq.append(-constraintDown)
def solveJerks(self):
jerk = self.qp.solve()
return jerk
def jerkToZMP(self,jerk):
return self.Pzs.dot(self.initalState)+self.Pzu.dot(jerk)
def jerkToAcc(self,jerk):
return self.Pas.dot(self.initalState)+self.Pau.dot(jerk)
def jerkToVel(self,jerk):
return self.Pvs.dot(self.initalState)+self.Pvu.dot(jerk)
def jerkToPos(self,jerk):
return self.Pps.dot(self.initalState)+self.Ppu.dot(jerk)
def test():
N = 16*5
dt=0.1
trj_y=QPTrajectory(samplingTime=dt,numtrjPoints=N)
index = [i*dt for i in range(N)]
ref = [float(int(round(math.sin(y*0.2)))) for y in range(N)]
com_yTrjRef = np.array(ref)
cop_max = 1.2
cop_min =-1.2
cop_yMax = np.array([cop_max for i in range(N)])
cop_yMin = np.array([cop_min for i in range(N)])
trj_y.generateCOPconstraints(cop_yMax,cop_yMin)
trj_y.generateGoalFunction(com_yTrjRef)
jerk_y=trj_y.solveJerks()
acc_y=trj_y.jerkToAcc(jerk_y)
vel_y=trj_y.jerkToVel(jerk_y)
pos_y=trj_y.jerkToPos(jerk_y)
zmp_y=trj_y.jerkToZMP(jerk_y)
ax = plt.subplot(2,2,1)
plt.plot(index,zmp_y,label="zmp")
plt.plot(index,cop_yMax,label="ZMP-Max")
plt.plot(index,cop_yMin,label="ZMP-Min")
plt.plot(index,pos_y,label="pos_y")
plt.plot(index,ref,label="ref_y")
ax.set_xlabel("s")
ax.set_ylabel("m")
legend = ax.legend(loc='lower right', shadow=True, prop={'size':10})
ax = plt.subplot(2,2,2)
ax.plot(index,vel_y,label="vel")
ax.plot(index,acc_y,label="acc")
ax.set_xlabel("s")
ax.set_ylabel("m/s and m/s^2")
legend = ax.legend(loc='upper right', shadow=True, prop={'size':10})
#now can do the same for another axis
#trj_x=QPTrajectory()
#but lets rather see what happens with stricter ZMP constraints
trj_y2=QPTrajectory(samplingTime=dt,numtrjPoints=N)
cop_max = 1.01 # if this is too strict, then solver can fail
cop_min =-1.01
cop_yMax2 = np.array([cop_max for i in range(N)])
cop_yMin2 = np.array([cop_min for i in range(N)])
trj_y2.generateCOPconstraints(cop_yMax2,cop_yMin2)
trj_y2.generateGoalFunction(com_yTrjRef)
jerk_y2=trj_y2.solveJerks()
acc_y2=trj_y2.jerkToAcc(jerk_y2)
vel_y2=trj_y2.jerkToVel(jerk_y2)
pos_y2=trj_y2.jerkToPos(jerk_y2)
zmp_y2=trj_y2.jerkToZMP(jerk_y2)
ax = plt.subplot(2,2,3)
plt.plot(index,zmp_y2,label="zmp")
plt.plot(index,cop_yMax2,label="ZMP-Max")
plt.plot(index,cop_yMin2,label="ZMP-Min")
plt.plot(index,pos_y2,label="pos_y")
plt.plot(index,ref,label="ref_y")
ax.set_xlabel("s")
ax.set_ylabel("m")
legend = ax.legend(loc='lower right', shadow=True, prop={'size':10})
ax = plt.subplot(2,2,4)
ax.plot(index,vel_y2,label="vel")
ax.plot(index,acc_y2,label="acc")
ax.set_xlabel("s")
ax.set_ylabel("m/s and m/s^2")
legend = ax.legend(loc='upper right', shadow=True, prop={'size':10})
if __name__ == "__main__":
test()
| {"/QPtrajectory.py": ["/QP.py"]} |
48,042 | kirillvh/Robotism | refs/heads/master | /forceDistributor.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 3 01:22:40 2017
@author: Kirill Van Heerden
"""
import numpy as np
class forceDistributor(object):
def __init__(self):
# COM coordinates
#
# F_z1------F_z2 . F_z5------F_z6
# | | x /|\ | |
# | Left foot | |____\ | Right foot |
# | | y / | |
# F_z3------F_z4 F_z7------F_z8
#
# Now lets define the relations
# sum(F_z) = mg , The combined F_z's must equal to the robots gravity force
# (A~)*F_z = [tau_x,tau_y] , Let tau be the torque generated by F_z
# A~ = [x1...x8;y1...y8] where xi,yi are the positions of the F_zi indexes
# Then combine it:
# [A~; 1] = [tau_x,tau_y;mg]
# A*F_z = [cop_x*mg;cop_y*mg;mg] , remember tau_x = cop_x*mg, cop is center of pressure
self.A=np.array([[1, 1, -1, -1, 1, 1, -1, -1], [-2, -1, 1, 2, -2, -1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 1]])
def solve(self,mg=9.8, cop_x=0, cop_y=0):
b = np.array([[cop_x*mg],[cop_y*mg],[mg]])
# may need to solve under defined system, thus least squares solver may be needed
# Remember, using matrix inverse to solve linear systems is usually
# computationaly expensive and has poor accuracy, use linear solver instead if possible
f_z=np.linalg.lstsq(self.A, b)[0]
return f_z
def reconstructAMatrix(self,x,y,weightRight=1.,weightLeft=1.):
lastrow = [weightRight,weightRight,weightRight,weightRight,\
weightLeft,weightLeft,weightLeft,weightLeft]
self.A = np.array([x,y,lastrow])
def FzLeft(self,Fz):
return Fz[0]+Fz[1]+Fz[2]+Fz[3]
def FzRight(self,Fz):
return Fz[4]+Fz[5]+Fz[6]+Fz[7]
if __name__ == "__main__":
fd = forceDistributor()
print("COM between two feet")
print(fd.solve(mg=10., cop_x=0., cop_y=0))
fd.reconstructAMatrix([1,1,-1,-1,1,1,-1,-1],[-1,1,-1,1,3,4,3,4],weightRight=1.,weightLeft=1.)
print("COM above right foot with left foot active")
print(fd.solve(mg=10., cop_x=0., cop_y=0))
fd.reconstructAMatrix([1,1,-1,-1,1,1,-1,-1],[-1,1,-1,1,3,4,3,4],weightRight=1.,weightLeft=0.)
print("COM above right foot with left foot inactive")
print(fd.solve(mg=10., cop_x=0., cop_y=0))
Fz=fd.solve(mg=10., cop_x=0., cop_y=0)
Fzl=fd.FzLeft(Fz) | {"/QPtrajectory.py": ["/QP.py"]} |
48,052 | scottdk/gurgle | refs/heads/master | /module/sheet.py | from urllib2 import urlopen
from urllib import urlencode
from config import Config
from cache import IsNotInCache, CacheUpdate
import json
import time
# Logger instance used by the functions in this module
_LOGGER = Config.getLogger("sheet")
# Configuration for the Google Sheet interaction
__SHEET_URL = Config.getRequiredString('sheet', 'url')
__SHEET_API_KEY = Config.getCrypt('sheet', 'apikey')
__SHEET_RETRIES = Config.getInteger('sheet', 'retries', 3)
__SHEET_RETRY_WAIT = Config.getInteger('sheet', 'retry_wait', 3)
__SHEET_TIMEOUT = Config.getInteger('sheet', 'timeout', 10)
__SHEET_RESPONSE_BUFFER = Config.getInteger('sheet', 'buffer', 1024)
def PostUpdate(update, factionList):
"""Responsible for sending the specified update to the Google Sheet."""
starName = update["StarSystem"]
eventDate = update["EventDate"]
distance = update["Distance"]
# Send the update, if Cache says we need to
if IsNotInCache(eventDate, starName, factionList):
if SendUpdate(update):
_LOGGER.info("Processed (sent) update for %s (%.1fly)", starName, distance)
# Update the Cache Entry (after send so we have definitely sent)
CacheUpdate(eventDate, starName, factionList)
else:
_LOGGER.warning("Failed to send update for %s (%.1fly)", starName, distance)
else:
_LOGGER.debug("Processed (not sent) update for %s (%.1fly)", starName, distance)
def SendUpdate(dictionary):
"""Posts the specified dictionary to the Google Sheet.
To be successful we need to provide an appropriate API_KEY value, and we also
want to retry any infrastructure errors (i.e. unable to complete the POST) but
abandon the entire process if the "application" does not report success (i.e.
on an invalid token, badly formed request, etc.).
"""
dictionary['API_KEY'] = __SHEET_API_KEY
data = urlencode(dictionary)
retries = __SHEET_RETRIES
success = 0
response = None
while success != 200 and retries > 0:
try:
request = urlopen(__SHEET_URL, data, __SHEET_TIMEOUT)
success = request.getcode()
response = request.read(__SHEET_RESPONSE_BUFFER)
request.close()
except Exception, e:
_LOGGER.info("(Retry %d) Exception while attempting to POST data: %s", retries, str(e))
retries -= 1
if retries > 0:
time.sleep(__SHEET_RETRY_WAIT)
# Check the response for validity, where "result"="success"
if success == 200 and response is not None:
try:
result = json.loads(response) # Throws Exception if JSON not returned
if (result["result"] != "success"):
raise Exception("Bad response from Sheet: %s" % result)
_LOGGER.debug("Success Response: %s" % result)
except:
_LOGGER.warning("Unexpected response from Sheet: %s", response)
return (success == 200)
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,053 | scottdk/gurgle | refs/heads/master | /module/config.py | """Provides for basic configuration of the system parameters and logging infrastructure."""
import ConfigParser
import json
import logging
import logging.config
import md5
from os import makedirs
from os.path import isdir, isfile
# Defines the file names checked for configuration overrides
_CONFIG_FILES = ['gurgle-local.ini', 'gurgle.local.ini']
# Defines the section and field used to hold logging framework configuration
_LOG_SECTION = 'logging'
_LOG_CONFIG = 'config'
_LOG_DIRECTORY = 'directory'
# Defines a default formatter for the logging framework, if not configured
_LOG_FORMAT = "%(asctime)-19.19s %(levelname)-5.5s [%(name)s] %(message)s"
class Configuration(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
self.config.readfp(open('gurgle.ini'))
# Check configuration files in preference order
for filename in _CONFIG_FILES:
if isfile(filename):
self.config.read(filename)
break # first config file found is used
def initialiseLogging(self):
# If a directory is specified, we might need to create it
if self.config.has_option(_LOG_SECTION, _LOG_DIRECTORY):
logDirectory = self.config.get(_LOG_SECTION, _LOG_DIRECTORY)
if not isdir(logDirectory):
makedirs(logDirectory)
# Use any logging configuration specified
if self.config.has_option(_LOG_SECTION, _LOG_CONFIG):
logConfig = self.config.get(_LOG_SECTION, _LOG_CONFIG)
logDict = json.loads(logConfig)
logging.config.dictConfig(logDict)
else:
logging.basicConfig(format=_LOG_FORMAT)
def hasSection(self, section):
return self.config.has_section(section)
def getLogger(self, name):
return logging.getLogger(name)
def getString(self, section, name, default=None):
if self.config.has_option(section, name):
return self.config.get(section, name)
return default
def getRequiredString(self, section, name):
return self.config.get(section, name) # throws Exception
def getInteger(self, section, name, default):
if self.config.has_option(section, name):
return self.config.getint(section, name)
return default
def getFloat(self, section, name):
return self.config.getfloat(section, name)
def getBoolean(self, section, name, default=False):
return self.config.getboolean(section, name) if self.config.has_option(section, name) else default
def getCrypt(self, section, name):
return md5.new(self.config.get(section, name)).hexdigest()
# Initialise on the first import of the module
Config = Configuration()
Config.initialiseLogging()
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,054 | scottdk/gurgle | refs/heads/master | /module/filter.py | from math import pow
from datetime import datetime as dt
from config import Config
# Logger instance used by the functions in this module
_LOGGER = Config.getLogger("filter")
# Determine if only looking for events today
_TODAY_ONLY = Config.getBoolean('events', 'today_only', True)
# Allow specific named systems to be included in the updates
_INCLUDE_SYSTEM_SET = set()
_INCLUDE_SYSTEMS = Config.getString('events', 'include_systems')
if _INCLUDE_SYSTEMS is not None and len(_INCLUDE_SYSTEMS.strip()) > 0:
_INCLUDE_SYSTEM_SET.update([system.strip() for system in _INCLUDE_SYSTEMS.split(",")])
if len(_INCLUDE_SYSTEM_SET) > 0:
_LOGGER.info("Configured for systems: %s", ", ".join(_INCLUDE_SYSTEM_SET))
# Interested in activity around specific locations
def InitialiseLocations():
"""Returns a list of dictionaries that define the volumes within which events
should be reported.
"""
locations = []
section = "location"
sectionNumber = 0
while Config.hasSection(section):
locationX = Config.getFloat(section, 'x')
locationY = Config.getFloat(section, 'y')
locationZ = Config.getFloat(section, 'z')
locationD = Config.getFloat(section, 'distance')
locations.append({'x': locationX, 'y': locationY, 'z': locationZ, 'd2': locationD**2})
_LOGGER.info("Configured for %.1f LY around %s", locationD, Config.getString(section, 'name'))
sectionNumber+=1
section = "location.%d" % sectionNumber
return locations
_LOCATIONS = InitialiseLocations()
def IsInteresting(event):
"""Returns True if the FSDJump event (or equivalent subset of Location event)
provided by Journal is interesting according to the filter configuration.
"""
isInterestingSystem = IsInterestingSystem(event)
if isInterestingSystem:
# Determine if the timestamp is considered relevant
# (NOTE: assumption we receive UTC)
timestamp = event["timestamp"]
eventDate = timestamp[0:10]
todayDate = dt.utcnow().strftime("%Y-%m-%d")
if _TODAY_ONLY and eventDate != todayDate:
starName = event["StarSystem"]
_LOGGER.debug("Event for %s discarded as not today: %s", starName, eventDate)
return False
return isInterestingSystem
def IsInterestingSystem(event):
"""Returns True if the FSDJump event (or equivalent subset of Location event)
provided by Journal references a system we are interested in, else False.
"""
# Extract the star name which is always provided
starName = event["StarSystem"]
# Determine if the system must always be included in updates
if starName in _INCLUDE_SYSTEM_SET:
return True
# Extract the StarPos to confirm we're interested
(starPosX, starPosY, starPosZ) = event["StarPos"]
for location in _LOCATIONS:
x = location['x']
y = location['y']
z = location['z']
d2 = location['d2']
starDist2 = pow(x-starPosX,2)+pow(y-starPosY,2)+pow(z-starPosZ,2)
if starDist2 <= d2:
return True
# Not included in any particular location selection, so not interested
return False
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,055 | scottdk/gurgle | refs/heads/master | /eddn.py | import zlib
import zmq
import json
import time
from module.config import Config
from module.influence import ConsumeFSDJump
# Configuration specified for the EDDN connection
__EDDN_RELAY = Config.getString('eddn', 'relay')
__EDDN_TIMEOUT = Config.getInteger('eddn', 'timeout', 60000)
__EDDN_RECONNECT = Config.getInteger('eddn', 'reconnect', 10)
# Only interested in the Journal Schema ($schemaRef)
_SCHEMA_REFS = [ "http://schemas.elite-markets.net/eddn/journal/1", "https://eddn.edcd.io/schemas/journal/1" ]
def processMessage(message, logger):
"""Processes the specified message, if possible."""
try:
jsonmsg = json.loads(message)
if jsonmsg["$schemaRef"] in _SCHEMA_REFS:
content = jsonmsg["message"]
# Only interested in FSDJump or Location events
if content["event"] in ["FSDJump", "Location"]:
ConsumeFSDJump(content)
except Exception:
logger.exception('Received message caused unexpected exception, Message: %s' % message)
def main():
"""Main method that connects to EDDN and processes messages."""
logger = Config.getLogger("eddn")
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.setsockopt(zmq.SUBSCRIBE, "")
while True:
try:
subscriber.connect(__EDDN_RELAY)
logger.info('Connected to EDDN at %s', __EDDN_RELAY)
poller = zmq.Poller()
poller.register(subscriber, zmq.POLLIN)
while True:
socks = dict(poller.poll(__EDDN_TIMEOUT))
if socks:
if socks.get(subscriber) == zmq.POLLIN:
message = subscriber.recv(zmq.NOBLOCK)
message = zlib.decompress(message)
processMessage(message, logger)
else:
logger.warning('Disconnect from EDDN (After timeout)')
subscriber.disconnect(__EDDN_RELAY)
break
except zmq.ZMQError, e:
logger.warning('Disconnect from EDDN (After receiving ZMQError)', exc_info=True)
subscriber.disconnect(__EDDN_RELAY)
logger.debug('Reconnecting to EDDN in %d seconds.' % __EDDN_RECONNECT)
time.sleep(__EDDN_RECONNECT)
except Exception:
logger.critical('Unhandled exception occurred while processing EDDN messages.', exc_info=True)
break # exit the main loop
# Enable command line execution
if __name__ == '__main__':
main()
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,056 | scottdk/gurgle | refs/heads/master | /file.py | import json
import sys
from module.config import Config
from module.influence import ConsumeFSDJump
def main():
"""Main method that reads file for update."""
logger = Config.getLogger("file")
fileName = sys.argv[1]
logger.info("Reading file: %s", fileName)
try:
with open(fileName, "r") as file:
for line in file:
content = json.loads(line)
# Only interested in FSDJump or Location events
if content["event"] in ["FSDJump", "Location"]:
ConsumeFSDJump(content)
except:
logger.critical('Unexpected exception while processing.', exc_info=True)
# Enable command line execution
if __name__ == '__main__':
main()
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,057 | scottdk/gurgle | refs/heads/master | /module/cache.py | from datetime import datetime as dt
# Cache mechanism that attempts to prevent duplicate updates
# While ideally we wanted the Google Sheet to prevent duplicates, this is
# actually very difficult to achieve due to a lack of optimised search functionality.
# Instead we'll attempt to prevent duplicates within a single instance and
# the sheet will handle selecting appropriate entries due to complexities such
# as the BGS Tick Date and whether we trust data around the tick time which
# can change 'on a whim'.
# This 'cache' is date-keyed, but we enforce only having an entry for today (which
# ensures automatic clean-up if we continue to execute over several days).
# The key (date) maps to a single map which maps System Name to a List of Faction
# Influence and State values, which we use to determine if there has been a change
# that we need to communicate to the Google Sheet.
_CACHE_BY_DATE = {}
def IsNotInCache(date, name, value):
"""Returns True if the specified value does NOT match the cache, else False.
Note that this cache implementation only ensures that values for the current
date are stored and is not a general cache mechanism.
"""
# We only ever cache the values for 'today', assuming either the caller
# will reject other dates or requires all updates to flow
todayDate = dt.utcnow().strftime("%Y-%m-%d")
# If we're provided an item that isn't for today, simply return True
if date != todayDate:
return True
# If the cache doesn't have an entry for today, clear it and add empty
if date not in _CACHE_BY_DATE:
_CACHE_BY_DATE.clear()
_CACHE_BY_DATE[date] = {}
return True
# Does the cache already have this key?
entries = _CACHE_BY_DATE[date]
if name not in entries:
return True
# Need to check if the cache entry matches what we want to send
if entries[name] != value:
return True
# Cache matches specified value
return False
def CacheUpdate(date, name, value):
"""Ensures the cache is updated with the lastest value."""
if date in _CACHE_BY_DATE:
entries = _CACHE_BY_DATE[date]
entries[name] = value
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,058 | scottdk/gurgle | refs/heads/master | /module/influence.py | from math import pow, sqrt
from config import Config
from filter import IsInteresting
from sheet import PostUpdate
import re
# Logger instance used by the functions in this module
_LOGGER = Config.getLogger("influence")
# Determine whether we are rounding the distance or location
_ROUND_DISTANCE = Config.getInteger('events', 'distancedp', -1)
_ROUND_LOCATION = Config.getInteger('events', 'locationdp', -1)
# Allow specific factions to be ignored
_IGNORE_FACTION_SET = set()
_IGNORE_FACTIONS = Config.getString('events', 'ignore_factions')
if _IGNORE_FACTIONS is not None and len(_IGNORE_FACTIONS.strip()) > 0:
_IGNORE_FACTION_SET.update([faction.strip() for faction in _IGNORE_FACTIONS.split(",")])
# Define the coordinates for the primary location used to define distance
_LOCATION_X = Config.getFloat('location', 'x')
_LOCATION_Y = Config.getFloat('location', 'y')
_LOCATION_Z = Config.getFloat('location', 'z')
# Provide regular expressions to remove extraneous text specifiers
_MATCH_GOV = re.compile(r'\$government_(.*);', re.IGNORECASE)
_MATCH_SEC = re.compile(r'\$system_security_(.*);', re.IGNORECASE)
_MATCH_SEC2 = re.compile(r'\$GAlAXY_MAP_INFO_state_(.*);', re.IGNORECASE)
_MATCH_ECO = re.compile(r'\$economy_(.*);', re.IGNORECASE)
def ConsumeFSDJump(event):
"""Consumes the FSDJump event (or equivalent subset of Location event)
provided by Journal, extracting the factions and influence levels.
"""
# Only update information if we are interested in the update
if not IsInteresting(event):
return
# Extract the StarPos
(starPosX, starPosY, starPosZ) = event["StarPos"]
starDist2 = pow(_LOCATION_X-starPosX,2)+pow(_LOCATION_Y-starPosY,2)+pow(_LOCATION_Z-starPosZ,2)
# Extract the star name which is always provided
starName = event["StarSystem"]
# Extract the timestamp information
timestamp = event["timestamp"]
eventDate = timestamp[0:10]
eventTime = timestamp[11:19]
# Nothing else below here guaranteed to be available
systemFaction = event.get("SystemFaction", "")
systemAllegiance = event.get("SystemAllegiance", "")
systemSecurity = event.get("SystemSecurity", "")
systemGovernment = event.get("SystemGovernment", "")
systemEconomy = event.get("SystemEconomy", "")
# Grab the list of factions, if available
factionList = event.get("Factions", [])
# Sort by descending influence (just in case)
factionList = sorted(factionList, key=lambda faction: float(faction["Influence"]), reverse=True)
# Compute the distance as square root
distance = sqrt(starDist2)
if _ROUND_DISTANCE >= 0:
distance = round(distance, _ROUND_DISTANCE)
if _ROUND_LOCATION >= 0:
starPosX = round(starPosX, _ROUND_LOCATION)
starPosY = round(starPosY, _ROUND_LOCATION)
starPosZ = round(starPosZ, _ROUND_LOCATION)
# Only want to update if we have factions to report on...
if len(factionList) == 0:
_LOGGER.debug("Event for %s (%.1fly) discarded since no factions present.", starName, distance)
elif set([x["Name"] for x in factionList]).issubset(_IGNORE_FACTION_SET):
_LOGGER.debug("Event for %s (%.1fly) discarded since no interesting factions present.", starName, distance)
else: # len(factionList) > 0
_LOGGER.debug("Processing update for %s (%.1fly) from %s", starName, distance, timestamp)
# Create the update
update = CreateUpdate(timestamp, starName, systemFaction, factionList)
update["EventDate"] = eventDate
update["EventTime"] = eventTime
# Add the other useful information
update["Distance"] = distance
update["LocationX"] = starPosX
update["LocationY"] = starPosY
update["LocationZ"] = starPosZ
update["Population"] = event.get("Population", "")
if len(systemAllegiance) > 0:
update["SystemAllegiance"] = systemAllegiance
if len(systemSecurity) > 0 and _MATCH_SEC.match(systemSecurity) is not None:
update["SystemSecurity"] = _MATCH_SEC.match(systemSecurity).group(1)
if len(systemSecurity) > 0 and _MATCH_SEC2.match(systemSecurity) is not None:
update["SystemSecurity"] = _MATCH_SEC2.match(systemSecurity).group(1)
if len(systemGovernment) > 0 and _MATCH_GOV.match(systemGovernment) is not None:
update["SystemGovernment"] = _MATCH_GOV.match(systemGovernment).group(1)
if len(systemEconomy) > 0 and _MATCH_ECO.match(systemEconomy) is not None:
update["SystemEconomy"] = _MATCH_ECO.match(systemEconomy).group(1)
# Send the update
PostUpdate(update, factionList)
def CreateUpdate(timestamp, starName, systemFaction, factionList):
"""Formats the information for the upload to the Google Sheet."""
data = { "Timestamp": timestamp, "StarSystem": starName, "SystemFaction": systemFaction }
data["SystemAllegiance"] = ""
data["SystemSecurity"] = ""
data["SystemGovernment"] = ""
data["SystemEconomy"] = ""
factionNo = 1
for faction in factionList:
# Not interested in these factions
if faction["Name"] in _IGNORE_FACTION_SET:
continue
prefix = "Faction{:d}".format(factionNo)
data[prefix+"Name"] = faction["Name"]
data[prefix+"Influence"] = faction["Influence"]
data[prefix+"State"] = faction["FactionState"]
data[prefix+"Allegiance"] = faction["Allegiance"]
data[prefix+"Government"] = faction["Government"]
# Support for Pending/Recovering States
# since sheet is expecting either all information or none for
# each faction we always need to specify these, even if not present
states = []
if "PendingStates" in faction and faction["PendingStates"] is not None:
for pendingState in faction["PendingStates"]:
states.append(pendingState["State"])
data[prefix+"PendingState"] = ",".join(states)
states = []
if "RecoveringStates" in faction and faction["RecoveringStates"] is not None:
for recoveringState in faction["RecoveringStates"]:
states.append(recoveringState["State"])
data[prefix+"RecoveringState"] = ",".join(states)
factionNo = factionNo + 1
return data
| {"/file.py": ["/module/config.py", "/module/influence.py"]} |
48,059 | cretomoharada/dddpy | refs/heads/main | /dddpy/domain/book/book.py | from typing import Optional
from .isbn import Isbn
class Book:
"""Book represents your collection of books as an entity."""
def __init__(
self,
id: str,
isbn: Isbn,
title: str,
page: int,
read_page: int = 0,
created_at: Optional[int] = None,
updated_at: Optional[int] = None,
):
self.id: str = id
self.isbn: Isbn = isbn
self.title: str = title
self.page: int = page
self.read_page: int = read_page
self.created_at: Optional[int] = created_at
self.updated_at: Optional[int] = updated_at
def __eq__(self, o: object) -> bool:
if isinstance(o, Book):
return self.id == o.id
return False
def is_already_read(self) -> bool:
return self.page == self.read_page
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,060 | cretomoharada/dddpy | refs/heads/main | /main.py | import logging
from logging import config
from typing import Iterator, List
from fastapi import Depends, FastAPI, HTTPException, status
from sqlalchemy.orm.session import Session
from dddpy.domain.book import (
BookIsbnAlreadyExistsError,
BookNotFoundError,
BookRepository,
BooksNotFoundError,
)
from dddpy.infrastructure.sqlite.book import (
BookCommandUseCaseUnitOfWorkImpl,
BookQueryServiceImpl,
BookRepositoryImpl,
)
from dddpy.infrastructure.sqlite.database import SessionLocal, create_tables
from dddpy.presentation.schema.book.book_error_message import (
ErrorMessageBookIsbnAlreadyExists,
ErrorMessageBookNotFound,
ErrorMessageBooksNotFound,
)
from dddpy.usecase.book import (
BookCommandUseCase,
BookCommandUseCaseImpl,
BookCommandUseCaseUnitOfWork,
BookCreateModel,
BookQueryService,
BookQueryUseCase,
BookQueryUseCaseImpl,
BookReadModel,
BookUpdateModel,
)
config.fileConfig("logging.conf", disable_existing_loggers=False)
logger = logging.getLogger(__name__)
app = FastAPI()
create_tables()
def get_session() -> Iterator[Session]:
session: Session = SessionLocal()
try:
yield session
finally:
session.close()
def book_query_usecase(session: Session = Depends(get_session)) -> BookQueryUseCase:
book_query_service: BookQueryService = BookQueryServiceImpl(session)
return BookQueryUseCaseImpl(book_query_service)
def book_command_usecase(session: Session = Depends(get_session)) -> BookCommandUseCase:
book_repository: BookRepository = BookRepositoryImpl(session)
uow: BookCommandUseCaseUnitOfWork = BookCommandUseCaseUnitOfWorkImpl(
session, book_repository=book_repository
)
return BookCommandUseCaseImpl(uow)
@app.post(
"/books",
response_model=BookReadModel,
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_409_CONFLICT: {
"model": ErrorMessageBookIsbnAlreadyExists,
},
},
)
async def create_book(
data: BookCreateModel,
book_command_usecase: BookCommandUseCase = Depends(book_command_usecase),
):
try:
book = book_command_usecase.create_book(data)
except BookIsbnAlreadyExistsError as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=e.message,
)
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
return book
@app.get(
"/books",
response_model=List[BookReadModel],
status_code=status.HTTP_200_OK,
responses={
status.HTTP_404_NOT_FOUND: {
"model": ErrorMessageBooksNotFound,
},
},
)
async def get_books(
book_query_usecase: BookQueryUseCase = Depends(book_query_usecase),
):
try:
books = book_query_usecase.fetch_books()
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
if len(books) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=BooksNotFoundError.message,
)
return books
@app.get(
"/books/{book_id}",
response_model=BookReadModel,
status_code=status.HTTP_200_OK,
responses={
status.HTTP_404_NOT_FOUND: {
"model": ErrorMessageBookNotFound,
},
},
)
async def get_book(
book_id: str,
book_query_usecase: BookQueryUseCase = Depends(book_query_usecase),
):
try:
book = book_query_usecase.fetch_book_by_id(book_id)
except BookNotFoundError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
)
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
return book
@app.put(
"/books/{book_id}",
response_model=BookReadModel,
status_code=status.HTTP_202_ACCEPTED,
responses={
status.HTTP_404_NOT_FOUND: {
"model": ErrorMessageBookNotFound,
},
},
)
async def update_book(
book_id: str,
data: BookUpdateModel,
book_command_usecase: BookCommandUseCase = Depends(book_command_usecase),
):
try:
updated_book = book_command_usecase.update_book(book_id, data)
except BookNotFoundError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
)
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
return updated_book
@app.delete(
"/books/{book_id}",
status_code=status.HTTP_202_ACCEPTED,
responses={
status.HTTP_404_NOT_FOUND: {
"model": ErrorMessageBookNotFound,
},
},
)
async def delete_book(
book_id: str,
book_command_usecase: BookCommandUseCase = Depends(book_command_usecase),
):
try:
book_command_usecase.delete_book_by_id(book_id)
except BookNotFoundError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=e.message,
)
except Exception as e:
logger.error(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,061 | cretomoharada/dddpy | refs/heads/main | /tests/domain/book/test_book.py | import pytest
from dddpy.domain.book import Book, Isbn
class TestBook:
def test_constructor_should_create_instance(self):
book = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
)
assert book.id == "book_01"
assert book.isbn == Isbn("978-0321125217")
assert (
book.title
== "Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
assert book.page == 560
assert book.read_page == 0
def test_book_entity_should_be_identified_by_id(self):
book_1 = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=50,
)
book_2 = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=120,
)
book_3 = Book(
id="book_02",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=50,
)
assert book_1 == book_2
assert book_1 != book_3
@pytest.mark.parametrize(
"read_page",
[
(0),
(1),
(320),
],
)
def test_read_page_setter_should_update_value(self, read_page):
book = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
)
book.read_page = read_page
assert book.read_page == read_page
@pytest.mark.parametrize(
"read_page, expected",
[
(0, False),
(559, False),
(560, True),
],
)
def test_is_already_read_should_true_when_read_page_has_reached_last_page(
self, read_page, expected
):
book = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
)
book.read_page = read_page
assert book.is_already_read() == expected
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,062 | cretomoharada/dddpy | refs/heads/main | /dddpy/infrastructure/sqlite/book/book_dto.py | from datetime import datetime
from typing import Union
from sqlalchemy import Column, Integer, String
from dddpy.domain.book import Book, Isbn
from dddpy.infrastructure.sqlite.database import Base
from dddpy.usecase.book import BookReadModel
def unixtimestamp() -> int:
return int(datetime.now().timestamp() * 1000)
class BookDTO(Base):
"""BookDTO is a data transfer object associated with Book entity."""
__tablename__ = "book"
id: Union[str, Column] = Column(String, primary_key=True, autoincrement=False)
isbn: Union[str, Column] = Column(String(17), unique=True, nullable=False)
title: Union[str, Column] = Column(String, nullable=False)
page: Union[int, Column] = Column(Integer, nullable=False)
read_page: Union[int, Column] = Column(Integer, nullable=False, default=0)
created_at: Union[int, Column] = Column(Integer, index=True, nullable=False)
updated_at: Union[int, Column] = Column(Integer, index=True, nullable=False)
def to_entity(self) -> Book:
return Book(
id=self.id,
isbn=Isbn(self.isbn),
title=self.title,
page=self.page,
read_page=self.read_page,
created_at=self.created_at,
updated_at=self.updated_at,
)
def to_read_model(self) -> BookReadModel:
return BookReadModel(
id=self.id,
isbn=self.isbn,
title=self.title,
page=self.page,
read_page=self.read_page,
created_at=self.created_at,
updated_at=self.updated_at,
)
@staticmethod
def from_entity(book: Book) -> "BookDTO":
now = unixtimestamp()
return BookDTO(
id=book.id,
isbn=book.isbn.value,
title=book.title,
page=book.page,
read_page=book.read_page,
created_at=now,
updated_at=now,
)
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,063 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/book_query_usecase.py | from abc import ABC, abstractmethod
from typing import List, Optional
from dddpy.domain.book import BookNotFoundError, BooksNotFoundError
from .book_query_model import BookReadModel
from .book_query_service import BookQueryService
class BookQueryUseCase(ABC):
"""BookQueryUseCase defines a query usecase inteface related Book entity."""
@abstractmethod
def fetch_book_by_id(self, id: str) -> Optional[BookReadModel]:
raise NotImplementedError
@abstractmethod
def fetch_books(self) -> List[BookReadModel]:
raise NotImplementedError
class BookQueryUseCaseImpl(BookQueryUseCase):
"""BookQueryUseCaseImpl implements a query usecases related Book entity."""
def __init__(self, book_query_service: BookQueryService):
self.book_query_service: BookQueryService = book_query_service
def fetch_book_by_id(self, id: str) -> Optional[BookReadModel]:
try:
book = self.book_query_service.find_by_id(id)
if book is None:
raise BookNotFoundError
except:
raise
return book
def fetch_books(self) -> List[BookReadModel]:
try:
books = self.book_query_service.find_all()
except:
raise
return books
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,064 | cretomoharada/dddpy | refs/heads/main | /dddpy/domain/book/book_repository.py | from abc import ABC, abstractmethod
from typing import List, Optional
from dddpy.domain.book import Book
class BookRepository(ABC):
"""BookRepository defines a repository interface for Book entity."""
@abstractmethod
def create(self, book: Book) -> Optional[Book]:
raise NotImplementedError
@abstractmethod
def find_by_id(self, id: str) -> Optional[Book]:
raise NotImplementedError
@abstractmethod
def find_by_isbn(self, isbn: str) -> Optional[Book]:
raise NotImplementedError
@abstractmethod
def update(self, book: Book) -> Optional[Book]:
raise NotImplementedError
@abstractmethod
def delete_by_id(self, id: str):
raise NotImplementedError
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,065 | cretomoharada/dddpy | refs/heads/main | /dddpy/infrastructure/sqlite/book/book_repository.py | from typing import Optional
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.session import Session
from dddpy.domain.book import Book, BookRepository
from dddpy.usecase.book import BookCommandUseCaseUnitOfWork
from .book_dto import BookDTO
class BookRepositoryImpl(BookRepository):
"""BookRepositoryImpl implements CRUD operations related Book entity using SQLAlchemy."""
def __init__(self, session: Session):
self.session: Session = session
def find_by_id(self, id: str) -> Optional[Book]:
try:
book_dto = self.session.query(BookDTO).filter_by(id=id).one()
except NoResultFound:
return None
except:
raise
return book_dto.to_entity()
def find_by_isbn(self, isbn: str) -> Optional[Book]:
try:
book_dto = self.session.query(BookDTO).filter_by(isbn=isbn).one()
except NoResultFound:
return None
except:
raise
return book_dto.to_entity()
def create(self, book: Book):
book_dto = BookDTO.from_entity(book)
try:
self.session.add(book_dto)
except:
raise
def update(self, book: Book):
book_dto = BookDTO.from_entity(book)
try:
_book = self.session.query(BookDTO).filter_by(id=book_dto.id).one()
_book.title = book_dto.title
_book.page = book_dto.page
_book.read_page = book_dto.read_page
_book.updated_at = book_dto.updated_at
except:
raise
def delete_by_id(self, id: str):
try:
self.session.query(BookDTO).filter_by(id=id).delete()
except:
raise
class BookCommandUseCaseUnitOfWorkImpl(BookCommandUseCaseUnitOfWork):
def __init__(
self,
session: Session,
book_repository: BookRepository,
):
self.session: Session = session
self.book_repository: BookRepository = book_repository
def begin(self):
self.session.begin()
def commit(self):
self.session.commit()
def rollback(self):
self.session.rollback()
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,066 | cretomoharada/dddpy | refs/heads/main | /dddpy/domain/book/__init__.py | from .book import Book
from .book_exception import (
BookIsbnAlreadyExistsError,
BookNotFoundError,
BooksNotFoundError,
)
from .book_repository import BookRepository
from .isbn import Isbn
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,067 | cretomoharada/dddpy | refs/heads/main | /dddpy/domain/book/isbn.py | import re
from dataclasses import dataclass
regex = r"978[-0-9]{10,15}"
pattern = re.compile(regex)
@dataclass(init=False, eq=True, frozen=True)
class Isbn:
"""Isbn represents an ISBN code as a value object"""
value: str
def __init__(self, value: str):
if pattern.match(value) is None:
raise ValueError("isbn should be a valid format.")
object.__setattr__(self, "value", value)
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,068 | cretomoharada/dddpy | refs/heads/main | /dddpy/presentation/schema/book/book_error_message.py | from pydantic import BaseModel, Field
from dddpy.domain.book import (
BookIsbnAlreadyExistsError,
BookNotFoundError,
BooksNotFoundError,
)
class ErrorMessageBookNotFound(BaseModel):
detail: str = Field(example=BookNotFoundError.message)
class ErrorMessageBooksNotFound(BaseModel):
detail: str = Field(example=BooksNotFoundError.message)
class ErrorMessageBookIsbnAlreadyExists(BaseModel):
detail: str = Field(example=BookIsbnAlreadyExistsError.message)
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,069 | cretomoharada/dddpy | refs/heads/main | /tests/usecase/book/test_book_query_usecase.py | from unittest.mock import MagicMock, Mock
import pytest
from dddpy.domain.book import BookNotFoundError
from dddpy.infrastructure.sqlite.book import BookQueryServiceImpl
from dddpy.usecase.book import BookQueryUseCaseImpl, BookReadModel
class TestBookQueryUseCase:
def test_fetch_book_by_id_should_return_book(self):
session = MagicMock()
book_query_service = BookQueryServiceImpl(session)
book_query_service.find_by_id = Mock(
return_value=BookReadModel(
id="cPqw4yPVUM3fA9sqzpZmkL",
isbn="978-0321125217",
title="Domain-Driven Design: Tackling Complexity in the Heart of Software",
page=560,
read_page=126,
created_at=1614051983128,
updated_at=1614056689464,
)
)
book_query_usecase = BookQueryUseCaseImpl(book_query_service)
book = book_query_usecase.fetch_book_by_id("cPqw4yPVUM3fA9sqzpZmkL")
assert (
book.title
== "Domain-Driven Design: Tackling Complexity in the Heart of Software"
)
def test_fetch_book_by_id_should_throw_book_not_found_error(self):
session = MagicMock()
book_query_service = BookQueryServiceImpl(session)
book_query_service.find_by_id = Mock(side_effect=BookNotFoundError)
book_query_usecase = BookQueryUseCaseImpl(book_query_service)
with pytest.raises(BookNotFoundError):
book_query_usecase.fetch_book_by_id("cPqw4yPVUM3fA9sqzpZmkL")
def test_fetch_books_should_return_books(self):
session = MagicMock()
book_query_service = BookQueryServiceImpl(session)
book_query_service.find_all = Mock(
return_value=[
BookReadModel(
id="cPqw4yPVUM3fA9sqzpZmkL",
isbn="978-0321125217",
title="Domain-Driven Design: Tackling Complexity in the Heart of Software",
page=560,
read_page=126,
created_at=1614051983128,
updated_at=1614056689464,
)
]
)
book_query_usecase = BookQueryUseCaseImpl(book_query_service)
books = book_query_usecase.fetch_books()
assert len(books) == 1
assert books[0].page == 560
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,070 | cretomoharada/dddpy | refs/heads/main | /tests/domain/book/test_isbn.py | import dataclasses
import pytest
from dddpy.domain.book import Isbn
class TestIsbn:
@pytest.mark.parametrize(
"value",
[
("978-0321125217"),
("978-4-949999-12-0"),
],
)
def test_constructor_should_create_instance(self, value):
isbn = Isbn(value)
assert isbn.value == value
@pytest.mark.parametrize(
"value",
[
("invalid-string"),
("123456789"),
("000-0141983479"),
],
)
def test_constructor_should_throw_value_error_when_params_are_invalid(self, value):
with pytest.raises(ValueError):
Isbn(value)
def test_isbn_should_be_frozen(self):
with pytest.raises(dataclasses.FrozenInstanceError):
isbn = Isbn("978-0321125217")
isbn.value = "978-1141983479" # type: ignore
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,071 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/book_command_usecase.py | from abc import ABC, abstractmethod
from typing import Optional, cast
import shortuuid
from dddpy.domain.book import (
Book,
BookIsbnAlreadyExistsError,
BookNotFoundError,
BookRepository,
Isbn,
)
from .book_command_model import BookCreateModel, BookUpdateModel
from .book_query_model import BookReadModel
class BookCommandUseCaseUnitOfWork(ABC):
"""BookCommandUseCaseUnitOfWork defines an interface based on Unit of Work pattern."""
book_repository: BookRepository
@abstractmethod
def begin(self):
raise NotImplementedError
@abstractmethod
def commit(self):
raise NotImplementedError
@abstractmethod
def rollback(self):
raise NotImplementedError
class BookCommandUseCase(ABC):
"""BookCommandUseCase defines a command usecase inteface related Book entity."""
@abstractmethod
def create_book(self, data: BookCreateModel) -> Optional[BookReadModel]:
raise NotImplementedError
@abstractmethod
def update_book(self, id: str, data: BookUpdateModel) -> Optional[BookReadModel]:
raise NotImplementedError
@abstractmethod
def delete_book_by_id(self, id: str):
raise NotImplementedError
class BookCommandUseCaseImpl(BookCommandUseCase):
"""BookCommandUseCaseImpl implements a command usecases related Book entity."""
def __init__(
self,
uow: BookCommandUseCaseUnitOfWork,
):
self.uow: BookCommandUseCaseUnitOfWork = uow
def create_book(self, data: BookCreateModel) -> Optional[BookReadModel]:
try:
uuid = shortuuid.uuid()
isbn = Isbn(data.isbn)
book = Book(id=uuid, isbn=isbn, title=data.title, page=data.page)
existing_book = self.uow.book_repository.find_by_isbn(isbn.value)
if existing_book is not None:
raise BookIsbnAlreadyExistsError
self.uow.book_repository.create(book)
self.uow.commit()
created_book = self.uow.book_repository.find_by_id(uuid)
except:
self.uow.rollback()
raise
return BookReadModel.from_entity(cast(Book, created_book))
def update_book(self, id: str, data: BookUpdateModel) -> Optional[BookReadModel]:
try:
existing_book = self.uow.book_repository.find_by_id(id)
if existing_book is None:
raise BookNotFoundError
book = Book(
id=id,
isbn=existing_book.isbn,
title=data.title,
page=data.page,
read_page=data.read_page,
)
self.uow.book_repository.update(book)
updated_book = self.uow.book_repository.find_by_id(book.id)
self.uow.commit()
except:
self.uow.rollback()
raise
return BookReadModel.from_entity(cast(Book, updated_book))
def delete_book_by_id(self, id: str):
try:
existing_book = self.uow.book_repository.find_by_id(id)
if existing_book is None:
raise BookNotFoundError
self.uow.book_repository.delete_by_id(id)
self.uow.commit()
except:
self.uow.rollback()
raise
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,072 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/book_query_model.py | from typing import cast
from pydantic import BaseModel, Field
from dddpy.domain.book import Book
class BookReadModel(BaseModel):
"""BookReadModel represents data structure as a read model."""
id: str = Field(example="vytxeTZskVKR7C7WgdSP3d")
isbn: str = Field(example="978-0321125217")
title: str = Field(
example="Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
page: int = Field(ge=0, example=320)
read_page: int = Field(ge=0, example=120)
created_at: int = Field(example=1136214245000)
updated_at: int = Field(example=1136214245000)
class Config:
orm_mode = True
@staticmethod
def from_entity(book: Book) -> "BookReadModel":
return BookReadModel(
id=book.id,
isbn=book.isbn.value,
title=book.title,
page=book.page,
read_page=book.read_page,
created_at=cast(int, book.created_at),
updated_at=cast(int, book.updated_at),
)
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,073 | cretomoharada/dddpy | refs/heads/main | /dddpy/infrastructure/sqlite/book/__init__.py | from .book_dto import BookDTO
from .book_query_service import BookQueryServiceImpl
from .book_repository import BookCommandUseCaseUnitOfWorkImpl, BookRepositoryImpl
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,074 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/book_command_model.py | from pydantic import BaseModel, Field, validator
class BookCreateModel(BaseModel):
"""BookCreateModel represents a write model to create a book."""
isbn: str = Field(example="978-0321125217")
title: str = Field(
example="Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
page: int = Field(ge=0, example=320)
class BookUpdateModel(BaseModel):
"""BookUpdateModel represents a write model to update a book."""
title: str = Field(
example="Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
page: int = Field(ge=0, example=320)
read_page: int = Field(ge=0, example=120)
@validator("read_page")
def _validate_read_page(cls, v, values, **kwargs):
if "page" in values and v > values["page"]:
raise ValueError(
"read_page must be between 0 and {}".format(values["page"])
)
return v
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,075 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/book_query_service.py | from abc import ABC, abstractmethod
from typing import List, Optional
from .book_query_model import BookReadModel
class BookQueryService(ABC):
"""BookQueryService defines a query service inteface related Book entity."""
@abstractmethod
def find_by_id(self, id: str) -> Optional[BookReadModel]:
raise NotImplementedError
@abstractmethod
def find_all(self) -> List[BookReadModel]:
raise NotImplementedError
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,076 | cretomoharada/dddpy | refs/heads/main | /dddpy/usecase/book/__init__.py | from .book_command_model import BookCreateModel, BookUpdateModel
from .book_command_usecase import (
BookCommandUseCase,
BookCommandUseCaseImpl,
BookCommandUseCaseUnitOfWork,
)
from .book_query_model import BookReadModel
from .book_query_service import BookQueryService
from .book_query_usecase import BookQueryUseCase, BookQueryUseCaseImpl
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,077 | cretomoharada/dddpy | refs/heads/main | /tests/infrastructure/sqlite/book/test_book_dto.py | import pytest
from dddpy.domain.book import Book, Isbn
from dddpy.infrastructure.sqlite.book import BookDTO
class TestBookDTO:
def test_to_read_model_should_create_entity_instance(self):
book_dto = BookDTO(
id="book_01",
isbn="978-0321125217",
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=120,
created_at=1614007224642,
updated_at=1614007224642,
)
book = book_dto.to_read_model()
assert book.id == "book_01"
assert book.isbn == "978-0321125217"
assert (
book.title
== "Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
assert book.page == 560
assert book.read_page == 120
def test_to_entity_should_create_entity_instance(self):
book_dto = BookDTO(
id="book_01",
isbn="978-0321125217",
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=120,
created_at=1614007224642,
updated_at=1614007224642,
)
book = book_dto.to_entity()
assert book.id == "book_01"
assert book.isbn == Isbn("978-0321125217")
assert (
book.title
== "Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
assert book.page == 560
assert book.read_page == 120
def test_from_entity_should_create_dto_instance(self):
book = Book(
id="book_01",
isbn=Isbn("978-0321125217"),
title="Domain-Driven Design: Tackling Complexity in the Heart of Softwares",
page=560,
read_page=120,
created_at=1614007224642,
updated_at=1614007224642,
)
book_dto = BookDTO.from_entity(book)
assert book_dto.id == "book_01"
assert book_dto.isbn == "978-0321125217"
assert (
book_dto.title
== "Domain-Driven Design: Tackling Complexity in the Heart of Softwares"
)
assert book_dto.page == 560
assert book_dto.read_page == 120
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,078 | cretomoharada/dddpy | refs/heads/main | /dddpy/infrastructure/sqlite/book/book_query_service.py | from typing import List, Optional
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.session import Session
from dddpy.usecase.book import BookQueryService, BookReadModel
from .book_dto import BookDTO
class BookQueryServiceImpl(BookQueryService):
"""BookQueryServiceImpl implements READ operations related Book entity using SQLAlchemy."""
def __init__(self, session: Session):
self.session: Session = session
def find_by_id(self, id: str) -> Optional[BookReadModel]:
try:
book_dto = self.session.query(BookDTO).filter_by(id=id).one()
except NoResultFound:
return None
except:
raise
return book_dto.to_read_model()
def find_all(self) -> List[BookReadModel]:
try:
book_dtos = (
self.session.query(BookDTO)
.order_by(BookDTO.updated_at)
.limit(100)
.all()
)
except:
raise
if len(book_dtos) == 0:
return []
return list(map(lambda book_dto: book_dto.to_read_model(), book_dtos))
| {"/dddpy/domain/book/book.py": ["/dddpy/domain/book/isbn.py"], "/main.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/presentation/schema/book/book_error_message.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_book.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/dddpy/usecase/book/book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py"], "/dddpy/domain/book/book_repository.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_repository.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"], "/dddpy/domain/book/__init__.py": ["/dddpy/domain/book/book.py", "/dddpy/domain/book/book_repository.py", "/dddpy/domain/book/isbn.py"], "/dddpy/presentation/schema/book/book_error_message.py": ["/dddpy/domain/book/__init__.py"], "/tests/usecase/book/test_book_query_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py", "/dddpy/usecase/book/__init__.py"], "/tests/domain/book/test_isbn.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/usecase/book/book_command_usecase.py": ["/dddpy/domain/book/__init__.py", "/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/book_query_model.py": ["/dddpy/domain/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/__init__.py": ["/dddpy/infrastructure/sqlite/book/book_dto.py", "/dddpy/infrastructure/sqlite/book/book_query_service.py", "/dddpy/infrastructure/sqlite/book/book_repository.py"], "/dddpy/usecase/book/book_query_service.py": ["/dddpy/usecase/book/book_query_model.py"], "/dddpy/usecase/book/__init__.py": ["/dddpy/usecase/book/book_command_model.py", "/dddpy/usecase/book/book_command_usecase.py", "/dddpy/usecase/book/book_query_model.py", "/dddpy/usecase/book/book_query_service.py", "/dddpy/usecase/book/book_query_usecase.py"], "/tests/infrastructure/sqlite/book/test_book_dto.py": ["/dddpy/domain/book/__init__.py", "/dddpy/infrastructure/sqlite/book/__init__.py"], "/dddpy/infrastructure/sqlite/book/book_query_service.py": ["/dddpy/usecase/book/__init__.py", "/dddpy/infrastructure/sqlite/book/book_dto.py"]} |
48,079 | whiterson/mockingJay | refs/heads/master | /tribute.py | import random
import engine
import json
import copy
import sys
from probability import uniform_variable as U
from weaponInfo import weaponInfo
from weapon import weapon
import mapReader
class Particle(object):
def __init__(self, state=(0, 0), width=1, height=1):
self.state = state
self.width, self.height = width, height
FIGHT_STATE = {'not_fighting': 0, 'fleeing': 1, 'fighting': 2}
NAVIGATION_POINTS = [(25, 25), (5, 5), (45, 5), (45, 45), (5, 45)]
FIGHT_EMERGENCY_CUTOFF = 80
class Tribute(Particle):
#Goals = list of goals for tribute
################ ACTIONS
# movement l,r,u,d
# hunt
# fight
# scavenge
# craft
# hide
# water
# rest
# talk
ID_COUNTER = 0
def __init__(self, goals, actions, x=0, y=0, district='d12', gender='male', do_not_load=False):
Particle.__init__(self, (x, y), 1, 1)
self.id = Tribute.ID_COUNTER
Tribute.ID_COUNTER += 1
self.goals = goals
self.actions = actions
# remove the fight action. we don't want them fighting unless someone is in range
self.fight_action = actions[5]
self.explore_action = actions[12]
self.actions = self.actions[:5] + self.actions[6:12]
self.district = district
self.has_weapon = False
self.weapon = weapon('')
self.has_ally = False
self.allies = []
self.craftPouch = []
self.fighting_state = FIGHT_STATE['not_fighting']
self.opponent = None
self.last_opponent = None
self.sighted = None
self.last_sighted_location = None
self.last_action = None
self.printy_action = 'none'
self.old_state = self.state
self.visited_set = set()
self.explore_point_index = 0
self.explore_point = NAVIGATION_POINTS[self.explore_point_index]
self.hidden = False
self.weaponInfo = weaponInfo()
self.wepCanCraft = ''
self.bestScavChoice = ''
self.bestScavPoints = 0
if do_not_load:
self.attributes = None
self.gender = gender
self.stats = None
self.last_name = None
self.first_name = None
self.killed = None
else:
d = json.load(open('./distributions/stats.json'))
self.attributes = {
'size': U(d['size']['mean'], d['size']['spread']),
'strength': U(d['strength']['mean'], d['strength']['spread']),
'speed': U(d['speed']['mean'], d['speed']['spread']),
'hunting_skill': U(d['hunting_skill'][self.district]['mean'], d['hunting_skill'][self.district]['spread']),
'fighting_skill': U(d['fighting_skill'][self.district]['mean'], d['fighting_skill'][self.district]['spread']),
'weapon_skill': U(d['weapon_skill'][self.district]['mean'], d['weapon_skill'][self.district]['spread']),
'camouflage_skill': U(d['camouflage_skill'][self.district]['mean'], d['camouflage_skill'][self.district]['spread']),
'friendliness': U(d['friendliness']['mean'], d['friendliness']['spread']),
'district_prejudices': dict(d['district_prejudices'][self.district]),
'stamina': U(d['stamina']['mean'], d['stamina']['spread']),
'endurance': U(d['endurance']['mean'], d['endurance']['spread']),
'crafting_skill': U(d['crafting_skill'][self.district]['mean'], d['crafting_skill'][self.district]['spread']),
'bloodlust': U(d['bloodlust']['mean'], d['bloodlust']['spread']),
'max_health': U(d['max_health']['mean'], d['max_health']['spread'])
}
self.gender = gender
self.stats = {
'health': self.attributes['max_health'],
'energy': self.attributes['stamina'],
'hunger_energy': 100
}
self.last_name = random.choice(d['last_names'])
if self.gender == 'male':
self.first_name = random.choice(d['first_names_male'])
else:
self.first_name = random.choice(d['first_names_female'])
self.killed = False
pass
def clone(self):
n_goals = [g.clone() for g in self.goals]
n_actions = self.actions[:5] + [self.fight_action] + self.actions[5:12] + [self.explore_action]
n_district = self.district[:]
n_gender = self.gender[:]
n = Tribute(n_goals, n_actions, x=self.state[0], y=self.state[1], district=n_district,
gender=n_gender, do_not_load=True)
n.killed = self.killed
n.attributes = self.attributes.copy()
n.stats = self.stats.copy()
n.opponent = self.opponent
n.sighted = self.sighted
n.last_action = self.last_action
n.printy_action = self.printy_action
n.last_opponent = self.last_opponent
n.bestScavChoice = self.bestScavChoice
n.bestScavPoints = self.bestScavPoints
n.visited_set = self.visited_set.copy()
n.explore_point = self.explore_point
n.explore_point_index = self.explore_point_index
n.craftPouch = self.craftPouch
n.wepCanCraft = self.wepCanCraft
n.hidden = self.hidden
n.last_sighted_location = self.last_sighted_location
n.id = self.id
return n
def __repr__(self):
s = '<Tribute>(' + self.last_name + ', ' + self.first_name + ', ' + self.gender + ')'
return s
def engage_in_combat(self, t):
if self.fighting_state == FIGHT_STATE['not_fighting']:
self.fighting_state = FIGHT_STATE['fighting']
self.opponent = t
self.last_opponent = self.opponent
t.engage_in_combat(self)
if engine.GameEngine.FIGHT_MESSAGES:
print str(self) + ' is engaging in combat with ' + str(t) + '!'
elif self.fighting_state == FIGHT_STATE['fleeing']:
self.opponent = t
if self.opponent.fighting_state != FIGHT_STATE['fleeing']:
t.engage_in_combat(self)
if engine.GameEngine.FIGHT_MESSAGES:
print str(self) + ' is being chased by ' + str(t) + '!'
def disengage_in_combat(self, t):
if self.fighting_state != FIGHT_STATE['not_fighting']:
self.fighting_state = FIGHT_STATE['not_fighting']
self.opponent = None
t.disengage_in_combat(self)
if engine.GameEngine.FIGHT_MESSAGES:
print str(self) + ' is disengaging in combat with ' + str(t) + '!'
def surmise_enemy_hit(self, tribute):
"""
returns the estimate average HP hit for an enemy
:param tribute: the enemy to surmise about
:return: the surmised value
"""
return 1 + int(tribute.has_weapon) * 5 + int(tribute.attributes['strength']) / 2
def surmise_escape_turns(self, tribute):
turns = -1
if self.attributes['speed'] >= tribute.attributes['speed']:
turns = sys.maxint
else:
s = tribute.attributes['speed'] - self.attributes['speed']
distance = abs(self.state[0] - tribute.state[0]) + abs(self.state[1] - tribute.state[1])
turns = distance / s
return turns
def surmise_enemy_weakness(self, tribute):
index = tribute.attributes['max_health'] - tribute.stats['health']
val = float(index) / tribute.attributes['max_health']
return int(round(val * 5))
def enemy_in_range(self, game_state):
for t in game_state.grid['particle']:
p = t[3]
d = abs(t[0] - self.state[0]) + abs(t[1] - self.state[1])
if 0 < d < 5 and p not in self.allies:
return p
return None
def hurt(self, damage, place):
if engine.GameEngine.FIGHT_MESSAGES:
print str(self) + ' was hit in the ' + place + ' for ' + str(damage) + ' damage'
self.goals[3].modify_value(-3)
self.stats['health'] -= damage
self.goals[7].value += damage*10
if self.stats['health'] <= 0:
self.killed = True
self.killedBy = self.opponent
if engine.GameEngine.FIGHT_MESSAGES:
print str(self) + ' was killed by ' + str(self.killedBy)
self.disengage_in_combat((self.opponent or self.killedBy or self.last_opponent))
#Need to figure out exactly how far
#/ how we want to handle depth in this function
#it will be very important
def calc_min_discomfort(self, depth, max_depth, gameMap, actions):
min_val = sys.maxint
if depth == max_depth:
return self.calc_discomfort()
for action in actions:
tribute = self.clone()
tribute.apply_action(action, gameMap)
min_val = min(tribute.calc_min_discomfort(depth + 1, max_depth, gameMap, actions), min_val)
return min_val
def decide_fight_move(self, game_map):
if self.goals[7].value < random.randrange(105, 150):
actions = ['attack_head', 'attack_chest', 'attack_gut', 'attack_legs']
return random.choice(actions)
else:
###print str(self), ' became scared and is trying to flee!'
return 'flee'
def act(self, gameMap, game_state):
if self.fighting_state != FIGHT_STATE['fighting']:
best_action = (None, sys.maxint)
actions = self.actions
self.sighted = self.enemy_in_range(game_state)
if self.sighted:
self.last_sighted_location = self.sighted.state
if self.sighted and not self.sighted.killed:
actions = self.actions + [self.fight_action]
if self.goals[0].value > 90 or self.goals[1].value > 50 and self.sighted is None:
actions = self.actions + [self.explore_action]
self.explore_point = NAVIGATION_POINTS[self.explore_point_index]
elif self.goals[3].value > FIGHT_EMERGENCY_CUTOFF and self.sighted is None:
actions = self.actions + [self.explore_action]
if self.last_sighted_location:
self.explore_point = self.last_sighted_location
neighbors = mapReader.get_neighbors2(gameMap, self.state)
forbidden_states = []
for trib in engine.GameEngine.tributes:
if trib.state in neighbors and trib.id != self.id:
forbidden_states.append(trib.state)
for a in actions:
n_pos = mapReader.add_states(self.state, a.delta_state)
if n_pos in forbidden_states:
continue
t = copy.deepcopy(self)
t.apply_action(a, gameMap)
v = t.calc_min_discomfort(0, 2, gameMap, actions)
if v < best_action[1]:
best_action = (a, v)
thirst = 0
hung = 0
rest = 0
# for goal in self.goals:
# rand = random.randint(0,2)
# #very hungry and slightly hungry
# if goal.name == 'hunger' and ((goal.value > 22 and goal.value < 26) or (goal.value >13 and goal.value <16)):
# best_action = (self.actions[rand], 100)
# hung = goal.value
#
#
# #very thirsty and slightly thirsty
# if goal.name == 'thirst' and ((goal.value > 22 and goal.value < 26) or (goal.value>13 and goal.value < 16)):
# best_action = (self.actions[rand], 100)
# thirst = goal.value
#
# if self.goals[3].value >= 150 and thirst < 33 and hung < 33 and rest < 40:
# best_action = (self.actions[rand+1], 100)
self.do_action(best_action[0], gameMap)
elif self.fighting_state == FIGHT_STATE['fighting']:
best_action = self.decide_fight_move(gameMap)
self.do_fight_action(best_action)
def do_fight_action(self, action_name):
if self.opponent and mapReader.l1_dist(self.state, self.opponent.state) > 2:
self.disengage_in_combat(self.opponent)
return
if self.opponent.killed:
self.disengage_in_combat(self.opponent)
return
self.goals[3].modify_value(-1)
if self.opponent.hidden:
print str(self), ' cannot find ', str(self.opponent)
self.last_action = action_name
self.printy_action = action_name
damage = 0
# with weapon 1d6 damage + 1d(str/2) + 1
if self.has_weapon:
damage = self.weapon.damage + random.randrange(1, (self.attributes['strength'] / 4) + 2) + random.randint(0, self.attributes['weapon_skill']/2 + 1)+ 1
else: # without, 1d2 damage + 1d(str)
damage = random.randrange(1, 3) + random.randrange(1, self.attributes['strength'] + 1)
draw = random.random()
chance_mult = 1
if self.attributes['fighting_skill'] > 3:
chance_mult += 0.1
if self.attributes['fighting_skill'] > 7:
chance_mult += 0.15
if action_name == 'attack_head':
if draw < 0.5 * chance_mult:
self.opponent.hurt(damage + 2, 'head')
self.goals[7].value = max(self.goals[7].value - (damage + 2) / 2, 0)
elif action_name == 'attack_chest':
if draw < 0.8 * chance_mult:
self.opponent.hurt(damage + 1, 'chest')
self.goals[7].value = max(self.goals[7].value - (damage + 1) / 2, 0)
elif action_name == 'attack_gut':
if draw < 0.8 * chance_mult:
self.opponent.hurt(damage, 'gut')
self.goals[7].value = max(self.goals[7].value - (damage) / 2, 0)
elif action_name == 'attack_legs':
if draw < 0.9 * chance_mult:
self.opponent.hurt(damage - 1, 'legs')
self.goals[7].value = max(self.goals[7].value - (damage - 1) / 2, 0)
elif action_name == 'flee':
self.opponent.disengage_in_combat(self)
for goal in self.goals:
if goal.name == "kill":
goal.value = 0
self.fighting_state = FIGHT_STATE['fleeing']
def do_action(self, action, game_map):
##IF you can Craft a weapon, do it
##if(not self.has_weapon):
## for weapon in self.weaponInfo.weaponList:
## if self.weaponInfo.canCraft(weapon, self.craftPouch):
## action.index = 7
## self.wepCanCraft = weapon
self.hidden = False
self.last_action = action
self.printy_action = action.description
rand = (random.randint(1, 10)) / 10
loc = game_map[self.state[0]][self.state[1]]
if action.index >= 0 and action.index <= 3: # moving so don't know what gonna do here
loc.setTribute(None)
self.old_state = self.state
(game_map[self.state[0]][self.state[1]]).setTribute(None)
self.state = ((self.state[0] + action.delta_state[0]) % engine.GameEngine.map_dims[0],
(self.state[1] + action.delta_state[1]) % engine.GameEngine.map_dims[1])
(game_map[self.state[0]][self.state[1]]).setTribute(self)
elif action.index == 4: # find food
food_prob = loc.getFoodChance()
for goal in self.goals:
if goal.name == "hunger":
if rand <= food_prob:
goal.value -= action.values[0]*3
elif action.index == 5: # fight
self.sighted.engage_in_combat(self)
self.goals[3].value = max(self.goals[3].value - action.values[0], 0)
elif action.index == 6: # scavenge
wep_prob = loc.getWeaponChance()
for goal in self.goals:
if goal.name == "getweapon":
if wep_prob > 0.9:
if rand <= wep_prob:
self.getWeapon()
goal.value -= action.values[0]
else:
#doCraftScavenge will return zero if you fail to find something, and one if you succeed
num = self.checkCraftScavenge(game_map)
goal.value -= self.bestScavPoints * self.doCraftScavenge(game_map, self.bestScavChoice)
elif action.index == 7: # craft
##Crafting Probability is factored into doCraftWeapon
self.checkCraftWeapon()
if self.wepCanCraft != '':
for goal in self.goals:
if goal.name == "getweapon":
## Returns boolean if you did it or not
crafted = self.doCraftWeapon(game_map, self.wepCanCraft)
if crafted:
goal.value = 0
else:
goal.value -= (self.attributes['crafting_skill'])
elif action.index == 8: # hide
ub = self.attributes['camouflage_skill']
if random.randrange(0, 11) < ub:
self.hidden = True
elif action.index == 9: # get water
water_prob = loc.getWaterChance()
for goal in self.goals:
if goal.name == "thirst":
if rand <= water_prob:
goal.value -= action.values[0]
elif action.index == 10: # rest
for goal in self.goals:
if goal.name == "rest":
goal.value -= action.values[0]
elif action.index == 11: # talk ally
f1 = self.attributes['friendliness']
x = self.state[0]
y = self.state[1]
w = engine.GameEngine.map_dims[0]
h = engine.GameEngine.map_dims[1]
targ = game_map[(x + 1) % w][y].tribute or \
game_map[(x - 1) % w][y].tribute or \
game_map[x][(y + 1) % h].tribute or \
game_map[x][(y - 1) % h].tribute
if not targ:
print 'No target for ally!'
elif targ not in self.allies and targ.id != self.id:
f2 = targ.attributes['friendliness']
a1 = self.attributes['district_prejudices'][targ.district]
a2 = targ.attributes['district_prejudices'][self.district]
v = (f1 + f2 + a1 + a2) / 224.0
if random.random() < v:
##print str(self), ' and ', str(targ), ' have gotten allied!'
self.allies.append(targ)
targ.allies.append(self)
self.goals[6].value = 0
elif action.index == 12: # explore
directions = mapReader.get_neighbors(game_map, self.state)
evals = []
for i, direction in enumerate(directions):
if game_map[direction[0]][direction[1]].tribute is None:
evals.append((mapReader.l1_dist(direction, self.explore_point), direction, i))
if len(evals) > 0:
direction = min(evals, key=lambda x: x[0] + random.random() / 1000) # rand is for breaking ties
if mapReader.l1_dist(self.explore_point, direction[1]) < 3:
if self.goals[3].value > FIGHT_EMERGENCY_CUTOFF:
self.last_sighted_location = (self.explore_point[0] + U(0, 16),
self.explore_point[1] + U(0, 16))
else:
self.explore_point_index = (self.explore_point_index + 1) % len(NAVIGATION_POINTS)
self.explore_point = NAVIGATION_POINTS[self.explore_point_index]
##print 'exploring!!'
self.state = direction[1]
def calc_disc(self, gameMap):
ret = 0
for goals in self.goals:
ret += goals.value * goals.value
return ret
def end_turn(self):
for goal in self.goals:
if goal.name == "kill" and self.fighting_state != FIGHT_STATE['fleeing']:
goal.value += ((self.attributes["bloodlust"]-1)/5.0) + 1
if (int(self.district[1:]) == 1 or int(self.district[1:]) or int(self.district[1:]) == 4):
if goal.name == 'kill':
goal.value +=0.1
if(goal.name == 'getweapon' and not self.has_weapon):
goal.value += 0.05
if (int(self.district[1:]) == 1 or int(self.district[1:]) or int(self.district[1:]) == 4):
if goal.name == 'kill':
goal.value +=0.25
if goal.name == 'getweapon' and not self.has_weapon:
goal.value += (1/(self.attributes['size'] + self.attributes['strength']))
if (self.attributes['size'] + self.attributes['strength']) < 4:
if goal.name == 'weapon' and not self.has_weapon:
goal.value += 0.1
if(goal.name == 'ally' and not self.has_ally and not self.has_weapon):
goal.value +=0.05
if(goal.name == 'hide' and not self.has_ally and not self.has_weapon):
goal.value += 0.01
if goal.name == 'ally':
goal.value += 0.05 / (len(self.allies) + 1)**2
if goal.name == 'hunger':
goal.value += ((1.0/self.attributes['endurance']) + (self.attributes['size']/5.0))
if goal.name == 'thirst':
goal.value += 1.0/self.attributes['endurance']
if goal.name == 'rest':
goal.value += (1.0/self.attributes['stamina'] + self.goals[0].value/50.0 + self.goals[1].value/30.0)
if goal.name == 'fear':
goal.value = max(goal.value - 2.5, 0)
if goal.value < 30 and self.fighting_state == FIGHT_STATE['fleeing']:
self.fighting_state = FIGHT_STATE['not_fighting']
if goal.name == 'getweapon' and not self.has_weapon:
goal.value += 0.5
goal.value = max(goal.value, 0)
#Action will update the state of the world by calculating
#Goal updates and where it is / fuzzy logic of where other tributes are
#will update current selfs world.
def apply_action(self, action, gameMap):
# [hunger, thirst, rest, kill, hide, getweapon, ally, fear]
loc = gameMap[self.state[0]][self.state[1]]
distance_before = 0
if self.last_opponent and self.fighting_state == FIGHT_STATE['fleeing']:
distance_before = abs(self.state[0] - self.last_opponent.state[0]) + \
abs(self.state[1] + self.last_opponent.state[1])
if 3 >= action.index >= 0: # moving so don't know what gonna do here
self.old_state = self.state
self.state = ((self.state[0] + action.delta_state[0]) % engine.GameEngine.map_dims[0],
(self.state[1] + action.delta_state[1]) % engine.GameEngine.map_dims[1])
g = random.choice(self.goals)
g.value -= -0.5
elif action.index == 4: # hunt
foodProb = loc.getFoodChance()
self.goals[0].value -= foodProb * action.values[0]
elif action.index == 5: # kill
if abs(self.sighted.state[0] - self.state[0]) + abs(self.sighted.state[1] - self.state[1]) <= 2:
self.goals[3].value = max(self.goals[3].value - action.values[0]*10, 0)
if self.surmise_enemy_hit(self.sighted) > self.surmise_enemy_hit(self):
self.goals[7].value += 5
if self.surmise_escape_turns(self.sighted) < 5:
self.goals[7].value += 5
weakness = self.surmise_enemy_weakness(self.sighted)
# self.goals[7].value -= weakness
if weakness < 1:
self.goals[7].value -= 11
elif action.index == 6: # scavenge
wepChance = loc.getWeaponChance()
if wepChance > 0.9 and not self.has_weapon:
self.goals[5].value -= wepChance * action.values[0]
elif(not self.has_weapon):
self.goals[5].value -= self.checkCraftScavenge(gameMap)
elif action.index == 7: # craft
craftProb = self.checkCraftWeapon()
self.goals[5].value -= (self.goals[5].value * craftProb)
elif action.index == 8: # hide
self.goals[7].modify_value(-(action.values[0] * (self.attributes['camouflage_skill'] / 10.0)))
elif action.index == 9: # get_water
waterProb = loc.getWaterChance()
self.goals[1].value -= waterProb * action.values[0]
elif action.index == 10: # rest
self.goals[2].value -= action.values[0]
elif action.index == 11: # talk ally
x = self.state[0]
y = self.state[1]
w = engine.GameEngine.map_dims[0]
h = engine.GameEngine.map_dims[1]
if (gameMap[(x + 1) % w][y].tribute is not None and gameMap[(x + 1) % w][y].tribute not in self.allies) or \
(gameMap[(x - 1) % w][y].tribute is not None and gameMap[(x - 1) % w][y].tribute not in self.allies) or \
(gameMap[x][(y + 1) % h].tribute is not None and gameMap[x][(y + 1) % h].tribute not in self.allies) or \
(gameMap[x][(y - 1) % h].tribute is not None and gameMap[x][(y - 1) % h].tribute not in self.allies):
self.goals[6].value -= action.values[0]
elif action.index == 12: # explore
self.goals[0].value = max(self.goals[0].value - action.values[0], 0)
self.goals[1].value = max(self.goals[1].value - action.values[1], 0)
self.goals[3].value = max(self.goals[1].value - action.values[2], 0)
distance_after = 1
if self.last_opponent and self.fighting_state == FIGHT_STATE['fleeing']:
distance_after = abs(self.state[0] - self.last_opponent.state[0]) + \
abs(self.state[1] + self.last_opponent.state[1])
if distance_after <= distance_before and self.fighting_state == FIGHT_STATE['fleeing']:
self.goals[7].value += 100
def calc_discomfort(self):
val = 0
for goal in self.goals:
if(goal.value > 0):
val += goal.value*goal.value
return val
def checkDead(self):
for goal in self.goals:
if goal.name == "hunger":
if goal.value >= 200:
self.killed = True
return " starvation "
#You get thirsty a lot faster than you get hungry
if goal.name == "thirst":
if goal.value >= 200:
self.killed = True
return " terminal dehydration "
if goal.name == "rest":
if goal.value >= 250:
self.killed = True
return " exhaustion "
if self.killed:
return self.killedBy
else:
return None
def getWeapon(self):
self.has_weapon = True
weaponType = random.randint(1, 10)
self.weapon = weapon(self.weaponInfo.weaponType(weaponType))
print str(self), ' has picked up a ', str(self.weapon)
def checkCraftScavenge(self, game_map):
self.bestScavChoice = ''
self.bestScavPoints = 0
location = game_map[self.state[0]][self.state[1]]
craftTypes = self.weaponInfo.craftTypes
bestPossPoints = 0
for type in craftTypes:
poss = (self.retScavTypeProb(type, location) * 10)
if poss != 0:
mockPouch = copy.deepcopy(self.craftPouch)
##If you've already got what you're scavenging for
already_have = 0
for item in mockPouch:
if item == type:
already_have = 1
if already_have < 1:
mockPouch.append(type)
for weapon in self.weaponInfo.weaponList:
possPoints = 0
canCraft = self.weaponInfo.canCraft(weapon,mockPouch)
if canCraft:
possPoints += 5 + (self.weaponInfo.weaponStrength(weapon)/2)
if possPoints > self.bestScavPoints:
self.bestScavPoints = possPoints
self.bestScavChoice = type
bestPossPoints = possPoints
return bestPossPoints
else:
numItemsNeedToCraft = len(self.weaponInfo.itemsNeededToCraft(weapon,mockPouch))
possPoints += 5 - numItemsNeedToCraft + (self.weaponInfo.weaponStrength(weapon)/10) + poss
if possPoints > self.bestScavPoints:
self.bestScavPoints = possPoints
self.bestScavChoice = type
bestPossPoints = possPoints
return bestPossPoints
def doCraftScavenge(self, game_map, type):
loc = game_map[self.state[0]][self.state[1]]
crTyProb = self.retScavTypeProb(type, loc)
chance = random.randint(1, 10)
if chance <= (10*crTyProb):
cValue = 1
self.craftPouch.append(type)
else:
cValue = 0
return cValue
def retScavTypeProb(self, type, loc):
if type == 'shortStick':
crTyProb = loc.shortStickChance
elif type == 'sharpStone':
crTyProb = loc.sharpStoneChance
elif type == 'feather':
crTyProb = loc.featherChance
elif type == 'vine':
crTyProb = loc.vineChance
elif type == 'longStick':
crTyProb = loc.longStickChance
elif type == 'broadStone':
crTyProb = loc.broadStoneChance
elif type == 'longGrass':
crTyProb = loc.longGrassChance
elif type == 'reeds':
crTyProb = loc.reedsChance
elif type == 'pebbles':
crTyProb = loc.pebblesChance
elif type == 'thorns':
crTyProb = loc.thornsChance
else:
crTyProb = 0
return crTyProb
#Returns the probability of Crafting a Weapon based on your items & skill
def checkCraftWeapon(self):
probCraft = self.attributes['crafting_skill']
craftableWeapon = None
maxWepStrength = 0
numItemsCraftWep = 0
canCraft = 0
for wepType in self.weaponInfo.weaponList:
ans = self.weaponInfo.canCraft(wepType, self.craftPouch)
if(ans):
canCraft = 1
strength = self.weaponInfo.weaponStrength(wepType)
if strength > maxWepStrength:
maxWepStrength = strength
numItemsCraftWep = self.weaponInfo.totalNumItemsToCraft(wepType)
craftableWeapon = wepType
elif strength == maxWepStrength:
if self.weaponInfo.totalNumItemsToCraft(wepType) < numItemsCraftWep:
maxWepStrength = strength
numItemsCraftWep = self.weaponInfo.totalNumItemsToCraft(wepType)
craftableWeapon = wepType
else:
craftableWeapon = self.wepCanCraft
self.wepCanCraft = craftableWeapon
return probCraft*canCraft*100
#Craft the weapon based on your skill. If you fail to craft, you still lose the items. Wah-wah.
def doCraftWeapon(self, game_map, wepToCraft):
itemsUsed = self.weaponInfo.totalItemsToCraft(wepToCraft)
for needed in itemsUsed:
for supply in self.craftPouch:
if needed == supply:
self.craftPouch.remove(supply)
chance = random.randint(1,10)
if chance <= self.attributes['crafting_skill']:
crafted = True
self.weapon = weapon(wepToCraft)
else:
crafted = False
self.wepCanCraft = None
self.has_weapon = crafted
return crafted
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,080 | whiterson/mockingJay | refs/heads/master | /probability.py | __author__ = 'Nathan'
import random
def uniform_variable(mean, spread):
base = random.randrange(0, 2*spread) - spread
s = base + mean
return s
def discrete_variable(pmf, domain):
cum_sum = 0
cdf = [0]
for x in range(domain[0], domain[1]):
cum_sum += pmf(x)
cdf.append(cum_sum)
if cum_sum != 1:
print 'Invalid pmf given to discrete_variable'
num = random.random()
index = 0
while num > cdf[index]:
index += 1
return domain[0] + index
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,081 | whiterson/mockingJay | refs/heads/master | /weaponInfo.py | class weaponInfo:
def __init__(self):
self.bow = ['longStick', 'shortStick', 'vine', 'sharpStone', 'feather']
self.slingshot= ['longGrass', 'pebbles']
self.blowgun = ['reeds', 'feather', 'thorn']
self.hammer = ['broadStone','shortStick']
self.mace = ['sharpStone', 'thorn', 'shortStick']
self.trident = ['longStick', 'shortStick', 'sharpStone']
self.spear = ['longStick', 'sharpStone']
self.axe = ['broadStone', 'longStick', 'reeds']
self.sword = []
self.dagger = ['sharpStone', 'longGrass']
self.craftTypes = ['shortStick', 'longStick', 'sharpStone', 'broadStone', 'pebbles', 'feather', 'vine', 'reeds', 'longGrass', 'thorns']
self.weaponList = ['bow', 'slingshot', 'blowgun', 'hammer', 'mace', 'trident', 'spear', 'axe', 'sword', 'dagger']
self.error = []
def weaponType(self, num):
if(num == 1):
res = 'bow'
elif(num == 2):
res= 'slingshot'
elif(num == 3):
res = 'blowgun'
elif(num == 4):
res = 'hammer'
elif(num == 5):
res = 'mace'
elif(num == 6):
res= 'trident'
elif(num == 7):
res = 'spear'
elif(num == 8):
res = 'axe'
elif(num == 9):
res = 'sword'
elif(num == 10):
res = 'dagger'
else:
res = None
return res
def weaponStrength(self, type):
if(type == 'bow'):
strength = 6
elif(type == 'slingshot'):
strength = 3
elif(type == 'blowgun'):
strength = 3
elif(type == 'hammer'):
strength = 5
elif(type == 'mace'):
strength = 6
elif(type == 'trident'):
strength = 5
elif(type == 'spear'):
strength = 5
elif(type == 'axe'):
strength = 5
elif(type == 'sword'):
strength = 6
elif(type == 'dagger'):
strength = 4
else:
strength = 5
return strength
def weaponRange(self, type):
if(type == 'bow'):
range = 7
elif(type == 'slingshot'):
range = 5
elif(type == 'blowgun'):
range = 4
else:
range = 1
return range
## Returns full list of items needed to craft a certain weapon
def totalItemsToCraft(self, type):
if(type == 'bow'):
return self.bow
elif(type == 'slingshot'):
return self.slingshot
elif(type == 'blowgun'):
return self.blowgun
elif(type == 'hammer'):
return self.hammer
elif(type == 'mace'):
return self.mace
elif(type == 'trident'):
return self.trident
elif(type == 'spear'):
return self.spear
elif(type == 'axe'):
return self.axe
elif(type == 'sword'):
return self.sword
elif(type == 'dagger'):
return self.dagger
else:
return self.error
def totalNumItemsToCraft(self, type):
if(type == 'bow'):
return len(self.bow)
elif(type == 'slingshot'):
return len(self.slingshot)
elif(type == 'blowgun'):
return len(self.blowgun)
elif(type == 'hammer'):
return len(self.hammer)
elif(type == 'mace'):
return len(self.mace)
elif(type == 'trident'):
return len(self.trident)
elif(type == 'spear'):
return len(self.spear)
elif(type == 'axe'):
return len(self.axe)
elif(type == 'sword'):
return len(self.sword)
elif(type == 'dagger'):
return len(self.dagger)
else:
return len(self.error)
def canCraft(self, type, items):
itemList = self.totalItemsToCraft(type)
tribItems = items
ans = False
if(type == 'sword'):
return False
if(len(itemList) > len(tribItems)):
ans = False
else:
matchedItems = 0
for needed in itemList:
for item in tribItems:
if item == needed:
matchedItems += 1
if matchedItems >= len(itemList):
ans = True
else:
ans = False
return ans
def itemsNeededToCraft(self, type, items):
itemList = self.totalItemsToCraft(type)
tribItems = items
ans = []
if(type == 'sword'):
return []
for needed in itemList:
match = 0
for item in tribItems:
if item == needed:
match = 1
if match == 0:
ans.append(needed)
return ans
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,082 | whiterson/mockingJay | refs/heads/master | /action.py | class Action:
def __init__(self, values, effected, duration, index, delta_state, desc=''):
self.values = values
self.effected = effected
self.duration = duration
self.index = index
self.delta_state = delta_state
self.description = desc
def __repr__(self):
return '<Action>(' + str(self.index) + ', ' + str(self.delta_state) + ', "' + self.description + '")'
#def getGoalChange(self, curGoal):
# count = 0
# ret = 0.0
# for eff in self.effected:
# if eff == curGoal.name:
# ret = curGoal.value - value[count]
# break
# count += 1
# return ret
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,083 | whiterson/mockingJay | refs/heads/master | /engine.py | __author__ = 'Nathan'
import pygame
import graphics
import random
import map
from action import Action
from tribute import Tribute
from goal import Goal
from mapReader import readMap
from random import randint
from pygame.locals import *
import json
class GameEngine(object):
"""
here we will essentially manage everything and probably handle the controls
"""
constants = range(1)
is_looping = False
tributes = []
PAUSED = False
curTrib = None
tributes_by_district = []
map_dims = []
FIGHT_MESSAGES = False
@staticmethod
def start():
me = GameEngine
d = json.load(open('./distributions/action_values.json'))
#create actions (will be overwritten in a minute)
move_up = Action([], '', 1, 0, (0, -1), 'move_up')
move_down = Action([], '', 1, 1, (0, 1), 'move_down')
move_right = Action([], '', 1, 2, (1, 0), 'move_right')
move_left = Action([], '', 1, 3, (-1, 0), 'move_left')
hunt = Action([d['hunt']], ["hunger"], 1, 4,(0, 0), 'hunt')
fight = Action([d['fight']], ["kill"], 1, 5, (0, 0), 'fight')
scavenge = Action([d['scavenge']], ["getweapon"], 1, 6, (0, 0), 'scavenge')
craft = Action([d['craft']], ["getweapon"], 1, 7, (0, 0), 'craft')
hide = Action([d['hide']], ["hide"], 1, 8, (0, 0), 'hide')
getwater = Action([d['get_water']], ["thirst"], 1, 9, (0, 0), 'get_water')
rest = Action([d['rest']], ["rest"], 1, 10, (0, 0), 'rest')
talkAlly = Action([d['talk_ally']], ["ally"], 1, 11, (0, 0), 'talk_ally')
explore = Action(d['explore'], ['hunger', 'thirst', 'kill'], 1, 12, (0, 0), 'explore')
me.FIGHT_MESSAGES = d['fight_messages']
#create actions (will be overwritten in a minute)
hunger = Goal("hunger", 2)
thirst = Goal("thirst", 2)
goalRest = Goal("rest", 0)
kill = Goal("kill", 0)
goalHide = Goal("hide", 0)
getweapon = Goal("getweapon", 0)
ally = Goal("ally", 0)
goals = [hunger, thirst, goalRest, kill, goalHide, getweapon, ally]
actions = [move_up, move_down, move_right, move_left, hunt, fight, scavenge, craft, hide, getwater, rest, talkAlly, explore]
#create the goals here
#not really needed right now
init_locations = [(x, y) for x in range(15,30) for y in range(15,35)]
districts = ['d' + str(x) for x in range(1, 4)]
for d in districts:
location = random.choice(init_locations)
init_locations.remove(location)
t1 = Tribute(goals, actions, *location, district=d, gender='male')
me.tributes.append(t1)
location = random.choice(init_locations)
init_locations.remove(location)
t2 = Tribute(goals, actions, *location, district=d, gender='female')
me.tributes.append(t2)
me.tributes_by_district.append((d, t1, t2))
for i in range(len(me.tributes)):
initTribute = me.create_goals(me.tributes[i])
me.tributes[i].goals = initTribute
#me.create_actions(me.tributes[i])
mapToBeUsed = 'maps/allTerr.jpg'
me.dims = (110, 70)
me.map_dims = (50, 50)
me.gameMap = readMap(mapToBeUsed)
me.view = graphics.GameView(*me.dims)
me.map = map.Map(mapToBeUsed)
me.state = me.map.seed_game_state(me.tributes) # game.GameState()
me.is_looping = True
me.curTrib = me.tributes[0]
while me.is_looping and GameEngine.loop():
pass
@staticmethod
def stop():
GameEngine.is_looping = False
@staticmethod
def loop():
"""
What to do on each loop iteration
@return: None
"""
me = GameEngine
buttons = me.view.getButtons()
names = me.view.getNames()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_q:
me.PAUSED = not me.PAUSED
if event.key == K_f:
me.curTrib.goals[0].modify_value(-10)
if event.key == K_d:
me.curTrib.goals[1].modify_value(-10)
if event.key == K_w:
me.curTrib.getWeapon()
me.curTrib.goals[5].modify_value(-10)
if event.type == pygame.QUIT:
pygame.quit()
return False
if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
x = pos[0] / 10
y = pos[1] / 10
for tribute in me.tributes:
if (x,y) == tribute.state:
me.curTrib = tribute
else:
namePos = 0
for button in buttons:
if button.collidepoint(pos):
for tribute in me.tributes:
if tribute.first_name == names[namePos]:
me.curTrib = tribute
namePos += 1
if not me.PAUSED:
#for tribute in me.tributes:
#me.gameMap[tribute.old_state[0]][tribute.old_state[1]].tribute = None
for x in range(50):
for y in range(50):
me.gameMap[x][y].tribute = None
for tribute in me.tributes:
me.gameMap[tribute.state[0]][tribute.state[1]].tribute = tribute
for tribute in me.tributes:
tribute.act(me.gameMap, me.state) # finds bestAction and does it.
tribute.end_turn()
death = tribute.checkDead()
if death is not None:
print tribute.first_name, " ", tribute.last_name, " death by ", death
me.tributes.remove(tribute)
if me.curTrib == tribute and len(me.tributes) > 1:
me.curTrib = random.choice(me.tributes)
if len(me.tributes) == 1:
me.PAUSED = True;
me.view.render(me.state, me.curTrib, me.tributes_by_district, me.tributes, 0)
me.state.update()
else:
if len(me.tributes)==1:
me.view.render(me.state, me.curTrib, me.tributes_by_district, me.tributes, 1)
else:
me.view.render(me.state, me.curTrib, me.tributes_by_district, me.tributes, 0)
return True
@staticmethod
def create_actions(tribute):
#Move action
move_up = Action([], '', 1, 0, (0, -1), 'move_up')
move_down = Action([], '', 1, 1, (0, 1), 'move_down')
move_right = Action([], '', 1, 2, (1, 0), 'move_right')
move_left = Action([], '', 1, 3, (-1, 0), 'move_left')
################ INDEX LIST
# 0-3 movement
# 4 hunt
# 5 fight
# 6 scavenge
# 7 craft
# 8 hide
# 9 water
# 10 rest
# 11 talk
############## ACTION ATTRIBUTES
#1. How much I get back for doing the action in 2. EDIT THIS ONE
#2. The action (lists, so it can affect more than one thing.)
#3. Duration
#4. Index
#5. Movement Stuff (don't mess wid that)
#as long as you hunt, you'll get at least 10 food points, maybe more depending on attributes & individual
hungerStats = (tribute.attributes['endurance']/2)+tribute.attributes['hunting_skill']-(tribute.attributes['size']/5)
foodEnergy = 10 + randint(0, hungerStats)
foodRest = (tribute.attributes['stamina'] - 1)/100
hunt = Action([foodEnergy,foodRest], ["hunger","rest"], 1, 4,(0,0),'hunt')
#if you fight your "bloodlust" goes down. If you're friendly, killng someone drastically reduces your desire to kill
#someone else. Unless you have a friendliness of 1
killStats = (((1/tribute.attributes['bloodlust'])*3)+(tribute.attributes['friendliness']-1))
if(int(tribute.district[1:]) == 1 or int(tribute.district[1:]) == 2 or int(tribute.district[1:])):
killStats += 3
else:
killStats += 5
fight = Action([killStats], ["kill"], 1, 5, (0,0),'fight')
#If they find a weapon, they'll get back 15 "find weapon" points, which will generally cover
#about 150 of wanting a weapon, and not having one. Same w/ crafting
scavenge = Action([15], ["getweapon"], 1, 6, (0,0),'scavenge')
craft = Action([15], ["getweapon"], 1, 7, (0,0),'craft')
#If you're small and good at hiding, you get more points for it
#You also recover some rest
hideStats = ((3/(tribute.attributes['size']+tribute.attributes['strength']))+((tribute.attributes['camouflage_skill']-1)/4))
hide = Action([hideStats, 3], ["hide", "rest"], 1, 8, (0,0),'hide')
#As long as you drink, you'll get at least 10 drink points. Maybe more depending on attributes & individual
thirstStats = (tribute.attributes['endurance'])-(tribute.attributes['size']/5)
thirstEnergy = 10 + randint(0, thirstStats)
getwater = Action([thirstEnergy], ["thirst"], 1, 9, (0,0),'get_water')
#Resting will automatically recover 10 rest points. Maybe more depending on attributes & individual
restStats = (tribute.attributes['stamina'] * 2)
restEnergy = 10 + randint(0, restStats)
rest = Action([restEnergy], ["rest"], 1, 10, (0,0), 'rest')
#If you're friendly, talking to buddies recovers a bunch of talking-to-buddy points
#And the smaller, weaker, and more terrible at fighting you are, the more recovery you get for making a buddy
allyStats = (tribute.attributes['friendliness'] + (1/tribute.attributes['size']) + (1/tribute.attributes['strength']) + (0.5/tribute.attributes['fighting_skill']))
talkAlly = Action([allyStats], ["ally"], 1, 11, (0,0),'talk_ally')
explore = Action([3], ['multiple'], 1, 12, (0, 0), 'explore')
newActions = [move_up, move_down, move_right, move_left, hunt,
fight, scavenge, craft, hide, getwater, rest, talkAlly, explore]
tribute.actions = newActions
return tribute
@staticmethod
def create_goals(tribute):
#Base Hunger Thirst and Rest Values
hunger = Goal("hunger", 2)
thirst = Goal("thirst", 2)
rest = Goal("rest", 5)
#Start-of-Game goals based on attributes and individual
district = int(tribute.district[1:])
if district == 1 or district == 2 or district == 4:
killBase = 5
else:
killBase = 1
killLimit = killBase + ((tribute.attributes['bloodlust']-1)*2) + (11/tribute.attributes['friendliness']) + ((tribute.attributes['size']-1)/2) + ((tribute.attributes['fighting_skill']-1)/2) + ((tribute.attributes['strength']-1)/2)
killStats = randint(killBase, killLimit) * 10
if(tribute.attributes['size'] + tribute.attributes['strength']) < 4:
hideBase = 10
else:
hideBase = 0
hideLimit = hideBase + (10/tribute.attributes['size']) + (5/tribute.attributes['strength']) + (tribute.attributes['camouflage_skill'] * 2) - tribute.attributes['fighting_skill']
hideStats = randint(hideBase, hideLimit)
getWeaponStats = ((tribute.attributes['weapon_skill']-1)*2) - (tribute.attributes['crafting_skill']-1)
allyStats = tribute.attributes['friendliness'] - tribute.attributes['bloodlust']
kill = Goal("kill", killStats)
hide = Goal("hide", hideStats)
getweapon = Goal("getweapon", getWeaponStats)
ally = Goal("ally", allyStats)
fear = Goal("fear", 0)
return [hunger, thirst, rest, kill, hide, getweapon, ally, fear] | {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,084 | whiterson/mockingJay | refs/heads/master | /goal.py | class Goal:
def __init__(self, name, value):
self.name = name
self.value = value
self.rate = 1
def clone(self):
g = Goal(self.name[:], self.value)
g.rate = self.rate
return g
def modify_value(self, mod):
self.value = max(self.value + mod, 0) | {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,085 | whiterson/mockingJay | refs/heads/master | /main.py | __author__ = 'Nathan'
"""
This file is for testing only
"""
import pygame
from engine import GameEngine
from tribute import Tribute
pygame.init()
GameEngine.start()
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,086 | whiterson/mockingJay | refs/heads/master | /graphics.py | __author__ = 'Nathan'
import pygame
from pygame import Rect
class GameView(object):
"""
GameView constructs the main GUI window and handles all the drawing routines
"""
def __init__(self, width, height, cell_size=(10, 10)):
self.buttons = []
self.names = []
self.size = self.width, self.height = width * 10, height * 10
self.screen = pygame.display.set_mode(self.size)
self.state = None
self.cell_size = cell_size
self.layers = {
'ground': (pygame.Surface(self.size), 0),
'particle': (pygame.Surface(self.size), 1)
}
self.layers['particle'][0].set_colorkey((255, 0, 255))
self.layers['particle'][0].fill((255, 0, 255))
def draw(self, tribute, tributes, alive, won):
self.layers['particle'][0].fill((255, 0, 255))
if bool(self.state):
for layer in self.layers:
for x, y, color, p in self.state.grid[layer]:
tile = pygame.Rect(x * self.cell_size[0], y * self.cell_size[1], *self.cell_size)
pygame.draw.rect(self.layers[layer][0], pygame.Color(*color), tile, 0)
layers_ordered = sorted(self.layers.iteritems(), key=lambda g: g[1][1])
for layer in layers_ordered:
self.screen.blit(layer[1][0], (0, 0))
if won:
self.drawWinner(tribute)
else:
self.textStats(tributes, alive)
self.textTribute(tribute)
pygame.display.flip()
def render(self, gs, tribute, tributes, alive, won):
"""
here, we set the game state to render
@param gs: the game state to render
"""
self.state = gs
self.draw(tribute, tributes, alive, won)
positions = []
def textStats(self, tributes, alive):
fontobject = pygame.font.SysFont('Arial', 18)
s_x = 5
s_y = 520
positions = []
for district, t1, t2 in tributes:
self.screen.blit(fontobject.render('District ' + district[1:], 1, (255, 255, 255)), (s_x, s_y))
color = ()
if t1 not in alive:
color = (255, 1, 0)
else:
color = (0, 255, 1)
self.screen.blit(fontobject.render(t1.first_name, 1, color), (s_x, s_y + 25))
positions.append((s_x, s_y,t1.first_name))
if t2.killed:
color = (255, 1, 0)
else:
color = (0, 255, 1)
self.screen.blit(fontobject.render(t2.first_name, 1, color), (s_x, s_y + 50))
positions.append((s_x, s_y,t2.first_name))
s_x += 90
rects = []
names = []
for pos in positions:
rects.append(Rect((pos[0], pos[1]), (85, 45)))
names.append(pos[2])
self.buttons = rects
self.names = names
def textTribute(self, tribute):
fontobject=pygame.font.SysFont('Arial', 18)
self.screen.blit(fontobject.render((tribute.first_name+ ' ' + tribute.last_name), 1, (255, 255, 255)), (510, 20))
if tribute.killed:
self.screen.blit(fontobject.render(('Status: Deceased'), 1, (255, 255, 255)), (680, 20))
else:
self.screen.blit(fontobject.render(('Status: Living'), 1, (255, 255, 255)), (680, 20))
self.screen.blit(fontobject.render(('*****************************************'), 1, (255, 255, 255)), (505, 55))
self.screen.blit(fontobject.render(('Size: ' +str(tribute.attributes['size'])), 1, (255, 255, 255)), (510, 80))
self.screen.blit(fontobject.render(('Strength: ' +str(tribute.attributes['strength'])), 1, (255, 255, 255)), (650, 80))
self.screen.blit(fontobject.render(('Speed: ' +str(tribute.attributes['speed'])), 1, (255, 255, 255)), (510, 120))
self.screen.blit(fontobject.render(('Hunting: ' +str(tribute.attributes['hunting_skill'])), 1, (255, 255, 255)), (650, 120))
self.screen.blit(fontobject.render(('Fighting: ' +str(tribute.attributes['fighting_skill'])), 1, (255, 255, 255)), (510, 160))
self.screen.blit(fontobject.render(('Camo Skill: ' +str(tribute.attributes['camouflage_skill'])), 1, (255, 255, 255)), (650, 160))
self.screen.blit(fontobject.render(('Friendliness: ' +str(tribute.attributes['friendliness'])), 1, (255, 255, 255)), (510, 200))
self.screen.blit(fontobject.render(('Stamina: ' +str(tribute.attributes['stamina'])), 1, (255, 255, 255)), (650, 200))
self.screen.blit(fontobject.render(('Endurance: ' +str(tribute.attributes['endurance'])), 1, (255, 255, 255)), (510, 240))
self.screen.blit(fontobject.render(('Health: ' +str(tribute.stats['health'])) + ' / ' +
str(tribute.attributes['max_health']), 1, (255, 255, 255)), (650, 240))
self.screen.blit(fontobject.render('Last Action: ' + tribute.printy_action, 1, (255, 255, 255)), (510, 275))
self.screen.blit(fontobject.render('Fighting: ' + str(tribute.fighting_state), 1, (255, 255, 255)), (510, 315))
self.screen.blit(fontobject.render('Weapon: ' + str(tribute.weapon.type), 1, (255, 255, 255)), (650, 315))
self.screen.blit(fontobject.render('****************GOALS*****************', 1, (255, 255, 255)), (505, 350))
for i, goal in enumerate(tribute.goals):
self.screen.blit(fontobject.render(goal.name + ': ' + ('%.2f' % goal.value), 1, (255, 255, 255)), (510 + 140 * (i % 2), 385 + (35 * (i / 2))))
pos = (510, 385 + (35 * ((i + 1) / 2)))
self.screen.blit(fontobject.render('Sighted: ' + str(tribute.sighted), 1, (255, 255, 255)), pos)
def drawWinner(self, tribute):
trib = tribute
fontobject = pygame.font.SysFont('Arial', 18)
self.screen.blit(fontobject.render('Winner: ' + trib.first_name + " " + trib.last_name, 1, (255, 255, 255)), (250, 540))
def getButtons(self):
return self.buttons
def getNames(self):
return self.names
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,087 | whiterson/mockingJay | refs/heads/master | /map.py | import mapReader
import PIL
import game
class Map:
def __init__(self, path):
self.map_image = PIL.Image.open(path)
self.pixel_map = self.map_image.load()
def seed_game_state(self, parts):
gs = game.GameState(parts)
gs.world['ground'] = self
gs.grid['ground'] = [(x, y, self.pixel_map[x, y], None) for x in range(gs.width) for y in range(gs.height)]
return gs | {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.