index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
47,516
RushikeshGholap/Projects
refs/heads/master
/Django/django_sinha/addme/adder/models.py
from django.db import models # Create your models here. class numbers(models.Model): a = models.IntegerField() b = models.IntegerField() result = models.IntegerField(default=0)
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,517
RushikeshGholap/Projects
refs/heads/master
/Django/Code/mysite/polls/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('caps',views.caps, name='caps') ]
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,518
RushikeshGholap/Projects
refs/heads/master
/Flask and Docker/deploy_model.py
from sklearn.externals import joblib from flask import Flask, jsonify app = Flask(__name__) @app.route('/<inp>') def predict_category(inp): responsibility = [str(inp)] model = joblib.load('test_model.pkl') output = model.predict(responsibility)[0] return jsonify(category = output) if __name__ == '__main__': app.run(host='0.0.0.0',port=5000)
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,519
RushikeshGholap/Projects
refs/heads/master
/Flask and Docker/Flask Coursera/app.py
#FLASK API (COURSERA) from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', out=text) @app.route('/', methods=['POST']) def index1(): text = request.form['text'] return render_template('index.html', out='text') if __name__ == '__main__': app.run(debug=True)
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,520
RushikeshGholap/Projects
refs/heads/master
/Django/Django/bin/django-admin.py
#!/Users/akshay/Dropbox/Personal/Data Science/iPython/Personal/Django/Django/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,521
RushikeshGholap/Projects
refs/heads/master
/ML App/mysite/mlpanel/apps.py
from django.apps import AppConfig class MlpanelConfig(AppConfig): name = 'mlpanel'
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,522
RushikeshGholap/Projects
refs/heads/master
/Django/django_sinha/imagepred/core/views.py
from django.shortcuts import render, redirect from django.http import HttpResponse from django.conf import settings from .forms import * # Create your views here. def index(request): if request.method=='POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else: form = DocumentForm() return render(request, 'index.html', {'form': form})
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,523
RushikeshGholap/Projects
refs/heads/master
/Random/untitled0.py
# -*- coding: utf-8 -*- """ Created on Sun Jul 16 00:56:55 2017 @author: Akshay """ import os import pandas as pd import missingno as msno import numpy as np from scipy.spatial.distance import cosine from sklearn.metrics.pairwise import linear_kernel import pymysql import itertools from collections import Counter os.chdir("C:\\Users\\Akshay\\Desktop\\Designation wise mapping") os.getcwd() df = pd.read_csv("user_skills_raw.csv") df1 = df.dropna() z = list(df1["mapped_skills"].unique()) b = list(df1["mapped_skills"].unique()).copy() z.append("id") feature_list = z ids = list(df1["candidate_id"].unique()) columnz = ["candidate_id","mapped_skills"] df3 = df1[columnz].copy() df3["val"] = 1 df4 = df3.pivot(index='candidate_id', columns='mapped_skills', values='val').reset_index() df4.fillna(0, inplace=True) df5 = df4.set_index("candidate_id") #Initialize dataframe as placeholder data=df5.values.T ibcf=pd.DataFrame(linear_kernel(data),index=df5.columns,columns=df5.columns) #len(ibcf.columns) #Neighbours based on descending order of cosine similarity neighbours=pd.DataFrame({"skills":list(df5.columns)}) neighbours["associated_skills"]=neighbours["skills"].apply(lambda x: sorted(dict(ibcf.loc[x]).items(),key=lambda x:x[1],reverse=True)[0:5]) type(dict(ibcf.loc['2g']).items()) data=df5.values.T a=linear_kernel(data) dbconnect=pymysql.connect(host="54.254.219.225",user="shivankhome",passwd="password",database="consumer",charset="utf8mb4") skill_data=pd.read_sql("select A.user_id,B.skill_name from user_skill A, master_skill B where A.skill_id=B.skill_id and user_id=3",con=dbconnect) extracted_data=neighbours[neighbours["skills"].isin(list(map(lambda x: x.lower(),skill_data["skill_name"])))] extracted_list=extracted_data["associated_skills"].tolist() extracted_list=list(itertools.chain.from_iterable(extracted_list)) unique_list=list(set(list(map(lambda x: x[0],extracted_list)))) xe=neighbours["associated_skills"].apply(lambda x: list(map(lambda y:y[0],x))).tolist() xe=list(itertools.chain.from_iterable(xe)) xe=dict(Counter(xe)) s=pd.DataFrame(xe,index=["counts"]).T s.to_csv("count_data.csv") p=pd.read_sql("select A.user_id,A.skill_id,B.skill_name from user_skill A,master_skill B where A.skill_id=B.skill_id and user_id in(select user_id from user_skill where skill_id=18077)",con=dbconnect)
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,524
RushikeshGholap/Projects
refs/heads/master
/Django/django_sinha/addme/adder/views.py
from django.shortcuts import render from django.http import HttpResponse from adder.models import numbers # Create your views here. #first time page def index(request): return render(request, 'index.html') #second time page after submit (with result) def output(request): if request.method == 'POST': nums = numbers() nums.a = int(request.POST.get('a')) nums.b = int(request.POST.get('b')) nums.result = nums.a + nums.b nums.save() allnumbs = numbers() return render(request, 'index.html', {'result': nums.result, 'numbers': allnumbs.__class__.objects.all()}) else: return render(request, 'index.html')
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,525
RushikeshGholap/Projects
refs/heads/master
/Django/django_sinha/addme/adder/apps.py
from django.apps import AppConfig class AdderConfig(AppConfig): name = 'adder'
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,526
RushikeshGholap/Projects
refs/heads/master
/Django/django_sinha/addme/adder/admin.py
from django.contrib import admin from adder.models import numbers # Register your models here. admin.site.register(numbers)
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,527
RushikeshGholap/Projects
refs/heads/master
/Random/python_basics2.py
# -*- coding: utf-8 -*- """ Created on Sun Aug 6 22:52:12 2017 @author: Akshay """ import os os.chdir("C:\\Users\\Akshay\\Dropbox\\Personal\\Data Science\\iPython\\Personal\\Practice") os.getcwd() document = open("test_document.txt", "r") x = document.read() xl = x.split() xl #Problem statement - #Wearethepeople\nHimynameisakshay\npythonisfun\nwithouthim\nsuperman\ndestabilize\n dict1 = ['We','are','the','people','Hi','my','name','is','akshay','python','without','him','fun','superman','super','man','superman','stabilize','destabilize'] dict1 biglist=[] for i in xl: h=0 templist=[] g=0 for j in range(len(i)): element = i[g:j+1] if element in dict1: g = j+1 templist.append(element) biglist.append(templist) a=[1,2,3,4] [x**2 for x in a]
{"/Django/django_sinha/imagepred/core/forms.py": ["/Django/django_sinha/imagepred/core/models.py"], "/Django/django_sinha/imagepred/core/views.py": ["/Django/django_sinha/imagepred/core/forms.py"]}
47,528
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/registration/forms.py
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django.db import models from django import forms class UserCreate(UserCreationForm): class Meta: model = User fields=['username', 'password1', 'password2', 'email'] help_texts = {'username': None, 'password1': (""), 'password2': ("")} class Profile(forms.ModelForm): class Meta: model = UserProfile fields = '__all__' exclude = ('user', 'books',)
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,529
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/registration/views.py
from django.shortcuts import render, redirect, get_object_or_404 from .forms import UserCreate, Profile from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .models import UserProfile from django.contrib import messages # Create your views here. def register(request): form = UserCreate() if request.method == "POST": form = UserCreate(request.POST) if form.is_valid(): form.save() username = form.data.get('username') password = form.data.get('password1') user = authenticate(request, username=username, password=password) if user is not None: messages.success(request, "Your account was successfully created.") login(request, user) return redirect('profile') return render(request, 'registration/register.html', {'form': form}) def user_login(request): return render(request, 'registration/login.html') @login_required def profile(request): id_=request.user.id userprof = get_object_or_404(UserProfile, user=id_) return render(request, 'registration/profile.html', {'prof': userprof}) @login_required def profile_update(request): userprof = Profile(instance=request.user.userprofile) if request.method == "POST": userprof = Profile(request.POST, request.FILES, instance=request.user.userprofile) if userprof.is_valid(): userprof.save() messages.success(request, "Profile was successfully updated.") return redirect('profile') return render(request, 'registration/profile_update.html', {'form': userprof})
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,530
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0005_auto_20210301_1143.py
# Generated by Django 3.1.6 on 2021-03-01 11:43 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('books', '0004_auto_20210228_1517'), ] operations = [ migrations.AddField( model_name='userprofile', name='age', field=models.IntegerField(default=None), ), migrations.AddField( model_name='userprofile', name='books', field=models.ManyToManyField(to='books.Book'), ), migrations.AddField( model_name='userprofile', name='first_name', field=models.CharField(default=None, max_length=30), ), migrations.AddField( model_name='userprofile', name='last_name', field=models.CharField(default=None, max_length=30), ), migrations.AddField( model_name='userprofile', name='user', field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='book', name='book_image', field=models.ImageField(default='image.png', upload_to='book_cover_image'), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,531
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/views.py
from django.shortcuts import render, get_object_or_404 from .models import Book from .forms import DropdownForm from django.contrib.auth.decorators import login_required import os from django.conf import settings from django.http import HttpResponse from django.views.generic import TemplateView, ListView from django.db.models import Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from registration.models import UserProfile from django.contrib import messages class SearchResultsView(ListView): model = Book template_name = 'books/search_results.html' def get_queryset(self): query = self.request.GET.get('q') query1 =self.request.GET.get("age_group") print(self.request.GET, query1) object_list = Book.objects.filter( Q(title__icontains=query) | Q(category__icontains=query)| Q(author__icontains=query)| Q(language__icontains=query)| Q(publish_year__icontains=query) | Q(age_group=query1) ) return object_list class AdvancedSearch(ListView): model = Book template_name = 'books/advanced_search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Book.objects.filter( Q(title__icontains= query) ) return object_list def home(request): book = Book.objects.all() page = request.GET.get('page', 1) paginator = Paginator(book, 2) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'books/books_home.html', {'books': book[1:6]}) def rate_1(request, rate,pk): book = Book.objects.all() if request.method =="GET": specific_book = get_object_or_404(Book, pk=pk) specific_book.rate_times += 1 specific_book.rate += rate specific_book.rate_total = specific_book.rate / specific_book.rate_times specific_book.save() return render(request, 'books/books_home.html', {'books': book[1:6]}) def about(request): return render(request, 'books/about.html') @login_required def book_view(request, pk): specific_book = get_object_or_404(Book, pk=pk) return render(request, 'books/book_view.html', {'book': specific_book}) @login_required def book_download(request, pk): specific_book = get_object_or_404(Book, pk=pk) if request.method == "GET": specific_book.downloaded_times += 1 specific_book.save() user_profile = get_object_or_404(UserProfile, id=request.user.userprofile.id) user_profile.books.add(specific_book) user_profile.save() return render(request, 'books/book_download.html', {'book': specific_book}) @login_required() def download(request,path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/pdf_file') response['Content-Disposition']='inline;filename='+os.path.basename(file_path) return response raise Http404 class CategoryView(ListView): model = Book template_name = 'books/category.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Book.objects.filter( Q(category=query) ) return object_list
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,532
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/registration/models.py
from django.db import models from django.contrib.auth.models import User from books.models import Book class UserProfile(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(default=0) avatar = models.ImageField(upload_to="user_avatar", default="image.png") books = models.ManyToManyField(Book, default=None) def __str__(self): return f"{self.first_name} {self.last_name} "
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,533
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0014_auto_20210309_2335.py
# Generated by Django 3.1.6 on 2021-03-09 23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0013_auto_20210309_2052'), ] operations = [ migrations.AddField( model_name='book', name='rate_times', field=models.IntegerField(default=0), ), migrations.AddField( model_name='book', name='rate_total', field=models.FloatField(default=0), ), migrations.AlterField( model_name='book', name='rate', field=models.FloatField(default=0), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,534
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0004_auto_20210228_1517.py
# Generated by Django 3.1.6 on 2021-02-28 15:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0003_auto_20210221_1535'), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AddField( model_name='book', name='book_image', field=models.ImageField(default='image.png', upload_to='book_cover_iamge'), ), migrations.AlterField( model_name='book', name='age_group', field=models.IntegerField(choices=[(0, '0+'), (1, '7+'), (2, '13+'), (3, '18+')]), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,535
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0007_auto_20210301_1203.py
# Generated by Django 3.1.6 on 2021-03-01 12:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0006_userprofile_avatar'), ] operations = [ migrations.AlterField( model_name='userprofile', name='books', field=models.ManyToManyField(default=None, to='books.Book'), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,536
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/urls.py
from django.urls import path from . import views from .views import SearchResultsView, AdvancedSearch urlpatterns =[ path('', views.home, name="books_home"), path('rating_1/<int:rate>/<int:pk>', views.rate_1, name="rate_1"), path('about/', views.about, name="about"), path('book_view/<int:pk>', views.book_view, name="book_view"), path('book_download/<int:pk>', views.book_download, name="book_download"), path('search/', SearchResultsView.as_view(), name='search_results'), path('advanced/', AdvancedSearch.as_view(), name='advanced_search'), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,537
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0011_auto_20210306_1028.py
# Generated by Django 3.1.6 on 2021-03-06 10:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0010_auto_20210302_0810'), ] operations = [ migrations.AlterField( model_name='book', name='publish_year', field=models.CharField(max_length=5), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,538
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0012_auto_20210306_1030.py
# Generated by Django 3.1.6 on 2021-03-06 10:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0011_auto_20210306_1028'), ] operations = [ migrations.AlterField( model_name='book', name='age_group', field=models.CharField(choices=[(0, '0+'), (1, '7+'), (2, '13+'), (3, '18+')], max_length=5), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,539
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0010_auto_20210302_0810.py
# Generated by Django 3.1.6 on 2021-03-02 08:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0009_delete_userprofile'), ] operations = [ migrations.AlterField( model_name='book', name='pdf_file', field=models.FileField(default=True, upload_to='media'), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,540
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/models.py
from django.db import models from django.contrib.auth.models import User from languages.fields import LanguageField from PIL import Image GROUP_CHOICES = ( ("0", '0+'), ("1", '7+'), ("2", '13+'), ("3", '18+') ) # Create your models here. class Book(models.Model): title = models.CharField(max_length=40) author = models.CharField(max_length=30) description = models.TextField() category = models.CharField(max_length=20) publish_year = models.CharField(max_length=5) language = LanguageField(max_length=40, default=False) age_group = models.CharField(max_length=5, choices=GROUP_CHOICES) downloaded_times = models.IntegerField() rate = models.FloatField() rate_times = models.IntegerField() rate_total = models.FloatField() book_image = models.ImageField(upload_to='book_cover_image', default="image.png") pdf_file = models.FileField(default=True, upload_to='media') def __str__(self): return f"{self.title}|-|{self.category}|-|{self.author}" def save(self): super().save() img = Image.open(self.book_image.path) if img.height>300 or img.width>300: output_size=(300,300) img.thumbnail(output_size) img.save(self.book_image.path)
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,541
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0006_userprofile_avatar.py
# Generated by Django 3.1.6 on 2021-03-01 12:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('books', '0005_auto_20210301_1143'), ] operations = [ migrations.AddField( model_name='userprofile', name='avatar', field=models.ImageField(default='image.png', upload_to='user_avatar'), ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,542
VladislavJanibekyan/Online_Library
refs/heads/main
/online_library/books/migrations/0009_delete_userprofile.py
# Generated by Django 3.1.6 on 2021-03-01 14:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0008_auto_20210301_1240'), ] operations = [ migrations.DeleteModel( name='UserProfile', ), ]
{"/online_library/registration/forms.py": ["/online_library/registration/models.py"], "/online_library/registration/views.py": ["/online_library/registration/forms.py", "/online_library/registration/models.py"], "/online_library/books/views.py": ["/online_library/books/models.py"], "/online_library/books/urls.py": ["/online_library/books/views.py"]}
47,543
psahithireddy/BrickBreaker
refs/heads/main
/powerups.py
import input #fix bg powerups and ball trajectory by 1 :) import os from colorama import init, Fore, Back, Style import numpy as np import screen import utils import math import time class Powerup(): def __init__(self,ele,types,x,y): self._icon=ele self._type=types self.active=0 self.x_pos=x self.y_pos=y self.hit=0 #grabbed self.vel=0 self.x_vel=0 self.deactive=0 self.pypos=y self.inlife=0 self.starttime=0 self.currenttime=0 def clear(self): utils.the_screen._grid[self.y_pos][self.x_pos]=" " #print(Back.GREEN,self.pypos) def withwall(self): if self.x_coordinate+self.x_vel<=1 or self.x_coordinate+self.x_vel>=98: self.x_vel =self.x_vel*-1 elif self.y_coordinate+self.y_vel<=1: self.y_vel =self.y_vel*-1 #with bottom wall def print_powerup(self): self.currenttime=time.time() self.ballcollision() self.pypos=self.y_pos self.y_pos+=self.vel #self.x_pos+=self.x_vel self.paddlecollision() if self.hit==1 or self.hit==2: utils.remtime= 35 - int(self.currenttime - self.starttime) pos=27 if self.inlife == utils.the_ball.getlives() and self.currenttime - self.starttime <= 35 : if self.hit==1: #utils.the_screen.score(10) self.powerupact(self._type) self.hit=2 else: #utils.the_screen.score(-5) self.powerupdeact(self._type) self.hit=3 else: pos=29 if self.y_pos<pos : utils.the_screen._grid[self.pypos][self.x_pos]=" " utils.the_screen._grid[self.y_pos][self.x_pos]=self._icon if self.y_pos==28: utils.the_screen._grid[self.y_pos][self.x_pos]=" " def ballcollision(self): if utils.the_ball.get_x()==self.x_pos and utils.the_ball.get_y()==self.y_pos: self.y_pos-=5 self.vel=1 self.x_vel=utils.the_ball.x_vel self.x_pos+=self.x_vel def paddlecollision(self): for i in range(5): if self.x_pos==utils.the_paddle.get_x()+i and self.y_pos==utils.the_paddle.get_y(): #activate powerup based on type #get current life os.system('aplay -q ./sound/powerclaim.wav&') self.starttime=time.time() self.inlife=utils.the_ball.getlives() self.hit=1 self._icon=" " def powerupact(self,typee): self.active=1 if typee==1: utils.the_screen.poweru="EXPAND PADDLE" elif typee==2: utils.the_screen.poweru="SHRINK PADDLE" elif typee==3: utils.the_screen.poweru="FAST BALL" elif typee==4: utils.the_screen.poweru="PADDLE GRAB" elif typee==5: utils.the_screen.poweru="THROUGH BALL" elif typee==6: utils.the_screen.poweru="SHOOTING PADDLE" elif typee==7: utils.the_screen.poweru="FIREBALL" def powerupdeact(self,typee): utils.remtime=0 self.active=0 self.deactive=1 utils.the_screen.poweru=" " def powersdown(self): if self.active==0: self.y_pos+=1
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,544
psahithireddy/BrickBreaker
refs/heads/main
/elements.py
import input import os import time from colorama import init, Fore, Back, Style import numpy as np import screen import utils import random class element(): #element is 2d array, can be ball or paddle def __init__(self, element, x , y): self.x_coordinate = x self.y_coordinate = y self._height=len(element) self._width=len(element[0]) self._shape=element #shape of paddle and ball def change_x(self,x): #collision with left wall if self.x_coordinate<=2: self.x_coordinate=3 #collision with right wall elif self.x_coordinate>=98-self._width: self.x_coordinate=97-self._width else: self.x_coordinate += x def change_y(self,y): if self.y_coordinate<=1: self.y_coordinate=1 elif self.y_coordinate>=29: self._minus+=1 else: self.y_coordinate+=y def get_y(self): return self.y_coordinate def get_x(self): return self.x_coordinate def print_element(self): #shrink paddle if utils.power1.active == 1: paddle2=[['=',"=","="],[' ','=',' ']] self.clear() utils.the_paddle._width=3 utils.the_paddle._len=3 self._shape=paddle2 #expand paddle elif utils.power.active == 1: paddle1=[['=',"=",'=','=','=',"=","="],[' ',"=","=","=",'=','=',' ']] self.clear() utils.the_paddle._width=7 utils.the_paddle._len=7 self._shape=paddle1 elif utils.power5.active == 1: paddle4=[['T','=','=',"=","T"],[' ','=','=','=',' ']] self.clear() utils.the_paddle._width=5 utils.the_paddle._len=5 self._shape=paddle4 else: paddle3=[['=','=','=',"=","="],[' ','=','=','=',' ']] self.clear() utils.the_paddle._width=5 utils.the_paddle._len=5 self._shape=paddle3 for i in range(self._width): for j in range(self._height): utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] def clear(self): for i in range(self._width): for j in range(self._height): utils.the_screen._grid[j+self.y_coordinate][i+ self.x_coordinate]=" " #polymorhpism class Paddle(element): def __init__(self,ele,x,y,leng): self._len=leng super().__init__(ele,x,y) class Ball(element): def __init__(self,ele,x,y,lives): self._currentlives=lives self.x_vel=0 self.y_vel=1 self.start=0 super().__init__(ele,x,y) def xvel(self): return self.x_vel def yvel(self): return self.y_vel def shoot(self): self.start=1 def start(self): return self.start def resetlives(self): self._currentlives=5 def declives(self,lif): self._currentlives-=lif def getlives(self): return self._currentlives def withwall(self): if self.x_coordinate<=1 or self.x_coordinate>=98: self.x_vel =self.x_vel*-1 elif self.y_coordinate<=1: self.y_vel =self.y_vel*-1 #with bottom wall elif self.y_coordinate>=29: self._currentlives-=1 if self._currentlives>0: #start on paddle self.x_vel=0 self.y_vel=1 self.x_coordinate=95+self.x_vel self.x_coordinate=utils.the_paddle.get_x()+3 self.y_coordinate=utils.the_paddle.get_y()-1 self.start=0 def withbrick(self): for i in range(30): if self.x_coordinate==utils.the_ball.get_x()+i and self.y_coordinate==utils.the_ball.get_y(): utils.the_screen._grid[self.y_coordinate][self.x_coordinate]="m" def withpaddle(self): #on first star for i in range(utils.the_paddle._len): if self.x_coordinate==utils.the_paddle.get_x()+i and self.y_coordinate==26: fallingbricks() self.y_vel*=-1 if utils.the_paddle._len == 5: self.x_vel+=(-2+i) elif utils.the_paddle._len == 3: self.x_vel+=(-1+i) elif utils.the_paddle._len == 7: self.x_vel+=(-3+i) if utils.power3.active==1: utils.the_ball.start=0 #print("yes") def static_ball(self): self.x_coordinate=utils.the_paddle.get_x()+2 self.y_coordinate=utils.the_paddle.get_y()-1 for i in range(self._width): for j in range(self._height): utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] def print_element(self): if utils.power2.active==1: if self.x_vel>=0: self.x_vel+=1 else: self.x_vel-=1 utils.power2.active=2 self.x_coordinate +=self.x_vel if self.x_coordinate<1: self.x_coordinate=4+self.x_vel #collision with right wall elif self.x_coordinate>98: if self.x_vel>3: self.x_vel=3 elif self.x_vel<-3: self.x_vel=-3 self.x_coordinate=95+self.x_vel #since we are going from botton to top self.y_coordinate -=self.y_vel if self.y_coordinate<1: self.y_coordinate=1-self.y_vel self.withwall() self.withpaddle() #self.withbrick() #if self.x_coordinate>=99: #print(self.x_vel) utils.the_screen._grid[self.y_coordinate][self.x_coordinate]=self._shape[0][0] class Brick(element): def __init__(self,element,x,y,strength): super().__init__(element,x,y) self.strength = strength def print_element(self): for i in range(self._width): for j in range(self._height): # utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] if ((self.x_coordinate,self.y_coordinate) in utils.sidebricks) and self.strength > 0: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=" " self.strength=0 else: if self.strength > 0: if self.strength == 1: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.BLUE + self._shape[j][i]) if self.strength == 2: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.GREEN + self._shape[j][i]) if self.strength == 3: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.RED + self._shape[j][i]) if self.strength == np.inf: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.WHITE + self._shape[j][i]) else: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=' ' def collisionballandbrick(self): if utils.the_ball.y_coordinate == self.y_coordinate and utils.the_ball.x_coordinate == self.x_coordinate : if self.strength > 0: utils.the_ball.y_vel *= -1 if self.strength != np.inf: utils.the_screen.score(1) self.strength -= 1 if utils.power6.active==1: utils.the_screen.score(10) xco=self.x_coordinate yco=self.y_coordinate templist=[(xco-1,yco+1),(xco-1,yco),(xco,yco),(xco+1,yco),(xco+1,yco+1),(xco-1,yco-1),(xco+1,yco-1),(xco,yco+1),(xco,yco-1)] for i in templist: utils.sidebricks.append(i) class RainbowBrick(element): def __init__(self,element,x,y,strength): super().__init__(element,x,y) self.strength = strength self.collided = 0 def print_element(self): for i in range(self._width): for j in range(self._height): # utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] if (self.x_coordinate,self.y_coordinate) in utils.sidebricks and self.strength >0: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=" " self.strength=0 else: if self.collided==0: self.strength=random.randint(1,3) if self.strength > 0: if self.strength == 1: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.BLUE + self._shape[j][i]) if self.strength == 2: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.GREEN + self._shape[j][i]) if self.strength == 3: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.RED + self._shape[j][i]) if self.strength == np.inf: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=( Fore.WHITE + self._shape[j][i]) else: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=' ' def collisionballandbrick(self): if (utils.the_ball.y_coordinate == self.y_coordinate and utils.the_ball.x_coordinate == self.x_coordinate) or (utils.bullets.y_coordinate == self.y_coordinate and utils.bullets.x_coordinate == self.x_coordinate): if (utils.bullets.y_coordinate == self.y_coordinate and utils.bullets.x_coordinate == self.x_coordinate): utils.bullets.y_vel=0 utils.bullets._shape=" " if self.strength > 0: self.collided=1 utils.the_ball.y_vel *= -1 if self.strength != np.inf: utils.the_screen.score(1) self.strength -= 1 if utils.power6.active==1: utils.the_screen.score(10) xco=self.x_coordinate yco=self.y_coordinate templist=[(xco-1,yco+1),(xco-1,yco),(xco,yco),(xco+1,yco),(xco+1,yco+1),(xco-1,yco-1),(xco+1,yco-1),(xco,yco+1),(xco,yco-1)] for i in templist: utils.sidebricks.append(i) class ufo(element): def __init__(self,ele,x,y,leng): self._len=leng self.health=30 super().__init__(ele,x,y) def gethealth(self): return self.health def withball(self): #on first star for i in range(utils.the_ufo._len): if self.x_coordinate+i==utils.the_ball.get_x() and utils.the_ball.get_y()==5: #print(Back.WHITE + "hit") utils.the_ball.y_vel*=-1 self.health-=1 if self.health == 25: mylist=[1,2,3] for i in range(10,80): utils.brick6.append(Brick(utils.testbrick,i+5,10,random.choices(mylist,weights = [2,3,2], k = 1)[0])) utils.allnbricks.append(utils.brick6) if self.health == 20: mylist=[1,2,3] for i in range(10,80): utils.brick7.append(Brick(utils.testbrick,i+5,11,random.choices(mylist,weights = [2,2,2], k = 1)[0])) utils.allnbricks.append(utils.brick7) #produce bricks # if utils.the_paddle._len == 5: # self.x_vel+=(-2+i) # elif utils.the_paddle._len == 3: # self.x_vel+=(-1+i) # elif utils.the_paddle._len == 7: # self.x_vel+=(-3+i) # if utils.power3.active==1: # utils.the_ball.start=0 def print_element(self): self.withball() self.x_coordinate = utils.the_paddle.get_x() for i in range(self._width): for j in range(self._height): utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] class Bomb(element): def __init__(self,element,x,y): super().__init__(element,x,y) def setshoot(self): self.x_coordinate=utils.the_ufo.get_x() self.y_coordinate=utils.the_ufo.get_y() self.x_vel=0 self.y_vel=1 def print_element(self): self.y_coordinate+=self.y_vel self.with_paddle() for i in range(self._width): for j in range(self._height): if self.y_coordinate <=26: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] else: self.y_vel=0 utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=" " def with_paddle(self): for i in range(utils.the_paddle._len): if self.x_coordinate==utils.the_paddle.get_x()+i and self.y_coordinate ==26: os.system('aplay -q ./boss.mp3&') utils.the_ball.declives(1) class Bullets(element): def __init__(self,element,x,y): self.y_vel=0 super().__init__(element,x,y) def setshoot(self): self.x_coordinate=utils.the_paddle.get_x() self.y_coordinate=utils.the_paddle.get_y() self.x_vel=0 self.y_vel=1 def print_element(self): self.y_coordinate-=self.y_vel for i in range(self._width): for j in range(self._height): if self.y_coordinate <=26 and self.y_coordinate >1: utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=self._shape[j][i] else: self.y_vel=0 utils.the_screen._grid[j+self.y_coordinate][i+self.x_coordinate]=" " def fallingbricks(): timeup = utils.the_screen.gettime() for j in utils.allbricks: for i in j: i.clear() if i.y_coordinate >= 25 or i.y_coordinate <=0: utils.feltdown=1 else: if timeup > 10 and utils.level==0: i.y_coordinate+=1 elif timeup > 15 and utils.level==1: i.y_coordinate+=1 elif timeup > 20 and utils.level==2: i.y_coordinate+=1 #should see for level3 elif timeup > 25 and utils.level ==3: i.y_coordinate+=1 if (timeup > 10 and utils.level==0) or (timeup > 15 and utils.level==1) or (timeup > 20 and utils.level==2) or(timeup > 25 and utils.level ==3): utils.sidebricks=[] utils.power.powersdown() utils.power1.powersdown() utils.power2.powersdown() utils.power3.powersdown() utils.power4.powersdown() utils.power5.powersdown() utils.power6.powersdown() if utils.level == 3 and timeup > 25: for j in utils.allnbricks: for i in j: i.clear() if i.y_coordinate >= 25 or i.y_coordinate <=0: utils.feltdown=1 else: i.y_coordinate+=1
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,545
psahithireddy/BrickBreaker
refs/heads/main
/bricks.py
import input import os from colorama import init, Fore, Back, Style import numpy as np import screen import utils import math #-1 for non breakingbrick,1 class Bricks(): def __init__(self,ele,val,x,y,count): self._element=ele self.x_pos=x self.y_pos=y self._count=count self._val=val self._ballgrid=[[self._val for i in range (self._count)]for j in range (1)] self.hit=0 def clear(self): self._ballgrid=[[" " for i in range (self._count)]for j in range (1)] #self.print_brick() def print_brick(self): self.collision() for i in range(self._count): if self._ballgrid[0][i]=="m" and self._element!= "#": utils.the_screen._grid[self.y_pos][self.x_pos+i]=" " print(Back.RED+"lite") else: if self._element != "#": utils.the_screen._grid[self.y_pos][self.x_pos+i]=self._ballgrid[0][i] else: utils.the_screen._grid[self.y_pos][self.x_pos+i]=self._element self.hit=0 def collision(self): for i in range (self._count): #collision if utils.the_ball.get_x() == self.x_pos+i and utils.the_ball.get_y() == self.y_pos: #if already broke or not if self._ballgrid[0][i]!="m": #velocity part if utils.the_ball.xvel()!=0: _tan = math.atan(utils.the_ball.yvel()/utils.the_ball.xvel()) tan_deg=math.degrees(_tan) else: tan_deg=90 if utils.power4.active==0: if tan_deg<45 and tan_deg>-45 : if i==self._count-1: utils.the_ball.x_vel*=-1 elif self._ballgrid[0][i+1]=="m": utils.the_ball.x_vel*=-1 else: utils.the_ball.y_vel*=-1 elif (tan_deg>135 and tan_deg<=180) or(tan_deg>=-180 and tan_deg<-135): if i==0: utils.the_ball.x_vel*=-1 elif self._ballgrid[0][i-1]=="m": utils.the_ball.x_vel*=-1 else: utils.the_ball.y_vel*=-1 else: utils.the_ball.y_vel*=-1 if self._element=="B": #print(Back.RED+"yes") for j in range(self._count): for a in range (-1,2): for b in range (-1,2): if a==-1 and j==0: if utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] == "1": utils.bluebrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-28+j-1,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="2": for f in range(2): utils.greenbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-27+j-1,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="3": for f in range(3): utils.redbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-26+j-1,tan_deg) elif a==1 and j==self._count-1: if utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] == "1": utils.bluebrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-28+j+1,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="2": for f in range(2): utils.greenbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-27+j+1,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="3": for f in range(3): utils.redbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-26+j+1,tan_deg) elif a!=1 and b!=0: if a!=-1 and b!=0: if utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] == "1": utils.bluebrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-28+j,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="2": for f in range(2): utils.greenbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-27+j,tan_deg) elif utils.the_screen._grid[self.y_pos+b][self.x_pos+j+a] =="3": for f in range(3): utils.redbrick.decreasebrick(self.x_pos+j+a,self.y_pos+b,self.x_pos-26+j,tan_deg) elif a==0 and b==0: self.decreasebrick(self.x_pos+j+a,self.y_pos+b,j,tan_deg) else: self.decreasebrick(self.x_pos+i,self.y_pos,i,tan_deg) else: if self._element !="#": utils.the_screen._grid[self.y_pos][self.x_pos+i]=" " self._ballgrid[0][i]="m" #else: #utils.the_ball.y_vel*=-1 def decreasebrick(self,x,y,i,tan_deg): if self._element == "#": utils.the_screen._grid[y][x]="#" self._ballgrid[0][i]="#" if utils.power4.active==0: if self.hit == 0: if tan_deg<45 and tan_deg>-45: utils.the_ball.x_vel*=-1 elif (tan_deg>135 and tan_deg<=180) or(tan_deg>=-180 and tan_deg<-135) : utils.the_ball.x_vel*=-1 else: utils.the_ball.y_vel*=-1 self.hit=1 #print(Back.RED+"yes") else: #utils.the_ball.y_vel*=-1 if self._element == 1 and self._ballgrid[0][i] !="m": utils.the_screen.score(1) self._ballgrid[0][i]="m" elif self._element == 2 and self._ballgrid[0][i] !="m": self._ballgrid[0][i]-=1 if self._ballgrid[0][i]==0: self._ballgrid[0][i]="m" if i!=(31-27) and i!=(36-27) and i!=(32-27) and i!=(38-27) : utils.the_screen.score(1) else: self._ballgrid[0][i]=-1 elif self._element == 3 and self._ballgrid[0][i] !="m": self._ballgrid[0][i]-=1 if self._ballgrid[0][i]==0: self._ballgrid[0][i]="m" if i!=(30-26) and i!=(40-26)and i!=(28-26): utils.the_screen.score(1) else: self._ballgrid[0][i]=-1 #for each B removes it elif self._element == "B" and self._ballgrid[0][i] !="m": self._ballgrid[0][i]="m" if self._ballgrid[0][i]!="m": utils.the_screen._grid[y][x]=self._ballgrid[0][i] else: utils.the_screen._grid[y][x]=" " class Bluebricks(Bricks): def __init__(self,count,val,xco,yco,level): print(Back.WHITE+"initialised") #self._count=count super().__init__(val,val,xco,yco,count) class Greenbricks(Bricks): def __init__(self,count,val,xco,yco): super().__init__(val,val,xco,yco,count) class Redbricks(Bricks): def __init__(self,count,val,xco,yco): super().__init__(val,val,xco,yco,count) class Rockbricks(Bricks): def __init__(self,count,x,y,val): super().__init__(val,-1,x,y,1) class Explodebricks(Bricks): def __init__(self,count,x,y): self.typeo=1 super().__init__("B","B",x,y,count)
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,546
psahithireddy/BrickBreaker
refs/heads/main
/screen.py
import input import os from colorama import Fore, Back, Style import numpy as np import utils class Screen(): def __init__(self,height,width): self._height=height self._width=width self._grid=[[" "for i in range(self._width)] for j in range(self._height)] self.upperwall() self.lowerwall() self.sidewalls() self._score=0 self._time=0 self.poweru=" " #print(self._grid.shape) def clear(self): self._grid=[[" "for i in range(self._width)] for j in range(self._height)] def score(self,s): self._score +=s def gettime(self): return self._time def settime(self,tim): self._time=tim def getscore(self): return self._score def getpixel(self,x,y): return self._grid[y][x] def upperwall(self): for i in range(self._width): self._grid[0][i]="#" def lowerwall(self): for i in range(self._width): self._grid[self._height-1][i]="#" def sidewalls(self): for i in range(self._height): self._grid[i][0]="#" self._grid[i][self._width-1]="#" def print_screen(self): print (Fore.YELLOW + "CONTROLS : q-quit a-left d-right s-shoot") print(Fore.WHITE+"Powerups are lost if life is lost or 15 seconds are passed") print(Fore.GREEN + "LIVES",utils.the_ball._currentlives ," ","SCORE:",self._score," ","TIME:",self.gettime()) print("POWERUP: ",self.poweru," ","TIME REMAINING : ",utils.remtime) print("LEVEL: ",utils.level) if utils.level==3: print("UFO HEALTH : ",utils.the_ufo.gethealth()) for i in range(self._height): k=[] for j in range(self._width): k.append(Fore.BLUE + self._grid[i][j] + Style.RESET_ALL) print(Fore.BLUE+''.join(k)+Style.RESET_ALL) #s1=Screen(30,100) #s1.print_screen
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,547
psahithireddy/BrickBreaker
refs/heads/main
/utils.py
from screen import * from elements import * from colorama import Fore from bricks import * from powerups import * import random remtime=0 sidebricks=[] feltdown=0 level=0 allnbricks=[] #the_screen1=Screen(30,100) the_screen=Screen(30,100) paddle=[['=','=','=',"=","="],[' ','=','=','=',' ']] the_paddle=Paddle(paddle,3,26,5) ufo1=[["@","@","@","@","@"],["|","U","U","U","|"]] the_ufo = ufo(ufo1,3,4,5) bombstr=[["!"]] bomb=Bomb(bombstr,3,4) #expand paddle power=Powerup("U",1,34,10) #shrink paddle power1=Powerup("V",2,30,10) #fastball power2=Powerup("W",3,35,10) #paddlegrab power3=Powerup("X",4,32,10) #through ball power4=Powerup("Y",5,31,10) #shooting paddle power5=Powerup("Z",6,38,10) power6=Powerup("T",7,20,10) ball=[["O"]] the_ball=Ball(ball,3,25,5)#same at paddle position thebull=[["^"]] bullets=Bullets(thebull,3,5) global allbricks testbrick = [["#"]] brick1 = [] brick2 = [] brick3 = [] brick4 = [] rainbow = [] allbricks=[brick1,brick2,brick3,brick4,rainbow] mylist=[1,2,3,np.inf] for i in range(20,60): brick1.append(Brick(testbrick,i+5,10,random.choices(mylist,weights = [3,2,2,1], k = 1)[0])) brick2.append(Brick(testbrick,i+5,14,random.choices(mylist,weights = [2,3,2,2], k = 1)[0])) brick3.append(Brick(testbrick,i+5,13,random.choices(mylist,weights = [1,2,3,1], k = 1)[0])) brick4.append(Brick(testbrick,i+5,12,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) rainbow.append(RainbowBrick(testbrick,i+5,16,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) expbricks1=Explodebricks(6,40,9) expbricks2=Explodebricks(6,60,7) #bluebrick._ballgrid[0][10]="y" def buildbricks(): if utils.level == 1: brick1 = [] brick2 = [] brick3 = [] brick4 = [] rainbow = [] mylist=[1,2,3,np.inf] for i in range(20,60): brick1.append(Brick(testbrick,i+5,6,random.choices(mylist,weights = [3,2,2,1], k = 1)[0])) brick2.append(Brick(testbrick,i+5,7,random.choices(mylist,weights = [2,3,2,2], k = 1)[0])) brick3.append(Brick(testbrick,i+5,8,random.choices(mylist,weights = [1,2,3,1], k = 1)[0])) brick4.append(Brick(testbrick,i+5,9,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) rainbow.append(RainbowBrick(testbrick,i+5,10,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) rainbow.append(RainbowBrick(testbrick,i+5,5,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) allbricks=[brick1,brick2,brick3,brick4,rainbow] return allbricks elif utils.level == 2: brick1 = [] brick2 = [] brick3 = [] brick4 = [] rainbow = [] mylist=[1,2,3,np.inf] for i in range(20,70): brick1.append(Brick(testbrick,i+5,10,random.choices(mylist,weights = [3,2,2,1], k = 1)[0])) rainbow.append(RainbowBrick(testbrick,i+5,5,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) for i in range(30,60): brick2.append(Brick(testbrick,i+5,7,random.choices(mylist,weights = [2,3,2,2], k = 1)[0])) for i in range(40,50): brick3.append(Brick(testbrick,i+5,8,random.choices(mylist,weights = [1,2,3,1], k = 1)[0])) brick4.append(Brick(testbrick,i+5,9,random.choices(mylist,weights = [3,2,3,1], k = 1)[0])) allbricks=[brick1,brick2,brick3,brick4,rainbow] return allbricks elif utils.level == 3: brick1 = [] global brick6 brick6=[] global brick7 brick7=[] allbricks=[] for i in range(20,30): brick1.append(Brick(testbrick,i+5,10,np.inf)) allbricks=[brick1] return allbricks
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,548
psahithireddy/BrickBreaker
refs/heads/main
/game.py
import input import os import time #utils has screen and elements import utils from colorama import Fore,Back,Style #general info q to quit , a to left ,d to right (for paddle) #this would be the main file , so check it if __name__ == "__main__": #get input inp= input.Get() start=time.time() prin=0 def levelup(): utils.sidebricks=[] utils.the_ball.start=0 utils.the_ball.clear() utils.the_ball.static_ball() utils.the_ball.resetlives() global start1 start1=time.time() #print(Back.RED+"HI") for j in utils.allbricks: for i in j: i.clear() utils.allbricks=utils.buildbricks() while(1): if utils.the_ball.getlives()==0 or utils.level>3 or utils.feltdown == 1: os.system('clear') os.system('aplay -q ./sound/gameover.wav&') print(Fore.RED+"GAME ENDED") print(Fore.YELLOW + "YOU LOST :(") print(Fore.GREEN+"YOUR SCORE",utils.the_screen.getscore()) break inpt=input.input_to(inp) os.system('clear') #prints paddle and screen timed= utils.the_screen.gettime() if inpt == 'l' or inpt == "L" or timed > 400: utils.level+=1 if utils.level <= 2: os.system('aplay -q ./sound/levelup.wav&') if utils.level==3: os.system('aplay -q ./sound/bombdrop.wav&') levelup() #utils.render() utils.the_ball.clear() utils.the_paddle.print_element() if utils.level == 3: utils.the_ufo.clear() utils.the_ufo.print_element() if utils.level<= 3: for j in utils.allbricks: for i in j: i.clear() i.print_element() i.collisionballandbrick() # utils.redbrick.print_brick() # utils.greenbrick.print_brick() # utils.rockbrick1.print_brick() # utils.rockbrick2.print_brick() # utils.rockbrick3.print_brick() # utils.rockbrick4.print_brick() # utils.rockbrick5.print_brick() # utils.rockbrick6.print_brick() # utils.rockbrick7.print_brick() # utils.expbricks1.print_brick() # utils.expbricks2.print_brick() if inpt == 's' or inpt =='S': os.system('aplay -q ./sound/mixkit-game-ball-tap-2073.wav&') utils.the_ball.shoot() if utils.the_ball.start == 1: utils.the_ball.print_element() else: utils.the_ball.static_ball() utils.the_screen.print_screen() #utils.the_screen1.print_screen() #controls for game and paddle if inpt =='q' or inpt == "Q": os.system('clear') print(Fore.RED+"GAME TERMINATED") print(Fore.YELLOW+"YOUR SCORE : " , utils.the_screen.getscore()) break elif inpt == 'a' or inpt == "A": utils.the_paddle.clear() utils.the_paddle.change_x(-1) elif inpt == 'd' or inpt == "D": utils.the_paddle.clear() utils.the_paddle.change_x(1) #time current=time.time() if utils.level==0: utils.the_screen.settime(int(current-start)) else: utils.the_screen.settime(int(current-start1)) if utils.the_screen.gettime()%5 == 0 and utils.power5.active==1: utils.bullets.setshoot() starttime=time.time() utils.timrem=int(35-starttime) if utils.timrem<0: utils.timrem=0 if utils.power5.active==1: utils.bullets.clear() utils.bullets.print_element() if utils.level == 3: if utils.the_screen.gettime()%10 == 0: utils.bomb.setshoot() utils.bomb.clear() utils.bomb.print_element() for j in utils.allnbricks: for i in j: i.clear() i.print_element() i.collisionballandbrick() #powerups if utils.level <= 2: utils.power.print_powerup() utils.power1.print_powerup() utils.power2.print_powerup() utils.power3.print_powerup() utils.power4.print_powerup() utils.power5.print_powerup() if utils.level !=3: utils.power6.print_powerup() #win if utils.the_screen.getscore() >= 630 or utils.the_ufo.gethealth()<=0: os.system('clear') print(Fore.GREEN+"YOU WON :)") print(Fore.YELLOW+"YOUR SCORE : " , utils.the_screen.getscore()) break else: print("you are running a wrong file")
{"/powerups.py": ["/screen.py", "/utils.py"], "/elements.py": ["/screen.py", "/utils.py"], "/bricks.py": ["/screen.py", "/utils.py"], "/screen.py": ["/utils.py"], "/utils.py": ["/screen.py", "/elements.py", "/bricks.py", "/powerups.py"], "/game.py": ["/utils.py"]}
47,579
samcrang/project-euler
refs/heads/master
/euler/solution_005.py
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return int(a * b / gcd(a, b)) def answer(upper_bound): result = 1 for i in range(1, upper_bound + 1): result = lcm(result, i) return result def solution(): return answer(20)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,580
samcrang/project-euler
refs/heads/master
/tests/test_001.py
import unittest from euler.solution_001 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 233168) def test_example(self): self.assertEqual(answer(10), 23)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,581
samcrang/project-euler
refs/heads/master
/tests/test_004.py
import unittest from euler.solution_004 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 906609) def test_example(self): self.assertEqual(answer(2), 9009)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,582
samcrang/project-euler
refs/heads/master
/euler/solution_018.py
class Edge: def __init__(self, source, destination, weight): self.destination = destination self.source = source self.weight = weight class Vertex: def __init__(self, name): self.name = name class Graph: def __init__(self): self.vertices = [] self.edges = [] def add_vertex(self, vertex): self.vertices.append(vertex) def add_edge(self, source, destination, weight): self.edges.append(Edge(source, destination, weight)) def get_vertex(self, name): for v in self.vertices: if v.name == name: return v """ https://en.wikipedia.org/wiki/Bellman–Ford_algorithm """ def bellman_ford(graph, start, target): distance = {} predecessor = {} for v in graph.vertices: distance[v.name] = float("inf") predecessor[v.name] = None distance[start.name] = 0 for v in graph.vertices: for e in graph.edges: if distance[e.source.name] + e.weight < distance[e.destination.name]: distance[e.destination.name] = distance[e.source.name] + e.weight predecessor[e.destination.name] = e.source.name return distance[target.name] def tree_to_graph(tree): g = Graph() start = Vertex("start") end = Vertex("end") g.add_vertex(start) g.add_vertex(end) for r_idx, row in enumerate(tree): for c_idx, column in enumerate(row): if r_idx == 0: v = Vertex("{},{}".format(r_idx, c_idx)) g.add_vertex(v) g.add_edge(start, v, column * -1) else: v = Vertex("{},{}".format(r_idx, c_idx)) g.add_vertex(v) if c_idx == 0: parent = g.get_vertex("{},{}".format(r_idx-1, 0)) g.add_edge(parent, v, column *- 1) elif c_idx == len(row) - 1: parent = g.get_vertex("{},{}".format(r_idx-1, c_idx - 1)) g.add_edge(parent, v, column * -1) else: parent = g.get_vertex("{},{}".format(r_idx-1, c_idx)) g.add_edge(parent, v, column * -1) parent = g.get_vertex("{},{}".format(r_idx-1, c_idx-1)) g.add_edge(parent, v, column * -1) if r_idx == len(tree) - 1: g.add_edge(v, end, 0) return g def answer(tree): g = tree_to_graph(tree) return bellman_ford(g, g.get_vertex("start"), g.get_vertex("end")) * -1 def solution(): return answer([\ [75], \ [95,64], \ [17,47,82], \ [18,35,87,10], \ [20,4,82,47,65], \ [19,1,23,75,3,34], \ [88,2,77,73,7,63,67], \ [99,65,4,28,6,16,70,92], \ [41,41,26,56,83,40,80,70,33], \ [41,48,72,33,47,32,37,16,94,29], \ [53,71,44,65,25,43,91,52,97,51,14], \ [70,11,33,28,77,73,17,78,39,68,17,57], \ [91,71,52,38,17,14,91,43,58,50,27,29,48], \ [63,66,4,68,89,53,67,30,73,16,69,87,40,31], \ [4,62,98,27,23,9,70,98,73,93,38,53,60,4,23] \ ])
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,583
samcrang/project-euler
refs/heads/master
/tests/test_007.py
import unittest from euler.solution_007 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 104743) def test_example(self): self.assertEqual(answer(6), 13)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,584
samcrang/project-euler
refs/heads/master
/euler/solution_010.py
from .helpers.prime_sieve import prime_sieve def answer(number): return sum(prime_sieve(number)) def solution(): return answer(2000000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,585
samcrang/project-euler
refs/heads/master
/tests/test_005.py
import unittest from euler.solution_005 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 232792560) def test_example(self): self.assertEqual(answer(10), 2520)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,586
samcrang/project-euler
refs/heads/master
/tests/test_015.py
import unittest from euler.solution_015 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 137846528820) def test_example(self): self.assertEqual(answer(2, 2), 6)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,587
samcrang/project-euler
refs/heads/master
/euler/solution_007.py
from .helpers.prime_sieve import prime_sieve primes = prime_sieve(900000) def answer(position): return primes[position - 1] def solution(): return answer(10001)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,588
samcrang/project-euler
refs/heads/master
/euler/solution_015.py
import math """ We can write a path through our lattice using "N" or "E". The number of Ns is the height of the lattice, the number of Es is the width of the lattice. Every path through the same lattice has exactly the same number of Es and Ns. We can just find the number of anagrams in order to find the number of paths. https://en.wikipedia.org/wiki/Lattice_path#North-East_lattice_paths https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets """ def answer(width, height): return int(math.factorial(width + height)/(math.factorial(width) * math.factorial(height))) def solution(): return answer(20, 20)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,589
samcrang/project-euler
refs/heads/master
/tests/test_002.py
import unittest from euler.solution_002 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 4613732)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,590
samcrang/project-euler
refs/heads/master
/tests/test_006.py
import unittest from euler.solution_006 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 25164150) def test_example(self): self.assertEqual(answer(10), 2640)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,591
samcrang/project-euler
refs/heads/master
/tests/test_017.py
import unittest from euler.solution_017 import solution class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 21124)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,592
samcrang/project-euler
refs/heads/master
/euler/helpers/prime_sieve.py
import math """ https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def prime_sieve(size): sieve = [True] * size sieve[0] = False sieve[1] = False i = 2 while i < math.sqrt(size): if sieve[i]: j = int(math.pow(i, 2)) k = 0 while j < size: sieve[j] = False j = int(math.pow(i, 2)) + k * i k += 1 i = i + 1 primes = [] for x in enumerate(sieve): if x[1] == True: primes.append(x[0]) return primes
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,593
samcrang/project-euler
refs/heads/master
/euler/solution_002.py
def fib(): a, b = 1, 2 while True: yield a a, b = b, a + b def is_even(number): return number % 2 == 0 def answer(upper_bound): acc = 0 for x in fib(): if x < upper_bound: if is_even(x): acc = acc + x else: return acc def solution(): return answer(4000000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,594
samcrang/project-euler
refs/heads/master
/tests/test_016.py
import unittest from euler.solution_016 import solution class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 1366)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,595
samcrang/project-euler
refs/heads/master
/euler/solution_009.py
""" https://en.wikipedia.org/wiki/Coprime_integers#Generating_all_coprime_pairs """ def non_odd_odd_coprimes(): return coprimes(2, 1) def coprimes(m, n): queue = [] queue.append((m,n)) while True: node = queue.pop(0) m = node[0] n = node[1] branch_1 = (2 * m - n, m) branch_2 = (2 * m + n, m) branch_3 = (m + 2 * n, n) yield branch_1 yield branch_2 yield branch_3 queue.append(branch_1) queue.append(branch_2) queue.append(branch_3) """ https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple """ def primitive_triples(): for m, n in non_odd_odd_coprimes(): a = m**2 - n**2 b = 2 * m * n c = m**2 + n**2 yield (a, b, c) def answer(n): for x in primitive_triples(): summation = sum(x) if n % summation == 0: k = int(n / summation) a = (x[0] * k, x[1] * k, x[2] * k) return a[0] * a[1] * a[2] def solution(): return answer(1000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,596
samcrang/project-euler
refs/heads/master
/euler/solution_012.py
from collections import Counter from functools import reduce from .helpers.prime_sieve import prime_sieve primes = prime_sieve(9000) """ https://en.wikipedia.org/wiki/Trial_division """ def trial_division(n): if n < 2: return [] prime_factors = [] for p in primes: if p*p > n: break while n % p == 0: prime_factors.append(p) n //= p if n > 1: prime_factors.append(n) return prime_factors """ http://mathschallenge.net/library/number/number_of_divisors """ def count_divisors(n): c = Counter(trial_division(n)) return reduce(lambda x, y: x*(y[1]+1), c.items(), 1) def triangle_numbers(): pos = 1 i = 2 while True: yield pos pos += i i += 1 def solution(): for candidate in triangle_numbers(): divisors = count_divisors(candidate) if divisors > 500: return candidate candidate += 1
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,597
samcrang/project-euler
refs/heads/master
/euler.py
#!/usr/bin/env python3 import sys import importlib print(importlib.import_module( "euler.solution_%s" % sys.argv[1] ).solution())
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,598
samcrang/project-euler
refs/heads/master
/tests/test_003.py
import unittest from euler.solution_003 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 6857) def test_example(self): self.assertEqual(answer(13195), 29)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,599
samcrang/project-euler
refs/heads/master
/euler/solution_001.py
def divides_evenly_by_3_or_5(number): return number % 3 == 0 or number % 5 == 0 def answer(upper_bound): acc = 0 for x in range(1, upper_bound): if divides_evenly_by_3_or_5(x): acc = acc + x return acc def solution(): return answer(1000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,600
samcrang/project-euler
refs/heads/master
/tests/test_013.py
import unittest from euler.solution_013 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 5537376230)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,601
samcrang/project-euler
refs/heads/master
/euler/solution_004.py
import math def is_palindrome(number): return str(number) == str(number)[::-1] def answer(base_10_digits): best_candidate = 0 for i in reversed(range(int(math.pow(10, base_10_digits)))): for j in reversed(range(int(math.pow(10, base_10_digits)))): candidate = i * j if is_palindrome(candidate) and candidate > best_candidate: best_candidate = candidate return best_candidate def solution(): return answer(3)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,602
samcrang/project-euler
refs/heads/master
/euler/solution_006.py
""" https://en.wikipedia.org/wiki/Square_pyramidal_number n(n + 1)(2n + 1) /6 """ def sum_of_squares(n): return n * (n + 1) * (2 * n + 1) / 6 """ https://en.wikipedia.org/wiki/Triangular_number """ def sum(n): return n * (n + 1) / 2 def answer(n): return int(sum(n)**2 - sum_of_squares(n)) def solution(): return answer(100)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,603
samcrang/project-euler
refs/heads/master
/tests/test_067.py
import unittest from euler.solution_067 import solution, answer class TestCase(unittest.TestCase): def test_example(self): example = [\ [3], \ [7, 4], \ [2, 4, 6], \ [8, 5, 9, 3], \ ] self.assertEqual(answer(example), 23) def test_solution(self): self.assertEqual(solution(), 7273)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,604
samcrang/project-euler
refs/heads/master
/tests/test_008.py
import unittest from euler.solution_008 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 23514624000) def test_example(self): self.assertEqual(answer(4), 5832)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,605
samcrang/project-euler
refs/heads/master
/euler/solution_014.py
memo = {} def collatz(n): def _collatz(n): sequence = [] while True: n = int(n) if n in memo: sequence += memo[n] return sequence sequence.append(n) if n == 1: return sequence if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 memo[n] = _collatz(n) return memo[n] def answer(limit): best_candidate = (0, 0) for n in range(limit): length = len(collatz(n + 1)) if length > best_candidate[1]: best_candidate = (n + 1, length) return best_candidate[0] def solution(): return answer(1000000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,606
samcrang/project-euler
refs/heads/master
/tests/test_009.py
import unittest from euler.solution_009 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 31875000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,607
samcrang/project-euler
refs/heads/master
/tests/test_011.py
import unittest from euler.solution_011 import solution, answer class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 70600674)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,608
samcrang/project-euler
refs/heads/master
/tests/test_012.py
import unittest from euler.solution_012 import solution class TestCase(unittest.TestCase): def test_solution(self): self.assertEqual(solution(), 76576500)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,609
samcrang/project-euler
refs/heads/master
/euler/solution_003.py
import math from .helpers.prime_sieve import prime_sieve def answer(number): primes = prime_sieve(int(math.sqrt(number))) for x in reversed(primes): if number % x == 0: return x def solution(): return answer(600851475143)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,610
samcrang/project-euler
refs/heads/master
/euler/solution_016.py
from functools import reduce def answer(exponent): return reduce(lambda x, y: x + int(y), str(2**exponent), 0) def solution(): return answer(1000)
{"/tests/test_001.py": ["/euler/solution_001.py"], "/tests/test_004.py": ["/euler/solution_004.py"], "/tests/test_007.py": ["/euler/solution_007.py"], "/euler/solution_010.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_005.py": ["/euler/solution_005.py"], "/tests/test_015.py": ["/euler/solution_015.py"], "/euler/solution_007.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_002.py": ["/euler/solution_002.py"], "/tests/test_006.py": ["/euler/solution_006.py"], "/tests/test_016.py": ["/euler/solution_016.py"], "/euler/solution_012.py": ["/euler/helpers/prime_sieve.py"], "/tests/test_003.py": ["/euler/solution_003.py"], "/tests/test_009.py": ["/euler/solution_009.py"], "/tests/test_012.py": ["/euler/solution_012.py"], "/euler/solution_003.py": ["/euler/helpers/prime_sieve.py"]}
47,611
nowickam/time-series-classification
refs/heads/main
/src/utils.py
import pickle from copy import deepcopy import random def square(list): return map(lambda x: x ** 2, list) def save_obj(obj, name): with open('./drive/My Drive/AnC/' + name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name): with open('./drive/My Drive/BSc Thesis/AnC/' + name + '.pkl', 'rb') as f: return pickle.load(f) def random_step_single(weight): return weight + random.uniform(-1 - weight, 1 - weight) def input_random_step(input_matrix, dimensions, window): matrix = deepcopy(input_matrix) for i in range(dimensions): for j in range(window): matrix[i][i + dimensions * j] = random_step_single(matrix[i][i + dimensions * j]) return matrix
{"/main.py": ["/src/csv_reader.py", "/src/utils.py"], "/src/csv_reader.py": ["/src/config.py"]}
47,612
nowickam/time-series-classification
refs/heads/main
/main.py
import numpy as np from scipy.stats import logistic import random import math from time import time from sklearn.metrics import confusion_matrix, classification_report, accuracy_score import seaborn as sn import pandas as pd import matplotlib.pyplot as plt from src.csv_reader import read_csv, flatten_input from src.utils import random_step_single, input_random_step, square OUTPUT_NODES_NUMBER = 2 def f(weights, input): return logistic.cdf(weights.dot(input)) def apply_weights(input, weights): return f(weights, input) def apply_weights2(input, weights): return np.tanh(weights.dot(input)) def classify(series, weights, input_weights, output_weights, true_outcome): """ Classifies the whole series based on the sequence of window, where each window is classified separately and the most frequent class is chosen as the prediction """ results = np.zeros(OUTPUT_NODES_NUMBER) error = 0 for input in series: processed_input = apply_weights2(input, input_weights) map_output = apply_weights2(processed_input, weights) map_result = apply_weights(map_output, output_weights) error += evaluate(map_result, true_outcome) results = np.add(map_result, results) return results, error def evaluate(prediction, true_outcome): return sum(square(np.subtract(prediction, true_outcome))) def mse(weights, input_weights, output_weights, input_matrix, output_matrix): """ Counts the wrong predictions of the time series (naming does not indicate mean squared error) """ ret = 0 for i, series in enumerate(input_matrix): classification_result, error = classify(series, weights, input_weights, output_weights, output_matrix[i]) if np.argmax(np.array(output_matrix[i])) != np.argmax(np.array(classification_result)): ret += 1 return ret def mse2(weights, input_weights, output_weights, input_matrix, output_matrix): """ Add the difference between the desired probability for a class and the predicted of the time series (naming does not indicate mean squared error) """ ret = 0 for i, series in enumerate(input_matrix): classification_result, error = classify(series, weights, input_weights, output_weights, output_matrix[i]) ret += error return ret def change_weights(start_weights, start_input_weights, start_output_weights, start_energy, T, input_matrix, output_matrix, dimensions, window): """ Performs the change of the state by shuffling the weights of all matrices and checking the new energy """ new_weights = np.vectorize(random_step_single)(start_weights) new_output_weights = np.vectorize(random_step_single)(start_output_weights) new_input_weights = input_random_step(start_input_weights, dimensions, window) new_energy = mse(new_weights, new_input_weights, new_output_weights, input_matrix, output_matrix) diff = new_energy - start_energy if diff <= 0 or random.uniform(0, 1) < math.exp(-diff / T): return new_weights, new_input_weights, new_output_weights, new_energy else: return start_weights, start_input_weights, start_output_weights, start_energy def decrease_temp(T, cool_parameter): return T * cool_parameter def train(_file_type, _start_temp, _end_temp, _eq_number, _cool_parameter, _dimensions, _window, _stride): """ Performs the training of the model with the optimization by simulated annealing """ print("================") print("Train") input_matrix, output_matrix = read_csv('TRAIN', _file_type, _dimensions) input_matrix, _window = flatten_input(input_matrix, _window, _stride) # initialize the weights matrices weights = np.zeros((_dimensions, _dimensions)) output_weights = np.zeros((OUTPUT_NODES_NUMBER, _dimensions)) input_weights = np.zeros((_dimensions, (_window + 1) * _dimensions)) # initialize the temperatures start_temp = _start_temp end_temp = _end_temp T = start_temp energy = mse(weights, input_weights, output_weights, input_matrix, output_matrix) # initial states energies = [energy] best_energies = [energy] best_weights = weights best_input_weights = input_weights best_output_weights = output_weights best_energy = energy # initialize optimization hyperparameters eq_number = _eq_number cool_parameter = _cool_parameter wait = 0 start = time() # main optimization loop # minimizing the mse function by calling change_weights to find the best energy while T >= end_temp: print(T) # stay on the same temp (in the equilibrium) for eq_number iterations for _ in range(eq_number): weights, input_weights, output_weights, energy = change_weights( weights, input_weights, output_weights, best_energy, T, input_matrix, output_matrix, _dimensions, _window ) wait += 1 if energy < best_energy: best_energy = energy best_weights = weights best_input_weights = input_weights best_output_weights = output_weights wait = 0 energies.append(energy) best_energies.append(best_energy) T = decrease_temp(T, cool_parameter) end = time() processing_time = end - start print("Processing time: ", processing_time) plt.plot(energies, label="Energy") plt.plot(best_energies, label="Best energy") plt.xlabel("Epochs") plt.ylabel("Wrong predictions") plt.legend() plt.show() return best_weights, best_input_weights, best_output_weights, energies, best_energies def test(_file_type, best_weights, best_input_weights, best_output_weights, _dimensions, _window, _stride): """ Tests the output of the model by applying the pre-trained weights to the input and evaluating the loss function """ print("================") print("Test") input_matrix, output_matrix = read_csv('TEST', _file_type, _dimensions) input_matrix, _window = flatten_input(input_matrix, _window, _stride) predicted_output = [] for i, input in enumerate(input_matrix): result, error = classify(input, best_weights, best_input_weights, best_output_weights, output_matrix[i]) predicted_output.append(np.argmax(np.array(result))) np_output = np.array(output_matrix) true_output = np.argmax(np_output, axis=1) print(accuracy_score(true_output, predicted_output)) print(classification_report(true_output, predicted_output)) cm = confusion_matrix(true_output, predicted_output) df_cm = pd.DataFrame(cm, range(OUTPUT_NODES_NUMBER), range(OUTPUT_NODES_NUMBER)) sn.set(font_scale=1.4) # for label size sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}, cmap="YlGnBu") # font size plt.ylabel('True') plt.xlabel('Predicted') plt.show() def get_parameters(): """ Gets the parameters of the file and simulated annealing from the user """ print("================") print("File parameters\n") file_type = "" start_temp = end_temp = eq_number = cool_number = dimensions = window = stride = 0 while file_type.upper() != "LIGHTING" and file_type.upper() != "FACE": file_type = input("File (LIGHTING/FACE): ").upper() while dimensions < 3 or dimensions > 9: dimensions = int(input("Dimensions (d: 3 <= d <= 9 and d is an integer): ")) while window <= 0: window = float(input("Window length (w: 0 < w <= 1): ")) while stride <= 0: stride = int(input("Stride (s: s >= 1 and s is an integer): ")) print("================") print("Simulated annealing parameters\n") while start_temp <= 0: start_temp = float(input("Start temperature (ts: ts > 0): ")) while 0 >= end_temp or end_temp > start_temp: end_temp = float(input("End temperature (te: te > 0 and te < ts): ")) while eq_number <= 0: eq_number = int(input("Equilibrium number (e: e >= 1 and e is an integer): ")) while cool_number <= 0 or cool_number > 1: cool_number = float(input("Cooling parameter (c: 0 < c < 1): ")) return file_type, start_temp, end_temp, eq_number, cool_number, dimensions, window, stride if __name__ == '__main__': params = get_parameters() results = train(*params) test(params[0], *results[:3], *params[5:])
{"/main.py": ["/src/csv_reader.py", "/src/utils.py"], "/src/csv_reader.py": ["/src/config.py"]}
47,613
nowickam/time-series-classification
refs/heads/main
/src/config.py
LIGHTING_FILE = 'res/Lighting2/' FACE_FILE = 'res/FaceFour/'
{"/main.py": ["/src/csv_reader.py", "/src/utils.py"], "/src/csv_reader.py": ["/src/config.py"]}
47,614
nowickam/time-series-classification
refs/heads/main
/src/csv_reader.py
from src.config import FACE_FILE, LIGHTING_FILE import pandas as pd import numpy as np def read_csv(file_type, dataset, dimensions): """ Reads the csv, upsamples the lacking classes and returns the file divided into an input and output matrix """ global OUTPUT_NODES_NUMBER csvs = [] input = [] output = [] for i in range(1, dimensions + 1): if dataset == 'LIGHTING': csvs.append(pd.read_csv( LIGHTING_FILE + 'Lighting2_' + str(dimensions) + '_Dimensions/Lighting2Dimension' + str(i) + '_' + str( file_type).upper() + '.csv', sep=';', decimal=',')) OUTPUT_NODES_NUMBER = 2 elif dataset == 'FACE': csvs.append(pd.read_csv( FACE_FILE + 'FaceFour_' + str(dimensions) + '_Dimensions/FaceFourDimension' + str(i) + '_' + str( file_type).upper() + '.csv', sep=';', decimal=',')) OUTPUT_NODES_NUMBER = 4 max_count = max(csvs[0]['V1'].value_counts().tolist()) classes = csvs[0]['V1'].value_counts().keys().tolist() if file_type == 'TRAIN': for i in range(dimensions): for class_id in classes: class_list = csvs[i].loc[csvs[i]['V1'] == class_id].reset_index(drop=True) padding = max_count - len(class_list) for j in range(padding): csvs[i] = csvs[i].append(class_list.iloc[j % len(class_list)]) csvs[i] = csvs[i].reset_index(drop=True) new_idx = np.random.permutation(csvs[0].index) for i in range(dimensions): csvs[i] = csvs[i].reindex(new_idx).reset_index(drop=True) first_dim = True # input[dimension number][series number] for i, df in enumerate(csvs): input.append([]) for j, row in df.iterrows(): input[i].append([]) for element in row[1:].tolist(): input[i][j].append(element) if first_dim: output.append(row[0]) first_dim = False # input_matrix[dimension number][series number][element in the series] input_matrix = [] output_matrix = [] series_number = len(input[0]) elements_number = len(input[0][0]) for series_idx in range(series_number): # output output_value = output[series_idx] if dataset == 'LIGHTING': if output_value > 0: output_matrix.append([1, 0]) else: output_matrix.append([0, 1]) elif dataset == 'OLIVE' or dataset == 'ECG' or dataset == 'FACE': result = np.zeros(OUTPUT_NODES_NUMBER) result[int(output_value) - 1] = 1 output_matrix.append(result) # input input_matrix.append([]) for element_idx in range(elements_number): input_matrix[series_idx].append([]) for dim_idx in range(dimensions): input_matrix[series_idx][element_idx].append(input[dim_idx][series_idx][element_idx]) return input_matrix, output_matrix def flatten_input(input_matrix, _window, stride): """ Flattens a window of inputs into a 1-D array """ flattened_input = [] window = int(_window * len(input_matrix[0])) - 1 for i, series in enumerate(input_matrix): flattened_input.append([]) for j in range(0, len(input_matrix[0]) - window, stride): input = list(np.concatenate(series[j:j + window + 1])) flattened_input[i].append(input) return flattened_input, window
{"/main.py": ["/src/csv_reader.py", "/src/utils.py"], "/src/csv_reader.py": ["/src/config.py"]}
47,615
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/python/generateLightSettingFiles.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import argparse from houdiniDsGenerator import generate_houdini_ds light_settings = [ { 'name': 'Light', 'settings': [ { 'name': 'rpr:object:visibility:camera', 'ui_name': 'Camera Visibility', 'defaultValue': False, 'help': 'Used to show or hide an object from the camera.\\n' \ 'Disabling camera visibility is the most optimized way to hide ' \ 'an object from the camera but still have it cast shadows, ' \ 'be visible in reflections, etc.' }, { 'name': 'rpr:object:visibility:shadow', 'ui_name': 'Shadow Visibility', 'defaultValue': False, 'help': 'Shadow visibility controls whether to show or to hide shadows cast by ' \ 'the object onto other surfaces (including reflected shadows and shadows ' \ 'seen through transparent objects). You might need this option to hide shadows ' \ 'that darken other objects in the scene or create unwanted effects.' }, { 'name': 'rpr:object:visibility:reflection', 'ui_name': 'Reflection Visibility', 'defaultValue': True, 'help': 'Reflection visibility makes an object visible or invisible in reflections on ' \ 'specular surfaces. Note that hiding an object from specular reflections keeps ' \ 'its shadows (including reflected shadows) visible.' }, { 'name': 'rpr:object:visibility:glossyReflection', 'ui_name': 'Glossy Reflection Visibility', 'defaultValue': True }, { 'name': 'rpr:object:visibility:refraction', 'ui_name': 'Refraction Visibility', 'defaultValue': True, 'help': 'Refraction visibility makes an object visible or invisible when seen through ' \ 'transparent objects. Note that hiding an object from refractive rays keeps its ' \ 'shadows (including refracted shadows) visible.' }, { 'name': 'rpr:object:visibility:glossyRefraction', 'ui_name': 'Glossy Refraction Visibility', 'defaultValue': True }, { 'name': 'rpr:object:visibility:diffuse', 'ui_name': 'Diffuse Visibility', 'defaultValue': True, 'help': 'Diffuse visibility affects indirect diffuse rays and makes an object visible ' \ 'or invisible in reflections on diffuse surfaces.' }, { 'name': 'rpr:object:visibility:transparent', 'ui_name': 'Transparent Visibility', 'defaultValue': True }, { 'name': 'rpr:object:visibility:light', 'ui_name': 'Light Visibility', 'defaultValue': True }, { 'name': 'rpr:light:intensity:sameWithKarma', 'ui_name': 'Make Intensity Same With Karma', 'defaultValue': False } ] } ] def generate(install, generate_ds_files): if generate_ds_files: generate_houdini_ds(install, 'Light', light_settings)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,616
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/cmake/macros/testWrapper.py
# # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # # # Usage: testWrapper.py <options> <cmd> # # Wrapper for test commands which allows us to control the test environment # and provide additional conditions for passing. # # CTest only cares about the eventual return code of the test command it runs # with 0 being success and anything else indicating failure. This script allows # us to wrap a test command and provide additional conditions which must be met # for that test to pass. # # Current features include: # - specifying non-zero return codes # - comparing output files against a baseline # import argparse import os import platform import shutil import subprocess import sys import tempfile def _parseArgs(): parser = argparse.ArgumentParser(description='USD test wrapper') parser.add_argument('--requires-display', action='store_true', help='This test requires a display to run.') parser.add_argument('--stdout-redirect', type=str, help='File to redirect stdout to') parser.add_argument('--stderr-redirect', type=str, help='File to redirect stderr to') parser.add_argument('--diff-compare', nargs='*', help=('Compare output file with a file in the baseline-dir of the ' 'same name')) parser.add_argument('--files-exist', nargs='*', help=('Check that a set of files exist.')) parser.add_argument('--files-dont-exist', nargs='*', help=('Check that a set of files exist.')) parser.add_argument('--clean-output-paths', nargs='*', help=('Path patterns to remove from the output files being diff\'d.')) parser.add_argument('--post-command', nargs='*', help=('Command line action to run after running COMMAND.')) parser.add_argument('--pre-command', nargs='*', help=('Command line action to run before running COMMAND.')) parser.add_argument('--pre-command-stdout-redirect', type=str, help=('File to redirect stdout to when running PRE_COMMAND.')) parser.add_argument('--pre-command-stderr-redirect', type=str, help=('File to redirect stderr to when running PRE_COMMAND.')) parser.add_argument('--post-command-stdout-redirect', type=str, help=('File to redirect stdout to when running POST_COMMAND.')) parser.add_argument('--post-command-stderr-redirect', type=str, help=('File to redirect stderr to when running POST_COMMAND.')) parser.add_argument('--testenv-dir', type=str, help='Testenv directory to copy into test run directory') parser.add_argument('--baseline-dir', help='Baseline directory to use with --diff-compare') parser.add_argument('--expected-return-code', type=int, default=0, help='Expected return code of this test.') parser.add_argument('--env-var', dest='envVars', default=[], type=str, action='append', help='Variable to set in the test environment.') parser.add_argument('--pre-path', dest='prePaths', default=[], type=str, action='append', help='Path to prepend to the PATH env var.') parser.add_argument('--post-path', dest='postPaths', default=[], type=str, action='append', help='Path to append to the PATH env var.') parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output.') parser.add_argument('cmd', metavar='CMD', type=str, nargs='+', help='Test command to run') return parser.parse_args() def _resolvePath(baselineDir, fileName): # Some test envs are contained within a non-specific subdirectory, if that # exists then use it for the baselines nonSpecific = os.path.join(baselineDir, 'non-specific') if os.path.isdir(nonSpecific): baselineDir = nonSpecific return os.path.join(baselineDir, fileName) def _stripPath(f, pathPattern): import re import platform # Paths on Windows may have backslashes but test baselines never do. # On Windows, we rewrite the pattern so slash and backslash both match # either a slash or backslash. In addition, we match the remainder of # the path and rewrite it to have forward slashes so it matches the # baseline. repl = '' if platform.system() == 'Windows': def _windowsReplacement(m): return m.group(1).replace('\\', '/') pathPattern = pathPattern.replace('\\', '/') pathPattern = pathPattern.replace('/', '[/\\\\]') pathPattern = pathPattern + '(\S*)' repl = _windowsReplacement # Read entire file and perform substitution. with open(f, 'r+') as inputFile: data = inputFile.read() data = re.sub(pathPattern, repl, data) inputFile.seek(0) inputFile.write(data) inputFile.truncate() def _cleanOutput(pathPattern, fileName, verbose): if verbose: print "stripping path pattern {0} from file {1}".format(pathPattern, fileName) _stripPath(fileName, pathPattern) return True def _diff(fileName, baselineDir, verbose): # Use the diff program or equivalent, rather than filecmp or similar # because it's possible we might want to specify other diff programs # in the future. import platform if platform.system() == 'Windows': diff = 'fc.exe' else: diff = '/usr/bin/diff' cmd = [diff, _resolvePath(baselineDir, fileName), fileName] if verbose: print "diffing with {0}".format(cmd) # This will print any diffs to stdout which is a nice side-effect return subprocess.call(cmd) == 0 def _copyTree(src, dest): ''' Copies the contents of src into dest.''' if not os.path.exists(dest): os.makedirs(dest) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dest, item) if os.path.isdir(s): shutil.copytree(s, d) else: shutil.copy2(s, d) # Windows command prompt will not split arguments so we do it instead. # args.cmd is a list of strings to split so the inner list comprehension # makes a list of argument lists. The outer double comprehension flattens # that into a single list. def _splitCmd(cmd): return [arg for tmp in [arg.split() for arg in cmd] for arg in tmp] # subprocess.call returns -N if the process raised signal N. Convert this # to the standard positive error code matching that signal. e.g. if the # process encounters an SIGABRT signal it will return -6, but we really # want the exit code 134 as that is what the script would return when run # from the shell. This is well defined to be 128 + (signal number). def _convertRetCode(retcode): if retcode < 0: return 128 + abs(retcode) return retcode def _getRedirects(out_redir, err_redir): return (open(out_redir, 'w') if out_redir else None, open(err_redir, 'w') if err_redir else None) def _hasDisplay(): if platform.system() == 'Linux': linuxDisplayVar = 'DISPLAY' if (linuxDisplayVar not in os.environ or os.environ[linuxDisplayVar] == ''): return False return True def _runCommand(raw_command, stdout_redir, stderr_redir, env, expected_return_code): cmd = _splitCmd(raw_command) fout, ferr = _getRedirects(stdout_redir, stderr_redir) try: print "cmd: %s" % (cmd, ) retcode = _convertRetCode(subprocess.call(cmd, shell=False, env=env, stdout=(fout or sys.stdout), stderr=(ferr or sys.stderr))) finally: if fout: fout.close() if ferr: ferr.close() # The return code didn't match our expected error code, even if it # returned 0 -- this is a failure. if retcode != expected_return_code: if args.verbose: sys.stderr.write( "Error: return code {0} doesn't match " "expected {1} (EXPECTED_RETURN_CODE).".format(retcode, expected_return_code)) sys.exit(1) if __name__ == '__main__': args = _parseArgs() if args.diff_compare and not args.baseline_dir: sys.stderr.write("Error: --baseline-dir must be specified with " "--diff-compare.") sys.exit(1) if args.clean_output_paths and not args.diff_compare: sys.stderr.write("Error: --diff-compare must be specified with " "--clean-output-paths.") sys.exit(1) if args.requires_display and not _hasDisplay(): sys.stderr.write("Info: test will not be run, no display detected.") sys.exit(0) testDir = tempfile.mkdtemp() os.chdir(testDir) if args.verbose: print "chdir: {0}".format(testDir) # in case it's a maya test, set up a maya profile directory ($MAYA_APP_DIR) # that's empty, so we can ensure we test with a default profile - had some # crashes with 2017 when using an existing user profile (due to some # problems with color management settings) # Also, maya creates the $MAYA_APP_DIR on demand, so we don't need to bother # making the directory ourselves os.environ['MAYA_APP_DIR'] = os.path.join(testDir, 'maya_profile') # Copy the contents of the testenv directory into our test run directory so # the test has it's own copy that it can reference and possibly modify. if args.testenv_dir and os.path.isdir(args.testenv_dir): if args.verbose: print "copying testenv dir: {0}".format(args.testenv_dir) try: _copyTree(args.testenv_dir, os.getcwd()) except Exception as e: sys.stderr.write("Error: copying testenv directory: {0}".format(e)) sys.exit(1) # Add any envvars specified with --env-var options into the environment env = os.environ.copy() for varStr in args.envVars: if varStr == 'PATH': sys.stderr.write("Error: use --pre-path or --post-path to edit PATH.") sys.exit(1) try: k, v = varStr.split('=', 1) env[k] = v except IndexError: sys.stderr.write("Error: envvar '{0}' not of the form " "key=value".format(varStr)) sys.exit(1) # Modify the PATH env var. The delimiter depends on the platform. pathDelim = ';' if platform.system() == 'Windows' else ':' paths = env.get('PATH', '').split(pathDelim) paths = args.prePaths + paths + args.postPaths env['PATH'] = pathDelim.join(paths) # Avoid the just-in-time debugger where possible when running tests. env['ARCH_AVOID_JIT'] = '1' if args.pre_command: _runCommand(args.pre_command, args.pre_command_stdout_redirect, args.pre_command_stderr_redirect, env, 0) _runCommand(args.cmd, args.stdout_redirect, args.stderr_redirect, env, args.expected_return_code) if args.post_command: _runCommand(args.post_command, args.post_command_stdout_redirect, args.post_command_stderr_redirect, env, 0) if args.clean_output_paths: for path in args.clean_output_paths: for diff in args.diff_compare: _cleanOutput(path, diff, args.verbose) if args.files_exist: for f in args.files_exist: if args.verbose: print 'checking if {0} exists.'.format(f) if not os.path.exists(f): sys.stderr.write('Error: {0} does not exist ' '(FILES_EXIST).'.format(f)) sys.exit(1) if args.files_dont_exist: for f in args.files_dont_exist: if args.verbose: print 'checking if {0} does not exist.'.format(f) if os.path.exists(f): sys.stderr.write('Error: {0} does exist ' '(FILES_DONT_EXIST).'.format(f)) sys.exit(1) # If desired, diff the provided file(s) (must be generated by the test somehow) # with a file of the same name in the baseline directory if args.diff_compare: for diff in args.diff_compare: if not _diff(diff, args.baseline_dir, args.verbose): if args.verbose: sys.stderr.write('Error: diff for {0} failed ' '(DIFF_COMPARE).'.format(diff)) sys.exit(1) sys.exit(0)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,617
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/package/generatePackage.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import re import sys import shlex import shutil import tarfile import platform import argparse import subprocess import contextlib import multiprocessing def get_cpu_count(): try: return multiprocessing.cpu_count() except NotImplementedError: return 1 def format_multi_procs(numJobs): tag = '/M:' if platform.system() == 'Windows' else '-j' return "{tag}{procs}".format(tag=tag, procs=numJobs) def self_path(): path = os.path.dirname(sys.argv[0]) if not path: path = '.' return path @contextlib.contextmanager def current_working_directory(dir): curdir = os.getcwd() os.chdir(dir) try: yield finally: os.chdir(curdir) self_dir = os.path.abspath(self_path()) hdrpr_root_path = os.path.abspath(os.path.join(self_path(), '../../../../..')) parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-i', '--src_dir', type=str, default=hdrpr_root_path) parser.add_argument('-o', '--output_dir', type=str, default='.') parser.add_argument('-c', '--config', type=str, default='Release') parser.add_argument('--cmake_options', type=str, default='') parser.add_argument('--disable_auto_cleanup', default=False, action='store_true') args = parser.parse_args() output_dir = os.path.abspath(args.output_dir) package_dir = '_package' cmake_configure_cmd = ['cmake', '-DCMAKE_INSTALL_PREFIX='+package_dir, '-DDUMP_PACKAGE_FILE_NAME=ON'] cmake_configure_cmd += shlex.split(args.cmake_options) cmake_configure_cmd += ['..'] build_dir = 'build_generatePackage_tmp_dir' if not args.disable_auto_cleanup and os.path.isdir(build_dir): shutil.rmtree(build_dir) os.makedirs(build_dir, exist_ok=True) with current_working_directory(build_dir): configure_output = subprocess.check_output(cmake_configure_cmd).decode() print(configure_output) package_name = 'hdRpr' for line in reversed(configure_output.splitlines()): if line.startswith('-- PACKAGE_FILE_NAME'): package_name = line[len('-- PACKAGE_FILE_NAME: '):] break return_code = subprocess.call(['cmake', '--build', '.', '--config', args.config, '--target', 'install', '--', format_multi_procs(get_cpu_count())]) if return_code != 0: exit(return_code) with tarfile.open('tmpPackage.tar.gz', 'w:gz') as tar: tar.add(package_dir, package_name) output_package = os.path.join(output_dir, package_name+'.tar.gz') shutil.copyfile('tmpPackage.tar.gz', output_package) print('{} has been created'.format(os.path.relpath(output_package))) if not args.disable_auto_cleanup: shutil.rmtree(build_dir)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,618
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/cmake/macros/compilePython.py
# # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # # # Usage: compilePython source.py dest.pyc # # This program compiles python code, providing a reasonable # gcc-esque error message if errors occur. # # parameters: # src.py - the source file to report errors for # file.py - the installed location of the file # file.pyc - the precompiled python file from __future__ import print_function import sys import py_compile if len(sys.argv) < 4: print("Usage: {} src.py file.py file.pyc".format(sys.argv[0])) sys.exit(1) try: py_compile.compile(sys.argv[2], sys.argv[3], sys.argv[1], doraise=True) except py_compile.PyCompileError as compileError: exc_value = compileError.exc_value if compileError.exc_type_name == SyntaxError.__name__: # py_compile.compile stashes the type name and args of the exception # in the raised PyCompileError rather than the exception itself. This # is especially annoying because the args member of some SyntaxError # instances are lacking the source information tuple, but do have a # usable lineno. error = exc_value[0] try: linenumber = exc_value[1][1] line = exc_value[1][3] print('{}:{}: {}: "{}"'.format(sys.argv[1], linenumber, error, line)) except IndexError: print('{}: Syntax error: "{}"'.format(sys.argv[1], error)) else: print("{}: Unhandled compile error: ({}) {}".format( sys.argv[1], compileError.exc_type_name, exc_value)) sys.exit(1) except: exc_type, exc_value, exc_traceback = sys.exc_info() print("{}: Unhandled exception: {}".format(sys.argv[1], exc_value)) sys.exit(1)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,619
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/rprUsd/devicesConfiguration.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json from . import _rprUsd as RprUsd try: from hutil.Qt import QtCore, QtGui, QtWidgets except: from pxr.Usdviewq.qt import QtCore, QtGui, QtWidgets # from rpr import RprUsd _devices_info = None def _setup_devices_info(): global _devices_info if _devices_info == None: _devices_info = dict() for plugin_type in RprUsd.PluginType.allValues[1:]: try: devices_info = RprUsd.GetDevicesInfo(plugin_type) if devices_info.isValid: _devices_info[plugin_type] = devices_info except: pass class _GpuConfiguration: def __init__(self, is_enabled, gpu_info): self.is_enabled = is_enabled self.gpu_info = gpu_info def serialize(self): return { 'is_enabled': self.is_enabled, 'gpu_info': { 'index': self.gpu_info.index, 'name': self.gpu_info.name } } @staticmethod def deserialize(data): return _GpuConfiguration(is_enabled=data['is_enabled'], gpu_info=RprUsd.GPUDeviceInfo(data['gpu_info']['index'], data['gpu_info']['name'])) def __eq__(self, other): return self.is_enabled == other.is_enabled and \ self.gpu_info == other.gpu_info def __ne__(self, other): return not self == other def deepcopy(self): return _GpuConfiguration(is_enabled=self.is_enabled, gpu_info=self.gpu_info) class _CpuConfiguration: def __init__(self, num_active_threads, cpu_info): self.num_active_threads = num_active_threads self.cpu_info = cpu_info def serialize(self): return { 'num_active_threads': self.num_active_threads, 'cpu_info': { 'num_threads': self.cpu_info.numThreads } } @staticmethod def deserialize(data): return _CpuConfiguration(num_active_threads=data['num_active_threads'], cpu_info=RprUsd.CPUDeviceInfo(data['cpu_info']['num_threads'])) def __eq__(self, other): return self.num_active_threads == other.num_active_threads and \ self.cpu_info == other.cpu_info def __ne__(self, other): return not self == other def deepcopy(self): return _CpuConfiguration(num_active_threads=self.num_active_threads, cpu_info=self.cpu_info) class _PluginConfiguration: def __init__(self, plugin_type, cpu_config, gpu_configs): self.plugin_type = plugin_type self.cpu_config = cpu_config self.gpu_configs = gpu_configs @staticmethod def default(plugin_type, plugin_devices_info): gpu_configs = [_GpuConfiguration(is_enabled=idx==0, gpu_info=gpu_info) for idx, gpu_info in enumerate(plugin_devices_info.gpus)] cpu_config = _CpuConfiguration(num_active_threads=plugin_devices_info.cpu.numThreads if not gpu_configs else 0, cpu_info=plugin_devices_info.cpu) return _PluginConfiguration(plugin_type=plugin_type, cpu_config=cpu_config, gpu_configs=gpu_configs) def serialize(self): return { 'plugin_type': self.plugin_type.name, 'cpu_config': self.cpu_config.serialize(), 'gpu_configs': [gpu.serialize() for gpu in self.gpu_configs] } @staticmethod def deserialize(data): return _PluginConfiguration(plugin_type=RprUsd.PluginType.GetValueFromName(data['plugin_type']), cpu_config=_CpuConfiguration.deserialize(data['cpu_config']), gpu_configs=[_GpuConfiguration.deserialize(gpu_data) for gpu_data in data['gpu_configs']]) def __eq__(self, other): return self.plugin_type == other.plugin_type and \ self.cpu_config == other.cpu_config and \ self.gpu_configs == other.gpu_configs def __ne__(self, other): return not self == other def deepcopy(self): return _PluginConfiguration(plugin_type=self.plugin_type, cpu_config=self.cpu_config.deepcopy(), gpu_configs=[config.deepcopy() for config in self.gpu_configs]) class _Configuration: def __init__(self, context, plugin_configurations=list()): self.context = context self.plugin_configurations = plugin_configurations def is_outdated(self): for plugin_configuration in self.plugin_configurations: devices_info = _devices_info.get(plugin_configuration.plugin_type) if not devices_info: continue config_gpu_infos = [gpu_config.gpu_info for gpu_config in plugin_configuration.gpu_configs] if plugin_configuration.cpu_config.cpu_info == devices_info.cpu and \ config_gpu_infos == devices_info.gpus: continue return True return False @staticmethod def load(context, file): try: with open(file) as f: j = json.load(f) plugin_configurations = [_PluginConfiguration.deserialize(data) for data in j] configuration = _Configuration(context=context, plugin_configurations=plugin_configurations) if not configuration.is_outdated(): return configuration else: print('Hardware change detected. Falling back to default device configuration.') except IOError: pass except (ValueError, KeyError) as e: context.show_error('Failed to load device configuration', 'Error: "{}". Falling back to default device configuration.\n'.format(e.msg)) return _Configuration.default(context) def save(self, file): try: with open(file, 'w') as f: serialized_data = [config.serialize() for config in self.plugin_configurations] json.dump(serialized_data, f) return True except IOError as e: self.context.show_error('Failed to save device configuration', e.msg) return False @staticmethod def default(context): plugin_configurations = list() for plugin_type in [RprUsd.kPluginHybridPro, RprUsd.kPluginNorthstar, RprUsd.kPluginHybrid]: if plugin_type in _devices_info: plugin_configurations.append(_PluginConfiguration.default(plugin_type, _devices_info[plugin_type])) return _Configuration(context=context, plugin_configurations=plugin_configurations) def __eq__(self, other): return self.plugin_configurations == other.plugin_configurations def __ne__(self, other): return not self == other def deepcopy(self): return _Configuration(context=self.context, plugin_configurations=[config.deepcopy() for config in self.plugin_configurations]) BORDERSIZE=2 BORDERRADIUS=10 BORDERCOLOR = QtGui.QColor(42, 42, 42) class BorderWidget(QtWidgets.QFrame): def __init__(self, borderradius=BORDERRADIUS, bordersize=BORDERSIZE, bordercolor=BORDERCOLOR, parent=None): super(BorderWidget, self).__init__(parent) color = '{}, {}, {}'.format(bordercolor.red(), bordercolor.green(), bordercolor.blue()) self.setObjectName('BorderWidget') self.setStyleSheet('QFrame#BorderWidget {{ border-radius: {radius}px; border: {size}px; border-style: solid; border-color: rgb({color}) }}'.format(radius=borderradius, size=bordersize, color=color)) class _DeviceWidget(BorderWidget): on_change = QtCore.Signal() def __init__(self, cpu_config=None, gpu_config=None, parent=None): super(_DeviceWidget, self).__init__(parent=parent) self.cpu_config = cpu_config self.gpu_config = gpu_config if gpu_config: self.device_name_label = QtWidgets.QLabel(self) self.device_name_label.setText('GPU "{}"'.format(gpu_config.gpu_info.name)) self.main_layout = QtWidgets.QHBoxLayout(self) self.main_layout.addWidget(self.device_name_label) self.main_layout.addStretch() self.is_enabled_check_box = QtWidgets.QCheckBox(self) self.is_enabled_check_box.setChecked(gpu_config.is_enabled) self.is_enabled_check_box.stateChanged.connect(self.on_gpu_update) self.main_layout.addWidget(self.is_enabled_check_box) elif cpu_config: self.name_container_widget = QtWidgets.QWidget(self) self.name_container_layout = QtWidgets.QHBoxLayout(self.name_container_widget) self.name_container_layout.setContentsMargins(0, 0, 0, 0) self.name_label = QtWidgets.QLabel(self.name_container_widget) self.name_label.setText('CPU') self.name_container_layout.addWidget(self.name_label) self.name_container_layout.addStretch() is_cpu_enabled = cpu_config.num_active_threads > 0 self.is_enabled_check_box = QtWidgets.QCheckBox(self.name_container_widget) self.is_enabled_check_box.setChecked(is_cpu_enabled) self.is_enabled_check_box.stateChanged.connect(self.on_cpu_enabled_update) self.name_container_layout.addWidget(self.is_enabled_check_box) self.num_threads_container_widget = QtWidgets.QWidget(self) self.num_threads_container_layout = QtWidgets.QHBoxLayout(self.num_threads_container_widget) self.num_threads_container_layout.setContentsMargins(0, 0, 0, 0) self.num_threads_label = QtWidgets.QLabel(self.num_threads_container_widget) self.num_threads_label.setText('Number of Threads') self.num_threads_container_layout.addWidget(self.num_threads_label) self.num_threads_container_layout.addStretch() self.num_threads_spin_box = QtWidgets.QSpinBox(self.num_threads_container_widget) self.num_threads_spin_box.setValue(cpu_config.num_active_threads) self.num_threads_spin_box.setRange(1, cpu_config.cpu_info.numThreads) self.num_threads_spin_box.valueChanged.connect(self.on_cpu_num_threads_update) if not is_cpu_enabled: self.num_threads_container_widget.hide() self.num_threads_container_layout.addWidget(self.num_threads_spin_box) self.main_layout = QtWidgets.QVBoxLayout(self) self.main_layout.addWidget(self.name_container_widget) self.main_layout.addWidget(self.num_threads_container_widget) self.main_layout.setContentsMargins( self.main_layout.contentsMargins().left() // 2, self.main_layout.contentsMargins().top() // 4, self.main_layout.contentsMargins().right() // 2, self.main_layout.contentsMargins().bottom() // 4) def on_gpu_update(self, is_enabled): self.gpu_config.is_enabled = bool(is_enabled) self.on_change.emit() def on_cpu_enabled_update(self, is_enabled): if is_enabled: self.cpu_config.num_active_threads = self.cpu_config.cpu_info.numThreads self.num_threads_spin_box.setValue(self.cpu_config.num_active_threads) self.num_threads_container_widget.show() else: self.cpu_config.num_active_threads = 0 self.num_threads_container_widget.hide() self.on_change.emit() def on_cpu_num_threads_update(self, num_threads): self.cpu_config.num_active_threads = num_threads self.on_change.emit() class _PluginConfigurationWidget(BorderWidget): on_change = QtCore.Signal() def __init__(self, plugin_configuration, parent): super(_PluginConfigurationWidget, self).__init__(parent=parent) self.plugin_configuration = plugin_configuration self.main_layout = QtWidgets.QVBoxLayout(self) self.main_layout.setContentsMargins( self.main_layout.contentsMargins().left() // 2, self.main_layout.contentsMargins().top() // 2, self.main_layout.contentsMargins().right() // 2, self.main_layout.contentsMargins().bottom() // 2) self.plugin_type = plugin_configuration.plugin_type if self.plugin_type == RprUsd.kPluginHybridPro: plugin_qualities = 'HybridPro' elif self.plugin_type == RprUsd.kPluginNorthstar: plugin_qualities = 'Northstar' elif self.plugin_type == RprUsd.kPluginHybrid: plugin_qualities = 'Low-High Qualities' self.labels_widget = QtWidgets.QWidget(self) self.main_layout.addWidget(self.labels_widget) self.labels_widget_layout = QtWidgets.QHBoxLayout(self.labels_widget) self.labels_widget_layout.setContentsMargins(0, 0, 0, 0) self.plugin_qualities_label = QtWidgets.QLabel(self.labels_widget) self.plugin_qualities_label.setText(plugin_qualities) self.labels_widget_layout.addWidget(self.plugin_qualities_label) self.incomplete_config_label = QtWidgets.QLabel(self.labels_widget) self.incomplete_config_label.setStyleSheet('color: rgb(255,204,0)') self.incomplete_config_label.setText('Configuration is incomplete: no devices') self.labels_widget_layout.addWidget(self.incomplete_config_label) self.incomplete_config_label.hide() if plugin_configuration.cpu_config.cpu_info.numThreads: cpu_widget = _DeviceWidget(parent=self, cpu_config=plugin_configuration.cpu_config) cpu_widget.on_change.connect(self.on_device_change) self.main_layout.addWidget(cpu_widget) for gpu_config in plugin_configuration.gpu_configs: gpu_widget = _DeviceWidget(parent=self, gpu_config=gpu_config) gpu_widget.on_change.connect(self.on_device_change) self.main_layout.addWidget(gpu_widget) self.is_complete = True def on_device_change(self): self.is_complete = self.plugin_configuration.cpu_config.num_active_threads > 0 or \ any([gpu_config.is_enabled for gpu_config in self.plugin_configuration.gpu_configs]) if self.is_complete: self.incomplete_config_label.hide() else: self.incomplete_config_label.show() self.on_change.emit() class _DevicesConfigurationDialog(QtWidgets.QDialog): def __init__(self, configuration, show_restart_warning, is_modal): super(_DevicesConfigurationDialog, self).__init__() self.configuration = configuration self.initial_configuration = configuration.deepcopy() if self.configuration.context.parent: self.setParent(self.configuration.context.parent, self.configuration.context.parent_flags) self.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) self.setWindowTitle('RPR Render Devices') self.main_layout = QtWidgets.QVBoxLayout(self) self.main_layout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) self.plugin_configuration_widgets = list() for config in configuration.plugin_configurations: widget = _PluginConfigurationWidget(config, self) widget.on_change.connect(self.on_plugin_configuration_change) self.main_layout.addWidget(widget) self.plugin_configuration_widgets.append(widget) if show_restart_warning: self.restart_warning_label = QtWidgets.QLabel(self) self.restart_warning_label.setText('Changes will not take effect until the RPR renderer restarts.') self.restart_warning_label.setStyleSheet('color: rgb(255,204,0)') self.restart_warning_label.hide() self.main_layout.addWidget(self.restart_warning_label) else: self.restart_warning_label = None self.button_box = QtWidgets.QDialogButtonBox(self) self.save_button = self.button_box.addButton("Save", QtWidgets.QDialogButtonBox.AcceptRole) self.save_button.setEnabled(False) self.button_box.addButton("Cancel", QtWidgets.QDialogButtonBox.RejectRole) self.button_box.accepted.connect(self.on_accept) self.button_box.rejected.connect(self.on_reject) self.main_layout.addWidget(self.button_box) if is_modal: self.setModal(True) self.show() self.should_update_configuration = False def on_reject(self): self.close() def on_accept(self): self.should_update_configuration = True self.close() def on_plugin_configuration_change(self): is_save_enabled = all([widget.is_complete for widget in self.plugin_configuration_widgets]) and \ self.initial_configuration != self.configuration self.save_button.setEnabled(is_save_enabled) if self.restart_warning_label: if is_save_enabled: self.restart_warning_label.show() else: self.restart_warning_label.hide() def open_window(parent=None, parent_flags=QtCore.Qt.Widget, show_restart_warning=True, is_modal=False): _setup_devices_info() class Context: def __init__(self, parent, parent_flags): self.parent = parent self.parent_flags = parent_flags def show_error(title, text): msg = QtWidgets.QMessageBox() msg.setParent(self.parent, self.parent_flags) msg.setIcon(QtWidgets.QMessageBox.Critical) msg.setText(text) msg.setWindowTitle(title) msg.show() configuration_filepath = RprUsd.Config.GetDeviceConfigurationFilepath() configuration = _Configuration.load(Context(parent, parent_flags), configuration_filepath) dialog = _DevicesConfigurationDialog(configuration, show_restart_warning, is_modal) dialog.exec_() if dialog.should_update_configuration: return configuration.save(configuration_filepath) return False
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,620
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import re import hou import json import errno import shutil import zipfile from hutil.Qt import QtCore, QtGui, QtWidgets, QtUiTools from time import sleep from . materialLibraryClient import MatlibClient import MaterialX as mx maxElementCount = 10000 HELP_TEXT = ''' To import a material click on a corresponding swatch. The material is always imported as a separate "Material Library" LOP node. The importer always auto-assigns an imported material to the last modified prims of the selected LOP nodes. In this mode, the importer replaces the previously imported material with the new one, thus allowing to rapidly change materials. Use the text input widget at the bottom of the window to filter displayed materials. ''' class Cache: def __init__(self): self._categories = [] self._materials = [] self._material_thumbnails = {} # material id: (material, icon) def categories(self, matlib_client): if not self._categories: self._categories = matlib_client.categories.get_list(limit=maxElementCount) return self._categories def materials(self, matlib_client, category): if not self._materials: self.categories(matlib_client) # ensure categories are loaded self._materials = matlib_client.materials.get_list(limit=maxElementCount) category_id = None if category: for c in self._categories: if c['title'] == category: category_id = c['id'] return [m for m in self._materials if m['category'] == category_id] if category_id else self._materials def thumbnail_material(self, material_id): entry = self._material_thumbnails.get(material_id, None) return entry[0] if entry else None def thumbnail_icon(self, material_id): entry = self._material_thumbnails.get(material_id, None) return entry[1] if entry else None def set_thumbnail_icon(self, material, icon): self._material_thumbnails[material['id']] = (material, icon) cache = Cache() def build_mtlx_graph(library_node, mtlx_file): positionOffset = 3 positionStep = hou.Vector2(0.1, -1.5) parsed_nodes = {} def setParm(hou_node, input_name, input_type, value): if value is None: return t = type(value) if t == str and input_type == 'filename': for suffix in ('', '_string', '_filename'): parm = hou_node.parm(input_name) if parm: parm.set(os.path.dirname(mtlx_file).replace(os.path.dirname(hou.hipFile.path()), '$HIP') + '/' + value) break elif t == int or t == float or t == str or t == bool: for suffix in ('', '_integer', '_string', '_filename'): parm = hou_node.parm(input_name + suffix) if parm: parm.set(value) break elif t == mx.PyMaterialXCore.Color3 or t == mx.PyMaterialXCore.Color4: for suffix in ('', '_color3' if mx.PyMaterialXCore.Color3 else '_color4'): found = False parmr = hou_node.parm(input_name + suffix + 'r') parmg = hou_node.parm(input_name + suffix + 'g') parmb = hou_node.parm(input_name + suffix + 'b') if parmr and parmg and parmb: parmr.set(value[0]) parmg.set(value[1]) parmb.set(value[2]) found = True if t == mx.PyMaterialXCore.Color4: parma = hou_node.parm(input_name + suffix + 'a') if parma: parma.set(value[3]) if found: break elif t == mx.PyMaterialXCore.Vector2 or t == mx.PyMaterialXCore.Vector3 or t == mx.PyMaterialXCore.Vector4: for suffix in ('', '_vector2', '_vector3', '_vector4'): found = False parmx = hou_node.parm(input_name + 'x') parmy = hou_node.parm(input_name + 'y') if parmx and parmy: parmx.set(value[0]) parmy.set(value[1]) found = True if t == mx.PyMaterialXCore.Vector3: parmz = hou_node.parm(input_name + 'z') if parmz: parmz.set(value[2]) if t == mx.PyMaterialXCore.Vector4: parmw = hou_node.parm(input_name + 'w') if parmw: parmw.set(value[3]) if found: break elif t == mx.PyMaterialXCore.Matrix33: for i in range(9): parm = hou_node.parm(input_name + '_matrix33' + str(i + 1)) if parm: parm.set(value[int(i/3), i%3]) elif t == mx.PyMaterialXCore.Matrix44: for i in range(16): parm = hou_node.parm(input_name + '_matrix44' + str(i + 1)) if parm: parm.set(value[int(i/4), i%4]) def setSignature(hou_node, signature_string): parm = hou_node.parm('signature') if parm: parm.set(signature_string) def processNode(node, position, d=0): path = node.getNamePath() if path in parsed_nodes: hou_node = parsed_nodes[path] if hou_node.position()[0] >= position[0]: hou_node.setPosition(position + positionStep * d * 0.3) return hou_node hou_node = library_node.createNode('mtlx' + node.getCategory()) if not hou_node: return None hou_node.setName(node.getName().replace('_', '-'), unique_name=True) setSignature(hou_node, node.getType()) hou_node.setPosition(position + positionStep * d * 0.3) parsed_nodes[path] = hou_node nodes_in_layer = 0 for input in node.getInputs(): src_node = input.getConnectedNode() if src_node: hou_src_node = processNode(src_node, hou_node.position() - hou.Vector2(positionOffset, 0) + positionStep * nodes_in_layer, d + 1 if nodes_in_layer else d) if not hou_src_node: continue hou_src_node.setMaterialFlag(False) nodes_in_layer += 1 hou_node.setInput(hou_node.inputIndex(input.getName()), hou_src_node, 0) else: setParm(hou_node, input.getName(), input.getType(), input.getValue()) return hou_node doc = mx.createDocument() try: mx.readFromXmlFile(doc, mtlx_file) except: return None for node in doc.getNodes(): if node.getType() == 'material': position = hou.Vector2(0, 0) for existing_node in library_node.allNodes(): if existing_node != library_node and (existing_node.position() - position).length() < 0.00001: position += hou.Vector2(0, -10) return processNode(node, position) return None def recursive_mkdir(path): try: os.makedirs(path) except OSError as e: if errno.EEXIST != e.errno: raise def IsMouseOnWidget(widget): mouse_pos_global = QtGui.QCursor.pos() mouse_pos_local = widget.mapFromGlobal(mouse_pos_global) return widget.rect().contains(mouse_pos_local) def create_houdini_material_graph(material_name, mtlx_file): MATERIAL_LIBRARY_TAG = 'hdrpr_material_library_generated' selected_nodes = hou.selectedNodes() if selected_nodes: matlib_parent = selected_nodes[0].parent() else: matlib_parent = hou.node('/stage') if matlib_parent.type().name() == "materiallibrary" or matlib_parent.type().name() == "subnet": # call inside material library or subnet subnet_node = matlib_parent.createNode('subnet') subnet_node.deleteItems([subnet_node.node('subinput1')]) subnet_output_node = subnet_node.node('suboutput1') material_node = build_mtlx_graph(subnet_node, mtlx_file) subnet_output_node.setInput(0, material_node, 0) subnet_node.setMaterialFlag(True) subnet_node.setName(material_node.name(), unique_name=True) while True: for node in matlib_parent.allNodes(): if node != subnet_node and (node.position() - subnet_node.position()).length() < 0.00001: subnet_node.setPosition(subnet_node.position() + hou.Vector2(0, -1.5)) break else: break return matlib_node = matlib_parent.createNode('materiallibrary') matlib_node.setName(material_name, unique_name=True) matlib_node.setComment(MATERIAL_LIBRARY_TAG) build_mtlx_graph(matlib_node, mtlx_file) if len(selected_nodes) == 0: matlib_node.setSelected(True, clear_all_selected=True) material_assignment = [] for node in selected_nodes: if isinstance(node, hou.LopNode): material_assignment.extend(map(str, node.lastModifiedPrims())) if material_assignment: material_assignment = ' '.join(material_assignment) matlib_node.parm('assign1').set(True) matlib_node.parm('geopath1').set(material_assignment) viewer_node = matlib_node.network().viewerNode() # Ideally, we want to connect our material library node directly to the selected one, if len(selected_nodes) == 1: connect_node = selected_nodes[0] else: # but in case more than one node selected, we need to traverse the whole graph and find out the deepest node. # There is a lot of corner cases. It's much safer and cleaner to connect our node to the viewer node (deepest node with display flag set on). # Though, this can be revisited later. connect_node = viewer_node # TODO: consider making this behavior optional: what if the user wants to create few material at once? # Remove previously created material - this activates rapid change of material when scrolling through the library widget if connect_node.comment() == MATERIAL_LIBRARY_TAG and \ connect_node.parm('geopath1').evalAsString() == material_assignment: connect_node.destroy() viewer_node = matlib_node.network().viewerNode() connect_node = viewer_node # Insert our new node into existing connections for connection in connect_node.outputConnections(): if connection.outputNode().comment() == MATERIAL_LIBRARY_TAG: # TODO: consider making this behavior optional: what if the user wants to create few material at once? # Remove previously created material - this activates rapid change of material when scrolling through the library widget for subconnection in connection.outputNode().outputConnections(): subconnection.outputNode().setInput(subconnection.inputIndex(), matlib_node) connection.outputNode().destroy() else: connection.outputNode().setInput(connection.inputIndex(), matlib_node) matlib_node.setInput(0, connect_node) matlib_node.moveToGoodPosition() if connect_node == matlib_node.network().viewerNode(): matlib_node.setDisplayFlag(True) def add_mtlx_includes(materialx_file_path): # we need to insert include to downloaded file include_file_name = "standard_surface.mtlx" library_root = os.path.join(os.path.dirname(materialx_file_path), "..", "..") # local library structure is like RPRMaterialLibrary/Materials/some_material, so we need copy common include file to root if needed include_file_path = os.path.join(library_root, include_file_name) if not os.path.isfile(include_file_path): script_dir = os.path.realpath(os.path.dirname(__file__)) shutil.copyfile(os.path.join(script_dir, include_file_name), include_file_path) with open(materialx_file_path, "r") as mtlx_file: lines = mtlx_file.readlines() lines.insert(2, "\t<xi:include href=\"" + os.path.join("..", "..", include_file_name) + "\" />\n") # we need to include relative path with open(materialx_file_path, "w") as mtlx_file: mtlx_file.write("".join(lines)) PREVIEW_SIZE = 200 class LibraryListWidget(QtWidgets.QListWidget): def __init__(self, parent): super(LibraryListWidget, self).__init__(parent) self.setFrameShape(QtWidgets.QFrame.NoFrame) self.setDropIndicatorShown(False) self.setAcceptDrops(True) self.setIconSize(QtCore.QSize(PREVIEW_SIZE, PREVIEW_SIZE)) self.setFlow(QtWidgets.QListView.LeftToRight) self.setResizeMode(QtWidgets.QListView.Adjust) self.setSpacing(5) self.setViewMode(QtWidgets.QListView.IconMode) self.setWordWrap(True) self.setSelectionRectVisible(False) self.setAttribute(QtCore.Qt.WA_Hover) self._previewWindow = parent._fullPreviewWindow def mouseMoveEvent(self, mouse_event): if self._previewWindow.isVisible(): if not IsMouseOnWidget(self): self._previewWindow.hide() else: self._previewWindow.mouseMoveEvent(mouse_event) super(LibraryListWidget, self).mouseMoveEvent(mouse_event) def leaveEvent(self, event): if self._previewWindow.isVisible(): if not IsMouseOnWidget(self): self._previewWindow.hide() super(LibraryListWidget, self).leaveEvent(event) def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): e.accept() class ThumbnailLoader(QtCore.QRunnable): class ThumbnailLoaderSignals(QtCore.QObject): finished = QtCore.Signal(object) def __init__(self, matlib_client, material): super(ThumbnailLoader, self).__init__() self._matlib_client = matlib_client self._material = material self.signals = ThumbnailLoader.ThumbnailLoaderSignals() script_dir = os.path.realpath(os.path.dirname(__file__)) self._cache_dir = os.path.abspath(os.path.join(script_dir, "..", "..", "..", "..", "plugin", "usd", "rprUsd", "resources", "cache", "matlib", "thumbnails")) if not os.path.isdir(self._cache_dir): os.makedirs(self._cache_dir) def run(self): thumbnail_id = self._material["renders_order"][0] cached_thumbnail_path = str(os.path.join(self._cache_dir, thumbnail_id)) thumbnail_path = "" if(os.path.isfile(cached_thumbnail_path+"_thumbnail.jpeg")): thumbnail_path = cached_thumbnail_path+"_thumbnail.jpeg" elif(os.path.isfile(cached_thumbnail_path+"_thumbnail.jpg")): thumbnail_path = cached_thumbnail_path + "_thumbnail.jpg" elif (os.path.isfile(cached_thumbnail_path + "_thumbnail.png")): thumbnail_path = cached_thumbnail_path + "_thumbnail.png" else: for attempt in range(5): try: render_info = self._matlib_client.renders.get(thumbnail_id) self._matlib_client.renders.download_thumbnail(thumbnail_id, self._cache_dir) thumbnail_path = os.path.join(self._cache_dir, render_info["thumbnail"]) break except: sleep(1) # pause thread and retry if thumbnail_path != "": self.signals.finished.emit({"material": self._material, "thumbnail": thumbnail_path}) class MaterialLoader(QtCore.QRunnable): class MaterialLoaderSignals(QtCore.QObject): finished = QtCore.Signal() def __init__(self, matlib_client, material, package): super(MaterialLoader, self).__init__() self._matlib_client = matlib_client self._material = material self._package = package self.signals = MaterialLoader.MaterialLoaderSignals() def run(self): hip_dir = os.path.dirname(hou.hipFile.path()) dst_mtlx_dir = os.path.join(hip_dir, 'RPRMaterialLibrary', 'Materials') package_dir = os.path.join(dst_mtlx_dir, self._package["file"][:-4]) downloaded_now = False if not os.path.isdir(package_dir): # check if package is already loaded if not os.path.isdir(dst_mtlx_dir): os.makedirs(dst_mtlx_dir) self._matlib_client.packages.download(self._package["id"], dst_mtlx_dir) self._unpackZip(self._package["file"], dst_mtlx_dir) downloaded_now = True mtlx_file = self._findMtlx(package_dir) if mtlx_file == '': raise Exception("MaterialX file loading error") if downloaded_now: add_mtlx_includes(mtlx_file) create_houdini_material_graph(self._material["title"].replace(" ", "_").replace(":", "_"), mtlx_file) self.signals.finished.emit() def _unpackZip(self, filename, dst_dir): if filename.endswith('.zip'): zippath = os.path.join(dst_dir, filename) if not os.path.exists(zippath): raise Exception("Zip file not found") with zipfile.ZipFile(zippath, 'r') as zip_ref: packageDir = os.path.join(dst_dir, self._package["file"][:-4]) zip_ref.extractall(packageDir) os.remove(zippath) return True def _findMtlx(self, dir): if not os.path.exists(dir): return '' for f in os.listdir(dir): fullname = os.path.join(dir, f) if os.path.isfile(fullname) and f.endswith('.mtlx'): return fullname return '' class FullPreviewWindow(QtWidgets.QMainWindow): def __init__(self): super(FullPreviewWindow, self).__init__() self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint) icon_label = QtWidgets.QLabel() icon_label.setAlignment(QtCore.Qt.AlignCenter) icon_label.setFrameShape(QtWidgets.QFrame.Box) icon_label.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) icon_label.setBackgroundRole(QtGui.QPalette.Base) icon_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents) self.setCentralWidget(icon_label) self.setMouseTracking(True) self._currentIconName = '' self._requiredWidget = None def setIcon(self, icon_name, icon): mouse_pos = QtGui.QCursor.pos() self.move(mouse_pos.x() + 1, mouse_pos.y() + 1) if self._currentIconName != icon_name: icon_size = icon.availableSizes()[0] pixmap = icon.pixmap(icon_size) self.centralWidget().setPixmap(pixmap) if not self.isVisible(): self.show() def mouseMoveEvent(self, mouse_event): if self.isVisible(): if not IsMouseOnWidget(self._requiredWidget): self.hide() else: self.move(mouse_event.globalX() + 1, mouse_event.globalY() + 1) class MaterialLibraryWidget(QtWidgets.QWidget): def __init__(self): super(MaterialLibraryWidget, self).__init__() self._matlib_client = MatlibClient() self._fullPreviewWindow = FullPreviewWindow() self._materialIsLoading = False script_dir = os.path.dirname(os.path.abspath(__file__)) ui_filepath = os.path.join(script_dir, 'materialLibrary.ui') self._ui = QtUiTools.QUiLoader().load(ui_filepath, parentWidget=self) self._materialsView = LibraryListWidget(self) self._fullPreviewWindow._requiredWidget = self._materialsView self._ui.verticalLayout_3.insertWidget(0, self._materialsView) self._ui.helpButton.clicked.connect(self._helpButtonClicked) self._ui.filter.textChanged.connect(self._filterChanged) self._materialsView.itemEntered.connect(self._materialItemEntered) self._materialsView.clicked.connect(self._materialItemClicked) self._materialsView.viewportEntered.connect(self._materialViewportEntered) self._materialsView.setMouseTracking(True) self._materialsView.setSortingEnabled(True) self._initCategoryList() self._layout = QtWidgets.QVBoxLayout() self.setLayout(self._layout) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.addWidget(self._ui) def _initCategoryList(self): categories = cache.categories(self._matlib_client) item = QtWidgets.QListWidgetItem("All (" + str(sum([category["materials"] for category in categories])) + ")") item.value = None self._ui.categoryView.addItem(item) categories.sort(key=lambda c: c["title"]) for category in categories: item = QtWidgets.QListWidgetItem(" " + category["title"] + " (" + str(category["materials"]) + ")") item.value = category["title"] self._ui.categoryView.addItem(item) self._ui.categoryView.setCurrentItem(self._ui.categoryView.item(0)) self._ui.categoryView.clicked.connect(self._updateMaterialList) self._updateMaterialList() def _updateMaterialList(self): materials = cache.materials(self._matlib_client, self._ui.categoryView.currentItem().value) self._thumbnail_progress_dialog = QtWidgets.QProgressDialog('Loading thumbnails', None, 0, len(materials), self) self._thumbnail_progress = 0 self._thumbnail_progress_dialog.setValue(0) self._materialsView.clear() for material in materials: cached_material = cache.thumbnail_material(material['id']) if cached_material: self._addThumbnail(cached_material, cache.thumbnail_icon(material['id'])) else: loader = ThumbnailLoader(self._matlib_client, material) loader.signals.finished.connect(self._onThumbnailLoaded) QtCore.QThreadPool.globalInstance().start(loader) def _onThumbnailLoaded(self, result): icon = QtGui.QIcon(QtGui.QPixmap(result["thumbnail"])) cache.set_thumbnail_icon(result["material"], icon) self._addThumbnail(result["material"], icon) def _addThumbnail(self, material, icon): material_item = QtWidgets.QListWidgetItem(material["title"], self._materialsView) material_item.setIcon(icon) material_item.value = material # store material id in list item self._materialsView.addItem(material_item) self._thumbnail_progress += 1 self._thumbnail_progress_dialog.setValue(self._thumbnail_progress) self._filterItems() def _onMaterialLoaded(self): self._material_progress_dialog.setMaximum(100) self._material_progress_dialog.setValue(100) self._materialIsLoading = False def _materialItemClicked(self, index): if(self._materialIsLoading): print("Another material is loading now") return self._materialIsLoading = True # block while current material is loading self._fullPreviewWindow.hide() item = self._materialsView.item(index.row()) quality_box = QtWidgets.QMessageBox() quality_box.setWindowTitle("Textures quality") quality_box.setText("Choose quality of textures") quality_box.setIcon(QtWidgets.QMessageBox.Icon.Question) packages = self._matlib_client.packages.get_list(params={"material": item.value["id"]}) packages.sort(key=lambda x: x["label"]) for p in packages: button = QtWidgets.QPushButton(p["label"], self) quality_box.addButton(button, QtWidgets.QMessageBox.ButtonRole.AcceptRole) quality_box.addButton(QtWidgets.QPushButton("Cancel", self), QtWidgets.QMessageBox.ButtonRole.RejectRole) button_number = quality_box.exec() if button_number >= len(packages): # cancel button had been pressed self._materialIsLoading = False return self._material_progress_dialog = QtWidgets.QProgressDialog('Loading material', None, 0, 0, self) self._material_progress_dialog.setValue(0) loader = MaterialLoader(self._matlib_client, item.value, packages[button_number]) loader.signals.finished.connect(self._onMaterialLoaded) QtCore.QThreadPool.globalInstance().start(loader) def _materialItemEntered(self, item): self._fullPreviewWindow.setIcon(item.text(), item.icon()) def _materialViewportEntered(self): self._fullPreviewWindow.hide() def _helpButtonClicked(self): QtWidgets.QMessageBox.question(self, 'Help', HELP_TEXT, QtWidgets.QMessageBox.Ok) def _filterChanged(self): self._filterItems() def _filterItems(self): for i in range(self._materialsView.count()): self._setItemHidden(self._materialsView.item(i)) def _setItemHidden(self, item): pattern = self._ui.filter.text().lower() if pattern == '': item.setHidden(False) else: item.setHidden(not pattern in item.text().lower()) class MaterialLibraryWindow(QtWidgets.QMainWindow): def __init__(self): super(MaterialLibraryWindow, self).__init__() matLibWidget = MaterialLibraryWidget() layout = QtWidgets.QVBoxLayout() layout.addWidget(matLibWidget) central_widget = QtWidgets.QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) self.setParent(hou.qt.mainWindow(), QtCore.Qt.Window) self.setWindowTitle('RPR Material Library') desktop_widget = QtWidgets.QDesktopWidget() primary_screen = desktop_widget.screen(desktop_widget.primaryScreen()) self.resize(primary_screen.width() // 3, int(primary_screen.height() * 0.8)) def import_material(): window = MaterialLibraryWindow() window.show()
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,621
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/python/houdiniDsGenerator.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import platform houdini_ds_template = ( ''' #include "$HFS/houdini/soho/parameters/CommonMacros.ds" {{ name "RPR" label "RPR" parmtag {{ spare_opfilter "!!SHOP/PROPERTIES!!" }} parmtag {{ spare_classtags "render" }} {houdini_params} }} ''').strip() control_param_template = ( ''' parm {{ name "{name}" label "{label}" type string default {{ "none" }} {hidewhen} menujoin {{ [ "import loputils" ] [ "return loputils.createEditPropertiesControlMenu(kwargs, '{controlled_type}[]')" ] language python }} }} ''' ) def _get_valid_houdini_param_name(name): name = name.replace('$', '') if all(c.isalnum() or c == '_' for c in name): return name else: import hou return hou.encode(name) def _get_usd_render_setting_name(name): if not name.startswith('rpr:') and not name.startswith('primvars:') and not name.startswith('$'): name = 'rpr:' + name return name.replace('$', '') def _get_houdini_condition_string(condition, settings): houdini_conditions = [] def process_condition(condition): if not condition: return if callable(condition): return process_condition(condition(settings)) elif isinstance(condition, list): for entry in condition: process_condition(entry) elif isinstance(condition, str): if ':' in condition or '$' in condition: setting_name, tail = condition.split(' ', 1) setting_name = _get_usd_render_setting_name(setting_name) houdini_name = _get_valid_houdini_param_name(setting_name) condition = ' '.join([houdini_name, tail]) houdini_conditions.append(condition) else: print('ERROR: Unexpected condition value: {}'.format(condition)) exit(1) process_condition(condition) houdini_condition = '' if houdini_conditions: for condition in houdini_conditions: houdini_condition += '{{ {} }} '.format(condition) return houdini_condition def _get_houdini_hidewhen_string(condition, settings): conditions = _get_houdini_condition_string(condition, settings) return 'hidewhen "' + conditions + '"' if conditions else '' def _generate_ds_setting(setting, spare_category, global_hidewhen, settings): if not 'ui_name' in setting: return '' houdini_settings = setting.get('houdini', {}) houdini_hidewhen = _get_houdini_hidewhen_string([houdini_settings.get('hidewhen'), global_hidewhen], settings) disablewhen_predefined_conditions = _get_houdini_condition_string([houdini_settings.get('disablewhen')], settings) def CreateHoudiniParam(name, label, htype, default, values=[], tags=[], disablewhen_conditions=[], size=None, valid_range=None, help_msg=None): param = 'parm {\n' param += ' name "{}"\n'.format(name) param += ' label "{}"\n'.format(label) param += ' type {}\n'.format(htype) if size: param += ' size {}\n'.format(size) param += ' default {{ {} }}\n'.format(default) for tag in tags: param += ' parmtag {{ {} }}\n'.format(tag) if values: param += ' menu {\n' param += ' ' + values + '\n' param += ' }\n' if houdini_hidewhen: param += ' {}\n'.format(houdini_hidewhen) if disablewhen_conditions or disablewhen_predefined_conditions: param += ' disablewhen "' for condition in disablewhen_conditions: param += '{{ {} }} '.format(condition) param += disablewhen_predefined_conditions param += '"\n' if valid_range: param += ' range {{ {}! {} }}\n'.format(valid_range[0], valid_range[1]) if help_msg: param += ' help "{}"\n'.format(help_msg) param += '}\n' return param setting_name = _get_usd_render_setting_name(setting['name']) name = _get_valid_houdini_param_name(setting_name) control_param_name = _get_valid_houdini_param_name(setting_name + '_control') render_param_values = None default_value = setting['defaultValue'] c_type_str = type(default_value).__name__ controlled_type = c_type_str if c_type_str == 'str': c_type_str = 'string' controlled_type = 'string' render_param_type = c_type_str render_param_default = default_value if isinstance(default_value, bool): render_param_type = 'toggle' render_param_default = 1 if default_value else 0 elif 'values' in setting: default_value = next(value for value in setting['values'] if value == default_value) render_param_default = '"{}"'.format(default_value.get_key()) render_param_type = 'string' c_type_str = 'token' is_values_constant = True for value in setting['values']: if value.enable_py_condition: is_values_constant = False break render_param_values = '' if is_values_constant: for value in setting['values']: render_param_values += '"{}" "{}"\n'.format(value.get_key(), value.get_ui_name()) else: render_param_values += '[ "import platform" ]\n' render_param_values += '[ "menu_values = []" ]\n' for value in setting['values']: expression = 'menu_values.extend([\\"{}\\", \\"{}\\"])'.format(value.get_key(), value.get_ui_name()) if value.enable_py_condition: enable_condition = value.enable_py_condition().replace('"', '\\"') expression = 'if {}: {}'.format(enable_condition, expression) render_param_values += '[ "{}" ]\n'.format(expression) render_param_values += '[ "return menu_values" ]\n'.format(expression) render_param_values += 'language python\n' if 'type' in houdini_settings: render_param_type = houdini_settings['type'] render_param_range = None if 'minValue' in setting and 'maxValue' in setting and not 'values' in setting: render_param_range = (setting['minValue'], setting['maxValue']) houdini_param_label = setting['ui_name'] houdini_params = control_param_template.format( name=control_param_name, label=houdini_param_label, controlled_type=controlled_type, hidewhen=houdini_hidewhen) houdini_params += CreateHoudiniParam(name, houdini_param_label, render_param_type, render_param_default, values=render_param_values, tags=[ '"spare_category" "{}"'.format(spare_category), '"uiscope" "viewport"', '"usdvaluetype" "{}"'.format(c_type_str) ] + houdini_settings.get('custom_tags', []), disablewhen_conditions=[ control_param_name + ' == block', control_param_name + ' == none', ], size=1, valid_range=render_param_range, help_msg=setting.get('help', None)) return houdini_params def generate_houdini_ds(install_path, ds_name, settings): houdini_params = '' for category in settings: category_name = category['name'] category_hidewhen = None if 'houdini' in category: category_hidewhen = category['houdini'].get('hidewhen') for setting in category['settings']: if 'folder' in setting: houdini_params += 'groupcollapsible {\n' houdini_params += ' name "{}"\n'.format(setting['folder'].replace(' ', '')) houdini_params += ' label "{}"\n'.format(setting['folder']) houdini_settings = setting.get('houdini', {}) houdini_hidewhen = _get_houdini_hidewhen_string([houdini_settings.get('hidewhen'), category_hidewhen], settings) if houdini_hidewhen: houdini_params += ' {}\n'.format(houdini_hidewhen) for sub_setting in setting['settings']: houdini_params += _generate_ds_setting(sub_setting, category_name, category_hidewhen, settings) houdini_params += '}\n' else: houdini_params += _generate_ds_setting(setting, category_name, category_hidewhen, settings) if houdini_params: houdini_ds_dst_path = os.path.join(install_path, 'HdRprPlugin_{}.ds'.format(ds_name)) houdini_ds_file = open(houdini_ds_dst_path, 'w') houdini_ds_file.write(houdini_ds_template.format(houdini_params=houdini_params))
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,622
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/scripts/rendersettings_OnLoaded.py
import hou, re #hou.ui.displayMessage("I ran! I ran so far away!") def is_old_format_settings_node(node): # check some parms, no need to check all return node.parm('renderQuality') \ and node.parm('renderDevice') \ and node.parm('minAdaptiveSamples') \ and node.parm('maxRayDepthGlossyRefraction') \ and node.parm('interactiveMaxRayDepth') def replacer_name(stage, node): name = node.name() + '_' while stage.node(name): name += '_' return name def parm_name_key_part(full_name): found = re.search('xn__(.+?)_', full_name) return found.group(1) if found else '' def is_control(full_name, key_name): return key_name + '_control' in full_name def copy_rpr_params(node, replacer): names = { "enableDenoising": "rprdenoisingenable", "maxSamples": "rprmaxSamples", "minAdaptiveSamples": "rpradaptiveSamplingminSamples", "varianceThreshold": "rpradaptiveSamplingnoiseTreshold", "maxRayDepth": "rprqualityrayDepth", "maxRayDepthDiffuse": "rprqualityrayDepthDiffuse", "maxRayDepthGlossy": "rprqualityrayDepthGlossy", "maxRayDepthRefraction": "rprqualityrayDepthRefraction", "maxRayDepthGlossyRefraction": "rprqualityrayDepthGlossyRefraction", "maxRayDepthShadow": "rprqualityrayDepthShadow", "raycastEpsilon": "rprqualityraycastEpsilon", "radianceClamping": "rprqualityradianceClamping", "interactiveMaxRayDepth": "rprqualityinteractiverayDepth" } parm_index = 0 control_index = 1 replacer_parms = {name: [None, None] for name in names.values()} for parm in replacer.parms(): full_name = parm.name() key_name = parm_name_key_part(full_name) if key_name in replacer_parms: replacer_parms[key_name][control_index if is_control(full_name, key_name) else parm_index] = parm for src_name, dest_name in names.items(): src = node.parm(src_name) src_control = node.parm(src_name + '_control') dest = replacer_parms[dest_name][parm_index] dest_control = replacer_parms[dest_name][control_index] if src and dest: try: dest.set(src.eval()) except: print(src, '->', dest) if src_control and dest_control: try: dest_control.set(src_control.eval()) except: print(src_control, '->', dest_control) def copy_params(node, replacer): for src in node.parms(): dest = replacer.parm(src.name()) if dest: try: dest.set(src.eval()) except: print('common', src, '->', dest) node = kwargs["node"] stage = hou.node("/stage") if is_old_format_settings_node(node): replacer = stage.createNode('rendersettings', replacer_name(stage, node)) replacer.setPosition(node.position() + hou.Vector2(0.1, -0.1)) copy_params(node, replacer) copy_rpr_params(node, replacer) replacer.setInput(0, node.input(0)) for out in node.outputs(): for i in range(len(out.inputs())): if out.inputs()[i] == node: out.setInput(i, replacer) replacer.setDisplayFlag(True)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,623
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/usdviewMenu/rpr.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from pxr import Tf from pxr.Plug import Registry from pxr.Usdviewq.plugin import PluginContainer from pxr.Usdviewq.qt import QtWidgets, QtCore from ctypes import cdll, c_void_p, c_char_p, cast from ctypes.util import find_library import os import glob from rpr import RprUsd def setCacheDir(usdviewApi, type, startDirectory, setter): directory = QtWidgets.QFileDialog.getExistingDirectory( usdviewApi._UsdviewApi__appController._mainWindow, caption='RPR {} Cache Directory'.format(type), dir=startDirectory) if directory: setter(directory) def SetTextureCacheDir(usdviewApi): setCacheDir(usdviewApi, 'Texture', RprUsd.Config.GetTextureCacheDir(), RprUsd.Config.SetTextureCacheDir) def SetKernelCacheDir(usdviewApi): setCacheDir(usdviewApi, 'Kernel', RprUsd.Config.GetKernelCacheDir(), RprUsd.Config.SetKernelCacheDir) def clearCache(cache_dir): num_files_removed = 0 for pattern in ('*.bin.check', '*.bin', '*.cache'): for cache_file in glob.iglob(os.path.join(cache_dir, pattern)): os.remove(cache_file) num_files_removed += 1 print('RPR: removed {} cache files'.format(num_files_removed)) def ClearTextureCache(usdviewApi): clearCache(RprUsd.Config.GetTextureCacheDir()) def ClearKernelCache(usdviewApi): clearCache(RprUsd.Config.GetKernelCacheDir()) def getRprPath(_pathCache=[None]): if _pathCache[0]: return _pathCache[0] rprPluginType = Registry.FindTypeByName('HdRprPlugin') plugin = Registry().GetPluginForType(rprPluginType) if plugin and plugin.path: _pathCache[0] = plugin.path return _pathCache[0] def reemitStage(usdviewApi): usdviewApi._UsdviewApi__appController._reopenStage() usdviewApi._UsdviewApi__appController._rendererPluginChanged('HdRprPlugin') def setRenderQuality(usdviewApi, quality): rprPath = getRprPath() if rprPath is not None: lib = cdll.LoadLibrary(rprPath) lib.HdRprGetRenderQuality.restype = c_void_p lib.HdRprFree.argtypes = [c_void_p] currentQualityPtr = lib.HdRprGetRenderQuality() if not currentQualityPtr: # Enable RPR plugin if it was not done yet reemitStage(usdviewApi) currentQuality = cast(currentQualityPtr, c_char_p).value lib.HdRprFree(currentQualityPtr) if quality == currentQuality: return lib.HdRprSetRenderQuality(quality) def getPluginName(quality): if quality == b'Full': return 'Tahoe' elif quality == b'Northstar': return 'Northstar' elif quality == b'HybridPro': return 'HybridPro' else: return 'Hybrid' if getPluginName(quality) != getPluginName(currentQuality): reemitStage(usdviewApi) def ChooseRenderDevice(usdviewApi): if RprUsd.devicesConfiguration.open_window(usdviewApi._UsdviewApi__appController._mainWindow, QtCore.Qt.Window, show_restart_warning=False): reemitStage(usdviewApi) def SetRenderLowQuality(usdviewApi): setRenderQuality(usdviewApi, b'Low') def SetRenderMediumQuality(usdviewApi): setRenderQuality(usdviewApi, b'Medium') def SetRenderHighQuality(usdviewApi): setRenderQuality(usdviewApi, b'High') def SetRenderFullQuality(usdviewApi): setRenderQuality(usdviewApi, b'Full') def SetRenderNorthstarQuality(usdviewApi): setRenderQuality(usdviewApi, b'Northstar') def SetRenderHybridProQuality(usdviewApi): setRenderQuality(usdviewApi, b'HybridPro') class RprPluginContainer(PluginContainer): def registerPlugins(self, plugRegistry, usdviewApi): self.chooseRenderDevice = plugRegistry.registerCommandPlugin( "RprPluginContainer.chooseRenderDevice", "Render Devices", ChooseRenderDevice) self.setRenderLowQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderLowQuality", "Low", SetRenderLowQuality) self.setRenderMediumQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderMediumQuality", "Medium", SetRenderMediumQuality) self.setRenderHighQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderHighQuality", "High", SetRenderHighQuality) self.setRenderFullQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderFullQuality", "Full", SetRenderFullQuality) self.setRenderNorthstarQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderNorthstarQuality", "Northstar", SetRenderNorthstarQuality) self.setRenderHybridProQuality = plugRegistry.registerCommandPlugin( "RprPluginContainer.setRenderHybridProQuality", "HybridPro", SetRenderHybridProQuality) self.setTextureCacheDir = plugRegistry.registerCommandPlugin( "RprPluginContainer.setTextureCacheDir", "Set Texture Cache Directory", SetTextureCacheDir) self.setKernelCacheDir = plugRegistry.registerCommandPlugin( "RprPluginContainer.setKernelCacheDir", "Set Kernel Cache Directory", SetKernelCacheDir) self.clearTextureCache = plugRegistry.registerCommandPlugin( "RprPluginContainer.clearTextureCache", "Clear Texture Cache", ClearTextureCache) self.clearKernelCache = plugRegistry.registerCommandPlugin( "RprPluginContainer.clearKernelCache", "Clear Kernel Cache", ClearKernelCache) self.restartAction = plugRegistry.registerCommandPlugin( "RprPluginContainer.restartAction", "Restart", reemitStage) def configureView(self, plugRegistry, plugUIBuilder): rprMenu = plugUIBuilder.findOrCreateMenu("RPR") rprMenu.addItem(self.chooseRenderDevice) renderQualityMenu = rprMenu.findOrCreateSubmenu("Render Quality") renderQualityMenu.addItem(self.setRenderLowQuality) renderQualityMenu.addItem(self.setRenderMediumQuality) renderQualityMenu.addItem(self.setRenderHighQuality) renderQualityMenu.addItem(self.setRenderFullQuality) renderQualityMenu.addItem(self.setRenderNorthstarQuality) renderQualityMenu.addItem(self.setRenderHybridProQuality) cacheMenu = rprMenu.findOrCreateSubmenu('Cache') cacheMenu.addItem(self.setTextureCacheDir) cacheMenu.addItem(self.setKernelCacheDir) cacheMenu.addItem(self.clearTextureCache) cacheMenu.addItem(self.clearKernelCache) rprMenu.addItem(self.restartAction) Tf.Type.Define(RprPluginContainer)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,624
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/cmake/macros/generateDocs.py
# # Copyright 2017 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # # Generate doxygen based docs for USD. import sys, os, argparse, shutil, subprocess, tempfile, platform, stat # This finds all modules in the pxr/ source area, such as ar, usdGeom etc. def _getModules(pxrSourceRoot): modules = [] topLevel = [] for p in os.listdir(pxrSourceRoot): # Ignore any hidden directories if os.path.basename(p).startswith('.'): continue # add all lib/ subdirs, such as usdGeom path = os.path.join(os.path.join(pxrSourceRoot, p), 'lib/') if os.path.isdir(path): topLevel.append(path) # add all plugin subdirs, such as usdAbc path = os.path.join(os.path.join(pxrSourceRoot, p), 'plugin/') if os.path.isdir(path): topLevel.append(path) for t in topLevel: for p in os.listdir(t): if os.path.basename(p).startswith('.'): continue # Ignore any irrelevant directories elif os.path.basename(p).startswith('CMakeFiles'): continue elif os.path.basename(p).startswith('testenv'): continue path = os.path.join(os.path.join(pxrSourceRoot, t), p) if os.path.isdir(path): modules.append(path) return modules def _generateDocs(pxrSourceRoot, pxrBuildRoot, installLoc, doxygenBin, dotBin): docsLoc = os.path.join(installLoc, 'src/modules') if not os.path.exists(docsLoc): os.makedirs(docsLoc) for mod in _getModules(pxrSourceRoot): target = os.path.join(docsLoc, os.path.basename(mod)) # This ensures that we get a fresh view of the source # on each build invocation. if os.path.exists(target): def _removeReadOnly(func, path, exc): try: os.chmod(path, stat.S_IWRITE) func(path) except Exception as exc: print >>sys.stderr, "Failed to remove %s: %s" % (path, str(exc)) shutil.rmtree(target, onerror=_removeReadOnly) shutil.copytree(mod, target) # We need to copy the namespace header separately because # its a generated file from CMake pxrMod = os.path.join(docsLoc, 'pxr') if not os.path.exists(pxrMod): os.makedirs(pxrMod) pxrHeaderSrc = os.path.join(pxrBuildRoot, 'include', 'pxr', 'pxr.h') pxrHeaderDest = os.path.join(pxrMod, 'pxr.h') if os.path.exists(pxrHeaderDest): os.remove(pxrHeaderDest) shutil.copyfile(pxrHeaderSrc, pxrHeaderDest) doxyConfigSrc = os.path.join(pxrBuildRoot, 'Doxyfile') doxyConfigDest = os.path.join(docsLoc, 'usd', 'Doxyfile') if os.path.exists(doxyConfigDest): os.remove(doxyConfigDest) shutil.copyfile(doxyConfigSrc, doxyConfigDest) os.chdir(installLoc) cmd = [doxygenBin, doxyConfigDest] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.communicate()[0] if proc.wait() != 0: print >>sys.stderr, output.replace('\r\n', '\n') sys.exit('Error: doxygen failed to complete; ' 'exit code %d.' % proc.returncode) def _checkPath(path, ident, perm): if not os.path.exists(path): sys.exit('Error: file path %s (arg=%s) ' 'does not exist, exiting.' % (path,ident)) elif not os.access(path, perm): permString = '-permission' if perm == os.W_OK: permString = 'write'+permString elif perm == os.R_OK: permString = 'read'+permString elif perm == os.X_OK: permString = 'execute'+permString sys.exit('Error: insufficient permission for path %s, ' '%s required.' % (path, permString)) def _generateInstallLoc(installRoot): installPath = os.path.join(installRoot, 'docs') if not os.path.exists(installPath): os.mkdir(installPath) return installPath if __name__ == "__main__": p = argparse.ArgumentParser(description="Generate USD documentation.") p.add_argument("source", help="The path to the pxr source root.") p.add_argument("build", help="The path to the build directory root.") p.add_argument("install", help="The install root for generated docs.") p.add_argument("doxygen", help="The path to the doxygen executable.") p.add_argument("dot", help="The path to the dot executable.") args = p.parse_args() # Ensure all paths exist first _checkPath(args.doxygen, 'doxygen', os.X_OK) _checkPath(args.build, 'build', os.R_OK) _checkPath(args.install, 'install', os.W_OK) _checkPath(args.source, 'source', os.R_OK) _checkPath(args.dot, 'dot', os.X_OK) installPath = _generateInstallLoc(args.install) _generateDocs(args.source, args.build, installPath, args.doxygen, args.dot)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,625
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/cache.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import glob import hou from rpr import RprUsd def _set_cache_dir(type, start_directory, setter): directory = hou.ui.selectFile( title='RPR {} Cache Directory'.format(type), start_directory=start_directory.replace('\\', '/'), file_type=hou.fileType.Directory, chooser_mode=hou.fileChooserMode.Write) if directory: setter(hou.expandString(directory)) def set_texture_cache_dir(): _set_cache_dir('Texture', RprUsd.Config.GetTextureCacheDir(), RprUsd.Config.SetTextureCacheDir) def set_kernel_cache_dir(): _set_cache_dir('Kernel', RprUsd.Config.GetKernelCacheDir(), RprUsd.Config.SetKernelCacheDir) def _clear_cache(cache_dir): num_files_removed = 0 for pattern in ('*.bin.check', '*.bin', '*.cache'): for cache_file in glob.iglob(os.path.join(cache_dir, pattern)): os.remove(cache_file) num_files_removed += 1 print('RPR: removed {} cache files'.format(num_files_removed)) def clear_texture_cache(): _clear_cache(RprUsd.Config.GetTextureCacheDir()) def clear_kernel_cache(): _clear_cache(RprUsd.Config.GetKernelCacheDir())
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,626
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/python/generateRenderSettingFiles.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import sys import argparse import platform from houdiniDsGenerator import generate_houdini_ds from commonSettings import SettingValue def get_render_setting(render_setting_categories, category_name, name): for category in render_setting_categories: if category['name'] != category_name: continue for setting in category['settings']: if setting['name'] == name: return setting def hidewhen_render_quality(operator, quality, render_setting_categories=None): if operator in ('==', '!='): return '{} {} "{}"'.format(houdini_parm_name('core:renderQuality'), operator, quality) elif operator == '<': render_quality = get_render_setting(render_setting_categories, 'RenderQuality', 'core:renderQuality') values = render_quality['values'] hidewhen = [] for value in values: if value == quality: break hidewhen.append(hidewhen_render_quality('==', value.get_key())) return hidewhen else: raise ValueError('Operator "{}" not implemented'.format(operator)) def hidewhen_hybrid(render_setting_categories): return hidewhen_render_quality('<', 'Northstar', render_setting_categories) def hidewhen_not_northstar(render_setting_categories): return hidewhen_render_quality('!=', 'Northstar', render_setting_categories) def houdini_parm_name(name): import hou return hou.encode('rpr:' + name) HYBRID_IS_AVAILABLE_PY_CONDITION = lambda: 'platform.system() != "Darwin"' NORTHSTAR_ENABLED_PY_CONDITION = lambda: 'hou.pwd().parm("{}").evalAsString() == "Northstar"'.format(houdini_parm_name('core:renderQuality')) NOT_NORTHSTAR_ENABLED_PY_CONDITION = lambda: 'hou.pwd().parm("{}").evalAsString() != "Northstar"'.format(houdini_parm_name('core:renderQuality')) render_setting_categories = [ { 'name': 'RenderQuality', 'settings': [ { 'name': 'core:renderQuality', 'ui_name': 'Render Quality', 'help': 'Render restart might be required', 'defaultValue': 'Northstar', 'values': [ SettingValue('Low', enable_py_condition=HYBRID_IS_AVAILABLE_PY_CONDITION), SettingValue('Medium', enable_py_condition=HYBRID_IS_AVAILABLE_PY_CONDITION), SettingValue('High', enable_py_condition=HYBRID_IS_AVAILABLE_PY_CONDITION), SettingValue('HybridPro', enable_py_condition=HYBRID_IS_AVAILABLE_PY_CONDITION), SettingValue('Northstar', 'Full') ] }, { 'name': 'core:useOpenCL', 'ui_name': 'Use OpenCL Backend (legacy)', 'help': 'Render restart might be required', 'defaultValue': False, 'houdini': { 'hidewhen': hidewhen_not_northstar } } ] }, { 'name': 'RenderMode', 'settings': [ { 'name': 'core:renderMode', 'ui_name': 'Render Mode', 'defaultValue': 'Global Illumination', 'values': [ SettingValue('Global Illumination'), SettingValue('Direct Illumination'), SettingValue('Wireframe'), SettingValue('Material Index'), SettingValue('Position'), SettingValue('Normal'), SettingValue('Texcoord'), SettingValue('Ambient Occlusion'), SettingValue('Diffuse'), SettingValue('Contour', enable_py_condition=NORTHSTAR_ENABLED_PY_CONDITION), ] }, { 'name': 'ambientOcclusion:radius', 'ui_name': 'Ambient Occlusion Radius', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'houdini': { 'hidewhen': 'core:renderMode != "AmbientOcclusion"' } }, { 'folder': 'Contour Settings', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' }, 'settings': [ { 'name': 'contour:antialiasing', 'ui_name': 'Antialiasing', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 1.0, 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } }, { 'name': 'contour:useNormal', 'ui_name': 'Use Normal', 'defaultValue': True, 'help': 'Whether to use geometry normals for edge detection or not', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } }, { 'name': 'contour:linewidthNormal', 'ui_name': 'Linewidth Normal', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'help': 'Linewidth of edges detected via normals', 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:useNormal == 0'] } }, { 'name': 'contour:normalThreshold', 'ui_name': 'Normal Threshold', 'defaultValue': 45.0, 'minValue': 0.0, 'maxValue': 180.0, 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:useNormal == 0'] } }, { 'name': 'contour:usePrimId', 'ui_name': 'Use Primitive Id', 'defaultValue': True, 'help': 'Whether to use primitive Id for edge detection or not', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } }, { 'name': 'contour:linewidthPrimId', 'ui_name': 'Linewidth Primitive Id', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'help': 'Linewidth of edges detected via primitive Id', 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:usePrimId == 0'] } }, { 'name': 'contour:useMaterialId', 'ui_name': 'Use Material Id', 'defaultValue': True, 'help': 'Whether to use material Id for edge detection or not', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } }, { 'name': 'contour:linewidthMaterialId', 'ui_name': 'Linewidth Material Id', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'help': 'Linewidth of edges detected via material Id', 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:useMaterialId == 0'] } }, { 'name': 'contour:useUv', 'ui_name': 'Use UV', 'defaultValue': True, 'help': 'Whether to use UV for edge detection or not', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } }, { 'name': 'contour:linewidthUv', 'ui_name': 'Linewidth UV', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'help': 'Linewidth of edges detected via UV', 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:useUv == 0'] } }, { 'name': 'contour:uvThreshold', 'ui_name': 'UV Threshold', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 1.0, 'help': 'Threshold of edges detected via UV', 'houdini': { 'hidewhen': ['core:renderMode != "Contour"', 'contour:useUv == 0'] } }, { 'name': 'contour:debug', 'ui_name': 'Debug', 'defaultValue': False, 'help': 'Whether to show colored outlines according to used features or not.\\n' 'Colors legend:\\n' ' * red - primitive Id\\n' ' * green - material Id\\n' ' * blue - normal\\n' ' * yellow - primitive Id + material Id\\n' ' * magenta - primitive Id + normal\\n' ' * cyan - material Id + normal\\n' ' * black - all', 'houdini': { 'hidewhen': 'core:renderMode != "Contour"' } } ] } ], 'houdini': { 'hidewhen': hidewhen_hybrid } }, { 'name': 'Denoise', 'houdini': { 'hidewhen': lambda settings: hidewhen_render_quality('<', 'High', settings) }, 'settings': [ { 'name': 'denoising:enable', 'ui_name': 'Enable AI Denoising', 'defaultValue': False, 'houdini': { 'custom_tags': [ '"uiicon" VIEW_display_denoise' ] } }, { 'folder': 'Denoise Settings', 'houdini': { 'hidewhen': 'denoising:enable == 0' }, 'settings': [ { 'name': 'denoising:minIter', 'ui_name': 'Denoise Min Iteration', 'defaultValue': 4, 'minValue': 1, 'maxValue': 2 ** 16, 'help': 'The first iteration on which denoising should be applied.' }, { 'name': 'denoising:iterStep', 'ui_name': 'Denoise Iteration Step', 'defaultValue': 32, 'minValue': 1, 'maxValue': 2 ** 16, 'help': 'Denoise use frequency. To denoise on each iteration, set to 1.' } ] } ] }, { 'name': 'Sampling', 'houdini': { 'hidewhen': lambda settings: hidewhen_render_quality('==', 'Low', settings) }, 'settings': [ { 'name': 'maxSamples', 'ui_name': 'Max Samples', 'help': 'Maximum number of samples to render for each pixel.', 'defaultValue': 128, 'minValue': 1, 'maxValue': 2 ** 16 } ] }, { 'name': 'AdaptiveSampling', 'houdini': { 'hidewhen': hidewhen_hybrid }, 'settings': [ { 'name': 'adaptiveSampling:minSamples', 'ui_name': 'Min Samples', 'help': 'Minimum number of samples to render for each pixel. After this, adaptive sampling will stop sampling pixels where noise is less than \'Variance Threshold\'.', 'defaultValue': 32, 'minValue': 1, 'maxValue': 2 ** 16 }, { 'name': 'adaptiveSampling:noiseTreshold', 'ui_name': 'Noise Threshold', 'help': 'Cutoff for adaptive sampling. Once pixels are below this amount of noise, no more samples are added. Set to 0 for no cutoff.', 'defaultValue': 0.05, 'minValue': 0.0, 'maxValue': 1.0 } ] }, { 'name': 'Quality', 'settings': [ { 'name': 'quality:rayDepth', 'ui_name': 'Max Ray Depth', 'help': 'The number of times that a ray bounces off various surfaces before being terminated.', 'defaultValue': 8, 'minValue': 1, 'maxValue': 50 }, { 'name': 'quality:rayDepthDiffuse', 'ui_name': 'Diffuse Ray Depth', 'help': 'The maximum number of times that a light ray can be bounced off diffuse surfaces.', 'defaultValue': 3, 'minValue': 0, 'maxValue': 50 }, { 'name': 'quality:rayDepthGlossy', 'ui_name': 'Glossy Ray Depth', 'help': 'The maximum number of ray bounces from specular surfaces.', 'defaultValue': 3, 'minValue': 0, 'maxValue': 50 }, { 'name': 'quality:rayDepthRefraction', 'ui_name': 'Refraction Ray Depth', 'help': 'The maximum number of times that a light ray can be refracted, and is designated for clear transparent materials, such as glass.', 'defaultValue': 3, 'minValue': 0, 'maxValue': 50 }, { 'name': 'quality:rayDepthGlossyRefraction', 'ui_name': 'Glossy Refraction Ray Depth', 'help': 'The Glossy Refraction Ray Depth parameter is similar to the Refraction Ray Depth. The difference is that it is aimed to work with matte refractive materials, such as semi-frosted glass.', 'defaultValue': 3, 'minValue': 0, 'maxValue': 50 }, { 'name': 'quality:rayDepthShadow', 'ui_name': 'Shadow Ray Depth', 'help': 'Controls the accuracy of shadows cast by transparent objects. It defines the maximum number of surfaces that a light ray can encounter on its way causing these surfaces to cast shadows.', 'defaultValue': 2, 'minValue': 0, 'maxValue': 50 }, { 'name': 'quality:raycastEpsilon', 'ui_name': 'Ray Cast Epsilon', 'help': 'Determines an offset used to move light rays away from the geometry for ray-surface intersection calculations.', 'defaultValue': 2e-3, 'minValue': 1e-6, 'maxValue': 1.0 }, { 'name': 'quality:radianceClamping', 'ui_name': 'Max Radiance', 'help': 'Limits the intensity, or the maximum brightness, of samples in the scene. Greater clamp radiance values produce more brightness.', 'defaultValue': 0.0, 'minValue': 0.0, 'maxValue': 1e6 }, { 'name': 'quality:filterType', 'ui_name': 'Filter Type', 'defaultValue': 'None', 'values': [ SettingValue('None'), SettingValue('Box'), SettingValue('Triangle'), SettingValue('Gaussian'), SettingValue('Mitchell'), SettingValue('Lanczos'), SettingValue('BlackmanHarris') ], 'houdini': { 'hidewhen': hidewhen_hybrid } }, { 'name': 'quality:imageFilterRadius', 'ui_name': 'Pixel filter width', 'help': 'Determines Pixel filter width (anti-aliasing).', 'defaultValue': 1.5, 'minValue': 0.0, 'maxValue': 1.5, 'houdini': { 'hidewhen': hidewhen_hybrid } }, { 'name': 'quality:reservoirSampling', 'ui_name': 'ReSTIR (HybridPro only)', 'help': 'ReSTIR is a low computational cost technique for rendering realistic lighting with millions of lights in real-time.', 'defaultValue': 'PathSpace', 'values': [ SettingValue('Off'), SettingValue('ScreenSpace'), SettingValue('PathSpace'), ], 'houdini': { 'hidewhen': lambda settings: hidewhen_render_quality('!=', 'HybridPro', settings) } } ] }, { 'name': 'InteractiveQuality', 'settings': [ { 'name': 'quality:interactive:rayDepth', 'ui_name': 'Interactive Max Ray Depth', 'help': 'Controls value of \'Max Ray Depth\' in interactive mode.', 'defaultValue': 2, 'minValue': 1, 'maxValue': 50, 'houdini': { 'hidewhen': hidewhen_hybrid } }, { 'name': 'quality:interactive:downscale:resolution', 'ui_name': 'Interactive Resolution Downscale', 'help': 'Controls how much rendering resolution is downscaled in interactive mode. Formula: resolution / (2 ^ downscale). E.g. downscale==2 will give you 4 times smaller rendering resolution.', 'defaultValue': 3, 'minValue': 0, 'maxValue': 10, 'houdini': { 'hidewhen': hidewhen_not_northstar } }, { 'name': 'quality:interactive:downscale:enable', 'ui_name': 'Downscale Resolution When Interactive', 'help': 'Controls whether in interactive mode resolution should be downscaled or no.', 'defaultValue': True, 'houdini': { 'hidewhen': hidewhen_not_northstar } } ] }, { 'name': 'Gamma', 'settings': [ { 'name': 'gamma:enable', 'ui_name': 'Enable Gamma', 'help': 'Enable Gamma', 'defaultValue': False }, { 'name': 'gamma:value', 'ui_name': 'Gamma', 'help': 'Gamma value', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 5.0, 'houdini': { 'hidewhen': 'gamma:enable == 0' } } ] }, { 'name': 'GMON', 'settings': [ { 'name': 'core:useGmon', 'ui_name': 'Use GMON (HybridPro only)', 'help': 'Enable fireflies suppression by using adaptive median of mean estimator', 'defaultValue': False, 'houdini': { 'hidewhen': lambda settings: hidewhen_render_quality('!=', 'HybridPro', settings) } } ] }, { 'name': 'DisplayGamma', 'settings': [ { 'name': 'core:displayGamma', 'ui_name': 'Display Gamma', 'help': 'Adjusts the brightness of each pixel in the image based on the gamma correction value to make the overall image brightness appear more natural on the screen.', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 5.0 } ] }, { 'name': 'Hybrid', 'settings': [ { 'name': 'hybrid:tonemapping', 'ui_name': 'Hybrid Tonemapping', 'defaultValue': 'None', 'values': [ SettingValue('None'), SettingValue('Filmic'), SettingValue('Aces'), SettingValue('Reinhard'), SettingValue('Photolinear') ] }, { 'name': 'hybrid:denoising', 'ui_name': 'Hybrid Denoising', 'defaultValue': 'None', 'values': [ SettingValue('None'), SettingValue('SVGF'), SettingValue('ASVGF') ] }, { 'name': 'hybrid:accelerationMemorySizeMb', 'ui_name': 'Hybrid Acceleration Structure Memory Size (MB)', 'defaultValue': 2048, 'minValue': 1, 'maxValue': 4096 }, { 'name': 'hybrid:meshMemorySizeMb', 'ui_name': 'Hybrid Mesh Memory Size (MB)', 'defaultValue': 1024, 'minValue': 1, 'maxValue': 4096 }, { 'name': 'hybrid:stagingMemorySizeMb', 'ui_name': 'Hybrid Staging Memory Size (MB)', 'defaultValue': 512, 'minValue': 1, 'maxValue': 4096 }, { 'name': 'hybrid:scratchMemorySizeMb', 'ui_name': 'Hybrid Scratch Memory Size (MB)', 'defaultValue': 256, 'minValue': 1, 'maxValue': 4096 } ] }, { 'name': 'Tonemapping', 'settings': [ { 'name': 'tonemapping:enable', 'ui_name': 'Enable Tone Mapping', 'help': 'Enable linear photographic tone mapping filter. More info in RIF documentation', 'defaultValue': False }, { 'name': 'tonemapping:exposureTime', 'ui_name': 'Film Exposure Time (sec)', 'help': 'Film exposure time', 'defaultValue': 0.125, 'minValue': 0.0, 'maxValue': 10.0, 'houdini': { 'hidewhen': 'tonemapping:enable == 0' } }, { 'name': 'tonemapping:sensitivity', 'ui_name': 'Film Sensitivity', 'help': 'Luminance of the scene (in candela per m^2)', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 10.0, 'houdini': { 'hidewhen': 'tonemapping:enable == 0' } }, { 'name': 'tonemapping:fstop', 'ui_name': 'Fstop', 'help': 'Aperture f-number', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 100.0, 'houdini': { 'hidewhen': 'tonemapping:enable == 0' } }, { 'name': 'tonemapping:gamma', 'ui_name': 'Tone Mapping Gamma', 'help': 'Gamma correction value', 'defaultValue': 1.0, 'minValue': 0.0, 'maxValue': 5.0, 'houdini': { 'hidewhen': 'tonemapping:enable == 0' } } ] }, { 'name': 'Alpha', 'settings': [ { 'name': 'alpha:enable', 'ui_name': 'Enable Color Alpha', 'defaultValue': False } ] }, { 'name': 'MotionBlur', 'settings': [ { 'name': 'beautyMotionBlur:enable', 'ui_name': 'Enable Beauty Motion Blur', 'defaultValue': True, 'help': 'If disabled, only velocity AOV will store information about movement on the scene. Required for motion blur that is generated in post-processing.', 'houdini': { 'hidewhen': hidewhen_not_northstar } } ] }, { 'name': 'OCIO', 'settings': [ { 'name': 'ocio:configPath', 'ui_name': 'OpenColorIO Config Path', 'defaultValue': '', 'c_type': 'SdfAssetPath', 'help': 'The file path of the OpenColorIO config file to be used. Overrides any value specified in OCIO environment variable.', 'houdini': { 'type': 'file', 'hidewhen': hidewhen_not_northstar } }, { 'name': 'ocio:renderingColorSpace', 'ui_name': 'OpenColorIO Rendering Color Space', 'defaultValue': '', 'c_type': 'std::string', 'houdini': { 'hidewhen': hidewhen_not_northstar } } ] }, { 'name': 'Seed', 'settings': [ { 'name': 'uniformSeed', 'ui_name': 'Use Uniform Seed', 'defaultValue': True, 'houdini': { 'hidewhen': hidewhen_hybrid } }, { 'name': 'seedOverride', 'ui_name': 'Random Seed Override', 'defaultValue': 0, 'minValue': 0, 'maxValue': 2 ** 16 } ] }, { 'name': 'Cryptomatte', 'settings': [ { 'name': 'cryptomatte:outputPath', 'ui_name': 'Cryptomatte Output Path', 'defaultValue': '', 'c_type': 'SdfAssetPath', 'help': 'Controls where cryptomatte should be saved. Use \'Cryptomatte Output Mode\' to control when cryptomatte is saved.', 'houdini': { 'type': 'file' } }, { 'name': 'cryptomatte:outputMode', 'ui_name': 'Cryptomatte Output Mode', 'defaultValue': 'Batch', 'values': [ SettingValue('Batch'), SettingValue('Interactive') ], 'help': 'Batch - save cryptomatte only in the batch rendering mode (USD Render ROP, husk). Interactive - same as the Batch but also save cryptomatte in the non-batch rendering mode. Cryptomatte always saved after \'Max Samples\' is reached.', 'houdini': { 'hidewhen': 'cryptomatte:outputPath == ""', } }, { 'name': 'cryptomatte:previewLayer', 'ui_name': 'Cryptomatte Add Preview Layer', 'defaultValue': False, 'help': 'Whether to generate cryptomatte preview layer or not. Whether you need it depends on the software you are planning to use cryptomatte in. For example, Houdini\'s COP Cryptomatte requires it, Nuke, on contrary, does not.', 'houdini': { 'hidewhen': 'cryptomatte:outputPath == ""', } } ], 'houdini': { 'hidewhen': hidewhen_not_northstar } }, { 'name': 'Camera', 'settings': [ { 'name': 'core:cameraMode', 'ui_name': 'Camera Mode', 'defaultValue': 'Default', 'values': [ SettingValue('Default'), SettingValue('Latitude Longitude 360'), SettingValue('Latitude Longitude Stereo'), SettingValue('Cubemap', enable_py_condition=NOT_NORTHSTAR_ENABLED_PY_CONDITION), SettingValue('Cubemap Stereo', enable_py_condition=NOT_NORTHSTAR_ENABLED_PY_CONDITION), SettingValue('Fisheye'), ] } ] }, { 'name': 'UsdNativeCamera', 'settings': [ { 'name': 'aspectRatioConformPolicy', 'defaultValue': 'UsdRenderTokens->expandAperture', }, { 'name': 'instantaneousShutter', 'defaultValue': False, }, ] }, { 'name': 'RprExport', 'settings': [ { 'name': 'export:path', 'defaultValue': '', 'c_type': 'SdfAssetPath' }, { 'name': 'export:asSingleFile', 'defaultValue': False }, { 'name': 'export:useImageCache', 'defaultValue': False } ] }, { 'name': 'Session', 'settings': [ { 'name': 'renderMode', 'defaultValue': 'interactive', 'values': [ SettingValue('batch'), SettingValue('interactive') ] }, { 'name': 'progressive', 'defaultValue': True } ] }, { 'name': 'ImageTransformation', 'settings': [ { 'name': 'core:flipVertical', 'defaultValue': False } ] }, { 'name': 'ViewportSettings', 'houdini': {}, 'settings': [ { 'name': 'openglInteroperability', 'ui_name': 'OpenGL interoperability (Needs render restart)', 'help': '', 'defaultValue': False, }, { 'name': 'viewportUpscaling', 'ui_name': 'Viewport Upscaling', 'help': '', 'defaultValue': False, 'houdini': { 'hidewhen': ['denoising:enable == 0', lambda settings: hidewhen_render_quality('<', 'High', settings)] } }, { 'name': 'viewportUpscalingQuality', 'ui_name': 'Viewport Upscaling Quality', 'help': '', 'defaultValue': 'Ultra Performance', 'values': [ SettingValue('Ultra Quality'), SettingValue('Quality'), SettingValue('Balance'), SettingValue('Performance'), SettingValue('Ultra Performance'), ], 'houdini': { 'hidewhen': ['rpr:viewportUpscaling == 0', 'denoising:enable == 0', lambda settings: hidewhen_render_quality('<', 'High', settings), lambda settings: hidewhen_render_quality('==', 'Northstar', settings)] } } ] } ] def camel_case_capitalize(w): return w[0].upper() + w[1:] def generate_render_setting_files(install_path, generate_ds_files): header_template = ( ''' #ifndef GENERATED_HDRPR_CONFIG_H #define GENERATED_HDRPR_CONFIG_H #include "pxr/imaging/hd/tokens.h" #include "pxr/imaging/hd/renderDelegate.h" #include "pxr/usd/sdf/assetPath.h" #include <mutex> PXR_NAMESPACE_OPEN_SCOPE {rs_tokens_declaration} {rs_mapped_values_enum} class HdRprConfig {{ public: HdRprConfig() = default; enum ChangeTracker {{ Clean = 0, DirtyAll = ~0u, DirtyInteractiveMode = 1 << 0, {rs_category_dirty_flags} }}; static HdRenderSettingDescriptorList GetRenderSettingDescriptors(); void Sync(HdRenderDelegate* renderDelegate); void SetInteractiveMode(bool enable); bool GetInteractiveMode() const; {rs_get_set_method_declarations} bool IsDirty(ChangeTracker dirtyFlag) const; void CleanDirtyFlag(ChangeTracker dirtyFlag); void ResetDirty(); private: struct PrefData {{ bool enableInteractive; {rs_variables_declaration} PrefData(); void SetDefault(); bool IsValid(); }}; PrefData m_prefData; uint32_t m_dirtyFlags = DirtyAll; int m_lastRenderSettingsVersion = -1; }}; PXR_NAMESPACE_CLOSE_SCOPE #endif // GENERATED_HDRPR_CONFIG_H ''').strip() cpp_template = ( ''' #include "config.h" #include "rprApi.h" #include "pxr/base/arch/fileSystem.h" #include "pxr/usd/usdRender/tokens.h" PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PUBLIC_TOKENS(HdRprRenderSettingsTokens, HDRPR_RENDER_SETTINGS_TOKENS); TF_DEFINE_PRIVATE_TOKENS(_tokens, ((houdiniInteractive, "houdini:interactive")) ((rprInteractive, "rpr:interactive")) ); {rs_public_token_definitions} namespace {{ {rs_range_definitions} }} // namespace anonymous HdRenderSettingDescriptorList HdRprConfig::GetRenderSettingDescriptors() {{ HdRenderSettingDescriptorList settingDescs; {rs_list_initialization} return settingDescs; }} void HdRprConfig::Sync(HdRenderDelegate* renderDelegate) {{ int currentSettingsVersion = renderDelegate->GetRenderSettingsVersion(); if (m_lastRenderSettingsVersion != currentSettingsVersion) {{ m_lastRenderSettingsVersion = currentSettingsVersion; auto getBoolSetting = [&renderDelegate](TfToken const& token, bool defaultValue) {{ auto boolValue = renderDelegate->GetRenderSetting(token); if (boolValue.IsHolding<int64_t>()) {{ return static_cast<bool>(boolValue.UncheckedGet<int64_t>()); }} else if (boolValue.IsHolding<bool>()) {{ return static_cast<bool>(boolValue.UncheckedGet<bool>()); }} return defaultValue; }}; bool interactiveMode = getBoolSetting(_tokens->rprInteractive, false); if (renderDelegate->GetRenderSetting<std::string>(_tokens->houdiniInteractive, "normal") != "normal") {{ interactiveMode = true; }} SetInteractiveMode(interactiveMode); {rs_sync} }} }} void HdRprConfig::SetInteractiveMode(bool enable) {{ if (m_prefData.enableInteractive != enable) {{ m_prefData.enableInteractive = enable; m_dirtyFlags |= DirtyInteractiveMode; }} }} bool HdRprConfig::GetInteractiveMode() const {{ return m_prefData.enableInteractive; }} {rs_get_set_method_definitions} bool HdRprConfig::IsDirty(ChangeTracker dirtyFlag) const {{ return m_dirtyFlags & dirtyFlag; }} void HdRprConfig::CleanDirtyFlag(ChangeTracker dirtyFlag) {{ m_dirtyFlags &= ~dirtyFlag; }} void HdRprConfig::ResetDirty() {{ m_dirtyFlags = Clean; }} HdRprConfig::PrefData::PrefData() {{ SetDefault(); }} void HdRprConfig::PrefData::SetDefault() {{ enableInteractive = false; {rs_set_default_values} }} bool HdRprConfig::PrefData::IsValid() {{ return true {rs_validate_values}; }} PXR_NAMESPACE_CLOSE_SCOPE ''').strip() dirty_flags_offset = 1 rs_public_token_definitions = [] rs_tokens_declaration = ['#define HDRPR_RENDER_SETTINGS_TOKENS \\\n'] rs_category_dirty_flags = [] rs_get_set_method_declarations = [] rs_variables_declaration = [] rs_mapped_values_enum = [] rs_range_definitions = [] rs_list_initialization = [] rs_sync = [] rs_get_set_method_definitions = [] rs_set_default_values = [] rs_validate_values = [] for category in render_setting_categories: disabled_category = False category_name = category['name'] dirty_flag = 'Dirty{}'.format(category_name) rs_category_dirty_flags.append(' {} = 1 << {},\n'.format(dirty_flag, dirty_flags_offset)) dirty_flags_offset += 1 def process_setting(setting): name = setting['name'] first, *others = name.split(':') c_name = ''.join([first[0].lower() + first[1:], *map(camel_case_capitalize, others)]) rs_tokens_declaration.append(' (({}, "rpr:{}")) \\\n'.format(c_name, name)) name_title = camel_case_capitalize(c_name) default_value = setting['defaultValue'] if 'c_type' in setting: c_type_str = setting['c_type'] else: c_type_str = type(default_value).__name__ if c_type_str == 'str': c_type_str = 'TfToken' type_str = c_type_str if 'values' in setting: value_tokens_list_name = '__{}Tokens'.format(name_title) value_tokens_name = 'HdRpr{}Tokens'.format(name_title) rs_mapped_values_enum.append('#define ' + value_tokens_list_name) for value in setting['values']: rs_mapped_values_enum.append(' ({})'.format(value.get_key())) rs_mapped_values_enum.append('\n') rs_mapped_values_enum.append('TF_DECLARE_PUBLIC_TOKENS({}, {});\n\n'.format(value_tokens_name, value_tokens_list_name)) rs_public_token_definitions.append('TF_DEFINE_PUBLIC_TOKENS({}, {});\n'.format(value_tokens_name, value_tokens_list_name)) type_str = 'TfToken' c_type_str = type_str default_value = next(value for value in setting['values'] if value == default_value) rs_get_set_method_declarations.append(' void Set{}({} {});\n'.format(name_title, c_type_str, c_name)) rs_get_set_method_declarations.append(' {} const& Get{}() const {{ return m_prefData.{}; }}\n\n'.format(type_str, name_title, c_name)) rs_variables_declaration.append(' {} {};\n'.format(type_str, c_name)) if isinstance(default_value, bool): rs_sync.append(' Set{name_title}(getBoolSetting(HdRprRenderSettingsTokens->{c_name}, k{name_title}Default));\n'.format(name_title=name_title, c_name=c_name)) else: rs_sync.append(' Set{name_title}(renderDelegate->GetRenderSetting(HdRprRenderSettingsTokens->{c_name}, k{name_title}Default));\n'.format(name_title=name_title, c_name=c_name)) if 'values' in setting: rs_range_definitions.append('#define k{name_title}Default {value_tokens_name}->{value}'.format(name_title=name_title, value_tokens_name=value_tokens_name, value=default_value.get_key())) else: value_str = str(default_value) if isinstance(default_value, bool): value_str = value_str.lower() rs_range_definitions.append('const {type} k{name_title}Default = {type}({value});\n'.format(type=type_str, name_title=name_title, value=value_str)) set_validation = '' if 'minValue' in setting or 'maxValue' in setting: rs_validate_values.append(' ') if 'minValue' in setting: rs_range_definitions.append('const {type} k{name_title}Min = {type}({value});\n'.format(type=type_str, name_title=name_title, value=setting['minValue'])) set_validation += ' if ({c_name} < k{name_title}Min) {{ return; }}\n'.format(c_name=c_name, name_title=name_title) rs_validate_values.append('&& {c_name} < k{name_title}Min'.format(c_name=c_name, name_title=name_title)) if 'maxValue' in setting: rs_range_definitions.append('const {type} k{name_title}Max = {type}({value});\n'.format(type=type_str, name_title=name_title, value=setting['maxValue'])) set_validation += ' if ({c_name} > k{name_title}Max) {{ return; }}\n'.format(c_name=c_name, name_title=name_title) rs_validate_values.append('&& {c_name} > k{name_title}Max'.format(c_name=c_name, name_title=name_title)) if 'minValue' in setting or 'maxValue' in setting: rs_validate_values.append('\n') rs_range_definitions.append('\n') if 'values' in setting: value_range = value_tokens_name + '->allTokens' set_validation += ' if (std::find({range}.begin(), {range}.end(), {c_name}) == {range}.end()) return;\n'.format(range=value_range, c_name=c_name) if 'ui_name' in setting: rs_list_initialization.append(' settingDescs.push_back({{"{}", HdRprRenderSettingsTokens->{}, VtValue(k{}Default)}});\n'.format(setting['ui_name'], c_name, name_title)) if disabled_category: rs_get_set_method_definitions.append('void HdRprConfig::Set{name_title}({c_type} {c_name}) {{ /* Platform no-op */ }}'.format(name_title=name_title, c_type=c_type_str, c_name=c_name)) else: rs_get_set_method_definitions.append(( ''' void HdRprConfig::Set{name_title}({c_type} {c_name}) {{ {set_validation} if (m_prefData.{c_name} != {c_name}) {{ m_prefData.{c_name} = {c_name}; m_dirtyFlags |= {dirty_flag}; }} }} ''').format(name_title=name_title, c_type=c_type_str, c_name=c_name, dirty_flag=dirty_flag, set_validation=set_validation)) rs_set_default_values.append(' {c_name} = k{name_title}Default;\n'.format(c_name=c_name, name_title=name_title)) for setting in category['settings']: if 'folder' in setting: for sub_setting in setting['settings']: process_setting(sub_setting) else: process_setting(setting) rs_tokens_declaration.append('\nTF_DECLARE_PUBLIC_TOKENS(HdRprRenderSettingsTokens, HDRPR_RENDER_SETTINGS_TOKENS);\n') header_dst_path = os.path.join(install_path, 'config.h') header_file = open(header_dst_path, 'w') header_file.write(header_template.format( rs_tokens_declaration=''.join(rs_tokens_declaration), rs_category_dirty_flags=''.join(rs_category_dirty_flags), rs_get_set_method_declarations=''.join(rs_get_set_method_declarations), rs_variables_declaration=''.join(rs_variables_declaration), rs_mapped_values_enum=''.join(rs_mapped_values_enum))) cpp_dst_path = os.path.join(install_path, 'config.cpp') cpp_file = open(cpp_dst_path, 'w') cpp_file.write(cpp_template.format( rs_public_token_definitions=''.join(rs_public_token_definitions), rs_range_definitions=''.join(rs_range_definitions), rs_list_initialization=''.join(rs_list_initialization), rs_sync=''.join(rs_sync), rs_get_set_method_definitions=''.join(rs_get_set_method_definitions), rs_set_default_values=''.join(rs_set_default_values), rs_validate_values=''.join(rs_validate_values))) if generate_ds_files: production_render_setting_categories = [category for category in render_setting_categories if category['name'] != 'ViewportSettings'] generate_houdini_ds(install_path, 'Global', production_render_setting_categories) viewport_render_setting_categories = [category for category in render_setting_categories if category['name'] in ('RenderQuality', 'Sampling', 'AdaptiveSampling', 'Denoise', 'ViewportSettings')] for category in (cat for cat in viewport_render_setting_categories if cat['name'] == 'RenderQuality'): for setting in (s for s in category['settings'] if s['name'] == 'core:renderQuality'): setting['values'] = [SettingValue(value.get_key(), value.get_key() if value.get_key() != 'Northstar' else 'Full') for value in setting['values']] generate_houdini_ds(install_path, 'Viewport', viewport_render_setting_categories) def generate(install, generate_ds_files): generate_render_setting_files(install, generate_ds_files)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,627
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py
import hashlib import json import os import re import textwrap from enum import Enum from pathlib import Path from typing import Any, Callable, Collection, Dict, Tuple, Union from urllib.parse import parse_qsl, unquote, urlencode, urljoin, urlparse, urlunparse from uuid import UUID from requests import Response, Session from requests.exceptions import HTTPError class MaterialType(Enum): STATIC = "Static" PARAMETRIC = "Parametric" class MatlibEndpoint(Enum): PREFIX = "api" AUTH = "auth" AUTH_LOGIN = "auth/login" AUTH_LOGOUT = "auth/logout" AUTH_REFRESH = "auth/token/refresh" MATERIALS = "materials" CATEGORIES = "categories" COLLECTIONS = "collections" TAGS = "tags" RENDERS = "renders" PACKAGES = "packages" def expanded_raise_for_status( response: Response, on_status_callbacks: Dict[int, Callable] = None ): if not on_status_callbacks: on_status_callbacks = {} try: if callback := on_status_callbacks.get(response.status_code, None): callback() else: response.raise_for_status() except HTTPError as e: raise HTTPError(json.dumps(response.json(), indent=4) if response.text else e) class MatlibSession(Session): def __init__(self, base: str, *args, **kwargs): super().__init__(*args, **kwargs) self.base = base self.recent = {} self.refresh_token = "" def __set_auth_token(self, access_token: str, refresh_token: str): self.headers.update({"Authorization": f"Bearer {access_token}"}) self.refresh_token = refresh_token def _refresh_token(self, endpoint: str, on_action_success: Callable = None): if self.refresh_token: response = self.post( urljoin( base=self.base, url=f"/{MatlibEndpoint.PREFIX.value}/{endpoint}/" ), json={"refresh_token": self.refresh_token}, ) expanded_raise_for_status(response) if on_action_success: on_action_success(response) else: raise Exception( textwrap.dedent( """ You didn't login yet, first call `client.session.login()` """ ) ) def refresh_session(self): def on_refresh_success(response: Response): content = response.json() self.__set_auth_token(content["access_token"], content["refresh_token"]) self._refresh_token(MatlibEndpoint.AUTH_REFRESH.value, on_refresh_success) def _login(self, password: str, email: str = "", username: str = ""): if not email and not username: raise Exception("You should provide email OR username AND password") response = self.post( url=urljoin( base=self.base, url=f"/{MatlibEndpoint.PREFIX.value}/{MatlibEndpoint.AUTH_LOGIN.value}/", ), json={"username": username, "email": email, "password": password}, ) expanded_raise_for_status(response) content = response.json() self.__set_auth_token(content["access_token"], content["refresh_token"]) def _logout(self): self._refresh_token(MatlibEndpoint.AUTH_LOGOUT.value) @staticmethod def add_url_params(url: str, params: Dict): """Add GET params to provided URL being aware of existing. :param url: string of target URL :param params: dict containing requested params to be added :return: string with updated URL """ parsed_url = urlparse(unquote(url)) query_dict = dict(parse_qsl(parsed_url.query)) # convert bool and dict to json strings query_dict = { k: json.dumps(v) if isinstance(v, (bool, dict)) else v for k, v in query_dict.items() } # collect value to dict if they are not None for k, v in params.items(): if v: query_dict.update({k: v}) parsed_url = parsed_url._replace(query=urlencode(query_dict, doseq=True)) return urlunparse(parsed_url) @staticmethod def get_last_url_path(url: str): return urlparse(url).path.rsplit("/", 1)[-1] def clear_recent(self): self.recent = {} class MatlibEntityClient: endpoint = None session = None __working_on_id = "" def __init__( self, session: MatlibSession, endpoint: MatlibEndpoint, ): self.session = session self.endpoint = endpoint @property def base_url(self): return urljoin( self.session.base, f"/{MatlibEndpoint.PREFIX.value}/{self.endpoint.value}/" ) def delete(self, item_id: Union[str, UUID] = ""): response = self.session.delete( urljoin(self.base_url, f"{item_id if item_id else self.working_on}/") ) expanded_raise_for_status(response, {401: self.session.refresh_session}) self.stop_working_on() def _get_list( self, url: str = None, limit: int = None, offset: int = None, params: Dict = None, ): url = urljoin(base=self.base_url, url=url) url = self.session.add_url_params(url, {"limit": limit, "offset": offset}) if params: url = self.session.add_url_params(url, params) response = self.session.get(url) expanded_raise_for_status(response, {401: self.session.refresh_session}) return response.json()["results"] def _get_by_id( self, item_id: Union[str, UUID] = "", url: str = None, working_on: bool = False ): url = urljoin(base=self.base_url, url=url) url = urljoin(base=url, url=f"{item_id if item_id else self.working_on}/") response = self.session.get(url) expanded_raise_for_status(response, {401: self.session.refresh_session}) content = response.json() if working_on: self.__working_on_id = content["id"] return content def _get(self, url: str = None): url = urljoin(base=self.base_url, url=url) response = self.session.get(url) expanded_raise_for_status(response, {401: self.session.refresh_session}) return response.json() def _count( self, url: str = None, params: Dict = None, ): url = urljoin(base=self.base_url, url=url) if params: url = self.session.add_url_params(url, params) response = self.session.get(url) expanded_raise_for_status(response, {401: self.session.refresh_session}) return response.json()["count"] @property def working_on(self): if self.__working_on_id: return self.__working_on_id else: raise Exception( textwrap.dedent( """ You didn't save id of entity for working on it Save it by calling `get(..., working_on=True)` or specify in function which you called """ ) ) def stop_working_on(self): self.__working_on_id = None def _download(self, url: str, target_dir: str = None): response = self.session.get(url, allow_redirects=True) filename = self.session.get_last_url_path(response.url) or "file" if not target_dir or not os.path.exists(target_dir): target_dir = "." full_filename = os.path.abspath(os.path.join(target_dir, filename)) open(full_filename, "wb").write(response.content) def _upload_file( self, method: str, file_filter: Tuple[str, str], path: Union[os.PathLike, str], mime_type: str = "", blob_key: str = "file", item_id: Union[str, UUID] = "", ): url = self.base_url if not item_id else urljoin(self.base_url, f"{item_id}/") if re.match(file_filter[0], Path(path).name): response = self.session.request( method, url, data={}, files={blob_key: (Path(path).name, open(path, "rb"), mime_type)}, ) expanded_raise_for_status(response, {401: self.session.refresh_session}) content = response.json() last_renders = self.session.recent.get(self.endpoint.value, []) if not last_renders: self.session.recent[self.endpoint.value] = last_renders last_renders.append(content["id"]) return content else: raise Exception(textwrap.dedent(file_filter[1])) def _add_object_with_title_only( self, endpoint: Union[str, MatlibEndpoint], title: str ): response = self.session.post(self.base_url, json={"title": title}) expanded_raise_for_status(response, {401: self.session.refresh_session}) content = response.json() last_added = self.session.recent.get(endpoint, []) if not last_added: self.session.recent[endpoint] = last_added last_added.append(content["id"]) return response.json() def _get_workspace( self, entity: str, search: str = None, ordering: str = None, limit: int = None, offset: int = None, ): return self._get_list( "workspace", limit, offset, {"ordering": ordering, "search": search} ) def _create(self, data: Dict[str, Any], working_on: bool = False): response = self.session.post(self.base_url, json=data) expanded_raise_for_status(response, {401: self.session.refresh_session}) content = response.json() if working_on: self.__working_on_id = content["id"] return response.json() def _update( self, data: Dict[str, Any], item_id: Union[str, UUID] = "", working_on: bool = False, ): response = self.session.patch( urljoin(self.base_url, f"{item_id if item_id else self.working_on}/"), json=data, ) expanded_raise_for_status(response, {401: self.session.refresh_session}) content = response.json() if working_on: self.__working_on_id = content["id"] return response.json() def _post_as_action( self, item_id: Union[str, UUID], action: str, data: Dict[str, Any] = None ): response = self.session.post( urljoin(self.base_url, f"{item_id}/{action}/"), data=data ) expanded_raise_for_status(response, {401: self.session.refresh_session}) return response.json() def _calculate_s3_etag(self, filename, path): filepath = os.path.join(path, filename) if not os.path.exists(filepath): return None md5s = [] with open(filepath, "rb") as fp: while True: data = fp.read(8 * 1024 * 1024) if not data: break md5s.append(hashlib.md5(data)) if len(md5s) < 1: return f"{hashlib.md5().hexdigest()}" if len(md5s) == 1: return f"{md5s[0].hexdigest()}" digests = b"".join(m.digest() for m in md5s) digests_md5 = hashlib.md5(digests) return f"{digests_md5.hexdigest()}-{len(md5s)}" class MatlibEntityListClient(MatlibEntityClient): def get_list(self, limit: int = None, offset: int = None, params: dict = None): return self._get_list(limit=limit, offset=offset, params=params) def get(self, item_id: str, working_on: bool = False): return self._get_by_id(item_id=item_id, working_on=working_on) def count(self, params: dict = None): return super()._count(params=params) class MatlibMaterialsClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.MATERIALS) def create(self, title: str, working_on: bool = False, **kwargs): return super()._create( {"title": title, "renders": [], "packages": [], **kwargs}, working_on ) def update( self, item_id: Union[str, UUID] = "", working_on: bool = False, **kwargs ): return super()._update({**kwargs}, item_id, working_on) def create_from_recent( self, title: str, exclusions: Dict[str, Union[str, Collection[Union[str, UUID]]]], clear_recent: bool = False, **kwargs, ): get_recent_records = lambda it: exclusions.get( it, self.session.recent.get(it, []) ) response = self.create( title, renders=get_recent_records("renders"), packages=get_recent_records("packages"), category=self.session.recent.get("category", ""), tags=get_recent_records("tags"), **kwargs, ) if clear_recent: self.session.clear_recent() return response def update_from_recent( self, exclusions: Dict[str, Union[str, Collection[Union[str, UUID]]]], item_id: Union[str, UUID] = "", clear_recent: bool = False, **kwargs, ): get_recent_records = lambda it: exclusions.get( it, self.session.recent.get(it, []) ) response = self.update( item_id, renders=get_recent_records("renders"), packages=get_recent_records("packages"), category=self.session.recent.get("category", ""), tags=get_recent_records("tags"), **kwargs, ) if clear_recent: self.session.clear_recent() return response def __favorite_req(self, item_id: Union[str, UUID], action: str): response = self.session.post( urljoin(self.base_url, f"{item_id}/{action}_favorite/") ) expanded_raise_for_status(response, {401: self.session.refresh_session}) return response.json() def add_to_favorite(self, item_id: Union[str, UUID] = ""): return self.__favorite_req(item_id if item_id else self.working_on, "add_to") def remove_from_favorite(self, item_id: Union[str, UUID] = ""): return self.__favorite_req( item_id if item_id else self.working_on, "remove_from" ) def get_workspace( self, search: str = None, ordering: str = None, limit: int = None, offset: int = None, ): return super()._get_workspace( self.endpoint.value, search, ordering, limit, offset ) def send_for_review(self, item_id: Union[str, UUID] = ""): return super()._post_as_action( item_id if item_id else self.working_on, "send_for_review" ) def cancel_review(self, item_id: Union[str, UUID] = ""): return super()._post_as_action( item_id if item_id else self.working_on, "cancel_review" ) class MatlibCategoriesClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.CATEGORIES) class MatlibCollectionsClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.COLLECTIONS) def create(self, title: str, working_on: bool = False, **kwargs): return super()._create({"title": title, **kwargs}, working_on) def update( self, item_id: Union[str, UUID] = "", working_on: bool = False, **kwargs ): return super()._update({**kwargs}, item_id, working_on) def get_workspace( self, search: str = None, ordering: str = None, limit: int = None, offset: int = None, ): return super()._get_workspace( self.endpoint.value, search, ordering, limit, offset ) def get_favorite( self, search: str = None, ordering: str = None, limit: int = None, offset: int = None, ): return super()._get("favorite") def add_material( self, item_id: Union[str, UUID] = "", material_id: Union[str, UUID] = None ): return super()._post_as_action( item_id if item_id else self.working_on, "add_material", {"material_id": material_id}, ) class MatlibTagsClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.TAGS) def create(self, title: str): return super()._add_object_with_title_only(self.endpoint.value, title) class MatlibRendersClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.RENDERS) def download( self, item_id: Union[str, UUID] = "", target_dir: Union[os.PathLike, str] = None ): self._download( url=urljoin( self.base_url, f"{item_id if item_id else self.working_on}/download/" ), target_dir=target_dir, ) def download_thumbnail( self, item_id: Union[str, UUID] = "", target_dir: Union[os.PathLike, str] = None ): self._download( url=urljoin( self.base_url, f"{item_id if item_id else self.working_on}/download_thumbnail/", ), target_dir=target_dir, ) def upload(self, path: Union[os.PathLike, str]): return super()._upload_file( "post", ( r".+.(jpg|png|jpeg)", """ render image pattern 'name.<ext>' doesn't match, where ext - jpg, jpeg, png """, ), path, "image/jpeg", "image", ) class MatlibPackagesClient(MatlibEntityListClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, endpoint=MatlibEndpoint.PACKAGES) def compare_etags( self, item_id: Union[str, UUID] = "", target_dir: Union[os.PathLike, str] = ".", custom_filename: str = None, ): package = super()._get_by_id(item_id=item_id) s3_etag = package["etag"] if custom_filename: local_etag = super()._calculate_s3_etag(custom_filename, target_dir) else: local_etag = super()._calculate_s3_etag(package["file"], target_dir) return s3_etag == local_etag def download( self, item_id: Union[str, UUID] = "", target_dir: Union[os.PathLike, str] = "." ): if not self.compare_etags(item_id, target_dir): self._download( url=f"{self.base_url}{item_id if item_id else self.working_on}/download/", target_dir=target_dir, ) def upload(self, path: Union[os.PathLike, str]): return super()._upload_file( "post", ( r".+_(1|2|4|8)k_(8|16|32)b.zip", """ archive filename pattern 'MaterialName_<res>k_<depth>b.zip' doesn't match, where res: 1, 2, 4, 8 depth: 8, 16, 32 """, ), path, "application/zip", "file", ) class MatlibClient: def login(self, password: str, email: str = "", username: str = ""): self.session._login(password, email, username) def logout(self): self.session._logout() self.session.clear_recent() for entity in [ self.materials, self.collections, self.categories, self.tags, self.renders, self.packages, ]: entity.stop_working_on() def __init__(self, host: str = "https://api.matlib.gpuopen.com/"): """ MaterialX Library API Client :param host (str): MaterialX Library host (default: https://api.matlib.gpuopen.com/) """ self.session = MatlibSession(host) self.materials = MatlibMaterialsClient(session=self.session) self.collections = MatlibCollectionsClient(session=self.session) self.categories = MatlibCategoriesClient(session=self.session) self.tags = MatlibTagsClient(session=self.session) self.renders = MatlibRendersClient(session=self.session) self.packages = MatlibPackagesClient(session=self.session)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,628
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/python/commonSettings.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # visibility_flag_settings = [ { 'name': 'primvars:rpr:object:visibility:camera', 'ui_name': 'Camera Visibility', 'defaultValue': True, 'help': 'Used to show or hide an object from the camera.\\n' \ 'Disabling camera visibility is the most optimized way to hide ' \ 'an object from the camera but still have it cast shadows, ' \ 'be visible in reflections, etc.' }, { 'name': 'primvars:rpr:object:visibility:shadow', 'ui_name': 'Shadow Visibility', 'defaultValue': True, 'help': 'Shadow visibility controls whether to show or to hide shadows cast by ' \ 'the object onto other surfaces (including reflected shadows and shadows ' \ 'seen through transparent objects). You might need this option to hide shadows ' \ 'that darken other objects in the scene or create unwanted effects.' }, { 'name': 'primvars:rpr:object:visibility:reflection', 'ui_name': 'Reflection Visibility', 'defaultValue': True, 'help': 'Reflection visibility makes an object visible or invisible in reflections on ' \ 'specular surfaces. Note that hiding an object from specular reflections keeps ' \ 'its shadows (including reflected shadows) visible.' }, { 'name': 'primvars:rpr:object:visibility:glossyReflection', 'ui_name': 'Glossy Reflection Visibility', 'defaultValue': True }, { 'name': 'primvars:rpr:object:visibility:refraction', 'ui_name': 'Refraction Visibility', 'defaultValue': True, 'help': 'Refraction visibility makes an object visible or invisible when seen through ' \ 'transparent objects. Note that hiding an object from refractive rays keeps its ' \ 'shadows (including refracted shadows) visible.' }, { 'name': 'primvars:rpr:object:visibility:glossyRefraction', 'ui_name': 'Glossy Refraction Visibility', 'defaultValue': True }, { 'name': 'primvars:rpr:object:visibility:diffuse', 'ui_name': 'Diffuse Visibility', 'defaultValue': True, 'help': 'Diffuse visibility affects indirect diffuse rays and makes an object visible ' \ 'or invisible in reflections on diffuse surfaces.' }, { 'name': 'primvars:rpr:object:visibility:transparent', 'ui_name': 'Transparent Visibility', 'defaultValue': True }, { 'name': 'primvars:rpr:object:visibility:light', 'ui_name': 'Light Visibility', 'defaultValue': True } ] class SettingValue(object): def __init__(self, key, ui_name=None, enable_py_condition=None): self._key = key self._ui_name = ui_name self.enable_py_condition = enable_py_condition def __eq__(self, obj): return self._key == obj def __ne__(self, obj): return not self == obj def get_ui_name(self): return self._ui_name if self._ui_name else self._key def get_key(self): return self._key.replace(' ', '')
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,629
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/pxr/imaging/plugin/hdRpr/python/generateGeometrySettingFiles.py
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import argparse from commonSettings import visibility_flag_settings, SettingValue from houdiniDsGenerator import generate_houdini_ds geometry_settings = [ { 'name': 'Mesh', 'settings': [ { 'name': 'primvars:rpr:object:id', 'ui_name': 'ID', 'defaultValue': 0, 'minValue': 0, 'maxValue': 2 ** 16 }, { 'name': 'primvars:rpr:mesh:subdivisionLevel', 'ui_name': 'Subidivision Level', 'defaultValue': 0, 'minValue': 0, 'maxValue': 7 }, { 'name': 'primvars:rpr:mesh:subdivisionCreaseWeight', 'ui_name': 'Crease Weight', 'defaultValue': 0.0, 'minValue': 0.0, 'maxValue': 3.0 }, { 'name': '$interpolateBoundary', 'ui_name': 'Boundary', 'defaultValue': 'edgeAndCorner', 'values': [ SettingValue('edgeAndCorner'), SettingValue('edgeOnly') ] }, { 'name': 'primvars:rpr:mesh:ignoreContour', 'ui_name': 'Ignore Contour', 'defaultValue': False, 'help': 'Whether to extract contour for a mesh or not' }, { 'name': 'primvars:rpr:object:assetName', 'ui_name': 'Cryptomatte Name', 'defaultValue': '', 'c_type': 'std::string', 'help': 'String used to generate cryptomatte ID. If not specified, the path to a primitive used.' }, { 'name': 'primvars:rpr:object:deform:samples', 'ui_name': 'Geometry Time Samples', 'defaultValue': 1, 'minValue': 1, 'maxValue': 2 ** 16, 'help': 'The number of sub-frame samples to compute when rendering deformation motion blur over the shutter open time. The default is 1 (sample only at the start of the shutter time), giving no deformation blur by default. If you want rapidly deforming geometry to blur properly, you must increase this value to 2 or more. Note that this value is limited by the number of sub-samples available in the USD file being rendered.' }, { 'folder': 'Visibility Settings', 'settings': visibility_flag_settings } ] } ] def generate(install, generate_ds_files): if generate_ds_files: generate_houdini_ds(install, 'Geometry', geometry_settings)
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,630
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
refs/heads/master
/cmake/macros/shebang.py
# # Copyright 2017 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # # # Usage: # shebang shebang-str source.py dest.py # shebang file output.cmd # # The former substitutes '/pxrpythonsubst' in <source.py> with <shebang-str> # and writes the result to <dest.py>. The latter generates a file named # <output.cmd> with the contents '@python "%~dp0<file>"'; this is a # Windows command script to execute "python <file>" where <file> is in # the same directory as the command script. import sys if len(sys.argv) < 3 or len(sys.argv) > 4: print "Usage: %s {shebang-str source.py dest|file output.cmd}" % sys.argv[0] sys.exit(1) if len(sys.argv) == 3: with open(sys.argv[2], 'w') as f: print >>f, '@python "%%~dp0%s" %%*' % (sys.argv[1], ) else: with open(sys.argv[2], 'r') as s: with open(sys.argv[3], 'w') as d: for line in s: d.write(line.replace('/pxrpythonsubst', sys.argv[1]))
{"/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibrary.py": ["/pxr/imaging/plugin/rprHoudini/scripts/python/houRpr/materialLibraryClient.py"]}
47,631
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/test.py
from random import random import numpy as np import random # print(np.logical_xor([1, 1, 0, 0], [1, 0, 1, 0])) # print(1 & 0) # import networkx as nx # G = nx.Graph() # elist = [(1, 2), (2, 3), (1, 4), (4, 2), (2,1)] # G.add_edges_from(elist) # print(G[1]) # for i in G[1]: # print(i) # L = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0" # c = 0 # while c < len(L): # # print(c) # if L[c] == '1': # print(c//2) # c+=2 def LimitClique(Chrom,G): # Chrom is a vector with binary values nodes = [] for i in range(len(Chrom)): if Chrom[i] == 1: nodes.append(i+1) k = nodes.pop(random.randrange(len(nodes))) CliqueV = [] CliqueV.append(k) for n in nodes: if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) print(CliqueV) # Create New Chromosome of updated clique NewChrom = [0] * len(Chrom) for v in CliqueV: NewChrom[v-1] = 1 return NewChrom graph = {1:[2, 5], 2:[1, 3, 4, 6], 3:[2, 4, 6], 4:[2, 3, 5, 6], 5:[1, 4, 6], 6:[2, 3, 4, 5]} Chrom = [1,1,1,1,1,0] print(LimitClique(Chrom,graph)) import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar')) plt.show()
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,632
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/ReadGraph.py
import networkx as nx def importGraphs(fileName): with open(fileName, 'r') as f: content = f.read().splitlines() i = 0 while (i < len(content) and content[i][0] != 'e'): i+=1 content = content[i:] content = [x.split()[1:] for x in content] edges = [(int(x[0]),int(x[1])) for x in content] for j in edges: print(j) return edges importGraphs("Graphs/r125.1.col.txt")
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,633
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/cliqueAco.py
import numpy from ImportGraph import ImportGraph import matplotlib.pyplot as plt import networkx as nx import numpy as np import random import pandas as pd class AntClique: def __init__(self, G, noAnts=10, taoMax=4, taoMin=0.01, decay=0.995, iterr=3000, alpha=2): self.noAnts = noAnts self.taoMax = taoMax self.taoMin = taoMin self.decay = decay self.iterr = iterr self.alpha = alpha self.pher_matrix = None self.G = G self.best_clique_global = [] def init_pher_matrix(self): # initialize pheromone matrix with maximum tao value size = self.G.number_of_nodes() self.pher_matrix = np.zeros((size, size)) for node in self.G.nodes(): for nbr in self.G.neighbors(node): self.pher_matrix[node-1][nbr-1] = self.taoMax return self.pher_matrix def create_clique(self, indx): # initialize clique and possible candidates for clique as sets clique = set() candidates = set() def nbrs(node): return set(self.G.neighbors(node)) def pher_clique_sum(node): return sum([ self.pher_matrix[node-1][clique_node-1] for clique_node in clique]) init_node = random.sample(self.G.nodes(), 1)[0] clique.add(init_node) candidates.update(self.G.neighbors(init_node)) while candidates: # print(pher_matrix, clique) pher_values = [pher_clique_sum( node)**self.alpha for node in candidates] sum_pher = sum(pher_values) if sum_pher != 0: probs = [pher_value/sum_pher for pher_value in pher_values] else: probs = [0.0 for pher_value in pher_values] next_vertex = np.random.choice( list(candidates), size=1, p=probs)[0] clique.add(next_vertex) candidates = candidates.intersection(nbrs(next_vertex)) return clique def update_pher_matrix(self, ant_cliques): best_clique = max(ant_cliques, key=lambda x: len(x)) # print(best_clique) if len(best_clique) > len(self.best_clique_global): self.best_clique_global = best_clique.copy() best_len_global = len(self.best_clique_global) best_len = len(best_clique) # applying evaporation for node in self.G.nodes(): for nbr in self.G.neighbors(node): if node != nbr: self.pher_matrix[node-1][nbr - 1] = max(self.taoMin, self.decay*self.pher_matrix[node-1][nbr-1]) # updating the pheromone matrix according to the best ant in an iteration for node in best_clique: for nbr in self.G.neighbors(node): if node != nbr: self.pher_matrix[node-1][nbr-1] = min(self.taoMax, (1/( 1 + best_len_global - best_len)) + self.pher_matrix[node-1][nbr-1]) def max_clique_ACO(self): # initialize pheromone matrix self.pher_matrix = self.init_pher_matrix() # print(self.pher_matrix) # print(self.pher_matrix[29][9]) best, avg = [], [] ant_cliques = [] for i in range(self.iterr): temp_avg = [] for i in range(self.noAnts): clique = self.create_clique(i) ant_cliques.append(clique) temp_avg.append(len(clique)) # ant_cliques = [self.create_clique(i) for i in range(self.noAnts)] self.update_pher_matrix(ant_cliques) best.append(len(self.best_clique_global)) avg.append(sum(temp_avg)/self.noAnts) length = len(self.best_clique_global) print("The length of global best clear after", self.iterr, "iterations is", length) return avg, best def results_aco(iterr, G): antClique = AntClique(G=G, iterr=iterr) avg, best = antClique.max_clique_ACO() return avg, best, antClique.best_clique_global # G = ImportGraph("graphs/c125.9.txt") # print(results_aco(10, G)) # print(ant.init_pher_matrix()) # print(ant.create_clique()) # print(ant.max_clique_ACO()) # G = nx.Graph() # G.add_nodes_from([i for i in range(1, 6+1)]) # G.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 6), # (3, 4), (3, 6), (4, 5), (5, 6), (4, 6)]) # def init_pher_matrix(G): # # initialize pheromone matrix with maximum tao value # size = G.number_of_nodes() # pher_matrix = np.zeros((size, size)) # for node in G.nodes(): # for nbr in G.neighbors(node): # pher_matrix[node-1][nbr-1] = taoMax # return pher_matrix # def create_clique(G): # # initialize clique and possible candidates for clique as sets # clique = set() # candidates = set() # def nbrs(node): return set(G.neighbors(node)) # def pher_clique_sum(node): return sum([ # pher_matrix[node-1][clique_node-1] for clique_node in clique]) # init_node = random.sample(G.nodes(), 1)[0] # clique.add(init_node) # candidates.update(G.neighbors(init_node)) # while candidates: # # print(pher_matrix, clique) # pher_values = [pher_clique_sum(node)**alpha for node in candidates] # print(pher_values) # sum_pher = sum(pher_values) # if sum_pher != 0: # probs = [pher_value/sum_pher for pher_value in pher_values] # else: # probs = [0.0 for pher_value in pher_values] # print(probs) # next_vertex = np.random.choice(list(candidates), size=1, p=probs)[0] # clique.add(next_vertex) # candidates = candidates.intersection(nbrs(next_vertex)) # return clique # def update_pher_matrix(ant_cliques): # best_clique = max(ant_cliques, key=lambda x: len(x)) # # print(best_clique) # if len(best_clique) > len(best_clique_global): # best_clique_global = best_clique.deepcopy() # best_len_global = len(best_clique_global) # best_len = len(best_clique) # for node in G.nodes(): # for nbr in G.neighbors(node): # if n != nbr: # pher_matrix[node-1][nbr - # 1] = max(taoMin, decay*pher_matrix[node-1][nbr-1]) # for node in best_clique: # for nbr in G.neighbors(node): # if n != nbr: # pher_matrix[node-1][nbr-1] = min(taoMax, (1/( # 1 + best_len_global - best_len)) + pher_matrix[node-1][nbr-1]) # def max_clique_ACO(filname="graphs/r125.col-1.txt", noAnts_=7, taoMax_=4, taoMin_=0.01, decay_=0.995, alpha_=2, iterr_=3000): # #global parameters # global taoMax # global taoMin # global noAnts # global decay # global alpha # global iterr # global pher_matrix # global G # # initialize # # best_clique_global = None # noAnts = noAnts_ # taoMax = taoMax_ # taoMin = taoMin_ # decay = decay_ # iterr = iterr_ # alpha = alpha_ # #import Graph # G = nx.Graph() # G.add_nodes_from([i for i in range(1, 6+1)]) # G.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 6), # (3, 4), (3, 6), (4, 5), (5, 6), (4, 6)]) # # initialize pheromone matrix # pher_matrix = init_pher_matrix(G) # # print(pher_matrix) # for i in range(iterr): # ant_cliques = [create_clique(G) for i in range(noAnts)] # update_pher_matrix(ant_cliques) # length = len(best_clique_global) # return length # print(max_clique_ACO()) # # pher_matrix = init_pher_matrix(G) # # print(create_clique(G))
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,634
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/GA_clique.py
import random import numpy as np import pandas as pd import networkx as nx population_size = 40 no_parents = 2 fitness = [] population = [] b_population = [] mutation_rate = 0.9 crossover_rate = 0.9 # NumOfNodes = 0 def importGs(G, fileName): with open(fileName, 'r') as f: content = f.read().splitlines() # Extract Number of Nodes for line in content: if line[0] == "p": NumOfNodes = int(line.split()[2]) break # Extract Edges i = 0 while (i < len(content) and content[i][0] != 'e'): i += 1 content = content[i:] edges = [] for x in content: x = x.split() edges.append((int(x[1]), int(x[2]))) # create graph G = nx.Graph() G.add_nodes_from([i for i in range(1, NumOfNodes+1)]) G.add_edges_from(edges) G = nx.to_dict_of_lists(G) return G def init_pop(G): # print("len(graph.keys())", len(G.keys())) vertices = random.sample(range(1,len(G.keys())+1), population_size) # print(vertices) for vert in vertices: CliqueV = [] CliqueV.append(vert) # print(graph[vert]) random.shuffle(G[vert]) # print(random_values) # print(graph[vert]) for n in G[vert]: if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) # Create New Chromosome of updated clique NewChrom = [0] * len(G.keys()) for v in CliqueV: NewChrom[v-1] = 1 b_population.append(NewChrom) # print("new", b_population) return G def fit(arr): # fitness = [] for i in range(len(arr)): fitness.append(sum(arr[i])) # print("fitness" , fitness) def fps_selection(no_parents, survival=False): selected = list() prob = [] # print("fitness", fitness) # calculating fitness probability sum_fitness = np.sum(fitness) sum_fitness_inv = - np.sum(fitness - sum_fitness) if survival: selected = set() for i in range(len(fitness)): prob.append((sum_fitness-fitness[i])/sum_fitness_inv) else: for i in range(len(fitness)): prob.append(fitness[i]/sum_fitness) # print("prob", prob) # cumulative sum series = pd.Series(prob) cums_prob = series.cumsum() # print(cums_prob) # selecting parents/non-survivors if survival == True: count = no_parents//2 else: count = no_parents while len(selected) < count: rand = random.random() if rand < cums_prob[0]: if survival: selected.add(0) else: selected.append(0) else: for j in range(population_size): if cums_prob[j] < rand < cums_prob[j+1]: if survival: selected.add(j+1) else: selected.append(j+1) break return list(selected) # def random(): def finding_children(new_parents): #new parents is the list of indices of the parent children = [] for i in range(0, len(new_parents), 2): child = crossover(b_population[new_parents[i]], b_population[new_parents[i+1]]) children.append(child) return children def crossover(parent1, parent2): if(random.random() < crossover_rate ): child = np.bitwise_and(parent1, parent2) else: child = parent1 #if crossover doesnt happen then just return a copy of a parent return child def mutation(children_to_mutate, mutation_rate): for c in children_to_mutate: if(random.random() < mutation_rate ): #the selected vertex to flip vertex = random.randint(0, len(c) - 1 ) # print("vertex", vertex) #flipping c[vertex]= 1 - c[vertex] return children_to_mutate def trunc(): worst = [] for i in range(no_parents//2): worst.append(fitness.index(min(fitness))) return worst def add_to_pop(new_members): for i in new_members: b_population.append(i) fit(new_members) def pop_resize(selected): for i in selected: del b_population[i] del fitness[i] # ------------------------- Clique optimization functions ---------------- def check_Clique(Chrom, G): #Chrom is a vector with binary values nodes = [] for i in range(len(Chrom)): if Chrom[i] == 1: nodes.append(i+1) if (sum(nodes) != 0): k = nodes.pop(random.randrange(len(nodes))) else: k = random.randint(1, len(G.keys())) # randnums= np.random.randint(1,len(G.keys()) +1,len(G.keys())) # random.shuffle(randnums) # print(G.keys()) # print(randnums) # print(k) at = [] for i in G.keys(): at.append(i) at.remove(k) random.shuffle(at) CliqueV = [] CliqueV.append(k) # m = G.keys() # random.shuffle(m) for n in at: if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) # print(CliqueV) # Create New Chromosome of updated clique NewChrom = [0] * len(Chrom) for v in CliqueV: NewChrom[v-1] = 1 # print("new", NewChrom) return NewChrom def expand_clique(Chrom, G): #elements not a part of the clique nodes0 = [] for i in range(len(Chrom)): if Chrom[i] == 0: nodes0.append(i+1) #already present clique elements nodes1 = [] for i in range(len(Chrom)): if Chrom[i] == 1: nodes1.append(i+1) #we now have all the indexes and vertices where we have a zero and currently #they are not a part of the clique new_clique_elements = [] # CliqueV.append(k) for i in nodes0: for x in nodes1: if i in G[x]: p = True else: p = False break if p == True: new_clique_elements.append(i) # print("new", new_clique_elements) # Create New Chromosome of updated clique # NewChrom = [0] * len(Chrom) for v in new_clique_elements: Chrom[v-1] = 1 return Chrom #--------------------------------------- main ------------------------ def results_ga(generations, gr): # G = importGs(G, "graphs\c125.9.txt") return main(generations, gr) def main(iterr, graph): #function testing G = graph generations = iterr init_pop(G) # print("G", G) # print("Binary population", b_population) fit(b_population) # print("fitnesss", fitness) max_fitness_array = [] avg_fitness_array = [] max_nodes = [] for num in range(generations): print(num) parents = fps_selection(no_parents, False) # print("parents", parents) offspring = finding_children(parents) for y in range(len(offspring)): offspring[y] = check_Clique(offspring[y] , G) # print("Offspring", offspring) mutated_offspring = mutation(offspring, mutation_rate) # print("Mutated Offspring", mutated_offspring) #check if each offspring satisfies the condition of a clique #if not a clique, then make it a clique for y in range(len(mutated_offspring)): mutated_offspring[y] = check_Clique(mutated_offspring[y], G) for y in range(len(mutated_offspring)): mutated_offspring[y] = expand_clique(mutated_offspring[y], G) # print("mutated_final_cliques", mutated_offspring) add_to_pop(mutated_offspring) # print("after add to pop", len(b_population))46 to_remove = fps_selection(no_parents, True) # to_remove = trunc() # print("indices to be removed from pop", to_remove) pop_resize(to_remove) # print(len(b_population)) # print("final fitness array", fitness) #for graphs # avg_fitness_array.append(sum(fitness)/population_size) # max_fitness_array.append(max(fitness)) print("maxfit",max(fitness)) if max(fitness) == 65: break #----------------------------------------------------for graph---------------------------------------------# max_clique_idx = fitness.index(max(fitness)) max_clique_chrom = b_population[max_clique_idx] # print("max_clique_chrom", max_clique_chrom) for i in range(len(max_clique_chrom)): if max_clique_chrom[i] == 1: max_nodes.append(i+1) # return (max(max_fitness_array),max(avg_fitness_array), max_nodes) # print() return (avg_fitness_array, max_fitness_array, max_nodes) G = {} G = importGs(G, "graphs/C125.9.txt") # n , k, m= results_ga(10000, G) # print(n, k, m) # print(n, k, m) def checkClique(G, C): for v in C: for j in C: if v != j: if v not in G[j]: return False return True # C = m # # print(checkClique(G, C)) # print(checkClique(G, C)) # a = n # b = 44
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,635
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/testGA.py
from GA_clique import results_ga from ImportGraph import * from Visualize_Graph import * graph1fileName = "Graphs/r125.1.col.txt" graph2fileName = "Graphs/keller4.txt" G = ImportGraph(graph1fileName) maxCliqueNodes = results_ga(400, nx.to_dict_of_lists(G))[2] print("maxCliqueNodes: ",maxCliqueNodes) visualizeClique(G,maxCliqueNodes,"ACO Max Clique")
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,636
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/BPSO.py
from ImportGraph import ImportGraph from random import random, randint import numpy as np from LocalOptimizationFunctions import ExpandClique # Boolean Particle Swarm Optimization class BPSO: def __init__(self, numOfParticles, dimensions, fitnessFunc, maxIter, C1 = 0.6, C2 = 0.2, Omega=0.1, particleLocalOptimizationFunc = None, printParticles = False, printGbest = False): self.C1 = C1 # Probablity of c1 (cognitive boolean weightage) being 1 self.C2 = C2 # Probablity of c2 (social boolean weightage) being 1 self.Omega = Omega # Probablity of omega (inertia boolean weightage) being 1 self.particlesPosition = self.initializeRandomly( numOfParticles, dimensions) self.particlesVelocity = self.initializeRandomly( numOfParticles, dimensions) self.gBest = np.zeros(dimensions, dtype=int) self.gBestFitness = 0 self.pBest = np.zeros((numOfParticles, dimensions,), dtype=int) self.pBestFitness = np.zeros(numOfParticles, dtype=int) self.numOfParticles = numOfParticles self.dimensions = dimensions self.fitnessFunc = fitnessFunc self.maxIter = maxIter self.printParticles = printParticles self.printGbest = printGbest self.ParticleLocalOptimizationFunc = particleLocalOptimizationFunc def initializeRandomly(self, numOfParticles, dimensions): return (np.random.randint(2, size=(numOfParticles, dimensions))) def updateParticle(self, p): for d in range(self.dimensions): if random() < self.C1: c1 = 1 else: c1 = 0 if random() < self.C2: c2 = 1 else: c2 = 0 if random() < self.Omega: omega = 1 else: omega = 0 x = self.particlesPosition[p][d] v = self.particlesVelocity[p][d] self.particlesVelocity[p][d] = omega & v | c1 & ( self.pBest[p][d] ^ x) | c2 & (self.gBest[d] ^ x) self.particlesPosition[p][d] = x ^ self.particlesVelocity[p][d] if self.ParticleLocalOptimizationFunc is not None: # print("before",self.particlesPosition[p]) self.particlesPosition[p] = self.ParticleLocalOptimizationFunc(self.particlesPosition[p]) # print("after",self.particlesPosition[p]) def execute(self): for i in range(self.maxIter): for p in range(self.numOfParticles): fitness = self.fitnessFunc(self.particlesPosition[p]) # Update Personal Best if fitness > self.pBestFitness[p]: self.pBestFitness[p] = fitness self.pBest[p] = self.particlesPosition[p] # Update Global Best if fitness > self.gBestFitness: self.gBestFitness = fitness self.gBest = self.particlesPosition[p] self.updateParticle(p) if self.printParticles: print("Particles Position:") print(self.particlesPosition) print() if self.printGbest: print("Global Best Fitness: ", self.gBestFitness) print("Global Best: ", self.gBest) print() def benchmark(self): avgFitness = [] bestFitness = [] for i in range(self.maxIter): total = 0 for p in range(self.numOfParticles): fitness = self.fitnessFunc(self.particlesPosition[p]) # Update Personal Best if fitness > self.pBestFitness[p]: self.pBestFitness[p] = fitness self.pBest[p] = self.particlesPosition[p] # Update Global Best if fitness > self.gBestFitness: self.gBestFitness = fitness self.gBest = self.particlesPosition[p] total += fitness self.updateParticle(p) avgFitness.append(int(total/self.numOfParticles)) bestFitness.append(self.gBestFitness) if self.printParticles: print("Particles Position:") print(self.particlesPosition) print() if self.printGbest: print("Global Best Fitness: ", self.gBestFitness) print("Global Best: ", self.gBest) print() maxCliqueNodes = [] for i in range(self.dimensions): if self.gBest[i] == 1: maxCliqueNodes.append(i+1) return (avgFitness,bestFitness,maxCliqueNodes,) def gBestDimensionPositions(self): nodes = [] for i in range(self.dimensions): if self.gBest[i] == 1: nodes.append(i+1) return nodes # graph = { # 1: [2, 3, 4], # 2: [3, 1], # 3: [2, 1], # 4: [3, 1] # } graph1fileName = "Graphs/C125.9.txt" G = ImportGraph(graph1fileName) def maxCliqueFitness(array,graph=G): nodes = [] for i in range(len(array)): if array[i] == 1: nodes.append(i) # print("nodes: ",nodes) # for n in nodes: # print(graph[n+1]) for n1 in nodes: for n2 in nodes: if n1 != n2: if (n2+1) not in graph[n1+1]: # If other selected nodes are not in the neigbourhood of n1 return 0 return len(nodes) def maxCliqueClosenessFitness(array,graph): nodes = [] for i in range(len(array)): if array[i] == 1: nodes.append(i) # print("nodes: ",nodes) # for n in nodes: # print(graph[n+1]) return len(nodes) # from LocalOptimizationFunctions import ExpandExistingClique,LimitClique # def ParticleExpandClique(array): # return ExpandExistingClique(LimitClique(array,G),G) # def maxFunc(array): # return maxCliqueFitness(array,G) # bpso = BPSO(numOfParticles=200, dimensions= G.number_of_nodes(), # fitnessFunc=maxCliqueFitness, maxIter=400, particleLocalOptimizationFunc = ParticleExpandClique) # avgFitness,bestFitness,maxCliqueNodes = bpso.benchmark() # print() # print(bpso.gBestDimensionPositions()) # print('gbest',bpso.gBestFitness) # print('maxCliqueNodes',maxCliqueNodes) # print('avgFitness',avgFitness) # print('bestFitness',bestFitness)
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,637
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/ImportGraphCustom.py
import networkx as nx import matplotlib.pyplot as plt def ImportGraph(fileName): with open(fileName, 'r') as f: content = f.read().splitlines() NumOfNodes = int(content[0]) NumOfEdges = int(content[1]) # Extract Edges content = content[2:] print(content) # content = [x.split()[1:] for x in content] edges = [] for x in content: x = x.split() edges.append((int(x[1]), int(x[2]))) G = nx.Graph() G.add_nodes_from([i for i in range(1, NumOfNodes+1)]) G.add_edges_from(edges) return G # G = ImportGraph("r125.col.txt") # nx.draw(G) # plt.show()
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,638
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/testBPSO.py
from BPSO import * from ImportGraph import * from Visualize_Graph import * from LocalOptimizationFunctions import ExpandExistingClique,LimitClique graph1fileName = "Graphs/r125.1.col.txt" graph2fileName = "Graphs/keller4.txt" G = ImportGraph(graph1fileName) def maxFunc(array): return maxCliqueFitness(array,G) def ParticleExpandClique(array): return ExpandExistingClique(LimitClique(array,G),G) # bpso = BPSO(numOfParticles=5, dimensions=G.number_of_nodes(), # fitnessFunc=maxFunc, maxIter=30, particleLocalOptimizationFunc = ParticleExpandClique, # printParticles = True, printGbest = True) bpso = BPSO(numOfParticles=50, dimensions=G.number_of_nodes(), fitnessFunc=maxFunc, maxIter=100, particleLocalOptimizationFunc = ParticleExpandClique, printParticles = False, printGbest = True) bpso.benchmark() maxCliqueNodes = bpso.gBestDimensionPositions() print("maxCliqueNodes: ",maxCliqueNodes) visualizeClique(G,maxCliqueNodes,"BPSO Max Clique")
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,639
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/ImportGraph.py
import networkx as nx def ImportGraph(fileName): with open(fileName, 'r') as f: content = f.read().splitlines() # Extract Number of Nodes for line in content: if line[0] == "p": NumOfNodes = int(line.split()[2]) break # Extract Edges i = 0 while (i < len(content) and content[i][0] != 'e'): i += 1 content = content[i:] edges = [] for x in content: x = x.split() edges.append((int(x[1]), int(x[2]))) # create graph G = nx.Graph() G.add_nodes_from([i for i in range(1, NumOfNodes+1)]) G.add_edges_from(edges) return G # ImportGraph("Graphs/r125.1.col.txt")
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,640
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/Visualize_Graph.py
import networkx as nx import matplotlib.pyplot as plt def visualizeClique(graph,cliqueNodes,graphName = None): node_colors = [] for i in range(1,graph.number_of_nodes()+1): if i in cliqueNodes: node_colors.append("red") else: node_colors.append("blue") nx.draw_spring(graph, with_labels = True, node_color = node_colors) if graphName != None: plt.title(graphName) plt.show() def visualizeCliqueSave(graph,cliqueNodes,fileName): node_colors = [] for i in range(1,graph.number_of_nodes()+1): if i in cliqueNodes: node_colors.append("red") else: node_colors.append("blue") nx.draw_spring(graph, with_labels = True, node_color = node_colors) plt.savefig(fileName)
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,641
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/LocalOptimizationFunctions.py
import random import numpy as np def ExpandClique(Chrom,G): #Chrom is a vector with binary values nodes = [] for i in range(len(Chrom)): if Chrom[i] == 1: nodes.append(i+1) if (sum(nodes) != 0): k = nodes.pop(random.randrange(len(nodes))) else: k = random.randint(1,len(G.nodes())) CliqueV = [] CliqueV.append(k) for n in list(G.nodes()): if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) # Create New Chromosome of updated clique NewChrom = np.zeros(len(Chrom)) for v in CliqueV: NewChrom[v-1] = 1 return NewChrom def ExpandExistingClique(Chrom,G): #Chrom is a vector with binary values CliqueV = [] for i in range(len(Chrom)): if Chrom[i] == 1: CliqueV.append(i+1) for n in list(G.nodes()): if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) # Create New Chromosome of updated clique NewChrom = np.zeros(len(Chrom)) for v in CliqueV: NewChrom[v-1] = 1 return NewChrom def LimitClique(Chrom,G): # Chrom is a vector with binary values nodes = [] for i in range(len(Chrom)): if Chrom[i] == 1: nodes.append(i+1) if (sum(nodes) != 0): k = nodes.pop(random.randrange(len(nodes))) else: k = random.randint(1,len(G.nodes())) CliqueV = [] CliqueV.append(k) for n in nodes: if all(True if n in G[v] else False for v in CliqueV): # If n is in the neighbourhood of all nodes in the clique CliqueV.append(n) # Create New Chromosome of updated clique NewChrom = np.zeros(len(Chrom)) for v in CliqueV: NewChrom[v-1] = 1 return NewChrom graph = { 1:[2, 5], 2:[1, 3, 4, 6], 3:[2, 4, 6], 4:[2, 3, 5, 6], 5:[1, 4, 6], 6:[2, 3, 4, 5] } # Chrom = [1,1,1,1,1,0] # print(LimitClique(Chrom,graph))
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,642
rabeeaatif/Maximum-Clique-Solved-through-Evolutionary-Algorithms
refs/heads/main
/Performance.py
import networkx import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from BPSO import * from GA_clique import * from cliqueAco import results_aco from ImportGraph import * from Visualize_Graph import * from LocalOptimizationFunctions import ExpandExistingClique,LimitClique def results_GA(Iters,Graph): return main(Iters,nx.to_dict_of_lists(Graph)) def results_bpso_locally_optimized(Iters,Graph): def maxFunc(array): return maxCliqueFitness(array,Graph) def ParticleExpandClique(array): return ExpandExistingClique(LimitClique(array,Graph),Graph) bpso = BPSO(numOfParticles=100, dimensions=Graph.number_of_nodes(), fitnessFunc=maxFunc, maxIter= Iters, particleLocalOptimizationFunc = ParticleExpandClique, printParticles = False, printGbest = False) return bpso.benchmark() def results_bpso(Iters,Graph): def maxFunc(array): return maxCliqueFitness(array,Graph) bpso = BPSO(numOfParticles=200, dimensions=Graph.number_of_nodes(), fitnessFunc=maxFunc, maxIter= Iters, particleLocalOptimizationFunc = None, printParticles = False, printGbest = False) return bpso.benchmark() def compare_metaheuristics(graph,n_iters=15,graphName = "C125.9"): print("Starting Comparision...") iters = [i for i in range(n_iters)] avgFitness_bpso, bestFitness_bpso, maxCliqueNodes_bpso = results_bpso(n_iters,graph) print("bpso Complete") avgFitness_bpso_LO, bestFitness_bpso_LO, maxCliqueNodes_bpso_LO = results_bpso(n_iters,graph) print("bpso_LO Complete") avgFitness_GA, bestFitness_GA, maxCliqueNodes_GA = results_GA(n_iters,graph) print("GA Complete") avgFitness_ACO, bestFitness_ACO, maxCliqueNodes_ACO = results_aco(n_iters,graph) print("ACO Complete") y_names = ['BPSO', "BPSO with Local Optimization","ACO", "GA"] plot_style = '*' # Plot Average Fitness comparision graphs avgFitness = {"Iterations" : iters, "BPSO": avgFitness_bpso, "BPSO with Local Optimization": avgFitness_bpso_LO , "ACO" : avgFitness_ACO , "GA" : avgFitness_GA } frame = pd.DataFrame(avgFitness) frame.plot(x ='Iterations', y = y_names) plt.title('Average Fitness against Number of Iterations') plt.ylabel("Fitness (Nodes in Clique)") plt.savefig('Plots/plot-average-fitness-' + graphName + '.png') plt.show() print(frame) visualizeClique() # Plot Best Fitness comparision graphs bestFitness = {"Iterations" : iters, "BPSO": bestFitness_bpso, "BPSO with Local Optimization": bestFitness_bpso_LO , "ACO" : bestFitness_ACO , "GA" : bestFitness_GA } frame = pd.DataFrame(bestFitness) frame.plot(x ='Iterations', y = y_names) plt.title('Best Fitness (Clique Size) against Number of Iterations') plt.ylabel("Fitness (Maximum Clique Nodes)") plt.savefig('Plots/plot-best-fitness-'+ graphName +'.png') plt.show() print(frame) def compare_metaheuristics_graphs(n_iters=15): print("Starting Comparision...") graphFileNames = os.listdir("Graphs/") print(graphFileNames) fields=['Graph Name','BPSO','ACO'] with open('output.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) allGraphNames = [] bestFitness_bpso_LO = [] # bestFitness_GA = [] bestFitness_ACO = [] iters = [i for i in range(n_iters)] for fileName in graphFileNames: graph = ImportGraph("Graphs/"+fileName) graphName = fileName[:-4] if graphName[-4:] == ".col": graphName = graphName[:-4] print(graphName) allGraphNames.append(graphName) bestFitness_bpso_LO.append(max(results_bpso_locally_optimized(n_iters,graph)[1])) # bestFitness_GA.append(max(results_GA(n_iters,graph)[1])) bestFitness_ACO.append(max(results_aco(n_iters,graph)[1])) fields=[graphName,str(bestFitness_bpso_LO[-1]),bestFitness_ACO[-1]] with open('output.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) bestFitness = {"Graph Name" : allGraphNames, "BPSO": bestFitness_bpso_LO , "ACO" : bestFitness_ACO ,# "GA" : bestFitness_GA } frame = pd.DataFrame(bestFitness) frame.to_csv("Fitness_Comparision_Table.csv") print(frame) graph1fileName = "Graphs/C125.9.txt" graph2fileName = "Graphs/MANN_a27.txt" graph3fileName = "Graphs/r125.1.col.txt" graph4fileName = "Graphs/keller4.txt" G = ImportGraph(graph3fileName) compare_metaheuristics(G,500,"r125.1") # compare_metaheuristics_graphs(800)
{"/cliqueAco.py": ["/ImportGraph.py"], "/testGA.py": ["/GA_clique.py", "/ImportGraph.py", "/Visualize_Graph.py"], "/BPSO.py": ["/ImportGraph.py", "/LocalOptimizationFunctions.py"], "/testBPSO.py": ["/BPSO.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"], "/Performance.py": ["/BPSO.py", "/GA_clique.py", "/cliqueAco.py", "/ImportGraph.py", "/Visualize_Graph.py", "/LocalOptimizationFunctions.py"]}
47,698
dfana01/pbx-dashboard
refs/heads/master
/app/config.py
import os class BaseConfig(object): SITE_NAME = 'Dashboard-PBX' SECRET_KEY = os.environ.get('SECRET_KEY', 'Gox0Agv8KS') MYSQL_DATABASE_USER = 'pbx-dashboard' MYSQL_DATABASE_PASSWORD = 'password' MYSQL_DATABASE_DB = 'asteriskcdrdb' MYSQL_DATABASE_HOST = 'pbx.dfb.com.do' SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = 'mysql://{}:{}@{}/{}'.format( MYSQL_DATABASE_USER, MYSQL_DATABASE_PASSWORD, MYSQL_DATABASE_HOST, MYSQL_DATABASE_DB) SUPPORTED_LOCALES = ['es'] class DevConfig(BaseConfig): """Development configuration options.""" DEBUG = True ASSETS_DEBUG = True WTF_CSRF_ENABLED = False TESTING = False class TestConfig(BaseConfig): """Testing configuration options.""" TESTING = True WTF_CSRF_ENABLED = False
{"/app/__init__.py": ["/app/extensions.py"], "/run.py": ["/app/__init__.py"]}
47,699
dfana01/pbx-dashboard
refs/heads/master
/app/extensions.py
from flask_restless import APIManager from flask_assets import Environment from flask_marshmallow import Marshmallow from flask_socketio import SocketIO from flask_sqlalchemy import SQLAlchemy api = APIManager() assets = Environment() ma = Marshmallow() sk = SocketIO() db = SQLAlchemy()
{"/app/__init__.py": ["/app/extensions.py"], "/run.py": ["/app/__init__.py"]}
47,700
dfana01/pbx-dashboard
refs/heads/master
/app/__init__.py
from app import config as app_config from app.extensions import api, ma, sk, db from sqlalchemy import func, desc from sqlalchemy.sql import label from flask import Flask, render_template, jsonify from threading import Thread, Event from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker thread = Thread() thread_stop_event = Event() class CDR(db.Model): __tablename__ = 'cdr' uniqueid = db.Column(db.String(32), primary_key=True) calldate = db.Column(db.DateTime()) clid = db.Column(db.String(80)) src = db.Column(db.String(80)) dst = db.Column(db.String(80)) dcontext = db.Column(db.String(80)) channel = db.Column(db.String(80)) dstchannel = db.Column(db.String(80)) lastapp = db.Column(db.String(80)) lastdata = db.Column(db.String(80)) duration = db.Column(db.String(80)) billsec = db.Column(db.String(80)) disposition = db.Column(db.String(80)) amaflags = db.Column(db.String(80)) accountcode = db.Column(db.String(20)) userfield = db.Column(db.String(255)) did = db.Column(db.String(50)) recordingfile = db.Column(db.String(255)) cnum = db.Column(db.String(80)) cnam = db.Column(db.String(80)) outbound_cnum = db.Column(db.String(80)) outbound_cnam = db.Column(db.String(80)) dst_cnam = db.Column(db.String(80)) linkedid = db.Column(db.String(32)) peeraccount = db.Column(db.String(80)) sequence = db.Column(db.Integer) class CDRSchema(ma.Schema): class Meta: fields = ('calldate', 'src', 'dst', 'disposition', 'duration', 'billsec', 'calldate') cdr_schema = CDRSchema() cdrs_schema = CDRSchema(many=True) class NotificationThread(Thread): def __init__(self, app): self.delay = 1 self.app = app super(NotificationThread, self).__init__() def get_total_call(self): engine = create_engine(app_config.BaseConfig.SQLALCHEMY_DATABASE_URI) Session = sessionmaker(bind=engine, autocommit=True) session = Session() session.begin() count = session.query(CDR.uniqueid).count() session.commit() return count def notified(self): current_count = self.get_total_call() new_count = current_count while not thread_stop_event.isSet(): new_count = self.get_total_call() if current_count < new_count: sk.emit('notified', new_count, namespace='/notification') current_count = new_count def run(self): self.notified() def create_app(config=app_config.DevConfig): app = Flask(__name__) app.config.from_object(config) register_extensions(app) def get_dashboard_data(session): top_make_calls = list(session.query(CDR.src, label('call', func.count(CDR.uniqueid))).order_by(desc('2')) .group_by(CDR.src).limit(5).all()) top_got_calls = list(session.query(CDR.dst, label('call', func.count(CDR.uniqueid))).order_by(desc('2')) .group_by(CDR.dst).limit(5).all()) top_unanswer_calls = list(session.query(CDR.dst, label('call', func.count(CDR.uniqueid))).order_by(desc('2')) .group_by(CDR.dst).filter_by(disposition='NO ANSWER').limit(5).all()) data = { 'calls': cdrs_schema.dump(CDR.query.order_by(CDR.calldate).all()).data, 'total_calls': session.query(func.count(CDR.uniqueid)).scalar(), 'total_unanswer': session.query(func.count(CDR.uniqueid)).filter_by(disposition='NO ANSWER').scalar(), 'top_make_calls': top_make_calls, 'top_got_calls': top_got_calls, 'top_unanswer_calls': top_unanswer_calls, 'total_ext_active': session.query(CDR.src.distinct().label("src")).count() } return data @sk.on('connect', namespace='/notification') def connect(): global thread print('Client connected') if not thread.isAlive(): thread = NotificationThread(app) thread.start() @sk.on('disconnect', namespace='/notification') def disconnect(): print('Client disconnected') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/dashboard', methods=['GET']) def dashboard(): return jsonify(get_dashboard_data(db.session)) return app def register_extensions(app): db.init_app(app) api.init_app(app) ma.init_app(app) sk.init_app(app)
{"/app/__init__.py": ["/app/extensions.py"], "/run.py": ["/app/__init__.py"]}