index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
68,712 | CAAI/rh-queue | refs/heads/master | /rhqueue/squeue.py | import subprocess
from typing import List
from .datagrid import DataGridLine
class SqueueDataGridHandler:
def __init__(self):
super().__init__()
import getpass
import grp
# get users in sudo group
self.admin = grp.getgrnam("sudo").gr_mem
# get current user
self.user = getpass.getuser()
from .datagrid import DataGridHandler
# load the data from the queue
self.data = DataGridHandler()
def is_user_admin(self):
return self.user in self.admin
def cancel_job(self, job_id: str):
"""function used to cancel a job, first getting the job from the queue,
then checking if the user created the job or the user is part of sudo.
Following this will pass the job to the cancel check function
Args:
job_id (str): the id of the job to be cancelled
"""
# get the current job by id
job = self.data.get_job_from_id(job_id)
if self.data.is_user_job(self.user, job):
self.cancel_check("scancel {id}", job)
elif self.is_user_admin():
self.cancel_check("sudo -u slurm scancel {id}", job)
else:
print("You do not have the permission to cancel that job")
def cancel_check(self, cancel_command_struct: str, job_id: DataGridLine):
"""Function that confirms if the use wants to delete from the string for how to call the deletion funciton
Args:
cancel_command_struct (str): the command string for how to delete the job
job_id (DataGridLine): the id of the job to be cancelled
"""
valid = {"yes": True, "y": True, "no": False, "n": False}
print(f"job ID: {job_id}")
while True:
choice = input(
f"Do you wish delete job {job_id.id}? [y/n]").lower()
if choice in valid:
res = valid[choice]
break
else:
print("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
if res:
subprocess.call([cancel_command_struct.format(id=job_id.id)],
shell=True)
else:
print("cancelled script removal")
exit(0)
def print_vals(self, job_id:str=None, verbose:bool=False, columns:List[str]=[]):
from .printer import GridPrinter
if columns:
item_lists = [self.data.running_items, self.data.queued_items]
data = [[list(value.get_from_keys(columns).values()) for value in items]
for items in item_lists]
headers = [columns] * len(data)
GridPrinter(data,
title="Queue Information",
sections=["Running Items", "Items in Queue"],
headers=headers)
else:
keys = [
"EligibleTime", "SubmitTime", "StartTime", "ExcNodeList",
"JobId", "JobName", "JobState", "StdOut", "UserId", "WorkDir",
"NodeList"
]
output = self.data.get_job_from_id(job_id)
output = output.info if verbose else output.get_from_keys(keys)
GridPrinter([
sorted([list(j) for j in output.items()], key=lambda x: x[0])
],
headers=[["Key", "Value"]],
title=f"Information about job:{job_id}")
| {"/rhqueue/parser.py": ["/rhqueue/actions.py", "/rhqueue/servers.py", "/rhqueue/functions.py"], "/rhqueue/__init__.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/printer.py", "/rhqueue/datagrid.py", "/rhqueue/functions.py", "/rhqueue/parser.py", "/rhqueue/handler.py", "/rhqueue/servers.py", "/rhqueue/actions.py"], "/rhqueue/datagrid.py": ["/rhqueue/functions.py", "/rhqueue/servers.py"], "/rhqueue/handler.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/functions.py"], "/rhqueue/functions.py": ["/rhqueue/servers.py"], "/testfiles/run_parser_tests.py": ["/rhqueue/__init__.py"], "/rhqueue/squeue.py": ["/rhqueue/datagrid.py", "/rhqueue/printer.py"]} |
68,713 | CAAI/rh-queue | refs/heads/master | /testfiles/test_create_file.py | #!/usr/bin/env python3
with open("./new_file.txt", "w") as file:
file.write("new file is created")
| {"/rhqueue/parser.py": ["/rhqueue/actions.py", "/rhqueue/servers.py", "/rhqueue/functions.py"], "/rhqueue/__init__.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/printer.py", "/rhqueue/datagrid.py", "/rhqueue/functions.py", "/rhqueue/parser.py", "/rhqueue/handler.py", "/rhqueue/servers.py", "/rhqueue/actions.py"], "/rhqueue/datagrid.py": ["/rhqueue/functions.py", "/rhqueue/servers.py"], "/rhqueue/handler.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/functions.py"], "/rhqueue/functions.py": ["/rhqueue/servers.py"], "/testfiles/run_parser_tests.py": ["/rhqueue/__init__.py"], "/rhqueue/squeue.py": ["/rhqueue/datagrid.py", "/rhqueue/printer.py"]} |
68,714 | CAAI/rh-queue | refs/heads/master | /rhqueue/actions.py | import argparse
import os
class FooAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(FooAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class ScriptTypeHandler:
def __init__(self) -> None:
pass
def python(self, fname):
return os.path.abspath(fname)
def shell(self, fname):
return fname
def bash(self, fname):
return f"bash {os.path.abspath(fname)}"
def text(self, fname):
return f"cat {fname}"
def any(self, fname):
return fname
class ScriptTypeAction(argparse.Action):
handler = ScriptTypeHandler()
matches = {
"*.txt": handler.text,
"*.py": handler.python,
"*.sh": handler.bash,
}
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(ScriptTypeAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
call_value = self.find_match(values)
setattr(namespace, self.metavar, values)
setattr(namespace, "full_script", call_value)
def find_match(self, fname):
from fnmatch import fnmatch
for k, v in self.matches.items():
if fnmatch(fname, k):
return v(fname)
return self.handler.any(fname)
def priority_action(values):
class PriorityDefaultAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
self.default_values = values
if nargs is not None:
raise ValueError("nargs not allowed")
super(ScriptTypeAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values:
setattr(namespace, self.metavar, values)
for i in self.default_values:
if i:
setattr(namespace, self.metavar, i)
break
return PriorityDefaultAction
| {"/rhqueue/parser.py": ["/rhqueue/actions.py", "/rhqueue/servers.py", "/rhqueue/functions.py"], "/rhqueue/__init__.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/printer.py", "/rhqueue/datagrid.py", "/rhqueue/functions.py", "/rhqueue/parser.py", "/rhqueue/handler.py", "/rhqueue/servers.py", "/rhqueue/actions.py"], "/rhqueue/datagrid.py": ["/rhqueue/functions.py", "/rhqueue/servers.py"], "/rhqueue/handler.py": ["/rhqueue/scriptCreator.py", "/rhqueue/squeue.py", "/rhqueue/functions.py"], "/rhqueue/functions.py": ["/rhqueue/servers.py"], "/testfiles/run_parser_tests.py": ["/rhqueue/__init__.py"], "/rhqueue/squeue.py": ["/rhqueue/datagrid.py", "/rhqueue/printer.py"]} |
68,724 | VillageDeveloper2019/Variable-selection | refs/heads/main | /classification_model_selection.py | """
Author: Marktus Atanga
"""
import sys
import numpy as np
import pandas as pd
from naive_bayes_algorithm import Naive_Bayes_Classifier
def model_scores(result):
"""
calculate the model accuracy and error rate.
function compares the actula class label versus predicted class label
at each index. It sums all the true comparison results and divide by the
number of observations.
@return model scores
"""
if result is None:
raise ValueError( "The parameter 'data' must be assigned a non-nil reference to a Pandas DataFrame")
#save model model_scores
metrics = {}
metrics["accuracy"] = float(sum([p==a for p, a in zip(result["y_actual"], result["y_pred"])])/len(result))
metrics["error_rate"] = 1-metrics["accuracy"]
metrics["RMS"] = float(np.sqrt(sum([(p-a)**2 for p, a in zip(result["y_actual"], result["y_pred"])])/len(result)))
tp = 0; tn = 0; fn = 0; fp = 0
for y, y_hat in zip(result["y_actual"], result["y_pred"]):
if y == 0 and y_hat == 0:
tn += 1
elif y == 0 and y_hat == 1:
fp += 1
elif y == 1 and y_hat == 1:
tp += 1
else:
fn += 1
return metrics
class ModelSelctions():
def stepwise_forward_selection(X_train, X_test, y_train, y_test, threshold = 0.0001):
"""
first iterates through allthe features to find the feature
that gives best model score metric. Keep the best found feature
Perform pair-wise iteration of the best feature with all features to find the best two features
iterate to find the best 3 features, so on.
In each iteration, check model score metric against previous score metric.
If the difference in core is not greater than the threshold, return all best features found.
@return results data frame
"""
if ((X_train is None) | (X_test is None) | (y_train is None) | (y_test is None)):
raise ValueError( "The data sets must be assigned a non-nil reference to a Pandas DataFrame")
#initialize model performance metric
accuracy = 0
accuracy_list = []
error_rate = 0
error_rate_list = []
#save the best features into a list
best_features_list = []
feature_count = 0
feature_count_list = []
#save the number of features in each iteration step
step_features_list = []
while True:
# forward step
excluded = list(set(X_train.columns) - set(best_features_list))
#intialize series to save performance metrics
new_accuracy = pd.Series(index=excluded,dtype=float)
new_error_rate = pd.Series(index=excluded,dtype=float)
for new_column in excluded:
sel_X_train = np.array(X_train[best_features_list + [new_column]]).astype(float)
sel_X_test = np.array(X_test[best_features_list + [new_column]]).astype(float)
#fit the model
model=Naive_Bayes_Classifier()
model.fit(sel_X_train,y_train)
#predict the data class
model_pred=model.predict(sel_X_test)
#add the actuals to our results data set
model_pred["y_actual"] = y_test
#calculate model accuracy
current_perf = np.max(model_scores(model_pred)["accuracy"])
#assign the current_perf to its feature
new_accuracy[new_column] = current_perf
#new_error_rate[new_column] = 1-new_accuracy[new_column]
#find the best performance for the included + [new_column] round of iteration
best_accuracy = new_accuracy.max()
minimum_error_rate = 1- best_accuracy
#calculate change in model performance
perf_change = best_accuracy - accuracy
if perf_change > threshold:
accuracy = best_accuracy
error_rate = minimum_error_rate
best_feature = new_accuracy.idxmax()
feature_count = feature_count+1
best_features_list.append(best_feature)
feature_count_list.append(feature_count)
step_features_list.append(str(best_features_list))
accuracy_list.append(accuracy)
error_rate_list.append(error_rate)
print("features count =", feature_count)
print("best feature =", best_feature)
print("score with feature added =", accuracy)
print("error with feature added =", error_rate)
else:
break
results = pd.DataFrame()
results["iter_features"] = step_features_list
results["accuracy"] = accuracy_list
results["feature_count"] = feature_count_list
results["best_features"] = best_features_list
results["error_rate"] = error_rate_list
return results
| {"/classification_model_selection.py": ["/naive_bayes_algorithm.py"]} |
68,725 | VillageDeveloper2019/Variable-selection | refs/heads/main | /naive_bayes_algorithm.py | """
Author: Marktus Atanga
"""
import numpy as np
import pandas as pd
class Naive_Bayes_Classifier():
def __init__(self):
#save the classes and their data
self.data_class={}
def fit(self,X_train,y_train):
def group_data_to_classes(data_class,X_train,y_train):
class0=True
class1=True
for i in range(y_train.shape[0]):
X_temp=X_train[i,:].reshape(X_train[i,:].shape[0],1)
if y_train[i]==0:
if class0==True:
data_class[0]=X_temp
class0=False
else:
data_class[0]=np.append(data_class[0],X_temp,axis=1)
elif y_train[i]==1:
if class1==True:
data_class[1]=X_temp
class1=False
else:
data_class[1]=np.append(data_class[1],X_temp,axis=1)
return data_class
#set the train set and target
self.X_train=X_train
self.y_train=y_train
#initialize data array
self.data_class[0]=np.array([[]])
self.data_class[1]=np.array([[]])
#find data and their classess
self.data_class=group_data_to_classes(self.data_class,self.X_train,self.y_train)
self.data_class[0]=self.data_class[0].T
self.data_class[1]=self.data_class[1].T
#calculate the means for the train set
self.mean_1=np.mean(self.data_class[0],axis=0)
self.mean_2=np.mean(self.data_class[1],axis=0)
#calculate the standard deviation for the train set
self.std_1=np.std(self.data_class[0],axis=0)
self.std_2=np.std(self.data_class[1],axis=0)
def predict(self, X_test):
"""
For numerical data modeled as a normal distribution,
we can use the Gaussian/normal distribution function to calculate likelihood
"""
def calc_posterior(X, X_train_class, mean_, std_):
def class_likelihood(x, mean, std):
#use the normal pdf to calculate the likelihood
lieklihood = (np.sqrt(2*np.pi*std)**-1)*np.exp(-(x-mean)**2/(2*std**2))
return lieklihood
#product of class likelihoods for all features in the data
likelihood_prod = np.prod(class_likelihood(X,mean_,std_),axis=1)
#class prior
prior = X_train_class.shape[0]/self.X_train.shape[0]
#class posterior distribution
posterior=likelihood_prod*prior
return posterior
#class 0 posterior
class_0=calc_posterior(X_test,self.data_class[0],self.mean_1,self.std_1)
#class 1 posterior
class_1=calc_posterior(X_test,self.data_class[1],self.mean_2,self.std_2)
#find the class that each data row belongs to
y_pred =[]
for i, j in zip(class_0, class_1):
if (i > j):
y_pred.append(0)
else:
y_pred.append(1)
#store data to a dataframe to return
results = pd.DataFrame()
results["class_0_posterior"] = class_0
results["class_1_posterior"] = class_1
results["y_pred"] = y_pred
return results
| {"/classification_model_selection.py": ["/naive_bayes_algorithm.py"]} |
68,730 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/migrations/0004_auto_20210123_0046.py | # Generated by Django 3.1.3 on 2021-01-22 21:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('metatags', '0003_auto_20210123_0025'),
]
operations = [
migrations.AlterField(
model_name='metatags',
name='keywords',
field=models.CharField(help_text='Писать ключевые слова через запятую (с пробелом после запятой)', max_length=255, verbose_name='Ключевые слова'),
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,731 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/migrations/0001_initial.py | # Generated by Django 3.1.3 on 2021-01-22 21:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MetaTags',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('url', models.URLField(help_text='Пример: "/about/contact/". Убедитесь, что ввели начальную и конечную косые черы.', unique=True, verbose_name='URL - Путь')),
('keywords', models.CharField(max_length=255, verbose_name='Ключевые слова')),
('description', models.TextField(verbose_name='Описание')),
],
options={
'verbose_name': 'META-тег',
'verbose_name_plural': 'META-теги',
},
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,732 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/services.py | from .models import CartProduct, Cart, Category, Product
from django.contrib import messages
from django.shortcuts import get_object_or_404
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.conf import settings
def search_product(products, request):
search_query = request.GET.get('search', '')
if search_query:
products = products.filter(name__icontains=search_query)
else:
products = products.all()
return products
def make_order_user(request, order, cart):
order.customer = request.user
cart.in_order = True
cart.save()
for item in cart.cartproduct_set.all():
if item.size is not None:
size = item.size
size.qty -= item.qty
size.save()
else:
product = item.product
product.qty -= item.qty
product.save()
order.cart = cart
order.save()
def make_order_anonymous_user(cart, order):
cart_db = Cart.objects.create(total_product=cart.get_total_items(),
final_price=cart.get_total_price(), in_order=True)
for item in cart:
if item.get('size') is not None:
CartProduct.objects.create(product=item['product'], cart=cart_db, size=item['size_obj'], qty=item['qty'],
final_price=item['final_price'])
size = item['size_obj']
size.qty -= item['qty']
size.save()
else:
CartProduct.objects.create(product=item['product'], cart=cart_db, qty=item['qty'],
final_price=item['final_price'])
product = item['product']
product.qty -= item['qty']
product.save()
order.cart = cart_db
order.save()
cart.clear()
def get_products(request):
products = Product.objects.all()
return search_product(products, request)
def get_category():
return Category.objects.all()
def get_category_name(slug):
return get_object_or_404(Category, slug=slug)
def get_category_products(slug, request):
category = get_category_name(slug)
products = category.product_set.all()
return search_product(products, request)
def delete_from_cart_product_id(id):
cart_product = get_object_or_404(CartProduct, id=id)
cart_product.delete()
def validation_checkout_user(request, cart):
for item in cart.cartproduct_set.all():
if item.size:
if item.size.qty < item.qty and item.size.qty != 0:
cart_product = item
cart_product.qty = item.size.qty
cart_product.save()
messages.error(request,
'Осталось только {0} товара {1} | Размер({2})'.format(item.size.qty, item.product,
item.size.size.normalize()))
return True
if item.size.qty <= 0:
item.delete()
messages.error(request,
'Товара нет в наличии {0} размера ({1})'.format(item.product.name, item.size.size))
return True
else:
if item.product.qty < item.qty and item.product.qty != 0:
cart_product = item
cart_product.qty = item.product.qty
cart_product.save()
messages.error(request, 'Осталось только {0} товара {1}'.format(item.product.qty, item.product))
return True
if item.product.qty <= 0:
item.delete()
messages.error(request, 'Товара нет в наличии {0}'.format(item.product.name))
return True
def validation_checkout_anonymous_user(request, cart_data, size_num=None):
for item in cart_data.cart.values():
if len(str(item['id']).split('-')) == 2:
size_num = str(item['id']).split('-')[1]
product_id = str(item['id']).split('-')[0]
product_obj = get_object_or_404(Product, id=product_id)
if size_num is not None:
print(size_num)
size = product_obj.size_set.filter(size=size_num).first()
if size:
if size.qty < item['qty'] and size.qty != 0:
cart_data.change_qty(item['id'], size.qty)
messages.error(request,
'Осталось только {0} товара {1} | Размер({2})'.format(size.qty, product_obj.name,
size.size.normalize()))
return True
if size.qty <= 0:
cart_data.remove(item['id'])
messages.error(request,
'Товара нет в наличии {0} размера ({1})'.format(product_obj.name, size.size.normalize()))
return True
else:
if product_obj.qty < item['qty'] and product_obj.qty != 0:
cart_data.change_qty(item['id'], product_obj.qty)
messages.error(request,
'Осталось только {0} товара {1}'.format(product_obj.qty, product_obj.name))
return True
if product_obj.qty <= 0:
messages.error(request, 'Товара нет в наличии {0}'.format(product_obj.name))
cart_data.remove(item['id'])
return True
size_num = None
def change_qty(request, id, qty):
cart_product = get_object_or_404(CartProduct, id=id)
if cart_product.product.qty < qty:
messages.error(request, 'Нет больше в наличии')
return True
cart_product.qty = qty
cart_product.save()
def get_product_slug(slug):
return get_object_or_404(Product, slug=slug)
def get_product_filter_slug(slug):
return Product.objects.filter(slug=slug)
def add_to_cart_user(request, customer, cart, product):
cart_product, created = CartProduct.objects.get_or_create(customer=customer, cart=cart,
product=product)
if not created:
if cart_product.qty < product.qty:
cart_product.qty += 1
cart_product.save()
else:
messages.error(request, 'Нет больше в наличии')
return
messages.success(request, "Товар успешно добавлен")
def email_message(order):
subject = f'Заказ #{order.pk}'
context = {'order_id': order.pk,
'last_name': order.last_name,
'first_name': order.first_name,
'phone': order.phone,
'address': order.address,
'order_date': order.created_at,
'items': order.cart.cartproduct_set.all()
}
message = render_to_string('shop/message_email.html', context)
em = EmailMessage(subject=subject, body=message, to=[settings.EMAIL_MESSAGE_TO])
em.send()
def get_size_sneaker(product: object) -> object:
return product.size_set.order_by('size').all()
def add_to_cart(request, sizes_stock: list, product: object, cart: object):
form_sizes = set(request.POST.values())
size = set(map(lambda size: str(size.size.normalize()), sizes_stock))
sizes = form_sizes & size
if not sizes:
return messages.info(request, f'Вы не выбрали размер Товара {product.name}')
for size in sizes:
size_num = sizes_stock.filter(size=size).first()
if size_num:
if request.user.is_authenticated:
product_in_cart, create = CartProduct.objects.get_or_create(customer=cart.customer, cart=cart,
product=product, size=size_num)
if not create:
if product_in_cart.qty < size_num.qty:
product_in_cart.qty += 1
product_in_cart.save()
else:
messages.error(request,
'Товар {0} | Размер ({1}) больше нет в наличии'.format(product.name, size))
continue
messages.success(request, 'Товар {0} | Размер ({1}) добавлены в корзину'.format(product.name, size))
else:
cart.add_with_size(product, size_num)
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,733 | Reiko1337/shine-shop-django | refs/heads/master | /app/config/urls.py | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib.sitemaps.views import sitemap
from shop.sitemap import StaticSitemap, ItemSitemap, CategorySitemap
from django.contrib.staticfiles.views import serve
from django.views.static import serve as media_serve
sitemaps = {
'static': StaticSitemap,
'category': CategorySitemap,
'item': ItemSitemap,
}
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('shop.urls')),
path('account/', include('account.urls')),
path("robots.txt", TemplateView.as_view(template_name="robots.txt", content_type="text/plain")),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# if not settings.DEBUG:
# urlpatterns.append(path('static/<path:path>', serve, {'insecure': True}))
# urlpatterns.append(path('media/<path:path>', media_serve, {'document_root': settings .MEDIA_ROOT})) | {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,734 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/migrations/0002_auto_20210123_0023.py | # Generated by Django 3.1.3 on 2021-01-22 21:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('metatags', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='metatags',
name='url',
field=models.TextField(help_text='Пример: "/about/contact/". Убедитесь, что ввели начальную и конечную косые черы.', max_length=200, unique=True, verbose_name='URL - Путь'),
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,735 | Reiko1337/shine-shop-django | refs/heads/master | /app/account/views.py | from django.shortcuts import render, redirect
from django.views import View
from shop.utils import CartMixin, CategoryMixin
from django.contrib.auth.views import LoginView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib import messages
from .services import *
@method_decorator(login_required, name='dispatch')
class ProfileView(CartMixin, View):
template_name = 'account/profile.html'
def get(self, request):
categories = get_category()
context = {
'cart': self.cart_view,
'categories': categories,
}
return render(request, self.template_name, context)
class LoginView(LoginView):
template_name = 'account/login.html'
redirect_authenticated_user = True
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['categories'] = get_category()
return context
class RegistrationView(View):
template_name = 'account/registration.html'
def get(self, request):
form = UserCreationForm()
categories = get_category()
context = {
'categories': categories,
'form': form
}
return render(request, self.template_name, context)
def post(self, request):
form = UserCreationForm(request.POST)
categories = get_category()
context = {
'categories': categories,
'form': form
}
if form.is_valid():
form.save()
if request.user.is_authenticated:
logout(request)
return redirect('login')
return render(request, self.template_name, context)
@method_decorator(login_required, name='dispatch')
class DeleteOrderView(View):
def get(self, request, id):
delete_order(request, id)
messages.success(request, "Заказ успешно отменен")
return redirect('profile')
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,736 | Reiko1337/shine-shop-django | refs/heads/master | /app/account/services.py | from shop.models import Category, Order
from django.shortcuts import get_object_or_404
def get_category():
return Category.objects.all()
def delete_order(request, id):
order = get_object_or_404(Order, id=id, customer=request.user, status='new')
order.delete()
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,737 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/migrations/0002_auto_20210207_1347.py | # Generated by Django 3.1.3 on 2021-02-07 10:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Size',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('size', models.DecimalField(decimal_places=1, max_digits=9, verbose_name='Размер')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.product', verbose_name='Продукт')),
],
options={
'verbose_name': 'Размер',
'verbose_name_plural': 'Размеры',
'ordering': ['product__name'],
},
),
migrations.AddField(
model_name='cartproduct',
name='size',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='shop.size', verbose_name='Размер'),
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,738 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/templatetags/meta_tags.py | from django import template
from metatags.models import MetaTags
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def meta_tags_include(path):
meta_tag = MetaTags.objects.filter(url=path).first()
if meta_tag:
return mark_safe(
'<meta name="description" content="{0}"> <meta name="keywords" content="{1}">'.format(meta_tag.description, meta_tag.keywords))
return ''
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,739 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/admin.py | from django.contrib import admin
from . import models
from django import forms
from django.utils.html import mark_safe
from django.template.loader import render_to_string
class CountProductValidation(forms.ModelForm):
def clean_qty(self):
qty = self.cleaned_data.get('qty')
product = self.cleaned_data.get('product')
if product.qty < qty:
raise forms.ValidationError('Такого количества нет в наличии')
return qty
class SizePanel(admin.TabularInline):
model = models.Size
extra = 1
ordering = ['size']
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'slug')
search_fields = ('name', 'slug')
class CartProductAdmin(admin.ModelAdmin):
readonly_fields = ('final_price', 'get_image_100')
list_display = ('id', 'customer', 'product', 'get_image', 'cart', 'qty', 'final_price',)
list_filter = ('customer', 'product')
search_fields = ('customer', 'product')
form = CountProductValidation
def get_image(self, obj):
return mark_safe(f'<img src={obj.product.image.url} width="50">')
def get_image_100(self, obj):
return mark_safe(f'<img src={obj.product.image.url} width="200">')
get_image_100.short_description = 'Изображение'
get_image.short_description = 'Изображение'
class CartProductInline(admin.TabularInline):
model = models.CartProduct
readonly_fields = ('final_price', 'get_image_100')
extra = 0
form = CountProductValidation
def get_image_100(self, obj):
return mark_safe(f'<img src={obj.product.image.url} width="200">')
get_image_100.short_description = 'Изображение'
class CartAdmin(admin.ModelAdmin):
list_display = ('id', 'customer', 'total_product', 'final_price', 'in_order')
inlines = [CartProductInline, ]
list_filter = ('customer', 'in_order')
search_fields = ('customer', 'in_order')
readonly_fields = ('final_price', 'total_product')
class OrderAdmin(admin.ModelAdmin):
list_display = ('id', 'first_name', 'last_name', 'phone', 'cart_product', 'final_price', 'status')
list_editable = ('status',)
list_filter = ('first_name', 'last_name', 'status')
search_fields = ('first_name', 'last_name', 'status')
readonly_fields = ('get_product_list',)
def cart_product(self, obj):
cart_products = obj.cart.cartproduct_set.all()
return [f'{item.product.name}({item.qty})' for item in cart_products]
cart_product.short_description = 'Товар'
def final_price(self, obj):
return obj.cart.final_price
final_price.short_description = 'Цена'
def get_product_list(self, obj):
cart_products = obj.cart.cartproduct_set.all()
return render_to_string('shop/order_admin.html', {
'cart_products': cart_products,
'total_product': obj.cart.total_product,
'final_price': obj.cart.final_price
})
get_product_list.short_description = 'Список товаров'
class ProductAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'qty', 'category', 'price', 'get_image')
search_fields = ('name', 'category')
readonly_fields = ('get_image_100',)
inlines = [SizePanel]
def get_image_100(self, obj):
return mark_safe(f'<img src={obj.image.url} width="200">')
def get_image(self, obj):
return mark_safe(f'<img src={obj.image.url} width="50">')
get_image.short_description = 'Изображение'
get_image_100.short_description = 'Изображение'
def get_readonly_fields(self, request, obj=None):
if obj:
if not obj.size_set.all():
return ''
else:
return ('qty',)
return ''
class SizeAdmin(admin.ModelAdmin):
list_display = ('get_product__name', 'size')
search_fields = ('product__name', 'size')
def get_product__name(self, rec):
return rec.product.name
get_product__name.short_description = 'Товар'
admin.site.register(models.Category, CategoryAdmin)
admin.site.register(models.Product, ProductAdmin)
admin.site.register(models.CartProduct, CartProductAdmin)
admin.site.register(models.Cart, CartAdmin)
admin.site.register(models.Order, OrderAdmin)
admin.site.register(models.Size, SizeAdmin)
admin.site.site_title = 'Ювелирный Магазин'
admin.site.site_header = 'Ювелирный Магазин'
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,740 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/admin.py | from django.contrib import admin
from .models import MetaTags
admin.site.register(MetaTags) | {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,741 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/migrations/0003_size_qty.py | # Generated by Django 3.1.3 on 2021-02-07 11:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_auto_20210207_1347'),
]
operations = [
migrations.AddField(
model_name='size',
name='qty',
field=models.PositiveIntegerField(default=0, verbose_name='Количество'),
preserve_default=False,
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,742 | Reiko1337/shine-shop-django | refs/heads/master | /app/metatags/models.py | from django.db import models
class MetaTags(models.Model):
url = models.CharField(verbose_name='URL - Путь', unique=True, max_length=200,
help_text='Пример: "/about/contact/". Убедитесь, что ввели начальную и конечную косые черы.')
keywords = models.CharField(verbose_name='Ключевые слова', max_length=255, help_text='Писать ключевые слова через запятую (с пробелом после запятой)')
description = models.TextField(verbose_name='Описание')
class Meta:
verbose_name = 'META-тег'
verbose_name_plural = 'META-теги'
def __str__(self):
return self.url
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,743 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/migrations/0001_initial.py | # Generated by Django 3.1.3 on 2021-01-22 21:54
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import shop.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('total_product', models.PositiveIntegerField(default=0, verbose_name='Количество продуктов')),
('final_price', models.DecimalField(decimal_places=2, default=0, max_digits=9, verbose_name='Общая цена')),
('in_order', models.BooleanField(default=False, verbose_name='В заказе')),
('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),
],
options={
'verbose_name': 'Корзина',
'verbose_name_plural': 'Корзины',
},
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Наименование категории')),
('slug', models.SlugField(unique=True)),
],
options={
'verbose_name': 'Категория',
'verbose_name_plural': 'Категории',
'ordering': ['-id'],
},
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, verbose_name='Наименование')),
('description', models.TextField(blank=True, verbose_name='Описание')),
('slug', models.SlugField(unique=True)),
('image', models.ImageField(upload_to=shop.models.get_path_category, verbose_name='Изображение')),
('qty', models.PositiveIntegerField(verbose_name='Количество')),
('price', models.DecimalField(decimal_places=2, max_digits=9, validators=[django.core.validators.MinValueValidator(0)], verbose_name='Цена')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.category', verbose_name='Категория')),
],
options={
'verbose_name': 'Товар',
'verbose_name_plural': 'Товары',
'ordering': ['-id'],
},
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=255, verbose_name='Имя')),
('last_name', models.CharField(max_length=255, verbose_name='Фамилия')),
('phone', models.CharField(max_length=20, verbose_name='Телефон')),
('address', models.CharField(max_length=1024, verbose_name='Адрес')),
('status', models.CharField(choices=[('new', 'Новый заказ'), ('in_progress', 'Заказ в обработке'), ('is_ready', 'Заказ готов'), ('completed', 'Заказ выполнен'), ('cancel', 'Заказ отменен')], default='new', max_length=100, verbose_name='Статус заказ')),
('buying_type', models.CharField(choices=[('courier', 'Курьер в городе Молодечно (бесплатно)'), ('delivery', 'Доставка почтой, оплата при получении (стоимость 3-5 руб, от 40 руб. бесплатно)'), ('delivery_cart', 'Доставка почтой, предоплата (стоимость 3 РУБ, от 40 руб бесплатно)')], default='courier', max_length=100, verbose_name='Тип доставки')),
('payment_type', models.CharField(choices=[('cash', 'Наличные'), ('card', 'Карта')], default='cash', max_length=100, verbose_name='Тип оплаты')),
('comment', models.TextField(blank=True, null=True, verbose_name='Комментарий к заказу')),
('created_at', models.DateTimeField(auto_now=True, verbose_name='Дата создания заказа')),
('cart', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='shop.cart', verbose_name='Корзина')),
('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Покупатель')),
],
options={
'verbose_name': 'Заказ',
'verbose_name_plural': 'Заказы',
'ordering': ['-id'],
},
),
migrations.CreateModel(
name='CartProduct',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('qty', models.PositiveIntegerField(default=1, verbose_name='Общее количество')),
('final_price', models.DecimalField(decimal_places=2, default=0, max_digits=9, verbose_name='Общая цена')),
('cart', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.cart', verbose_name='Корзина')),
('customer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.product', verbose_name='Продукт')),
],
options={
'verbose_name': 'Корзина продукта',
'verbose_name_plural': 'Корзины продуктов',
},
),
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,744 | Reiko1337/shine-shop-django | refs/heads/master | /app/account/urls.py | from django.urls import path
from . import views
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('', views.ProfileView.as_view(), name='profile'),
path('login/', views.LoginView.as_view(), name='login'),
path('reg/', views.RegistrationView.as_view(), name='reg'),
path('logout/', LogoutView.as_view(), name='logout'),
path('delete-order/<int:id>/', views.DeleteOrderView.as_view(), name='delete_order')
]
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,745 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/utils.py | from .models import Category, Cart, CartProduct, Order, Size
from django.views.generic.detail import SingleObjectMixin
from django.db import models
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .cart import CartSession, CartUserView
class CategoryMixin(SingleObjectMixin):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
class CartMixin(object):
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated:
user = get_object_or_404(User, username=request.user.username)
cart = Cart.objects.filter(customer=user, in_order=False).first()
if not cart:
cart = Cart.objects.create(customer=user)
self.cart = cart
self.cart_view = CartUserView(cart)
else:
self.cart = CartSession(request)
self.cart_view = CartSession(request)
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['cart'] = self.cart_view
return context
@receiver(post_delete, sender=CartProduct)
@receiver(post_save, sender=CartProduct)
def recalc_cart(sender, instance, **kwargs):
cart = instance.cart
cart_data = cart.cartproduct_set.all().aggregate(models.Sum('final_price'), models.Sum('qty'))
if cart_data.get('final_price__sum') and cart_data.get('qty__sum'):
cart.final_price = cart_data['final_price__sum']
cart.total_product = cart_data['qty__sum']
else:
cart.final_price = 0
cart.total_product = 0
cart.save()
@receiver(post_delete, sender=Order)
def delete_order(sender, instance, **kwargs):
cart = instance.cart
for item in cart.cartproduct_set.all():
product = item.product
product.qty += item.qty
product.save()
cart.delete()
@receiver(post_delete, sender=Size)
@receiver(post_save, sender=Size)
def recalc_qty_product(instance, **kwargs):
product = instance.product
product_qty = product.size_set.all().aggregate(models.Sum('qty'))
if product_qty.get('qty__sum'):
product.qty = product_qty['qty__sum']
else:
product.qty = 0
product.save() | {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,746 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/cart.py | from django.conf import settings
from .models import Product
from decimal import Decimal
from django.contrib import messages
from django.shortcuts import get_object_or_404
class CartSession(object):
def __init__(self, request):
self.request = request
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, size=None, quantity=1):
"""
Добавить продукт в корзину.
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {
'id': product_id,
'qty': 0,
'price': str(product.price)
}
if self.cart[product_id]['qty'] < product.qty:
self.cart[product_id]['qty'] += quantity
self.save()
messages.success(self.request, "Товар успешно добавлен")
else:
messages.error(self.request, 'Нет больше в наличии')
def add_with_size(self, product, size, quantity=1):
product_id = str(product.id) + '-' + str(size.size.normalize())
if product_id not in self.cart:
self.cart[product_id] = {
'id': product_id,
'size': str(size.size.normalize()),
'qty': 0,
'price': str(product.price)
}
if self.cart[product_id]['qty'] < size.qty:
self.cart[product_id]['qty'] += quantity
self.save()
messages.success(self.request, 'Товар {0} | Размер ({1}) добавлены в корзину'.format(product.name, size))
else:
messages.error(self.request, 'Товар {0} | Размер ({1}) больше нет в наличии'.format(product.name, size))
def change_qty(self, product, quantity, size_num=None):
if len(str(product).split('-')) == 2:
size_num = str(product).split('-')[1]
product_id = str(product).split('-')[0]
product_obj = get_object_or_404(Product, id=product_id)
if size_num is not None:
size = product_obj.size_set.filter(size=size_num)[0]
if size:
if size.qty < quantity:
messages.error(self.request, 'Нет больше в наличии')
return True
else:
self.cart[product]['qty'] = quantity
self.save()
else:
if product_obj.qty < quantity:
messages.error(self.request, 'Нет больше в наличии')
return True
else:
self.cart[product_id]['qty'] = quantity
self.save()
def save(self):
# Обновление сессии cart
self.session[settings.CART_SESSION_ID] = self.cart
# Отметить сеанс как "измененный", чтобы убедиться, что он сохранен
self.session.modified = True
def remove(self, id):
product_id = str(id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
"""
Перебор элементов в корзине и получение продуктов из базы данных.
"""
product_ids = self.cart.keys()
# получение объектов product и добавление их в корзину
products = Product.objects.filter(id__in=list(map(lambda x: str(x).split('-')[0], product_ids)))
for product_id in product_ids:
for product in products:
if product_id.split('-')[0] == str(product.id):
self.cart[product_id]['product'] = product
if self.cart[product_id].get('size'):
self.cart[product_id]['size_obj'] = product.size_set.filter(size=self.cart[product_id]['size'])[
0]
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['final_price'] = item['price'] * item['qty']
yield item
def get_total_items(self):
"""
Подсчет всех товаров в корзине.
"""
return sum(item['qty'] for item in self.cart.values())
def get_total_price(self):
"""
Подсчет стоимости товаров в корзине.
"""
return sum(Decimal(item['price']) * item['qty'] for item in self.cart.values())
def clear(self):
# удаление корзины из сессии
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
class CartUserView(object):
def __init__(self, cart):
self.final_price = cart.final_price
self.cart_dict = {}
for item in cart.cartproduct_set.all():
self.cart_dict[str(item.id)] = {
'id': str(item.id),
'qty': item.qty,
'final_price': item.final_price
}
if item.size is not None:
self.cart_dict[str(item.id)]['size_obj'] = item.size
self.cart_dict[str(item.id)]['size'] = item.size.size
self.cart_dict[str(item.id)]['product'] = item.product
def __iter__(self):
for item in self.cart_dict.values():
yield item
def get_total_items(self):
return sum(item['qty'] for item in self.cart_dict.values())
def get_total_price(self):
return self.final_price
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,747 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/views.py | from django.shortcuts import render, redirect
from django.views import View
from django.views.generic import DetailView
from .utils import CategoryMixin, CartMixin
from .forms import OrderForm
from django.db import transaction
from .services import *
class MainPageView(CartMixin, View):
template_name = 'shop/main_page_shop.html'
def get(self, request):
products = get_products(request)
categories = get_category()
context = {
'products': products,
'categories': categories,
'cart': self.cart_view,
}
return render(request, self.template_name, context)
class DetailProductView(CartMixin, CategoryMixin, DetailView):
template_name = 'shop/product_detail.html'
context_object_name = 'product'
def get_queryset(self):
return get_product_filter_slug(self.kwargs['slug'])
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
product = super().get_object()
context['sizes'] = product.size_set.order_by('size').filter(qty__gt=0)
return context
class DetailCategoryView(CartMixin, View):
template_name = 'shop/category_detail.html'
def get(self, request, slug):
products = get_category_products(slug, request)
categories = get_category()
context = {
'category_name': get_category_name(slug),
'products': products,
'categories': categories,
'cart': self.cart_view,
}
return render(request, self.template_name, context)
class CartView(CartMixin, View):
template_name = 'shop/cart.html'
def get(self, request):
categories = get_category()
context = {
'categories': categories,
'cart': self.cart_view
}
return render(request, self.template_name, context)
class AddToCartView(CartMixin, View):
def get(self, request, slug):
product = get_product_slug(slug)
if not product.qty:
messages.error(request, 'Товара нет в наличии')
return redirect('main_page')
if request.user.is_authenticated:
add_to_cart_user(request, self.cart.customer, self.cart, product)
else:
self.cart.add(product)
return redirect(request.META.get('HTTP_REFERER'))
def post(self, request, slug):
product = get_product_slug(slug)
sizes = get_size_sneaker(product)
add_to_cart(request, sizes, product, self.cart)
return redirect(request.META.get('HTTP_REFERER'))
class DeleteFromCartView(CartMixin, View):
def get(self, request, id):
if request.user.is_authenticated:
delete_from_cart_product_id(id)
else:
self.cart.remove(id)
messages.success(request, "Товар успешно удален")
return redirect('cart')
class ChangeQTYView(CartMixin, View):
def post(self, request, id):
qty = int(request.POST.get('qty'))
if request.user.is_authenticated:
if change_qty(request, id, qty):
return redirect('cart')
else:
if self.cart.change_qty(id, quantity=qty):
return redirect('cart')
messages.success(request, "Кол-во успешно изменено")
return redirect('cart')
class CheckoutView(CartMixin, View):
template_name = 'shop/checkout.html'
def get(self, request):
if request.user.is_authenticated:
if validation_checkout_user(request, self.cart):
return redirect('cart')
else:
if validation_checkout_anonymous_user(request, self.cart):
return redirect('cart')
categories = get_category()
if not self.cart_view.get_total_items():
messages.error(request, "Ваша корзина покупок пуста")
return redirect('main_page')
form = OrderForm(request.POST or None)
context = {
'cart': self.cart_view,
'categories': categories,
'form': form
}
return render(request, self.template_name, context)
class MakeOrderView(CartMixin, View):
@transaction.atomic
def post(self, request):
form = OrderForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if request.user.is_authenticated:
make_order_user(request, order, self.cart)
else:
make_order_anonymous_user(self.cart, order)
email_message(order)
messages.success(request, "Заказ оформлен")
return redirect('main_page')
return redirect('cart')
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,748 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/sitemap.py | from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from .models import Product, Category
class StaticSitemap(Sitemap):
priority = 1
changefreq = 'daily'
def items(self):
return ['main_page']
def location(self, item):
return reverse(item)
class ItemSitemap(Sitemap):
priority = 0.50
changefreq = 'daily'
def items(self):
return Product.objects.all()
class CategorySitemap(Sitemap):
priority = 0.75
changefreq = 'daily'
def items(self):
return Category.objects.all()
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,749 | Reiko1337/shine-shop-django | refs/heads/master | /app/shop/models.py | from django.db import models
from django.contrib.auth.models import User
from pathlib import Path
from django.shortcuts import reverse
from django.core.validators import MinValueValidator
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
class Category(models.Model):
"""Категория"""
name = models.CharField('Наименование категории', max_length=255)
slug = models.SlugField(unique=True)
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
ordering = ['-id']
def get_tags_meta(self):
return [self.slug]
def get_absolute_url(self):
return reverse('category_detail', args=[self.slug])
def __str__(self):
return self.name
def get_path_category(instance, filename):
return '{0}/{1}{2}'.format(instance.category.slug, instance.slug, Path(filename).suffix)
class Product(models.Model):
"""Товар"""
name = models.CharField('Наименование', max_length=255)
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория')
description = models.TextField(verbose_name='Описание', blank=True)
slug = models.SlugField(unique=True)
image = models.ImageField('Изображение', upload_to=get_path_category)
qty = models.PositiveIntegerField(verbose_name='Количество')
price = models.DecimalField(validators=[MinValueValidator(0)], max_digits=9, decimal_places=2, verbose_name='Цена')
def get_tags_meta(self):
return [self.slug, self.name, self.category.name]
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
ordering = ['-id']
def get_absolute_url(self):
return reverse('product_detail', args=[self.category.slug, self.slug])
def save(self, *args, **kwargs):
for item in self.cartproduct_set.all():
if not item.cart.in_order:
item.save()
super().save(*args, **kwargs)
def __str__(self):
return self.name
class CartProduct(models.Model):
"""Корзина продукта"""
customer = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь', blank=True, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт')
size = models.ForeignKey('Size', verbose_name='Размер', on_delete=models.CASCADE, null=True)
cart = models.ForeignKey('Cart', on_delete=models.CASCADE, verbose_name='Корзина')
qty = models.PositiveIntegerField(default=1, verbose_name='Общее количество')
final_price = models.DecimalField(default=0, max_digits=9, decimal_places=2, verbose_name='Общая цена')
class Meta:
verbose_name = 'Корзина продукта'
verbose_name_plural = 'Корзины продуктов'
def save(self, *args, **kwargs):
self.final_price = self.qty * self.product.price
super().save(*args, **kwargs)
def __str__(self):
return "Продукт: {} (для корзины)".format(self.product.name)
class Cart(models.Model):
"""Корзина"""
customer = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь', null=True, blank=True)
total_product = models.PositiveIntegerField(default=0, verbose_name='Количество продуктов')
final_price = models.DecimalField(max_digits=9, default=0, decimal_places=2, verbose_name='Общая цена')
in_order = models.BooleanField(default=False, verbose_name='В заказе')
class Meta:
verbose_name = 'Корзина'
verbose_name_plural = 'Корзины'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def __str__(self):
return 'Пользователь: {0} | Корзина({1})'.format(
self.customer.username if self.customer else '-', self.id)
class Order(models.Model):
"""Заказ"""
STATUS_NEW = 'new'
STATUS_IN_PROGRESS = 'in_progress'
STATUS_READY = 'is_ready'
STATUS_COMPLETED = 'completed'
STATUS_CANCEL = 'cancel'
BUYING_TYPE_COURIER = 'courier'
BUYING_TYPE_DELIVERY = 'delivery'
BUYING_TYPE_DELIVERY_CART = 'delivery_cart'
PAYMENT_TYPE_CASH = 'cash'
PAYMENT_TYPE_CARD = 'card'
STATUS_CHOICES = (
(STATUS_NEW, 'Новый заказ'),
(STATUS_IN_PROGRESS, 'Заказ в обработке'),
(STATUS_READY, 'Заказ готов'),
(STATUS_COMPLETED, 'Заказ выполнен'),
(STATUS_CANCEL, 'Заказ отменен')
)
BUYING_TYPE_CHOICES = (
(BUYING_TYPE_COURIER, 'Курьер в городе Молодечно (бесплатно)'),
(BUYING_TYPE_DELIVERY, 'Доставка почтой, оплата при получении (стоимость 3-5 руб, от 40 руб. бесплатно)'),
(BUYING_TYPE_DELIVERY_CART, 'Доставка почтой, предоплата (стоимость 3 РУБ, от 40 руб бесплатно)')
)
PAYMENT_TYPE_CHOICES = (
(PAYMENT_TYPE_CASH, 'Наличные'),
(PAYMENT_TYPE_CARD, 'Карта')
)
customer = models.ForeignKey(User, verbose_name='Покупатель',
on_delete=models.CASCADE, blank=True, null=True)
first_name = models.CharField(max_length=255, verbose_name='Имя')
last_name = models.CharField(max_length=255, verbose_name='Фамилия')
phone = models.CharField(max_length=20, verbose_name='Телефон')
cart = models.ForeignKey(Cart, verbose_name='Корзина', on_delete=models.CASCADE, null=True, blank=True)
address = models.CharField(max_length=1024, verbose_name='Адрес')
status = models.CharField(
max_length=100,
verbose_name='Статус заказ',
choices=STATUS_CHOICES,
default=STATUS_NEW
)
buying_type = models.CharField(
max_length=100,
verbose_name='Тип доставки',
choices=BUYING_TYPE_CHOICES,
default=BUYING_TYPE_COURIER
)
payment_type = models.CharField(
max_length=100,
verbose_name='Тип оплаты',
choices=PAYMENT_TYPE_CHOICES,
default=PAYMENT_TYPE_CASH
)
comment = models.TextField(verbose_name='Комментарий к заказу', null=True, blank=True)
created_at = models.DateTimeField(auto_now=True, verbose_name='Дата создания заказа')
class Meta:
verbose_name = 'Заказ'
verbose_name_plural = 'Заказы'
ordering = ['-id']
def delete(self, *args, **kwargs):
super(Order, self).delete()
def __str__(self):
if self.customer:
return 'Заказ({0}): {1}'.format(self.id, self.customer.username)
else:
return 'Заказ({0}): {1} {2}'.format(self.id, self.first_name, self.last_name)
class Size(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт')
size = models.DecimalField(verbose_name='Размер', max_digits=9, decimal_places=1)
qty = models.PositiveIntegerField(verbose_name='Количество')
class Meta:
verbose_name = 'Размер'
verbose_name_plural = 'Размеры'
ordering = ['product__name']
def __str__(self):
return '{0} | {1}'.format(self.product.name, self.size)
| {"/app/shop/services.py": ["/app/shop/models.py"], "/app/account/views.py": ["/app/account/services.py"], "/app/metatags/admin.py": ["/app/metatags/models.py"], "/app/shop/utils.py": ["/app/shop/models.py", "/app/shop/cart.py"], "/app/shop/cart.py": ["/app/shop/models.py"], "/app/shop/views.py": ["/app/shop/utils.py", "/app/shop/services.py"], "/app/shop/sitemap.py": ["/app/shop/models.py"]} |
68,763 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py | from .arm_controller import *
from .arm_jointstate_pub import *
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,764 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/src/my_simulation/helpers/morse_local_config.py | # =======================================================================================
# Local configuration of the experiment.
# =======================================================================================
# Exported module information
# ---------------------------------------------
objects_dir = "";
environment_dir = "";
mw_dir = "";
mw_loc = "";
# Function that mount the structure of directories used by the simulation,
# and the middleware (ROS) location.
# ---------------------------------------------
def load_experiment_config( ExperimentName ):
global objects_dir, environment_dir
global mw_dir, mw_loc
# Mount structure of directories used by the simulation.
objects_dir = ExperimentName + '/props/'
environment_dir = ExperimentName + '/environments/'
mw_dir = ExperimentName + '/middleware_ros/'
# Middleware location based on directory.
# Remember that middleware objects must be added to "__init__.py" of the directory.
mw_loc = mw_dir
mw_loc = mw_loc.replace("/", ".")
# ---------------------------------------------------------------------------------------
# Configure with the name of the experiment.
experiment_name = 'my_simulation'
load_experiment_config( experiment_name )
# =======================================================================================
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,765 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/src/my_simulation/helpers/adapters.py | # =======================================================================================
# helpers/adapters.py
# =======================================================================================
from . import morse_local_config as exp_settings
from morse.builder import Component
from morse.middleware.ros_request_manager import ros_service, ros_action
from morse.core.overlay import MorseOverlay
from morse.core.exceptions import MorseServiceError
from morse.middleware.ros import ROSPublisher, ROSPublisherTF, ROSSubscriber
# ----------------------------------------------------------------------------------------
def morse_to_ros_namespace( name ):
return name.replace(".", "/")
# ----------------------------------------------------------------------------------------
class ros:
# Topics - Publisher/Subscriber and more
# --------------------------------------
class Publisher(ROSPublisher):
pass
class Subscriber(ROSSubscriber):
pass
class TfBroadcaster(ROSPublisherTF):
pass
# Decorators
# --------------------------------------
service = ros_service
action = ros_action
# Classes inherit from MorseOverlay
# --------------------------------------
class Service(MorseOverlay):
"""
A ROS service is created to export MORSE services through the overlay class.
Therefore, the class exporting this services must inherit from this.
"""
pass
class Action(MorseOverlay):
"""
A ROS action is created to export MORSE services through the overlay class.
Therefore, the class exporting this services must inherit from this.
"""
pass
# Registers
# --------------------------------------
class ServiceRegister:
"""
This class attaches (registers) a MORSE service to a ROS service that exports it.
"""
_mw_location = exp_settings.mw_loc;
@staticmethod
def register( component, service_class, name = "" ):
service = ros.Service._mw_location + service_class
component.add_overlay( "ros", service, namespace = name )
class ActionRegister:
pass
class TopicRegister:
"""
This class attaches (registers) a MORSE datastream to a ROS datastream that exports it.
"""
_mw_location = exp_settings.mw_loc;
@staticmethod
def register( component, name = "" ):
component.add_interface("ros", topic = name )
# ----------------------------------------------------------------------------------------
def register_ros_service( obj, name, service_class ):
service_path = exp_settings.mw_loc + service_class
obj.add_overlay("ros", service_path, namespace = name )
def register_ros_action( obj, name, action_class ):
action_path = exp_settings.mw_loc + action_class
obj.add_overlay("ros", action_path, namespace = name )
def register_ros_topic( obj, name, topic_class = None ):
if topic_class is not None:
topic_path = exp_settings.mw_loc + topic_class
obj.add_stream("ros", topic_path, topic = name )
else:
topic_path = ""
obj.add_stream("ros", topic = name )
# =======================================================================================
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,766 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py | import logging; logger = logging.getLogger("morse."+ __name__)
from my_simulation.helpers import adapters
import roslib;
import rospy
from control_msgs.msg import FollowJointTrajectoryAction
from morse.core.services import interruptible
from morse.core import status
from morse.core.exceptions import MorseServiceError
class ArmControllerByActions(adapters.ros.Service):
"""
This overlay provides a ROS JointTrajectoryAction amd FollowJointTrajectoryAction
interfaces to armatures.
Besides the ROS action server, it also sets a ROS parameter with the list of
joints.
"""
def __init__(self, overlaid_object, namespace = None):
# Call the constructor of the parent class
super(self.__class__,self).__init__(overlaid_object)
joints = list(overlaid_object.local_data.keys())
self.namespace = namespace
name = adapters.morse_to_ros_namespace( self.name() )
# ---
#base_name = "iri_kuka_joint_"
#joints = []
#for i in range(7):
# joint_name = base_name + ("%d" % (i+1) )
# joints.append( joint_name )
rospy.set_param(name + "/joint_names", joints)
def _stamp_to_secs(self, stamp):
return stamp.secs + stamp.nsecs / 1e9
def name(self):
if self.namespace:
return self.namespace
else:
return super(self.__class__, self).name()
# Export action for ROS
# ------------------------------------------------------
def follow_joint_trajectory_result(self, result):
return result
# The name of the 'action' in ROS is based on the name of this function.
@interruptible
@adapters.ros.action(type = FollowJointTrajectoryAction)
def follow_joint_trajectory(self, req):
""" Fill a MORSE trajectory structure from ROS JointTrajectory
"""
traj = {}
req = req.trajectory
traj["starttime"] = self._stamp_to_secs(req.header.stamp)
# Read joint names in message
joint_names = req.joint_names
logger.info( req.joint_names )
# Overwrite joint names from message to match ones defined by MORSE
for i in range( len(joint_names) ):
joint_names[i] = joint_names[i].replace("kuka_joint", "kuka")
logger.info( joint_names )
# Read positions from message
target_joints = self.overlaid_object.local_data.keys()
logger.info( target_joints )
# Check if trajectory is correct or not
diff = set(joint_names).difference(set(target_joints))
if diff:
raise MorseServiceError("Trajectory contains unknown joints! %s" % diff)
points = []
for p in req.points:
point = {}
# Re-order joint values to match the local_data order
pos = dict(zip(joint_names, p.positions))
point["positions"] = [pos[j] for j in target_joints if j in pos]
vel = dict(zip(joint_names, p.velocities))
point["velocities"] = [vel[j] for j in target_joints if j in vel]
acc = dict(zip(joint_names, p.accelerations))
point["accelerations"] = [acc[j] for j in target_joints if j in acc]
point["time_from_start"] = self._stamp_to_secs(p.time_from_start)
points.append(point)
traj["points"] = points
logger.info(traj)
self.overlaid_object.trajectory(
self.chain_callback(self.follow_joint_trajectory_result),
traj)
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,767 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/default.py | #! /usr/bin/env morseexec
# =======================================================================================
# Experiment using MORSE
# =======================================================================================
import my_simulation.helpers.morse_local_config as exp_settings
from my_simulation.helpers import adapters
from builder import environment
from morse.builder import Environment
from morse.core.morse_time import TimeStrategies
from morse.builder import Robot, FakeRobot
from morse.builder.actuators import KukaLWR, Gripper
from morse.builder.sensors import ArmaturePose
# ---------------------------------------------------------------------------------------
def create_simulation():
# Create the robot
# ----------------------------------------------------------
robot = FakeRobot()
robot.name = "kuka_lwr"
arm = KukaLWR()
arm_pose = ArmaturePose()
arm.append( arm_pose )
robot.append( arm )
# Set-up ROS connection
# ----------------------------------------------------------
topic_base_name = "/" + robot.name + "/"
robot.add_default_interface('ros')
# Arm - follow_joint_trajectory + joint_state ---
adapters.register_ros_topic( arm_pose,
name = ("kuka_lwr/joint_states"),
topic_class = 'JointStatePublisher' )
adapters.register_ros_action(arm,
name = ("kuka_lwr"),
action_class = 'ArmControllerByActions' )
# Environment
# ----------------------------------------------------------
env = Environment( exp_settings.environment_dir + "empty_world.blend")
env.set_camera_location([10.0, -10.0, 10.0])
env.set_camera_rotation([1.0470, 0, 0.7854])
#env.set_time_strategy(TimeStrategies.FixedSimulationStep)
env.show_framerate(True)
# ---------------------------------------------------------------------------------------
create_simulation()
# =======================================================================================
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,768 | dgerod/morse_and_ros-moveit_example | refs/heads/master | /iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py | import logging; logger = logging.getLogger("morse."+ __name__)
from my_simulation.helpers import adapters
import roslib
import rospy
from sensor_msgs.msg import JointState
class JointStatePublisher(adapters.ros.Publisher):
""" Publishes a JointState topic and set kuka_{1-7} to the position[0-6]. """
ros_class = JointState
def default(self, ci='unused'):
message = JointState()
message.header = self.get_ros_header()
message.name = [''] * 7
message.position = [0] * 7
message.velocity = [0] * 7
message.effort = [0] * 7
# Define name used to export joints
base_name = "kuka_joint_"
for i in range(7):
message.name[i] = base_name + ("%d" % (i+1) )
message.position[i] = self.data[ "kuka_" + ("%d" % (i+1) ) ]
self.publish(message)
| {"/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/__init__.py": ["/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_controller.py", "/iri_klwr_morse/morse/my_simulation/src/my_simulation/middleware_ros/arm_jointstate_pub.py"]} |
68,771 | Yelue/GenerateSchedule | refs/heads/master | /app/tasks.py | import sqlalchemy
import numpy as np
import pandas as pd
import requests
import os
from alg.population import Population
from alg.student_wishes import SWishesConnector
from alg.teacher_wishes import TWishesConnector
from alg.collection_cards import CollectionCards
from alg.genetic_algorithm import GeneticAlgorithm
from db.tasks import LoadDaysTask, LoadDepartmentTask, \
LoadFacultyTask, LoadGroupsTask, \
LoadLessonTask, LoadTeachersTask, \
LoadPairsTask, LoadCardTask,\
LoadEmailStudents, LoadEmailTeachers,\
LoadRandomTeacherScheduleTask,\
LoadRandomStudentScheduleTask,\
LoadFullInfo, LoadFullSearchInfo
from db.orm.tables import *
import csv
def send_messages(db):
urls = create_urls(db)
for url in list(urls.keys())[:1]:
requests.post(
os.environ.get('MAIL_URL'),
auth=("api", os.environ.get("MAIL_API")),
data={"from": os.environ.get("MAIL_FROM"),
"to": "test <testrozklad@gmail.com>",
"subject": "Hello",
"text": "Email to edit schedule: %s"%urls[url]})
def create_urls(db):
st_verif_query = "select * from verif_student;"
tchr_verif_query = "select * from verif_teacher;"
st_verif_df = pd.read_sql(st_verif_query, con=db.engine)
tchr_verif_df = pd.read_sql(tchr_verif_query, con=db.engine)
st_link = 'https://generateschedule.herokuapp.com/scheduledesign/student/' + st_verif_df.st_secret_key
tchr_link = 'https://generateschedule.herokuapp.com/scheduledesign/teacher/' + tchr_verif_df.tchr_secret_key
verif_teacher_links = {x: y for x,y in zip(tchr_verif_df.tchr_email, tchr_link)}
verif_students_links = {x: y for x,y in zip(st_verif_df.st_email, st_link)}
return {**verif_students_links, **verif_teacher_links}
def load_db(engine):
LoadDaysTask.LoadDaysTask(engine=engine).load_to_db()
LoadFacultyTask.LoadFacultyTask(engine=engine).load_to_db()
LoadDepartmentTask.LoadDepartmentTask(engine=engine).load_to_db()
LoadGroupsTask.LoadGroupsTask(engine=engine).load_to_db()
LoadLessonTask.LoadLessonTask(engine=engine).load_to_db()
LoadTeachersTask.LoadTeachersTask(engine=engine).load_to_db()
LoadPairsTask.LoadPairsTask(engine=engine).load_to_db()
LoadCardTask.LoadCardTask(engine=engine).load_to_db()
LoadEmailStudents.LoadEmailStudents(engine=engine).load_to_db()
LoadEmailTeachers.LoadEmailTeachers(engine=engine).load_to_db()
def prepare_random_schedule(db):
#prepare for teacher
LoadRandomTeacherScheduleTask.LoadRandomTeacherScheduleTask(db).load_to_db()
#prepare for student
LoadRandomStudentScheduleTask.LoadRandomStudentScheduleTask(db).load_to_db()
def prepare_schedule_interface(db, user_status, user_key):
return LoadFullInfo.LoadFullInfo(db=db, user_status=user_status, user_key=user_key).create_schedule()
def check_all_sended(db):
all_keys_wish_student = pd.read_sql('select st_secret_key from student_wish_schedule', con=db.engine).drop_duplicates(keep='first')
all_keys_wish_teacher = pd.read_sql('select tchr_secret_key from teacher_wish_schedule', con=db.engine).drop_duplicates(keep='first')
teachers_keys = pd.read_sql('select tchr_secret_key from verif_teacher', con=db.engine)
student_keys = pd.read_sql('select st_secret_key from verif_student', con=db.engine)
if len(pd.concat(all_keys_wish_teacher, teachers_keys, ignore_index=True).drop_duplicates(keep=False)) and \
len(pd.concat(all_keys_wish_student, student_keys, ignore_index=True).drop_duplicates(keep=False)):
return True
return False
def prepare_data_db(data, user_status, user_key):
data_db = []
if user_status=='student':
table = 'student_wish_schedule'
column_key = 'st_secret_key'
else:
table = 'teacher_wish_schedule'
column_key = 'tchr_secret_key'
for lesson in data:
data_db.append({
column_key: user_key,
'st_schedule_id': int(lesson['les_id']),
'days_id': lesson['week']*6+lesson['day']+1,
'pairs_id': lesson['les_num']+1})
return data_db
def load_schedule_db(data,
db,
user_status,
user_key):
if user_status=='student':
table = Student_Wish_Schedule
column_key = 'st_schedule_id'
else:
table = Student_Wish_Schedule
column_key = 'tchr_schedule_id'
data = prepare_data_db(data=data,user_status=user_status,user_key=user_key)
print(data)
for d in data:
db.session.query(table).filter_by(**{column_key:d[column_key]}).update(d)
db.session.commit()
def search_schedule(db, search_query):
student = find_in_student(db, search_query)
teacher = find_in_teacher(db, search_query)
if student:
#format_data
return 'stud', LoadFullSearchInfo.LoadFullSearchInfo(db, user_status='student', ids=student).create_schedule()
elif teacher:
#format_data
return 'teach', LoadFullSearchInfo.LoadFullSearchInfo(db, user_status='teacher', ids=teacher).create_schedule()
return False
def check_schedule(db, search_query):
student = find_in_student(db, search_query)
teacher = find_in_teacher(db, search_query)
return student or teacher
def find_in_student(db, search_query):
try:
group_id = db.session.query(Groups).filter_by(group_name=search_query).first().group_id
except:
return False
cards_id = db.session.query(Card.card_id).filter_by(group_id=group_id).all()
return db.session.query(Class.class_id).filter(Class.card_id.in_(cards_id)).all()
def find_in_teacher(db, search_query):
try:
teacher_id = db.session.query(Teacher).filter_by(teacher_short_name=search_query).first().teacher_id
except:
return False
cards_id = db.session.query(Card.card_id).filter_by(teacher_id=teacher_id).all()
return db.session.query(Class.class_id).filter(Class.card_id.in_(cards_id)).all()
def genetic_algorithm(db):
print('Start work of genetic_algorithm')
FACULTY_ID = 2
rooms = np.array(range(1, 30))
clc = CollectionCards(FACULTY_ID, db.session)
print('Done CLS')
swc = SWishesConnector(FACULTY_ID, db.session)
print('Done SWC')
twc = TWishesConnector(FACULTY_ID, db.session)
print('Done TWC')
ppl = Population(rooms, 100, FACULTY_ID, db.session)
ppl.create_chromosomes()
print('Done PPL')
ga = GeneticAlgorithm(ppl.chromosomes, clc, swc, twc)
ga.fit(n_iter = 10)
classesL = []
TB_chromosome = ga.chromosomes[0][0]
for lesson in TB_chromosome.lessons:
for card in lesson.cards:
room, wdc = TB_chromosome.get_wdcByLessonNum(lesson.unNum)
days_id = (wdc[0] + 1) * wdc[1] + 1
pairs_id = wdc[2] + 1
classesL.append(Class(card_id = int(card), days_id = int(days_id), pairs_id = int(pairs_id)))
print('Card_id: {}, days_id: {}, pairs_id: {}'.format(card, days_id, pairs_id))
db.session.add_all(classesL)
db.session.commit()
print('genetic_algorithm done')
def find_all_teachers(db):
return [dict((col, getattr(row, col)) for col in row.__table__.columns.keys()) for row in db.session.query(Teacher).all()]
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,772 | Yelue/GenerateSchedule | refs/heads/master | /alg/time_table.py | import numpy as np
class TimeTable:
def __init__(self, rooms, n_weeks = 2,
n_days = 6, n_classes = 5):
self.timeTable = {
room: np.zeros((n_weeks, n_days, n_classes)) for room in rooms }
def get_wdcByLessonNum(self, value):
for room in self.timeTable:
wdc = np.argwhere(self.timeTable[room] == value)
if wdc.size != 0:
return room, list(map(tuple, wdc))[0]
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,773 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadGroupsTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadGroupsTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_groups.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['group_name','group_course','department'])
def load_to_db(self):
src = self.get_data()
exi = pd.read_sql('select department_short_name,department_id from department', con=self.engine)
src = pd.merge(src, exi,
how='left',
left_on='department',
right_on='department_short_name').drop(['department_short_name','department'],
axis=1)
src.to_sql('groups', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,774 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadEmailStudents.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
from passlib.hash import sha256_crypt
from random import randint
class LoadEmailStudents(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_verif_students.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['group_name','st_email'])
def load_to_db(self):
src = self.get_data()
group = pd.read_sql('select group_name, group_id from groups', con=self.engine)
src = pd.merge(src, group,
how='left',
left_on='group_name',
right_on='group_name').drop(['group_name'],axis=1)
src['st_secret_key'] = src['group_id'].apply(lambda x: sha256_crypt.encrypt(str(randint(1,100))))
src.to_sql('verif_student', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,775 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadTeachersTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadTeachersTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_teacher.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['teacher_long_name',
'teacher_short_name',
'teacher_degree',
'teacher_short_degree'])
def load_to_db(self):
src = self.get_data()
src.iloc[:,:-1].to_sql('teacher', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,776 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadFullSearchInfo.py | import pandas as pd
class LoadFullSearchInfo:
def __init__(self, db, user_status, ids):
self.db = db
self.user_status = user_status
self.ids = tuple(map(lambda x: x[0], ids))
def find_card(self):
df = pd.read_sql(f"select class_id,card_id,pairs_id,days_id from class where class_id in {self.ids}", con=self.db.engine)
return df
def full_info(self, df):
ids = tuple(df.card_id.values)
card = pd.read_sql(f'select * from card where card_id in {ids}', con=self.db.engine)
df = df.merge(card, how='inner', on='card_id')
#lesson
lesson = pd.read_sql('select * from lesson', con=self.db.engine)
df = df.merge(lesson, how='inner', on='lesson_id').drop(columns=['lesson_id'])
del lesson
#group
group = pd.read_sql('select group_id, group_name from groups', con=self.db.engine)
df = df.merge(group, how='inner', on='group_id').drop(columns=['group_id'])
del group
#teacher
teacher = pd.read_sql('select * from teacher', con=self.db.engine)
df = df.merge(teacher, how='inner', on='teacher_id').drop(columns=['teacher_id','teacher_degree'])
del teacher
# return df.drop(columns=[self.column_key,'card_id', 'lesson_id', 'lesson_long_name'])
return df.drop(columns=['card_id','amount_time'])
def format_data(self, df):
df.loc[df.lesson_type=='None','lesson_type'] = ''
df.rename(columns={'class_id':'id'}, inplace=True)
df = self.format_lecture(df) if self.user_status=='teacher' else df
data = {
'week1':{
'lesson%s'%i: [df[(df.days_id==j)&(df.pairs_id==i)].to_dict('records') for j in range(1,7)] for i in range(1,6)
},
'week2':{
'lesson%s'%i: [df[(df.days_id==j)&(df.pairs_id==i)].to_dict('records') for j in range(7,13)] for i in range(1,6)
}
}
for week in data.keys():
for lesson in data[week].keys():
for k, cell in enumerate(data[week][lesson]):
if not cell:
data[week][lesson][k] = 0
return data
def format_lecture(self,df):
lectures = df[['pairs_id','days_id']][df[['pairs_id','days_id']].duplicated()].drop_duplicates(keep='first')
lectures = [list(i) for i in lectures.values]
data = {}
for i in lectures:
data[tuple(i)] = ', '.join(list(df[(df.pairs_id==i[0])&(df.days_id==i[1])]['group_name'].values))
df.drop_duplicates(subset=['pairs_id', 'days_id'], keep='first', inplace=True)
for i in data.keys():
df.loc[(df.pairs_id==i[0])&(df.days_id==i[1]),'group_name'] = data[i]
return df
def create_schedule(self):
df = self.find_card()
df = self.full_info(df)
df = self.format_data(df)
return df
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,777 | Yelue/GenerateSchedule | refs/heads/master | /alg/collection_cards.py | import numpy as np
import pandas as pd
from db.orm.tables import Department, Groups, Card
class LessonCard:
def __init__(self, card_id,
group_id, teacher_id):
self.card_id = card_id
self.group_id = group_id
self.teacher_id = teacher_id
class CollectionCards:
def __init__(self, facultyID, session_obj):
self.cards = {}
self.session = session_obj
self.facultyID = facultyID
self.create_cards()
def get_allFacultyCard(self):
data = pd.read_sql(self.session.query(Card).select_from(Department).\
join(Groups).join(Card).filter(Department.faculty_id == self.facultyID).statement, self.session.bind)
return data
def create_cards(self):
data = self.get_allFacultyCard()
for ind in data.index:
key = data.loc[ind, 'card_id']
self.cards[key] = LessonCard(
key,
data.loc[ind, 'group_id'],
data.loc[ind, 'teacher_id']
)
def get_cardByCardId(self, card_id):
return self.cards[card_id] | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,778 | Yelue/GenerateSchedule | refs/heads/master | /db/orm/engine.py | from sqlalchemy.engine import create_engine
import os
ENGINE_PATH_WIN_AUTH = os.environ.get('DATABASE_URL')
engine = create_engine(ENGINE_PATH_WIN_AUTH)
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,779 | Yelue/GenerateSchedule | refs/heads/master | /app/app.py | from flask import Flask, request, jsonify, redirect, url_for, render_template, jsonify, make_response
import json
import os
from threading import Timer
from werkzeug.utils import secure_filename
from numpy import random as rd
from flask_sqlalchemy import SQLAlchemy
import shutil
import requests
import connexion
from app.forms.search import Search_form
from app.forms.new_schedule import New_schedule_form
from app.tasks import load_db, prepare_random_schedule,\
prepare_schedule_interface,\
load_schedule_db,search_schedule, \
check_schedule, find_all_teachers,\
genetic_algorithm,\
send_messages, check_all_sended
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = int(os.environ.get('SEND_FILE_MAX_AGE_DEFAULT'))
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = bool(int(os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')))
db = SQLAlchemy(app)
db.create_all()
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route("/", methods=['GET', 'POST'])
def index():
return render_template('index.html',
search_form=Search_form(request.form),
new_schedule_form=New_schedule_form(request.form))
@app.route("/scheduledesign/<user_status>/<user_key>", methods=['GET', 'POST'])
def scheduledesign(user_status, user_key):
temp_data = prepare_schedule_interface(
db=db,
user_status=user_status,
user_key=user_key
)
return render_template('schedule_design.html',
data=temp_data,
search_form=Search_form(request.form))
@app.route("/loadfiles", methods=['GET', 'POST'])
def schedule_files_load():
return render_template('load_forms.html',
search_form=Search_form(request.form),
new_schedule_form=New_schedule_form(request.form))
@app.route('/post_desired_schedule/<user_status>/<user_key>', methods = ['GET', 'POST'])
def get_desired_schedule(user_status, user_key):
data = json.loads(request.form['javascript_data'])
load_schedule_db(data=data, db=db, user_status=user_status, user_key=user_key)
if check_all_sended(db):
send_messages(db)
return '', 200
@app.route("/no_schedule", methods=['GET', 'POST'])
def search():
s_f = Search_form(request.form)
search_query = ''
if request.method == 'POST':
search_query = request.form['search_value'].strip()
s_f.search_value.data = ''
if check_schedule(db, search_query):
return redirect(f'/schedule/{search_query}/1')
else:
return render_template('search_result.html',
search_form=s_f,
search_value=search_query)
@app.route("/schedule/<name>/<w_num>", methods=['GET', 'POST'])
def schedule(name, w_num):
search_type, schedule = search_schedule(db, name)
schedule = schedule[f'week{w_num}']
week_active_dropdown = ['active disabled', ''] if w_num == '1' else ['', 'active disabled']
return render_template('schedule.html',
week_active_dropdown=week_active_dropdown,
search_type=search_type,
schedule=schedule,
name=name,
search_form=Search_form(request.form))
@app.route('/upload_files', methods=['GET', 'POST'])
def upload_files():
if request.method == 'POST':
upload_data = {
'email': request.form['email'],
'name': request.form['name']
}
file_names = ['table_teacher',
'table_lesson',
'table_groups',
'table_faculty',
'table_depart',
'table_cards',
'table_teacher_emails',
'table_student_emails']
file = request.files['teachers']
print(os.path.splitext(secure_filename(file.filename)))
folder_name = '/' + str(rd.randint(0, 9999))
os.mkdir(app.config['UPLOAD_FOLDER'] + folder_name)
for f, new_name in zip(request.files, file_names):
file = request.files[f]
filename = new_name + os.path.splitext(secure_filename(file.filename))[1]
file.save(
os.path.join(app.config['UPLOAD_FOLDER'] + folder_name, filename)
)
load_db(db.engine)
shutil.rmtree(app.config['UPLOAD_FOLDER'] + folder_name)
prepare_random_schedule(db)
return render_template('upload.html',
search_form=Search_form(request.form),
data=upload_data)
@app.route('/api/readteachers', methods=['GET'])
def get_teachers():
teachers = find_all_teachers(db=db)
return jsonify({'teachers': teachers})
@app.route('/api/schedule/<query>', methods=['POST','GET'])
def get_schedule(query):
return jsonify({'schedule': search_schedule(db,query)})
@app.route('/api/lesson_cards/<user_status>/<user_key>', methods=['GET'])
def lesson_cards(user_status, user_key):
data = prepare_schedule_interface(db=db)
return jsonify({'cards': data})
if __name__ == '__main__':
app.run()
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,780 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadFullInfo.py | import pandas as pd
class LoadFullInfo:
def __init__(self, db, user_status, user_key):
self.db = db
self.user_status = user_status
self.user_key = user_key
def find_card(self):
if self.user_status=='student':
table = 'student_wish_schedule'
self.column_key = 'st_secret_key'
else:
table = 'teacher_wish_schedule'
self.column_key = 'tchr_secret_key'
df = pd.read_sql(f"select * from {table} where {self.column_key} = '{self.user_key}'", con=self.db.engine)
return df
def full_info(self, df):
card = pd.read_sql('select lesson_id, card_id from card', con=self.db.engine)
df = df.merge(card, how='inner', on='card_id')
#lesson
lesson = pd.read_sql('select * from lesson', con=self.db.engine)
df = df.merge(lesson, how='inner', on='lesson_id')
return df.drop(columns=[self.column_key,'card_id', 'lesson_id', 'lesson_long_name'])
def format_data(self, df):
df.loc[df.lesson_type=='None','lesson_type'] = ''
df['name'] = df['lesson_short_name']+ ' ' +df['lesson_type']
df.rename(columns={'st_schedule_id':'id','tchr_schedule_id':'id'}, inplace=True)
df.drop(columns=['lesson_short_name','lesson_type'],inplace=True)
data = {
'week1':{
'lesson%s'%i: [df[(df.days_id==j)&(df.pairs_id==i)].to_dict('records') for j in range(1,7)] for i in range(1,6)
},
'week2':{
'lesson%s'%i: [df[(df.days_id==j)&(df.pairs_id==i)].to_dict('records') for j in range(7,13)] for i in range(1,6)
}
}
for week in data.keys():
for lesson in data[week].keys():
for k, cell in enumerate(data[week][lesson]):
if not cell:
data[week][lesson][k] = 0
return data
def create_schedule(self):
df = self.find_card()
df = self.full_info(df)
df = self.format_data(df)
return df | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,781 | Yelue/GenerateSchedule | refs/heads/master | /app/forms/new_schedule.py | from flask_wtf import FlaskForm
from wtforms import SubmitField, ValidationError, StringField
from wtforms.validators import InputRequired
from flask_wtf.file import FileField, FileRequired
class New_schedule_form(FlaskForm):
email = StringField(validators=[InputRequired()])
name = StringField(validators=[InputRequired()])
teachers = FileField(validators=[FileRequired()])
subjects = FileField(validators=[FileRequired()])
groups = FileField(validators=[FileRequired()])
faculty = FileField(validators=[FileRequired()])
departments = FileField(validators=[FileRequired()])
load_list = FileField(validators=[FileRequired()])
teacher_emails = FileField(validators=[FileRequired()])
student_emails = FileField(validators=[FileRequired()])
submit = SubmitField("Підтвердити")
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,782 | Yelue/GenerateSchedule | refs/heads/master | /alg/chromosome_crossover.py | import numpy as np
from alg.chromosome import Chromosome
class ChromosomeCrossover:
def fill_data(self, chromosome, room,
wdc, teacherID, groupIDs, uniqueNumber):
chromosome.teachers[teacherID][wdc] = 1
chromosome.timeTable[room][wdc] = uniqueNumber
for group_id in groupIDs:
chromosome.groups[group_id][wdc] = 1
def crossover(self, chromosome1, chromosome2):
child = Chromosome(
chromosome1.rooms,
chromosome2.groupIDs,
chromosome1.teacherIDs,
chromosome2.collection_cards,
*chromosome1.wdc_shape
)
child.lessons = chromosome2.lessons
for lesson in child.lessons:
cardsL = lesson.cards
teacherID, groupIDs = child.get_GTIndexes(cardsL)
chromo1_room, chromo1_wdc = chromosome1.get_wdcByLessonNum(lesson.unNum)
chromo2_room, chromo2_wdc = chromosome2.get_wdcByLessonNum(lesson.unNum)
dice = np.random.randint(0, 2, 1)
if dice == 0 and child.check_place_time(teacherID, groupIDs, chromo1_room, chromo1_wdc):
self.fill_data(child, chromo1_room, chromo1_wdc, teacherID, groupIDs, lesson.unNum)
elif dice == 1 and child.check_place_time(teacherID, groupIDs, chromo2_room, chromo2_wdc):
self.fill_data(child, chromo2_room, chromo2_wdc, teacherID, groupIDs, lesson.unNum)
else:
room, wdc = child.choice_place_time(teacherID, groupIDs)
self.fill_data(child, room, wdc, teacherID, groupIDs, lesson.unNum)
return child | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,783 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/BasicTask.py | import abc
class BasicTask:
path_files = 'db/assets/'
@abc.abstractmethod
def file_name(self):
return None
def full_path(self):
return self.path_files+self.file_name()
def get_file(self):
return open(self.full_path())
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,784 | Yelue/GenerateSchedule | refs/heads/master | /db/orm/tables.py | from sqlalchemy import Column, Integer, Float, String, ForeignKey, Boolean, Time
from sqlalchemy.ext.declarative import declarative_base
from db.orm.engine import engine
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Faculty(Base):
__tablename__ = 'faculty'
faculty_id = Column(Integer, primary_key=True)
faculty_short_name = Column(String(20), nullable=True)
faculty_long_name = Column(String(100), nullable=True)
depart_faculty_id = relationship('Department', back_populates='depar_faculty_id')
class Department(Base):
__tablename__ = 'department'
department_id = Column(Integer, primary_key=True)
department_short_name = Column(String(20), nullable=True)
department_long_name = Column(String(100), nullable=True)
faculty_id = Column(Integer, ForeignKey('faculty.faculty_id'))
depar_faculty_id = relationship('Faculty', back_populates='depart_faculty_id')
depar_group_id = relationship('Groups', back_populates='group_depar_id')
class Groups(Base):
__tablename__ = 'groups'
group_id = Column(Integer, primary_key=True)
group_name = Column(String(10), nullable=True)
group_course = Column(Integer, nullable=True)
department_id = Column(Integer, ForeignKey('department.department_id'))
group_depar_id = relationship('Department', back_populates='depar_group_id')
group_card_id = relationship('Card', back_populates='card_group_id')
group_verif_student = relationship('Verif_Students', back_populates='verif_student_group')
class Teacher(Base):
__tablename__ = 'teacher'
teacher_id = Column(Integer, primary_key=True)
teacher_short_name = Column(String(100), nullable=True)
teacher_long_name = Column(String(100), nullable=True)
teacher_degree = Column(String(100), nullable=True)
teacher_card_id = relationship('Card', back_populates='card_teacher_id')
teacher_verif_teacher = relationship('Verif_Teachers', back_populates='verif_teacher_teacher')
class Lesson(Base):
__tablename__ = 'lesson'
lesson_id = Column(Integer, primary_key=True)
lesson_short_name = Column(String(100), nullable=True)
lesson_long_name = Column(String(100), nullable=True)
lesson_type = Column(String(30), nullable=True)
lesson_card_id = relationship('Card', back_populates='card_lesson_id')
class Room(Base):
__tablename__ = 'room'
room_id = Column(Integer, primary_key=True)
room_number = Column(Integer, nullable=True)
room_type = Column(String(100), nullable=True)
# room_class_id = relationship('Class', back_populates='class_room_id')
class Study_Days(Base):
__tablename__ = 'study_days'
days_id = Column(Integer, primary_key=True)
name_day = Column(String(100), nullable=True)
days_class_id = relationship('Class', back_populates='class_days_id')
days_id_wish_student = relationship('Student_Wish_Schedule', back_populates='wish_student_days_id')
days_id_wish_teacher = relationship('Teacher_Wish_Schedule', back_populates='wish_teacher_days_id')
class Pairs(Base):
__tablename__ = 'pairs'
pairs_id = Column(Integer, primary_key=True)
start_time = Column(Time, nullable=False)
end_time = Column(Time, nullable=False)
pairs_class_id = relationship('Class', back_populates='class_pairs_id')
pairs_id_wish_student = relationship('Student_Wish_Schedule', back_populates='wish_student_pairs_id')
pairs_id_wish_teacher = relationship('Teacher_Wish_Schedule', back_populates='wish_teacher_pairs_id')
class Card(Base):
__tablename__ = 'card'
card_id = Column(Integer, primary_key=True)
group_id = Column(Integer, ForeignKey('groups.group_id'))
teacher_id = Column(Integer, ForeignKey('teacher.teacher_id'))
lesson_id = Column(Integer, ForeignKey('lesson.lesson_id'))
amount_time = Column(Integer, nullable=True)
card_group_id = relationship('Groups', back_populates='group_card_id')
card_teacher_id = relationship('Teacher', back_populates='teacher_card_id')
card_lesson_id = relationship('Lesson', back_populates='lesson_card_id')
card_class_id = relationship('Class', back_populates='class_card_id')
card_id_wish_student = relationship('Student_Wish_Schedule', back_populates='wish_student_card_id')
card_id_wish_teacher = relationship('Teacher_Wish_Schedule', back_populates='wish_teacher_card_id')
class Class(Base):
__tablename__ = 'class'
class_id = Column(Integer, primary_key=True)
card_id = Column(Integer, ForeignKey('card.card_id'))
# room_id = Column(Integer, ForeignKey('room.room_id'))
days_id = Column(Integer, ForeignKey('study_days.days_id'))
pairs_id = Column(Integer, ForeignKey('pairs.pairs_id'))
class_pairs_id = relationship('Pairs', back_populates='pairs_class_id')
class_days_id = relationship('Study_Days', back_populates='days_class_id')
# class_room_id = relationship('Room', back_populates='room_class_id')
class_card_id = relationship('Card', back_populates='card_class_id')
class Verif_Students(Base):
__tablename__ = 'verif_student'
st_email = Column(String(100), primary_key=True)
st_secret_key = Column(String(100), nullable=False)
group_id = Column(Integer, ForeignKey('groups.group_id'))
verif_student_group = relationship('Groups', back_populates='group_verif_student')
student_secret_key = relationship('Student_Wish_Schedule', back_populates='secret_key_student')
class Verif_Teachers(Base):
__tablename__ = 'verif_teacher'
tchr_email = Column(String(100), primary_key=True)
tchr_secret_key = Column(String(100), nullable=False)
teacher_id = Column(Integer, ForeignKey('teacher.teacher_id'))
verif_teacher_teacher = relationship('Teacher', back_populates='teacher_verif_teacher')
teacher_secret_key = relationship('Teacher_Wish_Schedule', back_populates='secret_key_teacher')
class Student_Wish_Schedule(Base):
__tablename__ = 'student_wish_schedule'
st_schedule_id = Column(Integer, primary_key=True)
st_secret_key = Column(String(100), ForeignKey('verif_student.st_secret_key'))
card_id = Column(Integer, ForeignKey('card.card_id'))
days_id = Column(Integer, ForeignKey('study_days.days_id'))
pairs_id = Column(Integer, ForeignKey('pairs.pairs_id'))
wish_student_pairs_id = relationship('Pairs', back_populates='pairs_id_wish_student')
wish_student_days_id = relationship('Study_Days', back_populates='days_id_wish_student')
wish_student_card_id = relationship('Card', back_populates='card_id_wish_student')
secret_key_student = relationship('Verif_Students', back_populates='student_secret_key')
class Teacher_Wish_Schedule(Base):
__tablename__ = 'teacher_wish_schedule'
tchr_schedule_id = Column(Integer, primary_key=True)
tchr_secret_key = Column(String(100), ForeignKey('verif_teacher.tchr_secret_key'))
card_id = Column(Integer, ForeignKey('card.card_id'))
days_id = Column(Integer, ForeignKey('study_days.days_id'))
pairs_id = Column(Integer, ForeignKey('pairs.pairs_id'))
wish_teacher_pairs_id = relationship('Pairs', back_populates='pairs_id_wish_teacher')
wish_teacher_days_id = relationship('Study_Days', back_populates='days_id_wish_teacher')
wish_teacher_card_id = relationship('Card', back_populates='card_id_wish_teacher')
secret_key_teacher = relationship('Verif_Teachers', back_populates='teacher_secret_key')
Base.metadata.create_all(engine) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,785 | Yelue/GenerateSchedule | refs/heads/master | /alg/professor.py | class Professor:
def __init__(self, teacher_id, teacher_degree):
self.cards = dict()
self.work_time = None
self.teacher_id = teacher_id
self.teacher_degree = teacher_degree
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,786 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadRandomStudentScheduleTask.py | import pandas as pd
import numpy as np
import random
from db.orm.tables import *
class LoadRandomStudentScheduleTask:
def __init__(self, db):
self.db = db
def load_students(self):
return pd.read_sql('select * from verif_student', con=self.db.engine)
def load_to_db(self):
self.create_schedule().to_sql('student_wish_schedule', con=self.db.engine, if_exists='append', index=False, chunksize=100)
def create_schedule(self):
df_students = self.load_students()
groups_id = tuple(df_students.group_id.values)
df_cards = pd.read_sql(f'select c.card_id, c.group_id,c.teacher_id,c.lesson_id,c.amount_time,v.st_secret_key from card c join verif_student v on c.group_id=v.group_id', con=self.db.engine)
df_cards = self.multiply_amount_time(df_cards)
df_cards = self.prepare_data_db(df_cards, groups_id, df_students)
return df_cards
def multiply_amount_time(self, df_cards):
return df_cards.loc[df_cards.index.repeat(df_cards.amount_time)].reset_index(drop=True)
def prepare_data_db(self, df_cards, groups_id, df_students):
pair_days = pd.DataFrame([(i,j) for j in range(1,6)for i in range(1,13)], columns=['day','para'])
group_key = [tuple(x) for x in df_cards[['group_id','st_secret_key']].drop_duplicates(keep='first').to_numpy()]
for t in group_key:
mask = (df_cards.group_id==t[0]) & (df_cards.st_secret_key==t[1])
sample_day_pair = pair_days.sample(len(df_cards[mask]))
df_cards.loc[mask,['days_id','pairs_id']] = [tuple(x) for x in sample_day_pair.to_numpy()]
df_cards.loc[mask,['st_secret_key']] = [t[1] for _ in range(len(df_cards[mask]))]
df_cards.drop(columns=['group_id','teacher_id','lesson_id','amount_time'], inplace=True)
return df_cards | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,787 | Yelue/GenerateSchedule | refs/heads/master | /alg/group.py | class Group:
def __init__(self, group_id, group_course):
self.cards = dict()
self.work_time = None
self.group_id = group_id
self.group_course = group_course | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,788 | Yelue/GenerateSchedule | refs/heads/master | /alg/teacher_wishes.py | import numpy as np
import pandas as pd
from alg.professor import Professor
from db.orm.tables import (Department, Groups, Card, Teacher,
Teacher_Wish_Schedule, Verif_Teachers)
class TWishesConnector:
def __init__(self, facultyID, session_obj,
n_weeks = 2, n_days = 6, n_classes = 5):
self.teachers = {}
self.wdc_shape = (n_weeks, n_days, n_classes)
self.session = session_obj
self.facultyID = facultyID
self.create_teachers()
def get_allTeacherWishes(self):
data = pd.read_sql(self.session.query(Teacher_Wish_Schedule, Teacher.teacher_id, Teacher.teacher_degree).\
select_from(Department).join(Groups).join(Card).join(Teacher_Wish_Schedule).join(Verif_Teachers).\
join(Teacher).filter(Department.faculty_id == self.facultyID).statement, self.session.bind)
return data
def create_teachers(self):
data = self.get_allTeacherWishes()
for teacher_id, frame1 in data.groupby('teacher_id'):
ind = frame1.index
teacher_degree = frame1.loc[ind[0], 'teacher_degree']
new_teacher = Professor(teacher_id, teacher_degree)
work_time = np.zeros(self.wdc_shape)
for card_id, frame2 in frame1.groupby('card_id'):
time_table = np.zeros(self.wdc_shape)
for i in frame2.index:
week = (frame2.loc[i, 'days_id'] - 1) // 6
day = (frame2.loc[i, 'days_id'] - 1) % 6
pair = (frame2.loc[i, 'pairs_id']- 1)
time_table[week, day, pair] += 1
work_time[week, day, pair] += 1
new_teacher.cards[card_id] = time_table / np.sum(time_table)
new_teacher.work_time = work_time / np.sum(work_time)
self.teachers[teacher_id] = new_teacher
def get_teacherByTeacherId(self, teacher_id):
return self.teachers[teacher_id]
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,789 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadDaysTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadDaysTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_days.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['name_day'])
def load_to_db(self):
self.get_data().to_sql('study_days', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,790 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadCardTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadCardTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_cards.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['group_name',
'lesson_short_name',
'teacher_long_name',
'lesson_type',
'amount_time'])
def load_to_db(self):
src = self.get_data()
#work with groups
group = pd.read_sql('select group_name, group_id from groups', con=self.engine)
src = pd.merge(src, group,
how='left',
left_on='group_name',
right_on='group_name').drop(['group_name'],axis=1)
del group
#work with lesson
lesson = pd.read_sql('select lesson_short_name, lesson_type, lesson_id from lesson', con=self.engine)
src = pd.merge(src, lesson,
how='left',
left_on=['lesson_short_name', 'lesson_type'],
right_on=['lesson_short_name', 'lesson_type']).drop(['lesson_short_name',
'lesson_type'],axis=1)
del lesson
#work with teacher
teacher = pd.read_sql('select teacher_long_name, teacher_id from teacher', con=self.engine)
src = pd.merge(src, teacher,
how='left',
left_on=['teacher_long_name'],
right_on=['teacher_long_name']).drop(['teacher_long_name'], axis=1)
src['teacher_id'].fillna(teacher[teacher.teacher_long_name=='None'].teacher_id[0], inplace=True)
src.to_sql('card', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,791 | Yelue/GenerateSchedule | refs/heads/master | /alg/chromosome_mutation.py | import numpy as np
class ChromosomeMutation:
def mutation(self, chromosome):
n_lessons = len(chromosome.lessons)
n_mutation = np.random.randint(1, int(0.1 * n_lessons), 1)[0]
indexes = np.random.choice(n_lessons, n_mutation, replace = False)
for index in indexes:
cardsL = chromosome.lessons[index].cards
teacherID, groupIDs = chromosome.get_GTIndexes(cardsL)
new_room, new_wdc = chromosome.choice_place_time(teacherID, groupIDs)
old_room, old_wsc = chromosome.get_wdcByLessonNum(chromosome.lessons[index].unNum)
chromosome.teachers[teacherID][new_wdc], chromosome.teachers[teacherID][old_wsc] =\
chromosome.teachers[teacherID][old_wsc], chromosome.teachers[teacherID][new_wdc]
chromosome.timeTable[new_room][new_wdc], chromosome.timeTable[old_room][old_wsc] =\
chromosome.timeTable[old_room][old_wsc], chromosome.timeTable[new_room][new_wdc]
for group_id in groupIDs:
chromosome.groups[group_id][new_wdc], chromosome.groups[group_id][old_wsc] =\
chromosome.groups[group_id][old_wsc], chromosome.groups[group_id][new_wdc]
return chromosome
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,792 | Yelue/GenerateSchedule | refs/heads/master | /alg/population.py | import pandas as pd
from sqlalchemy import and_
from alg.chromosome import Chromosome
from alg.student_wishes import SWishesConnector
from alg.teacher_wishes import TWishesConnector
from alg.collection_cards import CollectionCards
from db.orm.tables import (Teacher, Groups, Card,
Lesson, Department)
class Population:
def __init__(self, rooms, n_chromo, facultyID, session_obj,
n_weeks = 2, n_days = 6, n_classes = 5):
self.rooms = rooms
self.chromosomes = []
self.n_chromo = n_chromo
self.facultyID = facultyID
self.session = session_obj
self.wdc_shape = (n_weeks, n_days, n_classes)
self.clc = CollectionCards(self.facultyID, self.session)
self.swc = SWishesConnector(self.facultyID, self.session, *self.wdc_shape)
self.twc = TWishesConnector(self.facultyID, self.session, *self.wdc_shape)
def get_allFacultyLecture(self):
dataL = pd.read_sql(self.session.query(Card.card_id, Lesson.lesson_id, Card.amount_time).select_from(Department).\
join(Groups).join(Card).join(Lesson).filter(and_(Department.faculty_id == self.facultyID,
Lesson.lesson_type == 'Лек')).statement, self.session.bind)
return dataL
def get_allFacultyPractice(self):
dataP = pd.read_sql(self.session.query(Card.card_id, Lesson.lesson_id, Card.amount_time).select_from(Department).\
join(Groups).join(Card).join(Lesson).filter(and_(Department.faculty_id == self.facultyID,
Lesson.lesson_type != 'Лек')).statement, self.session.bind)
return dataP
def get_allTeachersID(self):
return list(self.twc.teachers.keys())
def get_allGroupsID(self):
return list(self.swc.groups.keys())
def create_chromosomes(self):
dataL = self.get_allFacultyLecture()
dataP = self.get_allFacultyPractice()
groupIDs = self.get_allGroupsID()
teacherIDs = self.get_allTeachersID()
for _ in range(self.n_chromo):
chromo = Chromosome(self.rooms, groupIDs,
teacherIDs, self.clc, *self.wdc_shape)
chromo.create_chromosome(dataL, dataP)
self.chromosomes.append(chromo) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,793 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadPairsTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadPairsTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_pairs.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['start_time','end_time'])
def load_to_db(self):
src = self.get_data()
src.to_sql('pairs', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,794 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadEmailTeachers.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
from passlib.hash import sha256_crypt
from random import randint
class LoadEmailTeachers(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_verif_teachers.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['teacher_long_name','tchr_email'])
def load_to_db(self):
src = self.get_data()
teacher = pd.read_sql('select teacher_long_name, teacher_id from teacher', con=self.engine)
src = pd.merge(src, teacher,
how='left',
left_on=['teacher_long_name'],
right_on=['teacher_long_name']).drop(['teacher_long_name'], axis=1)
src['teacher_id'].fillna(teacher[teacher.teacher_long_name=='None'].teacher_id[0], inplace=True)
src['tchr_secret_key'] = src['teacher_id'].apply(lambda x: sha256_crypt.encrypt(str(randint(1,100))))
src.to_sql('verif_teacher', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,795 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadDepartmentTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadDepartmentTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_depart.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['department_short_name','department_long_name','faculty'])
def load_to_db(self):
src = self.get_data()
exi = pd.read_sql('select * from faculty', con=self.engine).loc[:,['faculty_short_name','faculty_id']]
src = pd.merge(src, exi,
how='left',
left_on='faculty',
right_on='faculty_short_name').drop(['faculty_short_name','faculty'],
axis=1)
src.to_sql('department', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,796 | Yelue/GenerateSchedule | refs/heads/master | /alg/chromosome_selection.py | import numpy as np
from alg.fitness_function import FitnessFunction
class ChromosomeSelection(FitnessFunction):
def __init__(self, chromosomes, clc_obj, swc_obj, twc_obj):
self.n_chromo = len(chromosomes)
super().__init__(clc_obj, swc_obj, twc_obj)
self.chromosomes = {
ind: [chromo, self.sumUpChromosome(chromo)]
for ind, chromo in enumerate(chromosomes)
}
def wfold_tour(self, w = 5):
keys = np.random.choice(self.n_chromo, w, replace = False)
score_values = [(self.chromosomes[key][1], key) for key in keys]
score_values.sort(reverse = True)
parent1_key = score_values[0][1]
parent2_key = np.random.choice(self.n_chromo, 1)[0]
parent1 = self.chromosomes[parent1_key][0]
parent2 = self.chromosomes[parent2_key][0]
return parent1, parent2 | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,797 | Yelue/GenerateSchedule | refs/heads/master | /alg/fitness_function.py | import numpy as np
import pandas as pd
from alg.student_wishes import SWishesConnector
from alg.teacher_wishes import TWishesConnector
from alg.collection_cards import CollectionCards
class Priority:
priorityCourses = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
}
priorityTeachers = {
'асистент': 1,
'викладач': 2,
'старший викладач': 2.5,
'доцент': 3,
'професор': 4,
'завідувач кафедри': 5,
'декан': 6,
'проректор': 7,
'ректор': 8
}
class FitnessFunction(Priority):
def __init__(self, clc_obj, swc_obj, twc_obj):
self.clc = clc_obj
self.swc = swc_obj
self.twc = twc_obj
def sumUpTeachers(self, chromosome, teacher_id, card_id):
teacher = self.twc.get_teacherByTeacherId(teacher_id)
score = FitnessFunction.priorityTeachers[teacher.teacher_degree] *\
np.sum(chromosome.teachers[teacher_id] * teacher.cards[card_id]) *\
np.sum(chromosome.teachers[teacher_id] * teacher.work_time)
return score
def sumUpGroups(self, chromosome, group_id, card_id):
group = self.swc.get_groupByGroupId(group_id)
score = FitnessFunction.priorityCourses[group.group_course] *\
np.sum(chromosome.groups[group_id] * group.cards[card_id]) *\
np.sum(chromosome.groups[group_id] * group.work_time)
return score
def sumUpChromosome(self, chromosome):
max_score = self.swc.wdc_shape[2]
pWindows = np.zeros(self.swc.wdc_shape)
for i in range(max_score):
pWindows[:,:,i] = max_score - i
pWindows[:,:,0] = pWindows[:,:,1]
pWindows /= np.sum(pWindows)
# the same priority for first and second lesson
chromosome_score = 0
for lesson in chromosome.lessons:
for card_id in lesson.cards:
card = self.clc.get_cardByCardId(card_id)
group_id, teacher_id = card.group_id, card.teacher_id
scoreG = self.sumUpGroups(chromosome, group_id, card_id)
scoreT = self.sumUpTeachers(chromosome, teacher_id, card_id)
chromosome_score += (scoreT + scoreG)
chromosome_score += np.sum(chromosome.groups[group_id] * pWindows)
return chromosome_score | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,798 | Yelue/GenerateSchedule | refs/heads/master | /app/forms/search.py | from flask_wtf import FlaskForm
from wtforms import SubmitField, ValidationError, StringField
from wtforms.validators import DataRequired
class Search_form(FlaskForm):
search_value = StringField(validators=[DataRequired()])
submit = SubmitField("Шукати")
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,799 | Yelue/GenerateSchedule | refs/heads/master | /sql/create_table.py | import psycopg2
import os
def create_tables():
""" create tables in the PostgreSQL database"""
with open("sql_request.sql", "r") as file_handler:
commands = file_handler.read()
conn = None
try:
# connect to the PostgreSQL server
conn = psycopg2.connect(os.environ.get('DATABASE_URL'))
cur = conn.cursor()
# create table one by one
cur.execute(commands)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
create_tables()
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,800 | Yelue/GenerateSchedule | refs/heads/master | /alg/chromosome.py | import numpy as np
import pandas as pd
from alg.time_table import TimeTable
from db.orm.tables import (Teacher, Groups, Card,
Lesson, Department)
class UniqueLesson:
def __init__(self, uniqueNumber, cards):
self.cards = cards
self.unNum = uniqueNumber
class Chromosome(TimeTable):
def __init__(self, rooms, groupIDs, teacherIDs, cc_obj,
n_weeks = 2, n_days = 6, n_classes = 5):
self.lessons = []
self.rooms = rooms
self.groupIDs = groupIDs
self.teacherIDs = teacherIDs
self.wdc_shape = (n_weeks, n_days, n_classes)
self.collection_cards = cc_obj
super().__init__(rooms, n_weeks,
n_days, n_classes)
self.groups = {
group_id: np.zeros((n_weeks, n_days, n_classes))
for group_id in groupIDs
}
self.teachers = {
teacher_id: np.zeros((n_weeks, n_days, n_classes))
for teacher_id in teacherIDs
}
def get_GTIndexes(self, cardsL):
groupIDs = []
for card_id in cardsL:
card = self.collection_cards.get_cardByCardId(card_id)
teacherID = card.teacher_id
groupIDs.append(card.group_id)
return teacherID, groupIDs
def check_place_time(self, teacherID, groupIDs, room, wdc):
occupationMatrix = self.teachers[teacherID].copy()
for group_id in groupIDs:
occupationMatrix += self.groups[group_id]
occupationMatrix += self.timeTable[room]
value = occupationMatrix[wdc]
return True if value == 0 else False
def choice_place_time(self, teacherID, groupIDs):
occupationMatrix = self.teachers[teacherID].copy()
for group_id in groupIDs:
occupationMatrix += self.groups[group_id]
np.random.shuffle(self.rooms)
for room in self.rooms:
wdc = np.argwhere((occupationMatrix + self.timeTable[room]) == 0)
if wdc.size:
ind = np.random.randint(0, wdc.shape[0], 1)[0]
return room, tuple(wdc[ind])
raise 'There is not any free room'
def create_chromosome(self, dataL, dataP):
uniqueNumber = 0
for group, frame in dataL.groupby('lesson_id'):
cardsL = frame.card_id.to_numpy()
teacherID, groupIDs = self.get_GTIndexes(cardsL)
for _ in range(pd.to_numeric(frame.amount_time.iloc[0])):
uniqueNumber += 1
room, wdc = self.choice_place_time(teacherID, groupIDs)
self.teachers[teacherID][wdc] = 1
self.timeTable[room][wdc] = uniqueNumber
self.lessons.append(UniqueLesson(uniqueNumber, cardsL))
for group_id in groupIDs:
self.groups[group_id][wdc] = 1
for ind in dataP.index:
cardsL = np.array([dataP.loc[ind, 'card_id']])
teacherID, groupIDs = self.get_GTIndexes(cardsL)
for _ in range(pd.to_numeric(dataP.amount_time.iloc[ind])):
uniqueNumber += 1
room, wdc = self.choice_place_time(teacherID, groupIDs)
self.teachers[teacherID][wdc] = 1
self.timeTable[room][wdc] = uniqueNumber
self.lessons.append(UniqueLesson(uniqueNumber, cardsL))
for group_id in groupIDs:
self.groups[group_id][wdc] = 1 | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,801 | Yelue/GenerateSchedule | refs/heads/master | /alg/student_wishes.py | import numpy as np
import pandas as pd
from alg.group import Group
from db.orm.tables import (Department, Groups,
Verif_Students, Student_Wish_Schedule)
class SWishesConnector:
def __init__(self, facultyID, session_obj,
n_weeks = 2, n_days = 6, n_classes = 5):
self.groups = {}
self.wdc_shape = (n_weeks, n_days, n_classes)
self.session = session_obj
self.facultyID = facultyID
self.create_groups()
def get_allStudentWishes(self):
data = pd.read_sql(self.session.query(Student_Wish_Schedule, Groups.group_id, Groups.group_course).select_from(Department).\
join(Groups).join(Verif_Students).join(Student_Wish_Schedule).filter(Department.faculty_id == self.facultyID).statement, self.session.bind)
return data
def create_groups(self):
data = self.get_allStudentWishes()
for group_id, frame1 in data.groupby('group_id'):
ind = frame1.index
group_course = frame1.loc[ind[0], 'group_course']
new_group = Group(group_id, group_course)
work_time = np.zeros(self.wdc_shape)
for card_id, frame2 in frame1.groupby('card_id'):
time_table = np.zeros(self.wdc_shape)
for i in frame2.index:
week = (frame2.loc[i, 'days_id'] - 1) // 6
day = (frame2.loc[i, 'days_id'] - 1) % 6
pair = (frame2.loc[i, 'pairs_id']- 1)
time_table[week, day, pair] += 1
work_time[week, day, pair] += 1
new_group.cards[card_id] = time_table / np.sum(time_table)
new_group.work_time = work_time / np.sum(work_time)
self.groups[group_id] = new_group
def get_groupByGroupId(self, group_id):
return self.groups[group_id]
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,802 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/_init__.py | from tasks import * | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,803 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadFacultyTask.py | import csv
import pandas as pd
from db.tasks.BasicTask import BasicTask
class LoadFacultyTask(BasicTask):
def __init__(self, engine):
self.engine = engine
def file_name(self):
return 'table_faculty.csv'
def get_data(self):
return pd.read_csv(self.full_path(), sep='$', names=['faculty_short_name', 'faculty_long_name'])
def load_to_db(self):
self.get_data().to_sql('faculty', con=self.engine, if_exists='append', index=False) | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,804 | Yelue/GenerateSchedule | refs/heads/master | /db/tasks/LoadRandomTeacherScheduleTask.py | import pandas as pd
import numpy as np
import random
from db.orm.tables import *
class LoadRandomTeacherScheduleTask:
def __init__(self, db):
self.db = db
def load_teachers(self):
return pd.read_sql('select * from verif_teacher', con=self.db.engine)
def load_to_db(self):
self.create_schedule().to_sql('teacher_wish_schedule', con=self.db.engine, if_exists='append', index=False)
def create_schedule(self):
df_teachers = self.load_teachers()
teachers_id = tuple(df_teachers.teacher_id.values)
df_cards = pd.read_sql(f'select * from card where teacher_id in {teachers_id}', con=self.db.engine)
df_cards = self.multiply_amount_time(df_cards)
df_cards = self.prepare_data_db(df_cards, teachers_id, df_teachers)
return df_cards
def multiply_amount_time(self, df_cards):
return df_cards.loc[df_cards.index.repeat(df_cards.amount_time)].reset_index(drop=True)
def prepare_data_db(self, df_cards, teachers_id, df_teachers):
pair_days = pd.DataFrame([(i,j) for j in range(1,6)for i in range(1,13)], columns=['day','para'])
for t in teachers_id:
mask = df_cards.teacher_id==t
sample_day_pair = pair_days.sample(len(df_cards[mask]))
df_cards.loc[mask,['days_id','pairs_id']] = [tuple(x) for x in sample_day_pair.to_numpy()]
df_cards.loc[mask,['tchr_secret_key']] = [df_teachers[df_teachers.teacher_id==t].tchr_secret_key for _ in range(len(df_cards[mask]))]
df_cards.drop(columns=['group_id','teacher_id','lesson_id','amount_time'], inplace=True)
return df_cards | {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,805 | Yelue/GenerateSchedule | refs/heads/master | /alg/genetic_algorithm.py | import numpy as np
from alg.chromosome_mutation import ChromosomeMutation
from alg.chromosome_selection import ChromosomeSelection
from alg.chromosome_crossover import ChromosomeCrossover
class GeneticAlgorithm(ChromosomeSelection,
ChromosomeCrossover, ChromosomeMutation):
def __init__(self, chromosomes, clc_obj, swc_obj, twc_obj):
super().__init__(chromosomes, clc_obj, swc_obj, twc_obj)
self.percent_mutation = 0.15
self.percent_crossover = 0.75
def update_population(self, new_chromosomes):
chromosomes = [value[0] for value in self.chromosomes.values()]
chromosomes.extend(new_chromosomes)
score_chromosomes = [(chromo, self.sumUpChromosome(chromo))
for chromo in chromosomes]
score_chromosomes.sort(key = lambda x: x[1], reverse = True)
self.chromosomes = { ind: [value[0], value[1]]
for ind, value in enumerate(score_chromosomes[:self.n_chromo])
}
def fit(self, n_iter = 5):
for iter in range(n_iter):
new_chromosomes = []
for _ in range(int(self.n_chromo * self.percent_crossover)):
parent1, parent2 = self.wfold_tour()
child = self.crossover(parent1, parent2)
number = np.random.uniform(0, 1, 1)[0]
if number < self.percent_mutation:
child = self.mutation(child)
new_chromosomes.append(child)
self.update_population(new_chromosomes)
print('\nPopulation: {}'.format(iter))
for key in range(5):
print('{} Score: {}'.format(key, self.chromosomes[key][1]))
| {"/app/tasks.py": ["/alg/population.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/alg/genetic_algorithm.py", "/db/orm/tables.py"], "/db/tasks/LoadGroupsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailStudents.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadTeachersTask.py": ["/db/tasks/BasicTask.py"], "/alg/collection_cards.py": ["/db/orm/tables.py"], "/app/app.py": ["/app/forms/search.py", "/app/forms/new_schedule.py", "/app/tasks.py"], "/alg/chromosome_crossover.py": ["/alg/chromosome.py"], "/db/orm/tables.py": ["/db/orm/engine.py"], "/db/tasks/LoadRandomStudentScheduleTask.py": ["/db/orm/tables.py"], "/alg/teacher_wishes.py": ["/alg/professor.py", "/db/orm/tables.py"], "/db/tasks/LoadDaysTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadCardTask.py": ["/db/tasks/BasicTask.py"], "/alg/population.py": ["/alg/chromosome.py", "/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py", "/db/orm/tables.py"], "/db/tasks/LoadPairsTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadEmailTeachers.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadDepartmentTask.py": ["/db/tasks/BasicTask.py"], "/alg/chromosome_selection.py": ["/alg/fitness_function.py"], "/alg/fitness_function.py": ["/alg/student_wishes.py", "/alg/teacher_wishes.py", "/alg/collection_cards.py"], "/alg/chromosome.py": ["/alg/time_table.py", "/db/orm/tables.py"], "/alg/student_wishes.py": ["/alg/group.py", "/db/orm/tables.py"], "/db/tasks/LoadFacultyTask.py": ["/db/tasks/BasicTask.py"], "/db/tasks/LoadRandomTeacherScheduleTask.py": ["/db/orm/tables.py"], "/alg/genetic_algorithm.py": ["/alg/chromosome_mutation.py", "/alg/chromosome_selection.py", "/alg/chromosome_crossover.py"]} |
68,806 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0017_auto_20170827_1504.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-27 07:04
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0016_auto_20170827_0544'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='date',
),
migrations.AlterField(
model_name='time',
name='date',
field=models.DateField(default=datetime.datetime(2017, 8, 27, 15, 4, 39, 376669), verbose_name='Date'),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,807 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0006_auto_20170823_1232.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 04:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0005_auto_20170823_1210'),
]
operations = [
migrations.CreateModel(
name='Time',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('duration', models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True)),
],
),
migrations.RemoveField(
model_name='project',
name='duration',
),
migrations.AddField(
model_name='time',
name='project',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='profiles.Project'),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,808 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0004_auto_20170823_0921.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 01:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0003_auto_20170822_2132'),
]
operations = [
migrations.CreateModel(
name='Time',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('duration', models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=4, null=True)),
],
),
migrations.RemoveField(
model_name='project',
name='duration',
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,809 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0002_auto_20170822_2130.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-22 13:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='time',
name='duration',
),
migrations.AddField(
model_name='project',
name='duration',
field=models.IntegerField(blank=True, default=0, null=True),
),
migrations.AddField(
model_name='project',
name='project_name',
field=models.CharField(default=django.utils.timezone.now, max_length=100),
preserve_default=False,
),
migrations.DeleteModel(
name='Time',
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,810 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0007_auto_20170823_1237.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 04:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0006_auto_20170823_1232'),
]
operations = [
migrations.AlterField(
model_name='time',
name='project',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='profiles.Project'),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,811 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0016_auto_20170827_0544.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-26 21:44
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0015_auto_20170826_0324'),
]
operations = [
migrations.RemoveField(
model_name='time',
name='description',
),
migrations.AddField(
model_name='project',
name='date',
field=models.DateField(default=datetime.datetime(2017, 8, 27, 5, 44, 55, 188069), verbose_name='Date'),
),
migrations.AlterField(
model_name='time',
name='date',
field=models.DateField(default=datetime.datetime(2017, 8, 27, 5, 44, 55, 188069), verbose_name='Date'),
),
migrations.AlterField(
model_name='time',
name='remarks',
field=models.TextField(),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,812 | Xednom/worklogger | refs/heads/master | /src/profiles/forms.py | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from profiles.models import Project, Time
class RegistrationForm(UserCreationForm):
username = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Username',
}
))
first_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'First name',
}
))
last_name = forms.CharField(required=True, widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Last name',
}
))
password1 = forms.CharField(required=True, widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder': 'Password',
}
))
password2 = forms.CharField(required=True, widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder': 'Confirm password',
}
))
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
'password'
)
class TimeForm(forms.ModelForm):
date = forms.DateTimeField(widget=forms.SelectDateWidget(
attrs={
'class': 'form-control',
'placeholder': 'Select a date',
}
))
class Meta:
model = Time
fields = (
'duration',
'remarks',
'date'
)
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,813 | Xednom/worklogger | refs/heads/master | /src/profiles/admin.py | from django.contrib import admin
from .models import Project, Time
# Register your models here.
class ProjectProfileAdmin(admin.ModelAdmin):
list_display = ['project','created_date']
class TimeProfileAdmin(admin.ModelAdmin):
list_display = ['duration','remarks']
admin.site.register(Project, ProjectProfileAdmin)
admin.site.register(Time, TimeProfileAdmin)
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,814 | Xednom/worklogger | refs/heads/master | /src/profiles/models.py | from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Project(models.Model):
project = models.CharField(max_length=100)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.project
class Time(models.Model):
project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True)
duration = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
remarks = models.TextField()
date = models.DateField(("Date"), default=datetime.now())
def __str__(self):
return self.remarks
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,815 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0011_auto_20170823_1442.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 06:42
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0010_auto_20170823_1438'),
]
operations = [
migrations.AlterField(
model_name='time',
name='project',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='profiles.Project'),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,816 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0005_auto_20170823_1210.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 04:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0004_auto_20170823_0921'),
]
operations = [
migrations.DeleteModel(
name='Time',
),
migrations.RenameField(
model_name='project',
old_name='project_name',
new_name='project',
),
migrations.AddField(
model_name='project',
name='duration',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,817 | Xednom/worklogger | refs/heads/master | /src/profiles/migrations/0008_auto_20170823_1255.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 04:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0007_auto_20170823_1237'),
]
operations = [
migrations.RemoveField(
model_name='time',
name='project',
),
migrations.AddField(
model_name='project',
name='time',
field=models.ForeignKey(default=0.0, on_delete=django.db.models.deletion.PROTECT, to='profiles.Time'),
preserve_default=False,
),
migrations.AlterField(
model_name='time',
name='duration',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=4, null=True, verbose_name='0.00'),
),
]
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,818 | Xednom/worklogger | refs/heads/master | /src/profiles/views.py | from django.shortcuts import render, redirect
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth import (login as auth_login, authenticate)
from django.db.models import Sum
from django.db.models import Q
from django.forms import ModelForm
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.views import View, generic
from .forms import RegistrationForm, TimeForm
from .models import Project, Time
# Create your views here.
class HomeView(View):
template_name = 'profiles/home.html'
class TimeForm(ModelForm):
class Meta:
model = Time
fields = ['project', 'duration', 'remarks', 'date']
class RegistrationFormView(View):
form_class = RegistrationForm
template_name = 'profiles/account/register.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
_username = form.cleaned_data['username']
_password = form.cleaned_data['password1']
user.set_password(_password)
user.save()
return render(request, 'profiles/account/register.html', {'form': form})
def login(request):
_message = "Please login"
if request.method == 'POST':
_username = request.POST['username']
_password = request.POST['password']
user = authenticate(username=_username, password=_password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect(reverse('add_project'))
else:
_message = 'Your account is not activated'
else:
_message = "Username or password is incorrect."
context = {'message': _message,}
return render(request, 'profiles/account/login.html', context)
def load_logs(request):
queryset_list = Time.objects.all()
query = request.GET.get("date")
if query:
queryset_list = queryset_list.filter(date__icontains=query)
context = {
"queryset_list": queryset_list
}
return render(request, 'profiles/projects/load_logs.html', context)
def add_project(request):
all_project = Project.objects.all()
all_time = Time.objects.all()
total_duration = Time.objects.all().aggregate(Sum('duration'))
if request.method == 'POST':
time_form = TimeForm(request.POST or None)
if time_form.is_valid():
time_form.save()
return redirect('add_project')
return render(request, 'profiles/projects/project.html')
else:
time_form = TimeForm()
context = {
'time_form': time_form,
'all_project': all_project,
'all_time': all_time,
'total_duration': total_duration
}
return render(request, 'profiles/projects/project.html', context)
| {"/src/profiles/admin.py": ["/src/profiles/models.py"], "/src/profiles/views.py": ["/src/profiles/forms.py", "/src/profiles/models.py"]} |
68,851 | arthurdehgan/sleep | refs/heads/master | /classif_cosp_backward.py | """Load crosspectrum matrix, perform classif, perm test, saves results.
Outputs one file per freq x state
Author: Arthur Dehgan"""
from time import time
from itertools import product
from scipy.io import savemat, loadmat
import pandas as pd
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import StratifiedKFold
from pyriemann.classification import TSclassifier
from utils import (
create_groups,
StratifiedLeave2GroupsOut,
elapsed_time,
prepare_data,
classification,
)
from params import (
SAVE_PATH,
FREQ_DICT,
STATE_LIST,
WINDOW,
OVERLAP,
LABEL_PATH,
CHANNEL_NAMES,
)
# import pdb
PREFIX = "classif_reduced_"
NAME = "cosp"
PREF_LIST = PREFIX.split("_")
REDUCED = "reduced" in PREF_LIST
FULL_TRIAL = "ft" in PREF_LIST or "moy" in PREF_LIST
SUBSAMPLE = "subsamp" in PREF_LIST
PERM = "perm" in PREF_LIST
N_PERM = 990 if PERM else None
SAVE_PATH = SAVE_PATH / NAME
print(NAME, PREFIX)
def backward_selection(
clf, data, labels, cv=3, groups=None, prev_ind=None, prev_score=0, index_list=[]
):
# Exit condition: we have tried everything
if prev_ind == -1:
return index_list, prev_score
if prev_ind is None:
ind = data.shape[1] - 1
else:
ind = prev_ind
if isinstance(cv, int):
index = np.random.permutation(list(range(len(data))))
labels = labels[index]
data = data[index]
croval = StratifiedKFold(n_splits=cv)
else:
croval = cv
# Do classification
save = classification(clf, cv=cv, X=data, y=labels, groups=groups, n_jobs=-1)
score = np.mean(save["acc_score"])
# removing ind from features
reduced_data = []
for submat in data:
temp_a = np.delete(submat, ind, 0)
temp_b = np.delete(temp_a, ind, 1)
reduced_data.append(temp_b)
reduced_data = np.asarray(reduced_data)
# reduced_data = np.concatenate((data[:, :ind], data[:, ind+1:]), axis=1)
# If better score we continue exploring this reduced data
print(data.shape, ind, score, prev_score)
if score >= prev_score:
if prev_ind is None and ind == data.shape[1] - 1:
ind = prev_ind
index_list.append(ind)
return backward_selection(
clf,
reduced_data,
labels,
croval,
groups,
prev_score=score,
index_list=index_list,
)
# Else we use the same data but we delete the next index
return backward_selection(
clf,
data,
labels,
croval,
groups,
prev_ind=ind - 1,
prev_score=prev_score,
index_list=index_list,
)
def main(state, freq):
"""Where the magic happens"""
print(state, freq)
if FULL_TRIAL:
labels = np.concatenate((np.ones(18), np.zeros(18)))
groups = range(36)
elif SUBSAMPLE:
info_data = pd.read_csv(SAVE_PATH.parent / "info_data.csv")[STATE_LIST]
n_trials = info_data.min().min()
n_subs = len(info_data) - 1
groups = [i for i in range(n_subs) for _ in range(n_trials)]
n_total = n_trials * n_subs
labels = [0 if i < n_total / 2 else 1 for i in range(n_total)]
else:
labels = loadmat(LABEL_PATH / state + "_labels.mat")["y"].ravel()
labels, groups = create_groups(labels)
file_path = (
SAVE_PATH / "results" / PREFIX
+ NAME
+ "_{}_{}_{}_{:.2f}.mat".format(state, freq, WINDOW, OVERLAP)
)
if not file_path.isfile():
file_name = NAME + "_{}_{}_{}_{:.2f}.mat".format(state, freq, WINDOW, OVERLAP)
data_file_path = SAVE_PATH / file_name
if data_file_path.isfile():
final_save = {}
random_seed = 0
data = loadmat(data_file_path)
if FULL_TRIAL:
data = data["data"]
elif SUBSAMPLE:
data = prepare_data(data, n_trials=n_trials, random_state=random_seed)
else:
data = prepare_data(data)
sl2go = StratifiedLeave2GroupsOut()
lda = LDA()
clf = TSclassifier(clf=lda)
best_combin, best_score = backward_selection(
clf, data, labels, sl2go, groups
)
final_save = {
"best_combin_index": best_combin,
"best_combin": CHANNEL_NAMES[best_combin],
"score": best_score,
}
savemat(file_path, final_save)
print(f"Best combin: {CHANNEL_NAMES[best_combin]}, score: {best_score}")
else:
print(data_file_path.NAME + " Not found")
if __name__ == "__main__":
TIMELAPSE_START = time()
for freq, state in product(FREQ_DICT, STATE_LIST):
main(state, freq)
print("total time lapsed : %s" % elapsed_time(TIMELAPSE_START, time()))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,852 | arthurdehgan/sleep | refs/heads/master | /visu_piecharts_fselect.py | """Generate topomaps"""
from scipy.io import loadmat
import matplotlib.pyplot as plt
from utils import super_count
from params import SAVE_PATH, STATE_LIST, CHANNEL_NAMES, REGIONS
plt.switch_backend("agg")
DATA_PATH = SAVE_PATH / "psd"
RESULTS_PATH = DATA_PATH / "results/"
FREQS = ["Delta", "Theta", "Alpha", "Sigma", "Beta"]
GRID_SIZE = (6, 4)
plt.figure(figsize=(8, 10))
for j, stage in enumerate(STATE_LIST):
counts, all_count = {}, {}
for elec in CHANNEL_NAMES:
file_name = "EFS_{}_{}_1000_0.00.mat".format(stage, elec)
freqs = loadmat(RESULTS_PATH / file_name)["freqs"].ravel()
count = super_count(
[freq.strip().capitalize() for sub in freqs for freq in sub]
)
counts[elec] = count
for freq in FREQS:
all_count[freq] = all_count.get(freq, 0) + count.get(freq, 0)
plt.subplot2grid(GRID_SIZE, (0, j))
plt.pie([all_count[freq] for freq in FREQS])
if j == 0:
plt.ylabel("All Stages")
plt.xlabel(stage, verticalalignment="top")
i = 1
for region in REGIONS:
elecs = REGIONS[region]
sub_count = {}
for freq in FREQS:
sub_count[freq] = sum([counts[elec].get(freq, 0) for elec in elecs])
plt.subplot2grid(GRID_SIZE, (i, j))
plt.pie([sub_count[freq] for freq in FREQS])
plt.tight_layout()
if j == 0:
plt.ylabel(region)
i += 1
FILE_NAME = "EFS_piechart"
print(file_name)
plt.legend(
FREQS,
loc="upper center",
bbox_to_anchor=(-1.8, -0.05),
fancybox=False,
shadow=False,
ncol=len(FREQS),
)
plt.tight_layout()
plt.savefig(SAVE_PATH.parent / "figures" / FILE_NAME, dpi=300)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,853 | arthurdehgan/sleep | refs/heads/master | /classif_subcosp.py | """Load crosspectrum matrix, perform classif, perm test, saves results.
Outputs one file per freq x state
Author: Arthur Dehgan"""
import sys
from time import time
from itertools import product
import pandas as pd
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import StratifiedShuffleSplit as SSS
from pyriemann.classification import TSclassifier
from utils import (
StratifiedShuffleGroupSplit,
elapsed_time,
prepare_data,
classification,
proper_loadmat,
)
from params import SAVE_PATH, FREQ_DICT, STATE_LIST, WINDOW, OVERLAP, CHANNEL_NAMES
PREFIX = "bootstrapped_subsamp_"
NAME = "cosp"
PREFIX_LIST = PREFIX.split("_")
BOOTSTRAP = "bootstrapped" in PREFIX_LIST
SUBSAMPLE = "subsamp" in PREFIX_LIST
ADAPT = "adapt" in PREFIX_LIST
PERM = "perm" in PREFIX_LIST
FULL_TRIAL = "ft" in NAME or "moy" in NAME.split("_")
N_PERM = 999 if PERM else None
N_BOOTSTRAPS = 1000 if BOOTSTRAP else 1
INIT_LABELS = [0] * 18 + [1] * 18
CHANGES = False
SAVE_PATH /= NAME
def classif_subcosp(state, freq, elec, n_jobs=-1):
global CHANGES
print(state, freq)
if SUBSAMPLE or ADAPT:
info_data = pd.read_csv(SAVE_PATH.parent / "info_data.csv")[STATE_LIST]
if SUBSAMPLE:
n_trials = info_data.min().min()
n_trials = 61
elif ADAPT:
n_trials = info_data.min()[state]
elif FULL_TRIAL:
groups = range(36)
labels_og = INIT_LABELS
file_path = (
SAVE_PATH / "results" / PREFIX
+ NAME
+ "_{}_{}_{}_{}_{:.2f}.npy".format(state, freq, elec, WINDOW, OVERLAP)
)
if not file_path.isfile():
n_rep = 0
else:
final_save = np.load(file_path)
n_rep = int(final_save["n_rep"])
n_splits = int(final_save["n_splits"])
print("Starting from i={}".format(n_rep))
file_name = NAME + "_{}_{}_{}_{}_{:.2f}.npy".format(
state, freq, elec, WINDOW, OVERLAP
)
data_file_path = SAVE_PATH / file_name
data_og = np.load(data_file_path)
if FULL_TRIAL:
cv = SSS(9)
else:
cv = StratifiedShuffleGroupSplit(2)
lda = LDA()
clf = TSclassifier(clf=lda)
for i in range(n_rep, N_BOOTSTRAPS):
CHANGES = True
if FULL_TRIAL:
data = data_og["data"]
elif SUBSAMPLE or ADAPT:
data, labels, groups = prepare_data(
data_og, labels_og, n_trials=n_trials, random_state=i
)
else:
data, labels, groups = prepare_data(data_og, labels_og)
n_splits = cv.get_n_splits(None, labels, groups)
save = classification(clf, cv, data, labels, groups, N_PERM, n_jobs=n_jobs)
if i == 0:
final_save = save
elif BOOTSTRAP:
for key, value in save.items():
if key != "n_splits":
final_save[key] += value
final_save["n_rep"] = i + 1
np.save(file_path, final_save)
final_save["auc_score"] = np.mean(final_save.get("auc_score", 0))
final_save["acc_score"] = np.mean(final_save["acc_score"])
if CHANGES:
np.save(file_path, final_save)
to_print = "accuracy for {} {} : {:.2f}".format(
state, freq, final_save["acc_score"]
)
if BOOTSTRAP:
standev = np.std(
[
np.mean(final_save["acc"][i * n_splits : (i + 1) * n_splits])
for i in range(N_BOOTSTRAPS)
]
)
to_print += " (+/- {:.2f})".format(standev)
print(to_print)
if PERM:
print("pval = {}".format(final_save["acc_pvalue"]))
if __name__ == "__main__":
TIMELAPSE_START = time()
ARGS = sys.argv
if len(ARGS) > 2:
ARGS = sys.argv[1:]
elif len(ARGS) == 2:
ARGS = sys.argv[1:][0].split(":")
else:
ARGS = []
if ARGS == []:
from joblib import delayed, Parallel
Parallel(n_jobs=1)(
delayed(classif_subcosp)(st, fr, el, n_jobs=1)
for st, fr, el in product(STATE_LIST, FREQ_DICT, CHANNEL_NAMES)
)
else:
print(ARGS)
classif_subcosp(ARGS[0], ARGS[1], ARGS[2])
print("total time lapsed : %s" % (elapsed_time(TIMELAPSE_START, time())))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,854 | arthurdehgan/sleep | refs/heads/master | /maxstat_pval.py | [200~In [1]: for state in STATE_LIST:
...: for freq in FREQS:
...: pscores = []
...: for file in file_list:
...: if freq in file and state in file:
...: a = loadmat(file)
...: pscores.append(a['pscore'].ravel())
...: pscores = np.array(pscores).max(axis=0)
...: for file in file_list:
...: if freq in file and state in file:
...: a = loadmat(file)
...: score = a['score'].ravel()
...: pvalue = .0
...: for pscore in pscores:
...: if pscore >= score:
...: pvalue += float(1/1001)
...: a['pvalue_ncorr'] = a['pvalue'].ravel()
...: a['pvalue'] = pvalue
...: savemat(file, a)
[201~
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,855 | arthurdehgan/sleep | refs/heads/master | /classif_all_bin_combinations.py | from utils import StratifiedLeave2GroupsOut, create_groups
from scipy.io import savemat, loadmat
import numpy as np
# from numpy.random import permutation
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import cross_val_score
from params import CHANNEL_NAMES, LABEL_PATH, SUBJECT_LIST, SAVE_PATH, path
N_FBIN = 45
WINDOW = 1000
OVERLAP = 0
N_PERMUTATIONS = 1000
SLEEP_LIST = ["S1", "S2", "SWS", "Rem", "NREM", "AWA"]
DATA_PATH = SAVE_PATH / "psd"
SAVE_PATH = DATA_PATH / "results"
SUB_LIST = ["s" + str(e) for e in SUBJECT_LIST]
if __name__ == "__main__":
for state in SLEEP_LIST:
print(state)
for elec in CHANNEL_NAMES:
results_file_path = SAVE_PATH / "da_bin_{}_{}_{}_{:.2f}.mat".format(
state, elec, WINDOW, OVERLAP
)
if not results_file_path.exists():
y = loadmat(LABEL_PATH / state + "_labels.mat")["y"].ravel()
y, groups = create_groups(y)
dataset = []
for sub in SUB_LIST:
data_file_path = DATA_PATH / "PSDs_{}_{}_{}_{}_{:.2f}.mat".format(
state, sub, elec, WINDOW, OVERLAP
)
if path(data_file_path).isfile():
dataset.append(loadmat(data_file_path)["data"])
else:
print(path(data_file_path) + " Not found")
dataset = np.vstack(dataset)
scores = np.ones((N_FBIN, N_FBIN)) * .5
for fbin_min in range(N_FBIN):
for fbin_max in range(fbin_min + 1, N_FBIN):
X = np.mean(dataset[:, fbin_min:fbin_max], axis=1).reshape(
-1, 1
)
sl2go = StratifiedLeave2GroupsOut()
clf = LDA()
perm_scores = []
pvalue = 0
good_scores = cross_val_score(
cv=sl2go, estimator=clf, X=X, y=y, groups=groups, n_jobs=1
)
scores[fbin_min, fbin_max] = good_scores.mean()
save = {"score": scores}
savemat(results_file_path, save)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,856 | arthurdehgan/sleep | refs/heads/master | /visu_data_boxplot.py | """Boxplots of the data"""
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
from scipy.stats import zscore
from itertools import product
from utils import rm_outliers
from params import STATE_LIST, FREQ_DICT, CHANNEL_NAMES, SAVE_PATH
SAVE_PATH /= "psd"
RANDOM = 666
N_SUBJ = 36
N_ELEC = len(CHANNEL_NAMES)
for st, fr in product(STATE_LIST, FREQ_DICT):
PSD_all_elec = []
first = True
for ch in CHANNEL_NAMES:
file_name = SAVE_PATH / f"psd_{st}_{fr}_{ch}_1000_0.00.mat"
PSD = loadmat(file_name)["data"].ravel()
for i, sub in enumerate(PSD):
# clean_psd = rm_outliers(sub.ravel(), 2)
clean_psd = sub.ravel()
if first:
PSD_all_elec.append(clean_psd / N_ELEC)
else:
PSD_all_elec[i] += clean_psd / N_ELEC
first = False
# sizes = []
# for sub in PSD:
# sizes.append(len(sub.ravel()))
# n_trials = min(sizes)
# final = []
# for i, submat in enumerate(PSD):
# index = np.random.RandomState(RANDOM).choice(
# range(len(submat.ravel())), n_trials, replace=False
# )
# chosen = submat.ravel()[index]
# final.append(chosen)
# to set ylim we check the highest that is not outlier (check zscore)
psdmax = 0
for sub in PSD_all_elec:
psd_max_c = rm_outliers(sub, 3).max()
if psdmax < psd_max_c:
psdmax = psd_max_c
plt.figure(figsize=(15, 15))
sns.boxplot(data=PSD_all_elec)
plt.ylim(0, psdmax)
plt.title(f"PSD per subject for {st}, {fr}")
plt.tight_layout()
plt.show()
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,857 | arthurdehgan/sleep | refs/heads/master | /classif_cosp_multif.py | """Load crosspectrum matrix, perform classif, perm test, saves results.
Outputs one file per freq x state
Author: Arthur Dehgan"""
import sys
from time import time
from itertools import product
from scipy.io import savemat, loadmat
import pandas as pd
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import StratifiedShuffleSplit as SSS
from pyriemann.classification import TSclassifier
from utils import (
create_groups,
StratifiedShuffleGroupSplit,
elapsed_time,
prepare_data,
classification,
proper_loadmat,
)
from params import SAVE_PATH, FREQ_DICT, STATE_LIST, WINDOW, OVERLAP, LABEL_PATH
# PREFIX = "perm_"
# PREFIX = "classif_"
# PREFIX = "reduced_classif_"
# PREFIX = "bootstrapped_subsamp_"
PREFIX = "bootstrapped_multif_subsamp_"
NAME = "cosp"
# NAME = "cosp"
# NAME = 'ft_cosp'
# NAME = "moy_cosp"
# NAME = 'im_cosp'
# NAME = 'wpli'
# NAME = 'coh'
# NAME = 'imcoh'
# NAME = 'ft_wpli'
# NAME = 'ft_coh'
# NAME = 'ft_imcoh'
PREFIX_LIST = PREFIX.split("_")
BOOTSTRAP = "bootstrapped" in PREFIX_LIST
SUBSAMPLE = "subsamp" in PREFIX_LIST
ADAPT = "adapt" in PREFIX_LIST
PERM = "perm" in PREFIX_LIST
FULL_TRIAL = "ft" in NAME or "moy" in NAME.split("_")
N_PERM = 999 if PERM else None
N_BOOTSTRAPS = 100 if BOOTSTRAP else 1
INIT_LABELS = [0] * 18 + [1] * 18
CHANGES = False
SAVE_PATH /= NAME
def classif_cosp(state, n_jobs=-1):
global CHANGES
print(state, "multif")
if SUBSAMPLE or ADAPT:
info_data = pd.read_csv(SAVE_PATH.parent / "info_data.csv")[STATE_LIST]
if SUBSAMPLE:
n_trials = info_data.min().min()
# n_trials = 30
elif ADAPT:
n_trials = info_data.min()[state]
elif FULL_TRIAL:
groups = range(36)
labels_og = INIT_LABELS
file_path = (
SAVE_PATH / "results" / PREFIX
+ NAME
+ "_{}_{}_{:.2f}.mat".format(state, WINDOW, OVERLAP)
)
if not file_path.isfile():
n_rep = 0
else:
final_save = proper_loadmat(file_path)
n_rep = int(final_save["n_rep"])
n_splits = int(final_save["n_splits"])
print("Starting from i={}".format(n_rep))
if FULL_TRIAL:
crossval = SSS(9)
else:
crossval = StratifiedShuffleGroupSplit(2)
lda = LDA()
clf = TSclassifier(clf=lda)
for i in range(n_rep, N_BOOTSTRAPS):
CHANGES = True
data_freqs = []
for freq in FREQ_DICT:
file_name = NAME + "_{}_{}_{}_{:.2f}.mat".format(
state, freq, WINDOW, OVERLAP
)
data_file_path = SAVE_PATH / file_name
data_og = loadmat(data_file_path)["data"].ravel()
data_og = np.asarray([sub.squeeze() for sub in data_og])
if SUBSAMPLE or ADAPT:
data, labels, groups = prepare_data(
data_og, labels_og, n_trials=n_trials, random_state=i
)
else:
data, labels, groups = prepare_data(data_og, labels_og)
data_freqs.append(data)
n_splits = crossval.get_n_splits(None, labels, groups)
data_freqs = np.asarray(data_freqs).swapaxes(0, 1).swapaxes(1, 3).swapaxes(1, 2)
save = classification(
clf, crossval, data, labels, groups, N_PERM, n_jobs=n_jobs
)
if i == 0:
final_save = save
elif BOOTSTRAP:
for key, value in save.items():
if key != "n_splits":
final_save[key] += value
final_save["n_rep"] = i + 1
if n_jobs == -1:
savemat(file_path, final_save)
final_save["auc_score"] = np.mean(final_save.get("auc_score", 0))
final_save["acc_score"] = np.mean(final_save["acc_score"])
if CHANGES:
savemat(file_path, final_save)
to_print = "accuracy for {} {} : {:.2f}".format(
state, freq, final_save["acc_score"]
)
if BOOTSTRAP:
standev = np.std(
[
np.mean(final_save["acc"][i * n_splits : (i + 1) * n_splits])
for i in range(N_BOOTSTRAPS)
]
)
to_print += " (+/- {:.2f})".format(standev)
print(to_print)
if PERM:
print("pval = {}".format(final_save["acc_pvalue"]))
if __name__ == "__main__":
TIMELAPSE_START = time()
ARGS = sys.argv
if len(ARGS) > 2:
ARGS = sys.argv[1:]
elif len(ARGS) == 2:
ARGS = sys.argv[1:]
else:
ARGS = []
if ARGS == []:
from joblib import delayed, Parallel
Parallel(n_jobs=-1)(delayed(classif_cosp)(st, n_jobs=1) for st in STATE_LIST)
else:
print(ARGS)
classif_cosp(ARGS[0])
print("total time lapsed : %s" % (elapsed_time(TIMELAPSE_START, time())))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,858 | arthurdehgan/sleep | refs/heads/master | /EFS_fixed_elec.py | """Exaustive feature selection on frequencies for each electrode.
Computes pvalues and saves them in a mat format with the decoding accuracies.
Author: Arthur Dehgan
"""
from time import time
import sys
from itertools import product
import numpy as np
from scipy.io import savemat, loadmat
# from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from mlxtend.feature_selection import ExhaustiveFeatureSelector as EFS
from utils import StratifiedLeave2GroupsOut, elapsed_time, compute_pval, create_groups
from params import SAVE_PATH, CHANNEL_NAMES, WINDOW, OVERLAP, STATE_LIST, FREQ_DICT
N_PERM = 1000
PERM = False
SAVE_PATH = SAVE_PATH / "psd"
if "Gamma1" in FREQ_DICT:
del FREQ_DICT["Gamma1"]
FREQS = np.array(list(FREQ_DICT.keys()))
print(FREQS)
STATE = sys.argv[1]
def main(elec):
"""feature selection and permutations.
For each separation of subjects with leave 2 subjects out, we train on the
big set (feature selection) and test on the two remaining subjects.
for each permutation, we just permute the labels at the trial level (we
could use permutations at the subject level, but we wouldn't get as many
permutations)
"""
final_data = None
print(STATE, elec)
results_file_path = (
SAVE_PATH
/ "results"
/ "EFS_NoGamma_{}_{}_{}_{:.2f}.mat".format(STATE, elec, WINDOW, OVERLAP)
)
if not results_file_path.isfile():
for freq in FREQS:
data_file_path = SAVE_PATH / "PSD_{}_{}_{}_{}_{:.2f}.mat".format(
STATE, freq, elec, WINDOW, OVERLAP
)
data = loadmat(data_file_path)["data"].ravel()
if final_data is None:
final_data = data
else:
for i, submat in enumerate(final_data):
final_data[i] = np.concatenate((submat, data[i]), axis=0)
final_data = np.array(list(map(np.transpose, final_data)))
lil_labels = [0] * 18 + [1] * 18
lil_labels = np.asarray(lil_labels)
lil_groups = list(range(36))
sl2go = StratifiedLeave2GroupsOut()
best_freqs = []
pvalues, pscores = [], []
test_scores, best_scores = [], []
for train_subjects, test_subjects in sl2go.split(
final_data, lil_labels, lil_groups
):
x_train, x_test = final_data[train_subjects], final_data[test_subjects]
y_train, y_test = lil_labels[train_subjects], lil_labels[test_subjects]
y_train = [[label] * len(x_train[i]) for i, label in enumerate(y_train)]
y_train, groups = create_groups(y_train)
x_train = np.concatenate(x_train[:], axis=0)
nested_sl2go = StratifiedLeave2GroupsOut()
clf = LDA()
f_select = EFS(estimator=clf, max_features=5, cv=nested_sl2go, n_jobs=-1)
f_select = f_select.fit(x_train, y_train, groups)
best_idx = f_select.best_idx_
best_freqs.append(list(FREQS[list(best_idx)]))
best_scores.append(f_select.best_score_)
test_clf = LDA()
test_clf.fit(x_train[:, best_idx], y_train)
y_test = [[label] * len(x_test[i]) for i, label in enumerate(y_test)]
y_test, groups = create_groups(y_test)
x_test = np.concatenate(x_test[:], axis=0)
test_score = test_clf.score(x_test[:, best_idx], y_test)
test_scores.append(test_score)
if PERM:
pscores_cv = []
for _ in range(N_PERM):
y_train = np.random.permutation(y_train)
y_test = np.random.permutation(y_test)
clf = LDA()
clf.fit(x_train[:, best_idx], y_train)
pscore = clf.score(x_test[:, best_idx], y_test)
pscores_cv.append(pscore)
pvalue = compute_pval(test_score, pscores_cv)
pvalues.append(pvalue)
pscores.append(pscores_cv)
score = np.mean(test_scores)
data = {
"score": score,
"train_scores": best_scores,
"test_scores": test_scores,
"freqs": best_freqs,
"pvalue": pvalues,
"pscores": pscores,
}
savemat(results_file_path, data)
if __name__ == "__main__":
T0 = time()
for elec in CHANNEL_NAMES:
main(elec)
print("total time lapsed : {}".format(elapsed_time(T0, time())))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,859 | arthurdehgan/sleep | refs/heads/master | /visu_topomap.py | """Generate topomaps"""
from mne.viz import plot_topomap
from scipy.io import loadmat
from scipy.stats import zscore, binom
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
from utils import compute_pval
# from matplotlib import ticker
from params import SAVE_PATH, STATE_LIST, CHANNEL_NAMES
plt.switch_backend("agg")
NAME = "psd"
# NAME = "zscore_psd"
# PREFIX = "bootstrapped_perm_subsamp_"
PREFIX = "bootstrapped_subsamp_"
# PREFIX = "perm_"
DATA_PATH = SAVE_PATH / NAME
TTEST_RESULTS_PATH = DATA_PATH / "results"
RESULTS_PATH = DATA_PATH / "results/"
POS_FILE = SAVE_PATH / "../Coord_EEG_1020.mat"
INFO_DATA = pd.read_csv(SAVE_PATH / "info_data.csv")[STATE_LIST]
SENSORS_POS = loadmat(POS_FILE)["Cor"]
FREQS = ["Delta", "Theta", "Alpha", "Sigma", "Beta"]
SUBSAMP = "subsamp" in PREFIX.split("_")
BOOTSTRAPPED = "bootstrapped" in PREFIX.split("_")
PERM = "perm" in PREFIX.split("_")
WINDOW = 1000
OVERLAP = 0
PVAL = .001
BINOM = not PERM
MAXSTAT_ELEC = True
info_data = pd.read_csv(SAVE_PATH / "info_data.csv")[STATE_LIST]
N_TRIALS = info_data.min().min()
TRIALS = list(INFO_DATA.iloc[36])
def gen_figure(stage):
k, j = 1, 1
fig = plt.figure(figsize=(8, 10))
for freq in FREQS:
scores, pscores_all_elec = [], []
HR, LR = [], []
for elec in CHANNEL_NAMES:
file_name = (
PREFIX
+ NAME
+ "_{}_{}_{}_{}_{:.2f}.mat".format(stage, freq, elec, WINDOW, OVERLAP)
)
try:
results = loadmat(RESULTS_PATH / file_name)
score_key = "acc"
pscores_key = "acc_pscores"
score = float(results[score_key].ravel().mean())
if PERM:
pscores = list(results[pscores_key].squeeze())
if BOOTSTRAPPED:
n_rep = int(results["n_rep"])
except:
score = .5
pscores = [.5] * 99
n_rep = 0
print("Error with:", file_name)
scores.append(score)
if PERM:
pscores_all_elec.append(pscores)
file_name = NAME + "_{}_{}_{}_{}_{:.2f}.mat".format(
stage, freq, elec, WINDOW, OVERLAP
)
try:
PSD = loadmat(DATA_PATH / file_name)["data"].ravel()
moy_PSD = [0] * 36
for i, submat in enumerate(PSD):
if BOOTSTRAPPED:
for random_state in range(n_rep):
index = np.random.RandomState(random_state).choice(
range(len(submat.ravel())), N_TRIALS, replace=False
)
prep_submat = submat.ravel()[index]
mean_for_the_sub = np.mean(prep_submat)
moy_PSD[i] += mean_for_the_sub / n_rep
else:
moy_PSD[i] = np.mean(submat)
# subject 10 has artefact on FC2, so we just remove it
moy_PSD = np.delete(moy_PSD, 9, 0)
except TypeError:
print(file_name)
HR.append(np.mean(moy_PSD[:17]))
LR.append(np.mean(moy_PSD[17:]))
if PERM:
pscores_all_elec = np.asarray(pscores_all_elec)
if MAXSTAT_ELEC:
pscores_all_elec = np.max(pscores_all_elec, axis=0)
pvalues = []
for i, score in enumerate(scores):
if MAXSTAT_ELEC:
pscores = pscores_all_elec
else:
pscores = pscores_all_elec[i]
pvalues.append(compute_pval(score, pscores))
ttest = loadmat(TTEST_RESULTS_PATH / "ttest_perm_{}_{}.mat".format(stage, freq))
tt_pvalues = ttest["p_values"].ravel()
t_values = zscore(ttest["t_values"].ravel())
HR = np.asarray(HR)
LR = np.asarray(LR)
DA = 100 * np.asarray(scores)
if PERM:
da_pvalues = np.asarray(pvalues)
# RPC = zscore((HR - LR) / LR)
# HR = HR / max(abs(HR))
# LR = LR / max(abs(LR))
# HR = zscore(HR)
# LR = zscore(LR)
da_mask = np.full((len(CHANNEL_NAMES)), False, dtype=bool)
tt_mask = np.full((len(CHANNEL_NAMES)), False, dtype=bool)
tt_mask[tt_pvalues < PVAL] = True
if BINOM:
thresholds = [
100 * binom.isf(PVAL, n_trials, .5) / n_trials for n_trials in TRIALS
]
da_mask[DA > thresholds[j]] = True
else:
da_mask[da_pvalues < PVAL] = True
mask_params = dict(
marker="*", markerfacecolor="white", markersize=9, markeredgecolor="white"
)
data = [
{
"name": "PSD HR",
"cmap": "jet",
"mask": None,
"cbarlim": [min(HR), max(HR)],
"data": HR,
},
{
"name": "PSD LR",
"cmap": "jet",
"mask": None,
"cbarlim": [min(LR), max(LR)],
"data": LR,
},
# {
# "name": "Relative Power Changes",
# "cmap": "inferno",
# "mask": None,
# "cbarlim": [min(RPC), max(RPC)],
# "data": RPC / max(RPC),
# },
{
"name": "corrected T-values",
"data": t_values,
"cmap": "viridis",
"mask": tt_mask,
"cbarlim": [min(t_values), max(t_values)],
},
{
"name": "Decoding Accuracies (%)",
"cmap": "viridis",
"mask": da_mask,
"cbarlim": [50, 60],
"data": DA,
},
]
for i, subset in enumerate(data):
plt.subplot(len(FREQS), len(data), i + k)
ch_show = False if i > 1 else True
ax, _ = plot_topomap(
subset["data"],
SENSORS_POS,
res=128,
cmap=subset["cmap"],
show=False,
vmin=subset["cbarlim"][0],
vmax=subset["cbarlim"][1],
names=CHANNEL_NAMES,
show_names=ch_show,
mask=subset["mask"],
mask_params=mask_params,
contours=0,
)
if freq == FREQS[-1]:
plt.xlabel(subset["name"])
if freq == FREQS[-1]:
pass
# cb = fig.colorbar(ax, orientation="horizontal")
# tick_locator = ticker.MaxNLocator(nbins=5)
# cb.locator = tick_locator
# cb.update_ticks()
if i == 0:
plt.ylabel(freq)
j += 1
k += len(data)
plt.subplots_adjust(
left=None, bottom=0.05, right=None, top=None, wspace=None, hspace=None
)
plt.tight_layout()
file_name = "topomap_{}{}_{}_p{}".format(PREFIX, NAME, stage, str(PVAL)[2:])
print(file_name)
plt.savefig(SAVE_PATH / "../figures" / file_name, dpi=400)
if __name__ == "__main__":
Parallel(n_jobs=-1)(delayed(gen_figure)(stage) for stage in STATE_LIST)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,860 | arthurdehgan/sleep | refs/heads/master | /ttest_perm_indep.py | """Function do perform ttest indep with permutations
Author: Arthur Dehgan"""
print(
"Warning, this package is no longer updated, there might be bugs here and there even if they were not reported to me. Please use the new version at https://github.com/arthurdehgan/NeuroPy-MLToolbox."
)
import time
import numpy as np
from scipy.stats import ttest_ind
from scipy.special import comb
from itertools import combinations
from joblib import Parallel, delayed
from sys import maxsize
def relative_perm(
cond1,
cond2,
n_perm=0,
correction="maxstat",
method="indep",
alpha=0.05,
two_tailed=False,
n_jobs=1,
):
"""compute relative changes (cond1 - cond2)/cond2
with permuattions and correction.
Parameters:
cond1, cond2: numpy arrays of shape n_subject x n_eletrodes
or n_trials x n_electrodes. arrays of data for
the independant conditions.
n_perm: int, number of permutations to do.
If n_perm = 0 then exaustive permutations will be done.
It will take exponential time with data size.
correction: string, None, the choice of correction to compute
pvalues. If None, no correction will be done
Options are 'maxstat', 'fdr', 'bonferroni', None
method : 'indep' | 'negcorr'
Necessary only for fdr correction.
Implements Benjamini/Hochberg method if 'indep' or
Benjamini/Yekutieli if 'negcorr'.
alpha: float, error rate
two_tailed: bool, set to True if you want two-tailed ttest.
n_jobs: int, Number of cores used to computer permutations in
parallel (-1 uses all cores and will be faster)
Returns:
values: list, the calculated relative changes
pval: pvalues after permutation test and correction if selected
"""
_check_correction(correction)
values = compute_relatives(cond1, cond2)
perm_t = perm_test(cond1, cond2, n_perm, compute_relatives, n_jobs=n_jobs)
pval = compute_pvalues(values, perm_t, two_tailed, correction=correction)
if correction in ["bonferroni", "fdr"]:
pval = pvalues_correction(pval, correction, method)
return values, pval
def ttest_perm_unpaired(
cond1,
cond2,
n_perm=0,
correction="maxstat",
method="indep",
alpha=0.05,
equal_var=False,
two_tailed=False,
n_jobs=1,
):
"""ttest indep with permuattions and maxstat correction
Parameters:
cond1, cond2: numpy arrays of shape n_subject x n_eletrodes
or n_trials x n_electrodes. arrays of data for
the independant conditions.
n_perm: int, number of permutations to do.
If n_perm = 0 then exaustive permutations will be done.
It will take exponential time with data size.
correction: string, None, the choice of correction to compute
pvalues. If None, no correction will be done
Options are 'maxstat', 'fdr', 'bonferroni', None
method : 'indep' | 'negcorr'
Necessary only for fdr correction.
Implements Benjamini/Hochberg method if 'indep' or
Benjamini/Yekutieli if 'negcorr'.
alpha: float, error rate
equal_var: bool, see scipy.stats.ttest_ind.
two_tailed: bool, set to True if you want two-tailed ttest.
n_jobs: int, Number of cores used to computer permutations in
parallel (-1 uses all cores and will be faster)
Returns:
tval: list, the calculated t-statistics
pval: pvalues after permutation test and correction if selected
"""
_check_correction(correction)
tval, _ = ttest_ind(cond1, cond2, equal_var=equal_var)
perm_t = perm_test(cond1, cond2, n_perm, _ttest_perm, equal_var, n_jobs=n_jobs)
pval = compute_pvalues(tval, perm_t, two_tailed, correction=correction)
if correction in ["bonferroni", "fdr"]:
pval = pvalues_correction(pval, correction, method)
return tval, pval
def perm_test(cond1, cond2, n_perm, function, equal_var=False, n_jobs=1):
"""permutation ttest.
Parameters:
cond1, cond2: numpy arrays of shape n_subject x n_eletrodes
or n_trials x n_electrodes. arrays of data for
the independant conditions.
n_perm: int, number of permutations to do, the more the better.
function: func, the function to execute in parallel on the data.
equal_var: bool, see scipy.stats.ttest_ind.
n_jobs: int, Number of cores used to computer permutations in
parallel (-1 uses all cores and will be faster)
Returns:
perm_t: list of permutation t-statistics
"""
full_mat = np.concatenate((cond1, cond2), axis=0)
n_samples = len(full_mat)
perm_t = []
n_comb = comb(n_samples, len(cond1))
if np.isinf(n_comb):
n_comb = maxsize
else:
n_comb = int(n_comb)
if n_perm >= n_comb - 1:
# print("All permutations will be done. n_perm={}".format(n_comb - 1))
if n_perm == 0:
print(
"size of the dataset does not allow {}"
+ "permutations, instead".format(n_perm)
)
n_perm = n_comb
print("All {} permutations will be done".format(n_perm))
if n_perm > 9999:
print("Warning: permutation number is very high : {}".format(n_perm))
print("it might take a while to compute ttest on all permutations")
perms_index = _combinations(range(n_samples), len(cond1), n_perm)
perm_t = Parallel(n_jobs=n_jobs)(
delayed(function)(full_mat, index, equal_var=equal_var) for index in perms_index
)
return perm_t[1:] # the first perm is not a permutation
def compute_pvalues(tval, perm_t, two_tailed, correction):
"""computes pvalues.
Parameters:
tstat: computed t-statistics
perm_t: list of permutation t-statistics
two_tailed: bool, if you want two-tailed ttest.
correction: string, None, the choice of correction to compute
pvalues. If None, no correction will be done
Options are 'maxstat', 'fdr', 'bonferroni', None
Returns:
pvalues: list of pvalues after permutation test
"""
scaling = len(perm_t)
perm_t = np.array(perm_t)
pvalues = []
if two_tailed:
perm_t = abs(perm_t)
if correction == "maxstat":
perm_t = np.asarray(perm_t).max(axis=1)
perm_t = np.array([perm_t for _ in range(len(tval))]).T
for i, tstat in enumerate(tval):
p_final = 0
compare_list = perm_t[:, i]
for t_perm in compare_list:
if tstat <= t_perm:
p_final += 1 / scaling
pvalues.append(p_final)
pvalues = np.asarray(pvalues, dtype=np.float32)
return pvalues
def pvalues_correction(pvalues, correction, method):
"""computes corrected pvalues from pvalues.
Parameters:
pvalues: list, list of pvalues.
correction: string, None, the choice of correction to compute
pvalues. If None, no correction will be done
Options are 'maxstat', 'fdr', 'bonferroni', None
method : 'indep' | 'negcorr'
Necessary only for fdr correction.
Implements Benjamini/Hochberg method if 'indep' or
Benjamini/Yekutieli if 'negcorr'.
Returns:
pvalues: list of corrected pvalues
"""
if correction == "bonferroni":
pvalues *= float(np.array(pvalues).size)
elif correction == "fdr":
n_obs = len(pvalues)
index_sorted_pvalues = np.argsort(pvalues)
sorted_pvalues = pvalues[index_sorted_pvalues]
sorted_index = index_sorted_pvalues.argsort()
ecdf = (np.arange(n_obs) + 1) / float(n_obs)
if method == "negcorr":
cm = np.sum(1. / (np.arange(n_obs) + 1))
ecdf /= cm
elif method == "indep":
pass
else:
raise ValueError(method, " is not a valid method option")
raw_corrected_pvalues = sorted_pvalues / ecdf
corrected_pvalues = np.minimum.accumulate(raw_corrected_pvalues[::-1])[::-1]
pvalues = corrected_pvalues[sorted_index].reshape(n_obs)
pvalues[pvalues > 1.0] = 1.0
return pvalues
def compute_relatives(cond1, cond2, **kwargs):
"""Computes the relative changes.
Parameters:
cond1, cond2: numpy arrays of shape n_subject x n_eletrodes
or n_trials x n_electrodes. arrays of data for
the independant conditions.
Returns:
values: list, the calculated relative changes
"""
cond1 = np.asarray(cond1).mean(axis=0)
cond2 = np.asarray(cond2).mean(axis=0)
values = (cond1 - cond2) / cond2
return values
def _generate_conds(data, index):
"""
Parameters:
data: numpy array of the concatenated condition data.
index: the permutation index to apply.
Returns:
cond1, cond2: numpy arrays of permutated values.
"""
index = list(index)
index_comp = list(set(range(len(data))) - set(index))
perm_mat = np.vstack((data[index], data[index_comp]))
cond1, cond2 = perm_mat[: len(index)], perm_mat[len(index) :]
return cond1, cond2
def _combinations(iterable, r, limit=None):
"""combinations generator"""
i = 0
for e in combinations(iterable, r):
yield e
i += 1
if limit is not None and i == limit:
break
def _relative_perm(data, index, **kwargs):
"""Compute realtives changes after on a selectes permutation"""
cond1, cond2 = _generate_conds(data, index)
return compute_relatives(cond1, cond2, kwargs)
def _ttest_perm(data, index, equal_var):
"""ttest with the permutation index"""
cond1, cond2 = _generate_conds(data, index)
return ttest_ind(cond1, cond2, equal_var=equal_var)[0]
def _check_correction(correction):
"""Checks if correction is a correct option"""
if correction not in ["maxstat", "bonferroni", "fdr", None]:
raise ValueError(correction, "is not a valid correction option")
if __name__ == "__main__":
cond1 = np.random.randn(10, 19)
cond2 = np.random.randn(10, 19)
tval, pval = ttest_perm_unpaired(cond1, cond2, n_perm=100)
tval4, pval4 = ttest_perm_unpaired(cond1, cond2, n_perm=100, correction="maxstat")
tval2, pval2 = ttest_perm_unpaired(
cond1, cond2, n_perm=100, correction="bonferroni"
)
tval3, pval3 = ttest_perm_unpaired(cond1, cond2, n_perm=100, correction="fdr")
val, pval4 = relative_perm(cond1, cond2, n_perm=10)
print(pval, pval2, pval4, pval3)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,861 | arthurdehgan/sleep | refs/heads/master | /ttest.py | """Ttest for PSD values.
by Arthur Dehgan"""
from scipy.io import loadmat, savemat
import numpy as np
from joblib import Parallel, delayed
from ttest_perm_indep import ttest_perm_unpaired
from params import STATE_LIST, FREQ_DICT, SAVE_PATH, WINDOW, OVERLAP, CHANNEL_NAMES
# NAME = "psd"
NAME = "zscore_psd"
SAVE_PATH = SAVE_PATH / NAME
RESULT_PATH = SAVE_PATH / "results"
n_perm = 9999
def main(stade, freq):
print(stade, freq)
HRs, LRs = [], []
for elec in CHANNEL_NAMES:
file_path = SAVE_PATH / NAME + "_{}_{}_{}_{}_{:.2f}.mat".format(
stade, freq, elec, WINDOW, OVERLAP
)
try:
X = loadmat(file_path)["data"].ravel()
except KeyError:
print(file_path, "corrupted")
except IOError:
print(file_path, "Not Found")
X = np.delete(X, 9, 0) # delete subj 10 cuz of artefact on FC2
HR = X[:17]
LR = X[17:]
HR = np.concatenate([psd.flatten() for psd in HR])
LR = np.concatenate([psd.flatten() for psd in LR])
# for i in range(len(HR)):
# HR[i] = HR[i].mean()
# LR[i] = LR[i].mean()
HRs.append(HR)
LRs.append(LR)
HRs = np.asarray(HRs, dtype=float).T
LRs = np.asarray(LRs, dtype=float).T
tval, pvalues = ttest_perm_unpaired(
cond1=HRs, cond2=LRs, n_perm=n_perm, equal_var=False, two_tailed=True, n_jobs=-1
)
data = {"p_values": np.asarray(pvalues), "t_values": tval}
file_path = RESULT_PATH / "ttest_perm_{}_{}.mat".format(stade, freq)
savemat(file_path, data)
if __name__ == "__main__":
Parallel(n_jobs=-1)(
delayed(main)(stade, freq) for stade in STATE_LIST for freq in FREQ_DICT
)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,862 | arthurdehgan/sleep | refs/heads/master | /neuroinf_topomap.py | '''Generate topomaps'''
from mne.viz import plot_topomap
from scipy.io import loadmat
from params import SAVE_PATH, CHANNEL_NAMES
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
DATA_PATH = SAVE_PATH / 'psd'
TTEST_RESULTS_PATH = DATA_PATH / 'results'
solver = 'svd'
RESULTS_PATH = DATA_PATH / 'results/'
POS_FILE = SAVE_PATH / '../Coord_EEG_1020.mat'
SENSORS_POS = loadmat(POS_FILE)['Cor']
FREQS = ['Delta', 'Theta', 'Alpha', 'Sigma', 'Beta', 'Gamma1']
STATE_LIST = ['S2', 'NREM', 'Rem']
# prefix = 'bootstrapped_perm_subsamp_'
prefix = 'perm_'
WINDOW = 1000
OVERLAP = 0
p = .01
fig = plt.figure(figsize=(15, 8))
j = 1
for stage in STATE_LIST:
for freq in FREQS:
plt.subplot(len(STATE_LIST), len(FREQS), j)
scores, pvalues = [], []
for elec in CHANNEL_NAMES:
file_name = prefix + 'PSD_{}_{}_{}_{}_{:.2f}.mat'.format(
stage, freq, elec, WINDOW, OVERLAP)
try:
score = loadmat(RESULTS_PATH / file_name)
pvalue = score['pvalue'].ravel()
score = score['score'].ravel().mean()
except TypeError:
score = [.5]
pvalue = [1]
print(RESULTS_PATH / file_name)
scores.append(score*100)
pvalues.append(pvalue[0])
DA = np.asarray(scores)
da_pvalues = np.asarray(pvalues)
da_mask = np.full((len(CHANNEL_NAMES)), False, dtype=bool)
da_mask[da_pvalues <= p] = True
mask_params = dict(marker='*', markerfacecolor='white', markersize=9,
markeredgecolor='white')
subset = {'name': 'Decoding Accuracies p<{}'.format(p), 'cmap': 'viridis',
'mask': da_mask, 'cbarlim': [50, 65], 'data': DA}
ch_show = False if j > 1 else True
ax, _ = plot_topomap(subset['data'], SENSORS_POS, res=128,
cmap=subset['cmap'], show=False,
vmin=subset['cbarlim'][0],
vmax=subset['cbarlim'][1],
names=CHANNEL_NAMES, show_names=ch_show,
mask=subset['mask'], mask_params=mask_params,
contours=0)
j += 1
fig.colorbar(ax)
plt.subplots_adjust(left=None, bottom=0.05, right=None, top=None,
wspace=None, hspace=None)
plt.tight_layout()
file_name = 'topomap_neuroinf_p{}'.format(str(p)[2:])
plt.savefig(SAVE_PATH / '../figures' / file_name, dpi=600)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,863 | arthurdehgan/sleep | refs/heads/master | /classif_psd_bins.py | from utils import StratifiedLeave2GroupsOut, create_groups
from scipy.io import savemat, loadmat
import numpy as np
from numpy.random import permutation
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import cross_val_score
from params import CHANNEL_NAMES, LABEL_PATH, SUBJECT_LIST, SAVE_PATH
N_FBIN = 45
WINDOW = 1000
OVERLAP = 0
N_PERMUTATIONS = 1000
SLEEP_LIST = ["S1", "S2", "SWS", "Rem"]
SAVE_PATH = SAVE_PATH / "psd/results"
SUB_LIST = SUBJECT_LIST
PERM_TEST = False
if __name__ == "__main__":
for state in SLEEP_LIST:
print(state)
for elec in CHANNEL_NAMES:
y = loadmat(LABEL_PATH / state + "_labels.mat")["y"].ravel()
y, groups = create_groups(y)
fbin_not_done = list(range(45))
dataset = []
for sub in SUB_LIST:
data_file_path = SAVE_PATH.dirname() / "PSDs_{}_s{}_{}_{}_{:.2f}.mat".format(
state, sub, elec, WINDOW, OVERLAP
)
if data_file_path.isfile():
dataset.append(loadmat(data_file_path)["data"])
else:
print(data_file_path + " Not found")
dataset = np.vstack(dataset)
print("frequency bins :", [f + 1 for f in fbin_not_done], sep="\n")
for fbin in fbin_not_done:
X = dataset[:, fbin].reshape(-1, 1)
sl2go = StratifiedLeave2GroupsOut()
clf = LDA()
perm_scores = []
pvalue = 0
good_scores = cross_val_score(
cv=sl2go, estimator=clf, X=X, y=y, groups=groups
)
good_score = good_scores.mean()
if PERM_TEST:
for perm in range(N_PERMUTATIONS):
clf = LDA()
perm_set = permutation(len(y))
y_perm = y[perm_set]
groups_perm = groups[perm_set]
perm_scores.append(
cross_val_score(
cv=sl2go,
estimator=clf,
X=X,
y=y_perm,
groups=groups_perm,
n_jobs=-1,
).mean()
)
for score in perm_scores:
if good_score <= score:
pvalue += 1 / N_PERMUTATIONS
data = {
"score": good_score,
"pscore": perm_scores,
"pvalue": pvalue,
}
print(
"{} : {:.2f} significatif a p={:.4f}".format(
fbin, good_score, pvalue
)
)
if PERM_TEST:
results_file_path = (
SAVE_PATH
/ "perm_PSD_bin_{}_{}_{}_{}_{:.2f}.mat".format(
fbin, state, elec, WINDOW, OVERLAP
)
)
else:
data = {"score": good_scores}
results_file_path = (
SAVE_PATH
/ "classif_PSD_bin_{}_{}_{}_{}_{:.2f}.mat".format(
fbin, state, elec, WINDOW, OVERLAP
)
)
savemat(results_file_path, data)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,864 | arthurdehgan/sleep | refs/heads/master | /permutations_EFS_fixed_elec.py | """Loads results from EFS and adds permutations to the savefile.
Author: Arthur Dehgan
"""
from itertools import product
import numpy as np
from scipy.io import savemat, loadmat
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from utils import StratifiedLeave2GroupsOut, create_groups, compute_pval
from params import SAVE_PATH, CHANNEL_NAMES, WINDOW, OVERLAP, STATE_LIST, FREQ_DICT
N_PERM = 1000
SAVE_PATH = SAVE_PATH / "psd"
RESULT_PATH = SAVE_PATH / "results"
if "Gamma1" in FREQ_DICT:
del FREQ_DICT["Gamma1"]
FREQS = list(FREQ_DICT.keys())
def load_data(state, elec):
"""Loads data for state, elec parameters."""
final_data = None
for freq in FREQS:
data_file_path = (
SAVE_PATH / f"PSD_{state}_{freq}_{elec}_{WINDOW}_{OVERLAP:.2f}.mat"
)
data = loadmat(data_file_path)["data"].ravel()
if final_data is None:
final_data = data
else:
for i, submat in enumerate(final_data):
final_data[i] = np.concatenate((submat, data[i]), axis=0)
return final_data
def main(state, elec):
"""Permutations.
For each separation of subjects with leave 2 subjects out, we train on the
big set and test on the two remaining subjects.
for each permutation, we just permute the labels at the trial level (we
could use permutations at the subject level, but we wouldn't get as many
permutations)
"""
file_name = f"EFS_NoGamma_{state}_{elec}_{WINDOW}_{OVERLAP:.2f}.mat"
print(file_name)
file_path = RESULT_PATH / file_name
data = loadmat(file_path)
lil_labels = [0] * 18 + [1] * 18
lil_labels = np.asarray(lil_labels)
lil_groups = list(range(36))
sl2go = StratifiedLeave2GroupsOut()
best_freqs = list(data["freqs"].ravel())
scores = list(data["test_scores"].ravel())
data = load_data(state, elec)
pscores = []
pvalues = []
i = 0
for train_subjects, test_subjects in sl2go.split(data, lil_labels, lil_groups):
x_feature, x_classif = data[train_subjects], data[test_subjects]
y_feature = lil_labels[train_subjects]
y_classif = lil_labels[test_subjects]
y_feature = [
np.array([label] * x_feature[i].shape[1])
for i, label in enumerate(y_feature)
]
y_feature, _ = create_groups(y_feature)
y_classif = [
np.array([label] * x_classif[i].shape[1])
for i, label in enumerate(y_classif)
]
y_classif, _ = create_groups(y_classif)
print(best_freqs[i])
best_idx = [FREQS.index(value.strip().capitalize()) for value in best_freqs[i]]
x_classif = np.concatenate(x_classif[:], axis=1).T
x_feature = np.concatenate(x_feature[:], axis=1).T
for _ in range(N_PERM):
y_feature = np.random.permutation(y_feature)
y_classif = np.random.permutation(y_classif)
clf = LDA()
clf.fit(x_feature[:, best_idx], y_feature)
pscore = clf.score(x_classif[:, best_idx], y_classif)
pscores.append(pscore)
score = scores[i]
pvalue = compute_pval(score, pscores)
pvalues.append(pvalue)
i += 1
data["pvalue"] = pvalues
data["pscores"] = pscores
savemat(file_path, data)
if __name__ == "__main__":
for state, elec in product(STATE_LIST, CHANNEL_NAMES):
main(state, elec)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,865 | arthurdehgan/sleep | refs/heads/master | /classif_cov_testn153SWS.py | """Load covariance matrix, perform classif, perm test, saves results.
Outputs one file per freq x state
Author: Arthur Dehgan"""
from time import time
from scipy.io import savemat, loadmat
import pandas as pd
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from pyriemann.classification import TSclassifier
from utils import (
create_groups,
StratifiedLeave2GroupsOut,
elapsed_time,
prepare_data,
classification,
)
from params import SAVE_PATH, STATE_LIST, LABEL_PATH
# import pdb
# name = 'moy_cov'
prefix = "classif_subsamp_"
name = "cov"
pref_list = prefix.split("_")
BOOTSTRAP = "bootstrapped" in pref_list
FULL_TRIAL = "ft" in pref_list or "moy" in pref_list
SUBSAMPLE = "subsamp" in pref_list
PERM = "perm" in pref_list
N_PERM = 999 if PERM else None
N_BOOTSTRAPS = 10 if BOOTSTRAP else 1
SAVE_PATH = SAVE_PATH / name
##### FOR A TEST #####
STATE_LIST = ["SWS"]
##### FOR A TEST #####
def main(state):
"""Where the magic happens"""
print(state)
if FULL_TRIAL:
labels = np.concatenate((np.ones(18), np.zeros(18)))
groups = range(36)
elif SUBSAMPLE:
info_data = pd.read_csv(SAVE_PATH.parent / "info_data.csv")[STATE_LIST]
##### FOR A TEST #####
info_data = info_data["SWS"]
##### FOR A TEST #####
N_TRIALS = info_data.min().min()
N_SUBS = len(info_data) - 1
groups = [i for _ in range(N_TRIALS) for i in range(N_SUBS)]
N_TOTAL = N_TRIALS * N_SUBS
labels = [0 if i < N_TOTAL / 2 else 1 for i in range(N_TOTAL)]
else:
labels = loadmat(LABEL_PATH / state + "_labels.mat")["y"].ravel()
labels, groups = create_groups(labels)
file_name = prefix + name + "n153_{}.mat".format(state)
save_file_path = SAVE_PATH / "results" / file_name
if not save_file_path.isfile():
data_file_path = SAVE_PATH / name + "_{}.mat".format(state)
if data_file_path.isfile():
final_save = None
for i in range(N_BOOTSTRAPS):
data = loadmat(data_file_path)
if FULL_TRIAL:
data = data["data"]
elif SUBSAMPLE:
data = prepare_data(data, n_trials=N_TRIALS, random_state=i)
else:
data = prepare_data(data)
sl2go = StratifiedLeave2GroupsOut()
lda = LDA()
clf = TSclassifier(clf=lda)
save = classification(
clf, sl2go, data, labels, groups, N_PERM, n_jobs=-1
)
save["acc_bootstrap"] = [save["acc_score"]]
save["auc_bootstrap"] = [save["auc_score"]]
if final_save is None:
final_save = save
else:
for key, value in final_save.items():
final_save[key] = final_save[key] + save[key]
savemat(save_file_path, final_save)
print(
"accuracy for %s : %0.2f (+/- %0.2f)"
% (state, save["acc_score"], np.std(save["acc"]))
)
else:
print(data_file_path.name + " Not found")
if __name__ == "__main__":
TIMELAPSE_START = time()
for state in STATE_LIST:
main(state)
print("total time lapsed : %s" % elapsed_time(TIMELAPSE_START, time()))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,866 | arthurdehgan/sleep | refs/heads/master | /visu_barplot_multifeature.py | """Generate barplot and saves it."""
from math import ceil
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns
import numpy as np
import pandas as pd
from scipy.io import loadmat
from scipy.stats import binom
from utils import super_count
from params import (
STATE_LIST,
SAVE_PATH,
WINDOW,
OVERLAP,
REGIONS,
CHANNEL_NAMES,
FREQ_DICT,
)
FIG_PATH = SAVE_PATH.dirname() / "figures"
NAME = "EFS_NoGamma"
RESULT_PATH = SAVE_PATH / "psd/results/"
MINMAX = [40, 80]
Y_LABEL = "Decoding accuracies (%)"
COLORS = list(sns.color_palette("deep"))
WIDTH = .90
GRAPH_TITLE = "multifeature classification"
RESOLUTION = 300
def autolabel(ax, rects, thresh):
"""Attach a text label above each bar displaying its height."""
for rect in rects:
height = rect.get_height()
width = rect.get_width()
if height > thresh:
color = "green"
else:
color = "black"
if height != 0:
ax.text(
rect.get_x() + width / 2.,
width + 1. * height,
"%d" % int(height),
ha="center",
va="bottom",
color=color,
size=14,
)
return ax
def get_max_key(dico):
"""Returns key with max value"""
our_max = 0
argmax = None
for key, val in dico.items():
if val > our_max:
argmax = key
our_max = val
return argmax
# barplot parameters
def visualisation():
labels = list(REGIONS)
groups = STATE_LIST
nb_labels = len(labels)
score_stade = {}
for stage in STATE_LIST:
scores_regions = dict.fromkeys(REGIONS.keys(), 0)
for region, elec_list in REGIONS.items():
counts, all_count = {}, {}
scores_elecs, freqs_elecs = {}, {}
for elec in elec_list:
file_name = "EFS_NoGamma_{}_{}_1000_0.00.mat".format(stage, elec)
data = loadmat(RESULT_PATH / file_name)
scores = data["test_scores"].ravel() * 100
if stage == "S2" and elec == "F4":
all_count["Sigma"] = all_count.get("Sigma", 0) + 324
freqs_elecs[elec] = ["Sigma"] * 324
scores_elecs[elec] = scores
continue
freqs = data["freqs"].ravel()
freqs_stripped = [
freq.strip().capitalize() for sub in freqs for freq in sub
]
freqs_elecs[elec] = freqs_stripped
scores_elecs[elec] = [
scores[i] for i, sub in enumerate(freqs) for freq in sub
]
count = super_count(freqs_stripped)
counts[elec] = count
for freq in FREQ_DICT:
all_count[freq] = all_count.get(freq, 0) + count.get(freq, 0)
freq = get_max_key(all_count)
for elec in elec_list:
best_freq_index = np.where(np.asarray(freqs_elecs[elec]) == freq)[0]
scores_regions[region] += np.mean(
np.asarray(scores_elecs[elec])[best_freq_index]
) / len(elec_list)
score_stade[stage] = scores_regions
fig = plt.figure(figsize=(10, 5)) # size of the figure
# Generating the barplot (do not change)
ax = plt.axes()
temp = 0
info_data = pd.read_csv(SAVE_PATH / "info_data.csv")[STATE_LIST]
trials = list(info_data.iloc[-1])
thresholds = [
100 * binom.isf(0.001, n_trials, .5) / n_trials for n_trials in trials
]
for j, group in enumerate(groups):
bars = []
for i, region in enumerate(REGIONS):
data = score_stade[group][region]
pos = i + 1
color = COLORS[i]
bars.append(ax.bar(temp + pos, data, WIDTH, color=color))
temp += pos + 1
start = j * (pos + 1) + .5
end = start + len(REGIONS)
ax.plot([start, end], [thresholds[j], thresholds[j]], "k--", label="p=0.001")
ax.set_ylabel(Y_LABEL)
ax.set_ylim(bottom=MINMAX[0], top=MINMAX[1])
ax.set_title(GRAPH_TITLE)
ax.set_xticklabels(groups)
ax.set_xticks(
[ceil(nb_labels / 2) + i * (1 + nb_labels) for i in range(len(groups))]
)
plt.legend(bars, labels, fancybox=False, shadow=False)
file_name = f"{NAME}_1000_0.png"
print(FIG_PATH / file_name)
save_path = str(FIG_PATH / file_name)
fig.savefig(save_path, dpi=RESOLUTION)
if __name__ == "__main__":
visualisation()
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,867 | arthurdehgan/sleep | refs/heads/master | /compute_psd.py | """Computes PSD vectors and save them.
Execute "group_PSD_per_subjects.py" after this script
Author: Arthur Dehgan
"""
from utils import load_samples, elapsed_time, computePSD
from scipy.io import savemat
from time import time
import numpy as np
from path import Path as path
from joblib import Parallel, delayed
from params import (
DATA_PATH,
SAVE_PATH,
SUBJECT_LIST,
FREQ_DICT,
STATE_LIST,
SF,
WINDOW,
OVERLAP,
CHANNEL_NAMES,
)
SAVE_PATH = SAVE_PATH / "psd"
def computeAndSavePSD(
SUBJECT_LIST, state, freq, window, overlap, fmin, fmax, fs, elec=None
):
"""loads data, compute PSD and saves PSD of all subjects in one file"""
N_ELEC = 19 if elec is None else len(elec)
print(state, freq, "bande {}: [{}-{}]Hz".format(freq, fmin, fmax))
for elec in range(N_ELEC): # pour chaque elec
channel_name = CHANNEL_NAMES[elec]
file_path = path(
SAVE_PATH
/ "PSD_{}_{}_{}_{}_{:.2f}.mat".format(
# 'PSD_EOG_sleepState_%s_%s_%i_%i_%.2f.mat' %
state,
freq,
channel_name,
window,
overlap,
)
)
if not file_path.isfile():
psds = []
for sub in SUBJECT_LIST: # pour chaque sujet
X = load_samples(DATA_PATH, sub, state)
psd_list = []
for j in range(X.shape[0]): # pour chaque trial
psd = computePSD(
X[j, elec],
window=window,
overlap=OVERLAP,
fmin=fmin,
fmax=fmax,
fs=fs,
)
psd_list.append(psd)
psd_list = np.asarray(psd_list)
psds.append(psd_list.ravel())
print(file_path)
savemat(file_path, {"data": psds})
if __name__ == "__main__":
"""Do the thing."""
t0 = time()
Parallel(n_jobs=-1)(
delayed(computeAndSavePSD)(
SUBJECT_LIST,
state,
freq=freq,
window=WINDOW,
overlap=OVERLAP,
fmin=FREQ_DICT[freq][0],
fmax=FREQ_DICT[freq][1],
fs=SF,
)
for freq in FREQ_DICT
for state in STATE_LIST
)
# for state in STATE_LIST:
# for freq in FREQ_DICT:
# computeAndSavePSD(SUBJECT_LIST, state, freq, WINDOW, OVERLAP,
# fmin=FREQ_DICT[freq][0],
# fmax=FREQ_DICT[freq][1],
# fs=SF)
print("total time lapsed : %s" % elapsed_time(t0, time()))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,868 | arthurdehgan/sleep | refs/heads/master | /compute_cosp.py | """Computes Crosspectrum matrices and save them.
Author: Arthur Dehgan"""
import os
from time import time
from itertools import product
from joblib import Parallel, delayed
import numpy as np
from scipy.io import savemat, loadmat
from utils import elapsed_time
# from utils import load_samples
from utils import load_full_sleep, load_samples
from params import (
DATA_PATH,
SAVE_PATH,
SUBJECT_LIST,
FREQ_DICT,
STATE_LIST,
SF,
WINDOW,
OVERLAP,
)
IMAG = False
FULL_TRIAL = False
if IMAG:
from pyriemann.estimationmod import CospCovariances
else:
from pyriemann.estimation import CospCovariances
if IMAG:
prefix = "im_cosp"
elif FULL_TRIAL:
prefix = "ft_cosp"
else:
prefix = "cosp"
SAVE_PATH = SAVE_PATH / "cosp/"
def combine_subjects(state, freq, window, overlap, cycle=None):
"""Combines crosspectrum matrices from subjects into one."""
dat, load_list = [], []
print(state, freq)
for sub in SUBJECT_LIST:
file_path = SAVE_PATH / prefix + "_s{}_{}_{}_{}_{:.2f}.mat".format(
sub, state, freq, window, overlap
)
save_file_path = SAVE_PATH / prefix + "_{}_{}_{}_{:.2f}.mat".format(
state, freq, window, overlap
)
if cycle is not None:
file_path = SAVE_PATH / prefix + "_s{}_{}_cycle{}_{}_{}_{:.2f}.mat".format(
sub, state, cycle, freq, window, overlap
)
save_file_path = SAVE_PATH / prefix + "_{}_cycle{}_{}_{}_{:.2f}.mat".format(
state, cycle, freq, window, overlap
)
try:
data = loadmat(file_path)["data"]
dat.append(data)
load_list.append(str(file_path))
except (IOError, TypeError) as e:
print(file_path, "not found")
savemat(save_file_path, {"data": np.asarray(dat)})
for f in load_list:
os.remove(f)
def compute_cosp(state, freq, window, overlap, cycle=None):
"""Computes the crosspectrum matrices per subjects."""
if cycle is not None:
print(state, freq, cycle)
else:
print(state, freq)
freqs = FREQ_DICT[freq]
for sub in SUBJECT_LIST:
if cycle is None:
file_path = SAVE_PATH / prefix + "_s{}_{}_{}_{}_{:.2f}.mat".format(
sub, state, freq, window, overlap
)
else:
file_path = SAVE_PATH / prefix + "_s{}_{}_cycle{}_{}_{}_{:.2f}.mat".format(
sub, state, cycle, freq, window, overlap
)
if not file_path.isfile():
# data must be of shape n_trials x n_elec x n_samples
if cycle is not None:
data = load_full_sleep(DATA_PATH, sub, state, cycle)
if data is None:
continue
data = data.swapaxes(1, 2)
else:
data = load_samples(DATA_PATH, sub, state)
if FULL_TRIAL:
data = np.concatenate(data, axis=1)
data = data.reshape(1, data.shape[0], data.shape[1])
cov = CospCovariances(
window=window, overlap=overlap, fmin=freqs[0], fmax=freqs[1], fs=SF
)
mat = cov.fit_transform(data)
if len(mat.shape) > 3:
mat = np.mean(mat, axis=-1)
savemat(file_path, {"data": mat})
if __name__ == "__main__":
T_START = time()
Parallel(n_jobs=-1)(
delayed(compute_cosp)(state, freq, WINDOW, OVERLAP, cycle)
for state, freq, cycle in product(STATE_LIST, FREQ_DICT, range(1, 4))
)
print("combining subjects data")
Parallel(n_jobs=-1)(
delayed(combine_subjects)(state, freq, WINDOW, OVERLAP, cycle)
for state, freq, cycle in product(STATE_LIST, FREQ_DICT, range(1, 4))
)
print("total time lapsed : %s" % elapsed_time(T_START, time()))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,869 | arthurdehgan/sleep | refs/heads/master | /visu_barplot.py | """Generate barplot and saves it."""
from math import ceil
import matplotlib.pyplot as plt
from path import Path as path
# Use for binomial threshold (if no perm test has been done) :
# from scipy.stats import binom
def autolabel(rects, thresh):
"""Attach a text label above each bar displaying its height."""
for rect in rects:
height = rect.get_height()
if height > thresh:
color = "green"
else:
color = "black"
if height != 0:
ax.text(
rect.get_x() + rect.get_width() / 2.,
1. * height,
"%d" % int(height),
ha="center",
va="bottom",
color=color,
)
# Path where the figure will be saved
SAVE_PATH = path("/home/arthur/tests")
# barplot parameters
labels = ["data{}".format(i) for i in range(7)] # label for each bar
nb_labels = len(labels)
GROUPS = ["group{}".format(i) for i in range(7)] # label for each GROUPS
data = [50, 60, 50, 65, 80, 40, 50] # the actual data
thresholds = [50] * 7 # The thresholds
MINMAX = [30, 90] # Minimum and maximum of x axis scale
Y_LABEL = "Decoding accuracies" # legend for the y axis
COLORS = [
"#DC9656",
"#D8D8D8",
"#86C1B9",
"#BA8BAF",
"#7CAFC2",
"#A1B56C",
"#AB4642",
] # hex code of bar COLORS '#F7CA88'
WIDTH = .90 # WIDTH of the bars, change at your own risks, it might break
GRAPH_TITLE = "Titre du barplot" # Graph title
FILE_NAME = "nom_fichier.png" # File name when saved
RESOLUTION = 300 # resolution of the saved image in pixel per inch
fig = plt.figure(figsize=(10, 5)) # size of the figure
# Generating the barplot (do not change)
ax = plt.axes()
temp = 0
for group in range(len(GROUPS)):
bars = []
for i, val in enumerate(data):
pos = i + 1
t = thresholds[i]
bars.append(ax.bar(temp + pos, val, WIDTH, color=COLORS[i]))
start = (
(temp + pos * WIDTH) / 2 + 1 - WIDTH
if pos == 1 and temp == 0
else temp + pos - len(data) / (2 * len(data) + 1)
)
end = start + WIDTH
ax.plot([start, end], [t, t], "k--")
autolabel(bars[i], t)
temp += pos + 1
ax.set_ylabel(Y_LABEL)
ax.set_ylim(bottom=MINMAX[0], top=MINMAX[1])
ax.set_title(GRAPH_TITLE)
ax.set_xticklabels(GROUPS)
ax.set_xticks([ceil(nb_labels / 2) + i * (1 + nb_labels) for i in range(len(GROUPS))])
ax.legend(
bars,
labels,
loc="upper center",
bbox_to_anchor=(0.5, -0.05),
fancybox=True,
shadow=True,
ncol=len(labels),
)
print(FILE_NAME)
plt.savefig(FILE_NAME, dpi=RESOLUTION)
# plt.show()
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,870 | arthurdehgan/sleep | refs/heads/master | /classif_psd_multi_fixed_elec.py | '''Uses a classifier to decode PSD values.
Computes pvalues and saves them in a mat format with the decoding accuracies.
Author: Arthur Dehgan
'''
from time import time
from itertools import product
import numpy as np
from scipy.io import savemat, loadmat
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from utils import StratifiedLeave2GroupsOut, elapsed_time, create_groups,\
classification
from params import SAVE_PATH, LABEL_PATH, path, CHANNEL_NAMES,\
WINDOW, OVERLAP, STATE_LIST, FREQ_DICT
N_PERMUTATIONS = 1000
SAVE_PATH = SAVE_PATH / 'psd'
def main(state, elec):
labels = loadmat(LABEL_PATH / state + '_labels.mat')['y'].ravel()
labels, groups = create_groups(labels)
final_data = None
print(state, elec)
results_file_path = SAVE_PATH / 'results' /\
'perm_PSDM_{}_{}_{}_{:.2f}_NoGamma.mat'.format(
state, elec, WINDOW, OVERLAP)
if not path(results_file_path).isfile():
# print('\nloading PSD for {} frequencies'.format(key))
for key in FREQ_DICT:
if not key.startswith('Gamma'):
data_file_path = SAVE_PATH /\
'PSD_{}_{}_{}_{}_{:.2f}.mat'.format(
state, key, elec, WINDOW, OVERLAP)
if path(data_file_path).isfile():
temp = loadmat(data_file_path)['data'].ravel()
data = temp[0].ravel()
for submat in temp[1:]:
data = np.concatenate((submat.ravel(), data))
data = data.reshape(len(data), 1)
final_data = data if final_data is None\
else np.hstack((final_data, data))
del temp
else:
print(path(data_file_path).name + ' Not found')
print('please run "computePSD.py" and\
"group_PSD_per_subjects.py" before\
running this script')
# print('classification...')
sl2go = StratifiedLeave2GroupsOut()
clf = LDA()
save = classification(clf, sl2go, final_data,
labels, groups, n_jobs=-1)
savemat(results_file_path, save)
if __name__ == '__main__':
T0 = time()
for state, elec in product(STATE_LIST, CHANNEL_NAMES):
main(state, elec)
print('total time lapsed : {}'.format(elapsed_time(T0, time())))
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
68,871 | arthurdehgan/sleep | refs/heads/master | /visu_gen_fig1.py | import matplotlib.pyplot as plt
import numpy as np
import math
from scipy.io import loadmat
from matplotlib import ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
from params import STATE_LIST, SAVE_PATH, CHANNEL_NAMES, SUBJECT_LIST
FIG_PATH = SAVE_PATH.parent / "figures"
COSP_PATH = SAVE_PATH / "cosp"
COV_PATH = SAVE_PATH / "cov"
PSD_PATH = SAVE_PATH / "psd/per_bin"
HR_LABELS = ("HR", "HR mean")
LR_LABELS = ("LR", "LR mean")
STATE = "S2"
FREQ = "Delta"
FONTSIZE = 16
def prepare_recallers(data):
HR = data[:18]
LR = data[18:]
for i, submat in enumerate(HR):
if i == 9:
vals = []
for mat in submat:
vals.append(mat[-3, -3])
std = np.std(vals)
for j, val in enumerate(vals):
if val > 2 * std:
np.delete(submat, j, 0)
HR[i] = submat.mean(axis=0)
for i, submat in enumerate(LR):
LR[i] = submat.mean(axis=0)
HR = np.delete(HR, 9, 0) # subject 10 has artifacts on FC2
HR = HR.mean()
HR /= HR.max()
LR = LR.mean()
LR /= LR.max()
return np.flip(HR, 0), np.flip(LR, 0)
def compute(val, k):
return math.log(val / (k + 1))
def do_matrix(fig, mat):
mat = fig.pcolormesh(mat, vmin=0, vmax=1)
fig.set_xticklabels(CHANNEL_NAMES, rotation=90)
fig.set_yticklabels(reversed(CHANNEL_NAMES))
ticks = [i + .5 for i, _ in enumerate(CHANNEL_NAMES)]
fig.set_xticks(ticks)
fig.set_yticks(ticks)
fig.tick_params(labeltop=False, labelbottom=True, top=False)
return mat
COV_NAME = COV_PATH / "cov_{}.mat".format(STATE)
DATA = loadmat(COV_NAME)["data"].ravel()
HR_COV, LR_COV = prepare_recallers(DATA)
cosp_name = COSP_PATH / "cosp_{}_{}_1000_0.00.mat".format(STATE, FREQ)
data = loadmat(cosp_name)
data = data["data"].ravel()
HR_COSP, LR_COSP = prepare_recallers(data)
all_subs = []
for sub in SUBJECT_LIST:
all_elecs = []
for elec in CHANNEL_NAMES:
data = []
for state in STATE_LIST:
psd_name = PSD_PATH / "PSDs_{}_s{}_{}_1000_0.00.mat".format(
state, sub, elec
)
data.append(loadmat(psd_name)["data"].mean(axis=0))
all_states = np.asarray(data).mean(axis=0)
all_elecs.append(all_states)
all_subs.append(np.asarray(all_elecs).mean(axis=0))
all_subs = np.asarray(all_subs)
hdr = all_subs[18:]
hdr = [[compute(a, i) for a in dat] for i, dat in enumerate(hdr)]
ldr = all_subs[:18]
ldr = [[compute(a, i) for a in dat] for i, dat in enumerate(ldr)]
fig = plt.figure(figsize=(25, 10))
ax1 = plt.subplot2grid((2, 5), (0, 0), colspan=2, rowspan=2)
ax2 = plt.subplot2grid((2, 5), (0, 2))
ax3 = plt.subplot2grid((2, 5), (0, 3))
ax4 = plt.subplot2grid((2, 5), (1, 2))
ax5 = plt.subplot2grid((2, 5), (1, 3))
ax6 = plt.subplot2grid((2, 5), (1, 4))
for i in range(len(hdr)):
ax1.plot(
range(1, 46), ldr[i], color="skyblue", label="_nolegend_" if i > 0 else "LR"
)
ax1.plot(
range(1, 46), hdr[i], color="peachpuff", label="_nolegend_" if i > 0 else "HR"
)
ax1.plot(range(1, 46), np.mean(hdr, axis=0), color="red", label="HR mean")
ax1.plot(range(1, 46), np.mean(ldr, axis=0), color="blue", label="LR mean")
ax1.legend(fontsize=FONTSIZE - 2, frameon=False)
ax1.set_xlabel("Frequency (Hz)", fontsize=FONTSIZE - 2)
ax1.set_ylabel("Power Spectral Density (dB/Hz)", fontsize=FONTSIZE)
ax1.spines["top"].set_visible(False)
ax1.spines["right"].set_visible(False)
do_matrix(ax2, LR_COV)
ax2.set_ylabel("Covariance", fontsize=FONTSIZE)
do_matrix(ax3, HR_COV)
do_matrix(ax4, LR_COSP)
ax4.set_ylabel("Cospectrum", fontsize=FONTSIZE)
ax4.set_xlabel("Low Recallers", fontsize=FONTSIZE)
mat = do_matrix(ax5, HR_COSP)
ax5.set_xlabel("High Recallers", fontsize=FONTSIZE)
TICKS = [0, .2, .4, .6, .8, 1]
fig.colorbar(mat, ax=ax6, ticks=TICKS, orientation="vertical")
plt.tight_layout(pad=1)
save_name = str(FIG_PATH / "Figure_1.png")
plt.savefig(save_name, dpi=300)
| {"/classif_cosp_backward.py": ["/utils.py"], "/visu_piecharts_fselect.py": ["/utils.py"], "/classif_subcosp.py": ["/utils.py"], "/classif_all_bin_combinations.py": ["/utils.py"], "/visu_data_boxplot.py": ["/utils.py"], "/classif_cosp_multif.py": ["/utils.py"], "/EFS_fixed_elec.py": ["/utils.py"], "/visu_topomap.py": ["/utils.py"], "/ttest.py": ["/ttest_perm_indep.py"], "/classif_psd_bins.py": ["/utils.py"], "/permutations_EFS_fixed_elec.py": ["/utils.py"], "/classif_cov_testn153SWS.py": ["/utils.py"], "/visu_barplot_multifeature.py": ["/utils.py"], "/compute_psd.py": ["/utils.py"], "/compute_cosp.py": ["/utils.py"], "/classif_psd_multi_fixed_elec.py": ["/utils.py"], "/classif_cov_test_simplified.py": ["/utils.py"], "/compute_cov.py": ["/utils.py"], "/classif_cov.py": ["/utils.py"], "/classif_psd.py": ["/utils.py"], "/classif_psd_nremvsrem.py": ["/utils.py"], "/classif_SVM_STATE_ELEC.py": ["/utils.py"], "/classif_perm_subsamp.py": ["/utils.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.