text:
import torch
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

import seaborn as sns
import sys

from gpsa import VariationalGPSA, rbf_kernel
from gpsa.plotting import callback_twod

sys.path.append("../../..")
from data.st.load_st_data import load_st_data
from data.warps import apply_gp_warp

# from models.gpsa_vi_lmc import VariationalWarpGP
from data.simulated.generate_oned_data import (
    generate_oned_data_affine_warp,
    generate_oned_data_gp_warp,
)

# from plotting.callbacks import callback_oned, callback_twod

from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import WhiteKernel, RBF

## For PASTE
import scanpy as sc
import squidpy as sq
import anndata
import matplotlib.patches as mpatches

sys.path.append("../../../paste")
from src.paste import PASTE, visualization

def scale_spatial_coords(X, max_val=10.0):
    X = X - X.min(0)
    X = X / X.max(0)
    return X * max_val

N_LAYERS = 1

device = "cuda" if torch.cuda.is_available() else "cpu"

def process_data(adata, n_top_genes=2000):
    adata.var_names_make_unique()
    adata.var["mt"] = adata.var_names.str.startswith("MT-")
    sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], inplace=True)

    sc.pp.filter_cells(adata, min_counts=100)
    # sc.pp.filter_cells(adata, max_counts=35000)
    # adata = adata[adata.obs["pct_counts_mt"] < 20]
    # sc.pp.filter_genes(adata, min_cells=10)

    sc.pp.normalize_total(adata, inplace=True)
    sc.pp.log1p(adata)
    sc.pp.highly_variable_genes(
        adata, flavor="seurat", n_top_genes=n_top_genes, subset=True
    )
    return adata

data_slice1 = load_st_data(layers=np.arange(N_LAYERS) + 1)[0]
process_data(data_slice1, n_top_genes=3000)

sq.gr.spatial_neighbors(data_slice1)
sq.gr.spatial_autocorr(
    data_slice1,
    mode="moran",
)

moran_scores = data_slice1.uns["moranI"]
genes_to_keep = moran_scores.index.values[np.where(moran_scores.I.values > 0.3)[0]]
N_GENES = len(genes_to_keep)
data_slice1 = data_slice1[:, genes_to_keep]

X_orig = data_slice1.obsm["spatial"]
Y_orig = data_slice1.X
n_samples_per_view = len(X_orig)

X_orig = scale_spatial_coords(X_orig)

X, Y, n_samples_list, view_idx = apply_gp_warp(
    X_orig,
    Y_orig,
    n_views=2,
    kernel_variance=0.5,
    kernel_lengthscale=5,
    noise_variance=0.0,
)

X[:n_samples_per_view] = X_orig

n_spatial_dims = 2
n_views = 2
n_outputs = Y.shape[1]

m_G = 40
m_X_per_view = 40

N_EPOCHS = 2000
PRINT_EVERY = 200
N_LATENT_GPS = {"expression": None}
NOISE_VARIANCE = 0.0

##  PASTE
slice1 = anndata.AnnData(Y[view_idx[0]])
slice2 = anndata.AnnData(Y[view_idx[1]])

slice1.obsm["spatial"] = X[view_idx[0]]
slice2.obsm["spatial"] = X[view_idx[1]]

pi12 = PASTE.pairwise_align(slice1, slice2, alpha=0.1)

slices = [slice1, slice2]
pis = [pi12]
new_slices = visualization.stack_slices_pairwise(slices, pis)

err_paste = np.mean(
    np.sum((new_slices[0].obsm["spatial"] - new_slices[1].obsm["spatial"]) ** 2, axis=1)
)
print("Error PASTE: {}".format(err_paste))

# Standardize expression
Y = (Y - Y.mean(0)) / Y.std(0)

## Drop part of the second view (this is the part we'll try to predict)
x = torch.from_numpy(X).float().clone()
y = torch.from_numpy(Y).float().clone()

data_dict = {
    "expression": {
        "spatial_coords": x,
        "outputs": y,
        "n_samples_list": n_samples_list,
    }
}

model = VariationalGPSA(
    data_dict,
    n_spatial_dims=n_spatial_dims,
    m_X_per_view=m_X_per_view,
    m_G=m_G,
    data_init=True,
    minmax_init=False,
    grid_init=False,
    n_latent_gps=N_LATENT_GPS,
    mean_function="identity_fixed",
    kernel_func_warp=rbf_kernel,
    kernel_func_data=rbf_kernel,
    # fixed_warp_kernel_variances=np.ones(n_views) * 1.,
    # fixed_warp_kernel_lengthscales=np.ones(n_views) * 10,
    fixed_view_idx=0,
).to(device)

view_idx, Ns, _, _ = model.create_view_idx_dict(data_dict)

optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)

def train(model, loss_fn, optimizer):
    model.train()

    # Forward pass
    G_means, G_samples, F_latent_samples, F_samples = model.forward(
        X_spatial={"expression": x}, view_idx=view_idx, Ns=Ns
    )

    # Compute loss
    loss = loss_fn(data_dict, F_samples)

    # Compute gradients and take optimizer step
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    return loss.item(), G_means

# Set up figure.
fig = plt.figure(figsize=(14, 7), facecolor="white", constrained_layout=True)
ax_dict = fig.subplot_mosaic(
    [
        ["data", "latent"],
    ],
)
plt.show(block=False)

for t in range(N_EPOCHS):
    loss, G_means = train(model, model.loss_fn, optimizer)

    if t % PRINT_EVERY == 0:
        print("Iter: {0:<10} LL {1:1.3e}".format(t, -loss))

        callback_twod(
            model,
            X,
            Y,
            data_expression_ax=ax_dict["data"],
            latent_expression_ax=ax_dict["latent"],
            # prediction_ax=ax_dict["preds"],
            X_aligned=G_means,
        )
        plt.draw()
        plt.pause(1 / 60.0)

        # err = np.mean(
        #     (
        #         G_means["expression"].detach().numpy().squeeze()[:n_samples_per_view]
        #         - G_means["expression"].detach().numpy().squeeze()[n_samples_per_view:]
        #     )
        #     ** 2
        # )
        # print("Error: {}".format(err))

plt.close()

import matplotlib

font = {"size": 30}
matplotlib.rc("font", **font)
matplotlib.rcParams["text.usetex"] = True

fig = plt.figure(figsize=(21, 7))
markers = [".", "+", "^"]
colors = ["blue", "orange"]

## Original data
plt.subplot(131)
plt.title("Data")
plt.scatter(
    slice1.obsm["spatial"][:, 0],
    slice1.obsm["spatial"][:, 1],
    s=400,
    c=np.log(slice1.X[:, 0] + 1),
    marker=markers[0],
)
plt.scatter(
    slice2.obsm["spatial"][:, 0],
    slice2.obsm["spatial"][:, 1],
    s=400,
    c=np.log(slice2.X[:, 0] + 1),
    marker=markers[1],
)
plt.axis("off")

## PASTE alignment
plt.subplot(132)
plt.title("Alignment, PASTE")
for i in range(len(new_slices)):
    plt.scatter(
        new_slices[i].obsm["spatial"][:, 0],
        new_slices[i].obsm["spatial"][:, 1],
        s=400,
        c=np.log(new_slices[i].X[:, 0] + 1),
        marker=markers[i],
        label="Sample {}".format(i + 1),
    )
plt.axis("off")

## GPSA alignment
plt.subplot(133)

model.eval()

plt.title("Alignment, GPSA")

curr_view_idx = model.view_idx["expression"]

for vv in range(model.n_views):

    plt.scatter(
        G_means["expression"].detach().numpy()[curr_view_idx[vv], 0],
        G_means["expression"].detach().numpy()[curr_view_idx[vv], 1],
        c=Y[curr_view_idx[vv], 0],
        label="View {}".format(vv + 1),
        marker=markers[vv],
        s=400,
    )
plt.axis("off")

plt.tight_layout()
plt.savefig("./out/two_d_simulation.png")
plt.show()
plt.close()

max_stars_repo_name: andrewcharlesjones/spatial-alignment

max_issues_repo_name: andrewcharlesjones/spatial-alignment

max_forks_repo_name: andrewcharlesjones/spatial-alignment


text:
#!/usr/bin/env python

import os,sys
import numpy as np

import simsio

#import matplotlib
#matplotlib.use('Agg')
#import pylab as p
#matplotlib.rc('xtick',labelsize=25)
#matplotlib.rc('ytick',labelsize=25)

if __name__ == "__main__":
    from optparse import OptionParser
    o = OptionParser()
    o.set_usage('%prog [options] [RMS txt files]')
    o.set_description(__doc__)
    opts, args = o.parse_args(sys.argv[1:])

    rmsFiles=args
    if rmsFiles[0]=='RMS.dat':
        rmsDict=simsio.loadTotalRMSDat(rmsFiles[0])
    elif rmsFiles[0]=='RMS.pkl':
        rmsDict=simsio.loadTotalRMSPkl(rmsFiles[0])
    else:
        rmsDict=simsio.rmsFromTxt(rmsFiles)
    print rmsDict

ext: py

max_stars_repo_name: griffinfoster/pulsar-polarization-sims

max_issues_repo_name: griffinfoster/pulsar-polarization-sims

max_forks_repo_name: griffinfoster/pulsar-polarization-sims

reason: import numpy


text:
import math as m
import numpy as np

from src.continuous.uniform import UniformDist
from src.prob_distribution import ProbDist
from src.spaces.spaces1d_leafs import ContinuousSpace

class LogisticDist(ProbDist):
    """Simple Logistic distribution."""

    def __init__(self, loc = 0, scale = 1):
        """Creates Logistic(loc,scale) distribution.

        :param loc Location of the distribution.
        :param scale Scale of the distribution
        """

        # save params
        self.loc = loc
        self.scale = scale

        # create generator
        self.UG = UniformDist()
        super().__init__(ContinuousSpace(-np.inf, np.inf))

    def expectation(self):
        """Calculates the expectations for that distribution.

        :returns The expectation of the distribution"""

        return self.loc

    def var(self):
        """Calculates the variance for that distribution.

        :returns The variance of the distribution"""

        return (m.pi ** 2 / 3) * (self.scale ** 2)

    def sample(self, num_samples = 1):
        """Generate random numbers from Logistic(loc, scale) by using acceptance rejection distributions.

        :param num_samples How many random numbers should be generated.
        :returns Random numbers x ~ Logistic(loc, scale).
        """

        # shortcut
        loc = self.loc
        scale = self.scale

        # sample data
        U = self.UG.sample(num_samples)
        X = np.log(U / (1 - U))
        return scale * X + loc

    def c_pdf(self, x):
        """This method calculates the density Logistic(loc, scale).

        :param x Which value should be evaluated.
        :returns The probability that this element occurs.
        """

        # shortcut
        loc = self.loc
        scale = self.scale

        # update x
        xn = np.subtract(x, loc) / scale
        t = np.exp(-xn)
        b = (1 + t) ** 2
        f = t / b
        return f / scale

max_stars_repo_name: kosmitive/univariate-distributions

max_issues_repo_name: kosmitive/univariate-distributions

max_forks_repo_name: kosmitive/univariate-distributions


text:
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
import scipy.io
import numpy as np
from sklearn.model_selection import GridSearchCV

mat=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-n1.mat')
mat1=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-n2.mat')
mat2=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-n3.mat')
mat3=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-n4.mat')
mat4=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s1.mat')
mat5=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s2.mat')
mat6=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s3.mat')
mat7=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s4.mat')
mat8=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s5.mat')
mat9=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-s6.mat')

var_train=np.concatenate((mat['CC_N_A1'],mat1['CC_N_A2'],mat2['CC_N_A3'],mat3['CC_N_A4'],mat4['CC_S_A1'],mat5['CC_S_A2'],mat6['CC_S_A3'],mat7['CC_S_A4'],mat8['CC_S_A5'],mat9['CC_S_A6']),axis=0)
targ_train=np.concatenate((-1*np.ones((40,1)),np.ones((60,1))),axis=0)

## find The best Parameters
svclassifier=SVC(kernel='linear',C=1)
grid_param = {
    'C': [1000,100,10,1,0.1,0.01,0.001,0.0001]}
clf=GridSearchCV(estimator=svclassifier,param_grid=grid_param,scoring='accuracy',cv=5,n_jobs=-1)
clf.fit(var_train,targ_train)
best_parameters = clf.best_params_
print(best_parameters)

##-----------------------------train error---------------------------------

svclassifier=SVC(kernel='linear',C=best_parameters['C'])
svclassifier.fit(var_train,targ_train)
y_pred_train_li = svclassifier.predict(var_train)
print(confusion_matrix(targ_train,y_pred_train_li))
print(classification_report(targ_train,y_pred_train_li))

#Test

mat_test=scipy.io.loadmat(r'F:\Projects\Master\Second Semester\Speech Processing\Final Project\Results\cc-a-test1.mat')
y_pred_test=svclassifier.predict(mat_test['CC_Test_A'])

max_stars_repo_path: Train SVM.py

max_issues_repo_path: Train SVM.py

max_forks_repo_path: Train SVM.py

reason: import numpy,import scipy


text:
"""
Target Problem:
---------------
* A classifier for the diagnosis of Autism Spectrum Disorder (ASD)

Proposed Solution (Machine Learning Pipeline):
----------------------------------------------
* Constant Feature Elimination -> SelectKBest Algorithm -> PCA -> Decision Tree Classifier

Input to Proposed Solution:
---------------------------
* Directories of training and testing data in csv file format
* These two types of data should be stored in n x m pattern in csv file format.

  Typical Example:
  ----------------
  n x m samples in training csv file (n number of samples, m - 1 number of features, ground truth labels at last column)
  k x s samples in testing csv file (k number of samples, s number of features)

* These data set files are ready by load_data() function.
* For comprehensive information about input format, please check the section
  "Data Sets and Usage Format of Source Codes" in README.md file on github.

Output of Proposed Solution:
----------------------------
* Predictions generated by learning model for testing set
* They are stored in "submission.csv" file.

Code Owner:
-----------
* Copyright © Team 7. All rights reserved.
* Copyright © Istanbul Technical University, Learning From Data Spring 2019. All rights reserved. """

import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

def load_data(tra_name, test_name):

    """
    The method reads the training and testing data from their csv files.

    Parameters
    ----------
    tra_name:  directory of the training dataset file
    test_name: directory of testing dataset file

    """

    train_data = pd.read_csv(tra_name)
    test_data = pd.read_csv(test_name)
    return train_data, test_data

def preprocessing(train_data, test_data):

    """
    The method at first eliminates constant features.
    Then, it chooses top 100 features by evaluating chi square values of each feature.
    Finally, these 100 features are reduced to 80 features by using principal component analysis.

    Parameters
    ----------
    train_data: training dataset containing features and labels
    test_data: testing dataset containing only features

    """

    train_data = train_data.drop(['X3', 'X31', 'X32', 'X127', 'X128', 'X590'], axis=1)
    train_data = np.asarray(train_data)

    train_x = train_data[:, :train_data.shape[1] - 1]
    train_y = train_data[:, train_data.shape[1] - 1]
    train_y.shape = (np.size(train_y), 1)

    test_data = test_data.drop(['X3', 'X31', 'X32', 'X127', 'X128', 'X590'], axis=1)
    test_data = np.asarray(test_data)

    selector = SelectKBest(score_func=chi2, k=100)
    selector.fit(train_x, train_y)

    train_features = selector.transform(train_x)
    test_features = selector.transform(test_data)

    pca = PCA(n_components=80)
    x_tra_pca = pca.fit_transform(train_features)
    x_test_pca = pca.transform(test_features)

    return x_tra_pca, train_y, x_test_pca

# ********** MAIN PROGRAM ********** #

train_data, test_data = load_data("train.csv", "test.csv")
x_tra_pca, train_y, x_test_pca = preprocessing(train_data, test_data)

clf = DecisionTreeClassifier(random_state=25)
clf.fit(x_tra_pca, train_y)
predictions = clf.predict(x_test_pca)

yt = pd.DataFrame(predictions, dtype='int32')
yt.columns = ["Predicted"]
yt.index += 1
yt.to_csv("./submission.csv", index_label="ID")

max_stars_repo_path: Team 7/main.py

max_stars_repo_name: basiralab/BrainNet-ML-ToolBox

max_issues_repo_path: Team 7/main.py

max_issues_repo_name: aycagokdag/BrainNet-ML-ToolBox

max_forks_repo_path: Team 7/main.py

max_forks_repo_name: aycagokdag/BrainNet-ML-ToolBox


text:
""" Most of these functions taken from the qtim_tools python package.

TODO: Accept many formats.
"""

import nibabel as nib
import numpy as np

def generate_identity_affine(timepoints=1):

    """ A convenient function for generating an identity affine matrix. Can be
        used for saving blank niftis.
    """

    # Needlessly complicated.

    if timepoints == 1:
        return np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])

    else:
        return np.swapaxes(np.tile(np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]), (timepoints, 1,1)), 0, 2)

def save_numpy_2_nifti(image_numpy, reference_nifti_filepath='', reference_affine=None, output_filepath=[]):

    if reference_nifti_filepath != '':
        nifti_image = nib.load(reference_nifti_filepath)
        image_affine = nifti_image.affine
    elif reference_affine is not None:
        image_affine = reference_affine
    else:
        # print 'Warning: no reference nifti file provided. Generating empty header.'
        image_affine = generate_identity_affine()

    output_nifti = nib.Nifti1Image(image_numpy, image_affine)

    if output_filepath == []:
        return output_nifti
    else:
        nib.save(output_nifti, output_filepath)

def nifti_2_numpy(filepath, return_affine=False):

    """ There are a lot of repetitive conversions in the current iteration
        of this program. Another option would be to always pass the nibabel
        numpy class, which contains image and attributes. But not everyone
        knows how to use that class, so it may be more difficult to troubleshoot.
    """

    img = nib.load(filepath)
    array = img.get_data().astype(float)

    if return_affine:
        return array, img.affine
    else:
        return array

def nifti_2_affine(filepath):

    return nib.load(filepath).affine


text:
import networkx as nx
from page_scorer import tokenize_alphanum
from page_scorer import WordSignificance

class GraphScorer(nx.Graph):
    def __init__(self,tokenized_sentences):
        super().__init__()

        words = []
        for _words in tokenized_sentences:
            self.add_edges(_words)
            words += _words
            #print(_words)
        self.word_sig = WordSignificance(words)

        self.total = 0
        self.n_flush = 0
        self.cumulative_score = 1
        self.cumulator = False

    def two_grams(self,words):
        for i in range (0,len(words)-1):
            yield tuple(words[i:i+2])

    def add_edges(self,words):
        for edge in self.two_grams(words):
            super().add_edge(*edge)

    def flush_scores(self,reset=False):
        if reset:
            self.n_flush = 0
            self.total = 0
        else:
            if self.cumulative_score > 0:
                self.n_flush += 1
                #print("\t\tflushing",self.cumulative_score)
                self.total += self.cumulative_score
        self.cumulative_score = 0
        self.cumulator = False

    def get_score(self,text,reset=True):
        self.flush_scores(reset=reset)

        last_word = None
        for word in tokenize_alphanum(text):
            _score = self.word_sig[word]

            if word not in self.nodes():
                self.flush_scores()
                self.cumulative_score = _score
                self.flush_scores()
            else:
                if last_word not in self.nodes():
                    self.cumulative_score = _score
                else:
                    self.cumulator = word in self.neighbors(last_word)
                    if self.cumulator:
                        #print(last_word,word,"--->",self.cumulative_score,"*",_score)
                        self.cumulative_score *= _score
                    else:
                        self.flush_scores()
                        self.cumulative_score = _score
            last_word = word
        self.flush_scores()
        if self.n_flush > 0:
            return self.total/self.n_flush
        return 0

# Print out test score for a page
def test(site):
    from markov_crawler import text_from_soup
    import numpy as np
    from collections import Counter

    g.flush_scores(reset=True)
    r = requests.get(site)
    soup = BeautifulSoup(r.text,"lxml")
    scores = {text:g.get_score(text)
              for text in text_from_soup(soup)}

    print(site,len(scores),np.mean([s for _,s in scores.items()]))
    print(Counter(scores).most_common()[0:10])
    print()

if __name__ == "__main__":

    import requests
    from bs4 import BeautifulSoup

    r = requests.get("http://search.ucas.com/subject/fulllist")
    tokenized_sentences = []
    soup = BeautifulSoup(r.text,"lxml")
    for a in soup.find_all("a"):
        if "href" not in a.attrs:
            continue
        if not a.attrs["href"].startswith("/subject/"):
            continue
        tokenized_sentences.append(tokenize_alphanum(a.text))

    g = GraphScorer(tokenized_sentences)
    #print(g.get_score("business studies"))
    #print(g.get_score("business chocolate studies"))
    #print(g.get_score("joel and klinger"))
    # print(g.get_score("business and joel studies"))
    #print(g.get_score("french and islamic studies"))
    # print(g.get_score("french band islamic studies"))

    #print(g.get_score("Academic Departments"))
    #import sys
    #sys.exit()

    test("https://www.masdar.ac.ae/")
    test("https://www.masdar.ac.ae/join-us/work-with-us")
    test("https://www.masdar.ac.ae/research-education/degree-offerings")

    test("https://www.manchester.ac.uk/")
    test("http://www.manchester.ac.uk/study/experience/accommodation")
    test("http://www.manchester.ac.uk/study/undergraduate/courses/2018/")
    #print(g.neighbors("research"))

reason: import numpy,import networkx


text:
from numpy import True_
import pytorch_lightning as pl
from lightning_med.datasets import ISIC2019, ISIC2019_CV
from lightning_med import GetModel
from lightning_med.datasets.utils import KFoldLoop

isic = ISIC2019_CV(data_dir='/host/ubuntu/data/isic2019')
model = GetModel(arch='vit_tiny_patch16_224', pretrained=True, learning_rate=0.01, num_classes=8, fine_tune=True)

trainer = pl.Trainer(gpus=1, max_epochs=5,num_sanity_val_steps=0)
trainer.fit_loop = KFoldLoop(5, trainer.fit_loop, export_path="./")
trainer.fit(model, train_dataloaders=isic)

reason: from numpy


text:
import dask as da
import numpy as np
import xarray as xr

def check(user_variable,
          var_name='variable',
          data_type=None,
          max_dimensions=None,
          min_dimensions=None,
          dimensions=None,
          shape=None,
          is_xarray=None,
          is_none=None,
          is_numpy=None,
          is_chunked=None,
          comparison=None,
          unchunked_dims=None,
          exceptions=True):
    """Function of data checks for use in wrapper functions.

    user_variable : :class:`xarray.DataArray` or :class:`numpy.ndarray`:
        Variable of interest

    data_type : :class:`type` or :type:`tuple of types`:
        Desired data_type of user_variable
        ex: data_type=np.ndarray

    max_dimensions : :class:`tuple`:
        Maximum number of dimensions needed from user_variable for function
        ex: max_dimensions=(3) or max_dimensions=3

    min_dimensions : :class:`tuple`:
        Minimum number of dimensions needed from user_variable for function
        ex: min_dimensions=(3) or min_dimensions=3

    dimensions : :class:`tuple`:
        Number of dimensions needed from user_variable for function
        ex: dimensions=(3) or dimensions=3

    shape : :class:`tuple`:
        Checks user_variable's shape
        ex: shape=(3, 3, 3)

    is_xarray : :class:`bool`:
        Checking whether user_variable is of class xarray.DataArray.
        Valid inputs are True or False

    is_none : :class:`bool`:
        Checking whether user_variable is of class NoneType.
        Valid input is True or False

    comparison : :class:`n/a`:
        Compares user variable against item passed in as comparison
        Valid input is anything

    unchunked_dims : :class:`tuple`:
        Checks for unchunked dimensions in user_variable
        ex: check(user_variable, unchunked_dims=[3]) *must include brackets*

    exceptions : :class:`bool`:
        Allows user to turn off exceptions in the check functions
        Valid input is True or False

    is_numpy : :class:`bool`:
        Checks whether variable is of class numpy.ndarray
        Valid input is True or False

    is_chunked : :class:`bool`:
        Checks whether variable is chunked
        Valid input is True or False
    """
    return_value = True

    if data_type is not None:
        if not isinstance(user_variable, data_type):
            if exceptions:
                raise TypeError(var_name + " failed data_type check.")
            else:
                return_value = False

    if dimensions is not None:
        if not (user_variable.ndim == dimensions):
            if exceptions:
                raise Exception(var_name + " failed dimensions check")
            else:
                return_value = False

    if shape is not None:
        if not (user_variable.shape == shape):
            if exceptions:
                raise Exception(var_name + " failed shape check")
            else:
                return_value = False

    if is_none is not None:
        if is_none is True:
            if user_variable is not None:
                if exceptions:
                    raise Exception(var_name + " is not None")
                else:
                    return_value = False
        if is_none is False:
            if user_variable is None:
                if exceptions:
                    raise Exception(var_name + " is None")
                else:
                    return_value = False

    if min_dimensions is not None:
        if not (user_variable.ndim >= min_dimensions):
            if exceptions:
                raise Exception(var_name + " failed min_dimensions check")
            else:
                return_value = False

    if max_dimensions is not None:
        if not (user_variable.ndim <= max_dimensions):
            if exceptions:
                raise Exception(var_name + " failed max_dimensions check")
            else:
                return_value = False

    if comparison is not None:
        if not (user_variable == comparison):
            if exceptions:
                raise Exception(var_name + " failed comparison check")
            else:
                return_value = False

    if is_numpy is not None:
        if is_numpy is True:
            if not isinstance(user_variable_1, np.array):
                if exceptions:
                    raise Exception(var_name + " is not a numpy.Array")
                else:
                    return_value = False
        if is_numpy is False:
            if isinstance(user_variable_1, np.array):
                if exceptions:
                    raise Exception(var_name + " is an numpy.Array")
                else:
                    return_value = False

    #
    # Xarray specific checks
    #
    if is_xarray is not None:
        if is_xarray is True:
            if not isinstance(user_variable_1, xr.DataArray):
                if exceptions:
                    raise Exception(var_name + " is not a xarray.DataArray")
                else:
                    return_value = False
        if is_xarray is False:
            if isinstance(user_variable_1, xr.DataArray):
                if exceptions:
                    raise Exception(var_name + " is an xarray.DataArray")
                else:
                    return_value = False

    if is_chunked is not None:
        if is_chunked is True:
            if var_name.chunks is None:
                if exceptions:
                    raise Exception(var_name + "is not chunked")
                else:
                    return_value = False
        if is_chunked is False:
            if var_name.chunks is not None:
                if exceptions:
                    raise Exception(var_name + "is chunked")
                else:
                    return_value = False

    if unchunked_dims is not None:
        for dim in unchunked_dims:
            if len(user_variable.chunks[dim]) > 1:
                if exceptions:
                    raise Exception(var_name +
                                    " must not be chunked along dimension " +
                                    str(dim))
                else:
                    return_value = False

    return return_value


text:
# 1 ---------

# A simple test of turbine_costsse model
from turbine_costsse.turbine_costsse import Turbine_CostsSE

turbine = Turbine_CostsSE()

# 1 ---------
# 2 ---------

# NREL 5 MW turbine component masses based on Sunderland model approach

# Rotor
turbine.blade_mass = 17650.67  # inline with the windpact estimates
turbine.hub_mass = 31644.5
turbine.pitch_system_mass = 17004.0
turbine.spinner_mass = 1810.5

# Drivetrain and Nacelle
turbine.low_speed_shaft_mass = 31257.3
#bearingsMass = 9731.41
turbine.main_bearing_mass = 9731.41 / 2
turbine.second_bearing_mass = 9731.41 / 2
turbine.gearbox_mass = 30237.60
turbine.high_speed_side_mass = 1492.45
turbine.generator_mass = 16699.85
turbine.bedplate_mass = 93090.6
turbine.yaw_system_mass = 11878.24

# Tower
turbine.tower_mass = 434559.0

# 2 ---------
# 3 ---------

# Additional non-mass cost model input variables
turbine.machine_rating = 5000.0
turbine.advanced = True
turbine.blade_number = 3
turbine.drivetrain_design = 'geared'
turbine.crane = True
turbine.offshore = True

# Target year for analysis results
turbine.year = 2010
turbine.month =  12

# 3 ---------
# 4 ---------

turbine.run()

# 4 ----------
# 5 ----------

print "The results for the NREL 5 MW Reference Turbine in an offshore 20 m water depth location are:"
print
print "Overall rotor cost with 3 advanced blades is ${0:.2f} USD".format(turbine.rotorCC.cost)
print "Blade cost is ${0:.2f} USD".format(turbine.rotorCC.bladeCC.cost)
print "Hub cost is ${0:.2f} USD".format(turbine.rotorCC.hubCC.cost)
print "Pitch system cost is ${0:.2f} USD".format(turbine.rotorCC.pitchSysCC.cost)
print "Spinner cost is ${0:.2f} USD".format(turbine.rotorCC.spinnerCC.cost)
print
print "Overall nacelle cost is ${0:.2f} USD".format(turbine.nacelleCC.cost)
print "LSS cost is ${0:.2f} USD".format(turbine.nacelleCC.lssCC.cost)
print "Main bearings cost is ${0:.2f} USD".format(turbine.nacelleCC.bearingsCC.cost)
print "Gearbox cost is ${0:.2f} USD".format(turbine.nacelleCC.gearboxCC.cost)
print "Hight speed side cost is ${0:.2f} USD".format(turbine.nacelleCC.hssCC.cost)
print "Generator cost is ${0:.2f} USD".format(turbine.nacelleCC.generatorCC.cost)
print "Bedplate cost is ${0:.2f} USD".format(turbine.nacelleCC.bedplateCC.cost)
print "Yaw system cost is ${0:.2f} USD".format(turbine.nacelleCC.yawSysCC.cost)
print
print "Tower cost is ${0:.2f} USD".format(turbine.towerCC.cost)
print
print "The overall turbine cost is ${0:.2f} USD".format(turbine.turbine_cost)
print

# 5 ----------
# 6 ----------

# A simple test of nrel_csm_tcc model
from turbine_costsse.nrel_csm_tcc import tcc_csm_assembly
import numpy as np

trb = tcc_csm_assembly()

# 6 ----------
# 7 ----------

# NREL 5 MW main parameters
trb.rotor_diameter = 126.0
trb.advanced_blade = True
trb.blade_number = 3
trb.hub_height = 90.0
trb.machine_rating = 5000.0
trb.offshore = True
trb.drivetrain_design = 'geared'
trb.crane = True
trb.advanced_bedplate = 0
trb.advanced_tower = False

# 7 ----------
# 8 ----------

# Rotor force calculations for nacelle inputs
maxTipSpd = 80.0
maxEfficiency = 0.90201
ratedWindSpd = 11.5064
thrustCoeff = 0.50
airDensity = 1.225

ratedHubPower  = trb.machine_rating / maxEfficiency
rotorSpeed     = (maxTipSpd/(0.5*trb.rotor_diameter)) * (60.0 / (2*np.pi))
trb.rotor_thrust  = airDensity * thrustCoeff * np.pi * trb.rotor_diameter**2 * (ratedWindSpd**2) / 8
trb.rotor_torque = ratedHubPower/(rotorSpeed*(np.pi/30))*1000

# 8 -----------

# Target year for analysis results
trb.year = 2009
trb.month = 12

# 8 -----------
# 9 -----------

trb.run()

# 9 -----------
# 10 ----------

print "The results for the NREL 5 MW Reference Turbine in an offshore 20 m water depth location are:"
print "Overall turbine mass is {0:.2f} kg".format(trb.turbine_mass)
print "Overall turbine cost is ${0:.2f} USD".format(trb.turbine_cost)

# 10 ----------
# 11 ----------
from turbine_costsse.turbine_costsse_2015 import Turbine_CostsSE_2015

turbine = Turbine_CostsSE_2015()

# 11 ----------
# 12 ----------

turbine.blade_mass = 17650.67  # inline with the windpact estimates
turbine.hub_mass = 31644.5
turbine.pitch_system_mass = 17004.0
turbine.spinner_mass = 1810.5
turbine.low_speed_shaft_mass = 31257.3
#bearingsMass = 9731.41
turbine.main_bearing_mass = 9731.41 / 2
turbine.second_bearing_mass = 9731.41 / 2 #KLD - revisit this in new model
turbine.gearbox_mass = 30237.60
turbine.high_speed_side_mass = 1492.45
turbine.generator_mass = 16699.85
turbine.bedplate_mass = 93090.6
turbine.yaw_system_mass = 11878.24
turbine.tower_mass = 434559.0
turbine.variable_speed_elec_mass = 0. #obsolete - using transformer #Float(iotype='in', units='kg', desc='component mass [kg]')
turbine.hydraulic_cooling_mass = 400. #Float(iotype='in', units='kg', desc='component mass [kg]')
turbine.nacelle_cover_mass = 6837. #Float(iotype='in', units='kg', desc='component mass [kg]')
turbine.other_mass = 8220. #Float(iotype='in', units='kg', desc='component mass [kg]')
turbine.transformer_mass = 11485. #Float(iotype='in', units='kg', desc='component mass [kg]')

# 12 ----------
# 13 ----------
# other inputs
turbine.machine_rating = 5000.0
turbine.blade_number = 3
turbine.crane = True
turbine.offshore = True
turbine.bearing_number = 2

# 13 ----------
# 14 ----------

turbine.run()

# 14 ----------
# 15 ----------

print "The results for the NREL 5 MW Reference Turbine in an offshore 20 m water depth location are:"
print
print "Overall rotor cost with 3 advanced blades is ${0:.2f} USD".format(turbine.rotorCC.cost)
print "Blade cost is ${0:.2f} USD".format(turbine.rotorCC.bladeCC.cost)
print "Hub cost is ${0:.2f} USD".format(turbine.rotorCC.hubCC.cost)
print "Pitch system cost is ${0:.2f} USD".format(turbine.rotorCC.pitchSysCC.cost)
print "Spinner cost is ${0:.2f} USD".format(turbine.rotorCC.spinnerCC.cost)
print
print "Overall nacelle cost is ${0:.2f} USD".format(turbine.nacelleCC.cost)
print "LSS cost is ${0:.2f} USD".format(turbine.nacelleCC.lssCC.cost)
print "Main bearings cost is ${0:.2f} USD".format(turbine.nacelleCC.bearingsCC.cost)
print "Gearbox cost is ${0:.2f} USD".format(turbine.nacelleCC.gearboxCC.cost)
print "High speed side cost is ${0:.2f} USD".format(turbine.nacelleCC.hssCC.cost)
print "Generator cost is ${0:.2f} USD".format(turbine.nacelleCC.generatorCC.cost)
print "Bedplate cost is ${0:.2f} USD".format(turbine.nacelleCC.bedplateCC.cost)
print "Yaw system cost is ${0:.2f} USD".format(turbine.nacelleCC.yawSysCC.cost)
print "Variable speed electronics cost is ${0:.2f} USD".format(turbine.nacelleCC.vsCC.cost)
print "HVAC cost is ${0:.2f} USD".format(turbine.nacelleCC.hydraulicCC.cost)
print "Electrical connections cost is ${0:.2f} USD".format(turbine.nacelleCC.elecCC.cost)
print "Controls cost is ${0:.2f} USD".format(turbine.nacelleCC.controlsCC.cost)
print "Mainframe cost is ${0:.2f} USD".format(turbine.nacelleCC.mainframeCC.cost)
print "Transformer cost is ${0:.2f} USD".format(turbine.nacelleCC.transformerCC.cost)
print
print "Tower cost is ${0:.2f} USD".format(turbine.towerCC.cost)
print
print "The overall turbine cost is ${0:.2f} USD".format(turbine.turbine_cost)
print

# 15 ----------
# 16 ----------

# simple test of module
from turbine_costsse.nrel_csm_tcc_2015 import nrel_csm_tcc_2015

trb = nrel_csm_tcc_2015()

# 16 ----------
# 17 ----------

trb.rotor_diameter = 100.0
trb.turbine_class = 'II/III'
trb.blade_has_carbon = True
trb.blade_number = 3
trb.machine_rating = 2000.0
trb.hub_height = 80.0
trb.bearing_number = 2
trb.crane = True
trb.offshore = False

# 17 ----------
# 18 ----------

# Rotor force calculations for nacelle inputs
maxTipSpd = 80.0
maxEfficiency = 0.9

ratedHubPower  = trb.machine_rating*1000. / maxEfficiency
rotorSpeed     = (maxTipSpd/(0.5*trb.rotor_diameter)) * (60.0 / (2*np.pi))
trb.rotor_torque = ratedHubPower/(rotorSpeed*(np.pi/30))

# 18 ----------
# 19 ----------

trb.run()

# 19 ----------
# 20 ----------

print "The results for the NREL 5 MW Reference Turbine in an offshore 20 m water depth location are:"
print "Overall turbine mass is {0:.2f} kg".format(trb.turbine_mass)
print "Overall turbine cost is ${0:.2f} USD".format(trb.turbine_cost)

# 20 ----------

max_stars_repo_name: ptrbortolotti/WISDEM

max_issues_repo_name: ptrbortolotti/WISDEM

max_forks_repo_name: ptrbortolotti/WISDEM


text:
#!/usr/bin/env python

import pytest
import networkx as nx
from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic
is_isomorphic = graph_could_be_isomorphic

"""Generators - Small
=====================

Some small graphs
"""

null = nx.null_graph()

class TestGeneratorsSmall():
    def test_make_small_graph(self):
        d = ["adjacencylist", "Bull Graph", 5, [[2, 3], [1, 3, 4], [1, 2, 5],
                                                [2], [3]]]
        G = nx.make_small_graph(d)
        assert is_isomorphic(G, nx.bull_graph())

        # Test small graph creation error with wrong ltype
        d[0] = "erroneouslist"
        pytest.raises(nx.NetworkXError, nx.make_small_graph,
                      graph_description=d)

    def test__LCF_graph(self):
        # If n<=0, then return the null_graph
        G = nx.LCF_graph(-10, [1, 2], 100)
        assert is_isomorphic(G, null)
        G = nx.LCF_graph(0, [1, 2], 3)
        assert is_isomorphic(G, null)
        G = nx.LCF_graph(0, [1, 2], 10)
        assert is_isomorphic(G, null)

        # Test that LCF(n,[],0) == cycle_graph(n)
        for a, b, c in [(5, [], 0), (10, [], 0), (5, [], 1), (10, [], 10)]:
            G = nx.LCF_graph(a, b, c)
            assert is_isomorphic(G, nx.cycle_graph(a))

        # Generate the utility graph K_{3,3}
        G = nx.LCF_graph(6, [3, -3], 3)
        utility_graph = nx.complete_bipartite_graph(3, 3)
        assert is_isomorphic(G, utility_graph)

    def test_properties_named_small_graphs(self):
        G = nx.bull_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 5
        assert sorted(d for n, d in G.degree()) == [1, 1, 2, 3, 3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 2

        G = nx.chvatal_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 24
        assert list(d for n, d in G.degree()) == 12 * [4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.cubical_graph()
        assert G.number_of_nodes() == 8
        assert G.number_of_edges() == 12
        assert list(d for n, d in G.degree()) == 8 * [3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.desargues_graph()
        assert G.number_of_nodes() == 20
        assert G.number_of_edges() == 30
        assert list(d for n, d in G.degree()) == 20 * [3]

        G = nx.diamond_graph()
        assert G.number_of_nodes() == 4
        assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 1

        G = nx.dodecahedral_graph()
        assert G.number_of_nodes() == 20
        assert G.number_of_edges() == 30
        assert list(d for n, d in G.degree()) == 20 * [3]
        assert nx.diameter(G) == 5
        assert nx.radius(G) == 5

        G = nx.frucht_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 18
        assert list(d for n, d in G.degree()) == 12 * [3]
        assert nx.diameter(G) == 4
        assert nx.radius(G) == 3

        G = nx.heawood_graph()
        assert G.number_of_nodes() == 14
        assert G.number_of_edges() == 21
        assert list(d for n, d in G.degree()) == 14 * [3]
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.hoffman_singleton_graph()
        assert G.number_of_nodes() == 50
        assert G.number_of_edges() == 175
        assert list(d for n, d in G.degree()) == 50 * [7]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.house_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 6
        assert sorted(d for n, d in G.degree()) == [2, 2, 2, 3, 3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.house_x_graph()
        assert G.number_of_nodes() == 5
        assert G.number_of_edges() == 8
        assert sorted(d for n, d in G.degree()) == [2, 3, 3, 4, 4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 1

        G = nx.icosahedral_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 30
        assert (list(d for n, d in G.degree()) ==
                [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
        assert nx.diameter(G) == 3
        assert nx.radius(G) == 3

        G = nx.krackhardt_kite_graph()
        assert G.number_of_nodes() == 10
        assert G.number_of_edges() == 18
        assert (sorted(d for n, d in G.degree()) ==
                [1, 2, 3, 3, 3, 4, 4, 5, 5, 6])

        G = nx.moebius_kantor_graph()
        assert G.number_of_nodes() == 16
        assert G.number_of_edges() == 24
        assert list(d for n, d in G.degree()) == 16 * [3]
        assert nx.diameter(G) == 4

        G = nx.octahedral_graph()
        assert G.number_of_nodes() == 6
        assert G.number_of_edges() == 12
        assert list(d for n, d in G.degree()) == 6 * [4]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.pappus_graph()
        assert G.number_of_nodes() == 18
        assert G.number_of_edges() == 27
        assert list(d for n, d in G.degree()) == 18 * [3]
        assert nx.diameter(G) == 4

        G = nx.petersen_graph()
        assert G.number_of_nodes() == 10
        assert G.number_of_edges() == 15
        assert list(d for n, d in G.degree()) == 10 * [3]
        assert nx.diameter(G) == 2
        assert nx.radius(G) == 2

        G = nx.sedgewick_maze_graph()
        assert G.number_of_nodes() == 8
        assert G.number_of_edges() == 10
        assert sorted(d for n, d in G.degree()) == [1, 2, 2, 2, 3, 3, 3, 4]

        G = nx.tetrahedral_graph()
        assert G.number_of_nodes() == 4
        assert G.number_of_edges() == 6
        assert list(d for n, d in G.degree()) == [3, 3, 3, 3]
        assert nx.diameter(G) == 1
        assert nx.radius(G) == 1

        G = nx.truncated_cube_graph()
        assert G.number_of_nodes() == 24
        assert G.number_of_edges() == 36
        assert list(d for n, d in G.degree()) == 24 * [3]

        G = nx.truncated_tetrahedron_graph()
        assert G.number_of_nodes() == 12
        assert G.number_of_edges() == 18
        assert list(d for n, d in G.degree()) == 12 * [3]

        G = nx.tutte_graph()
        assert G.number_of_nodes() == 46
        assert G.number_of_edges() == 69
        assert list(d for n, d in G.degree()) == 46 * [3]

        # Test create_using with directed or multigraphs on small graphs
        pytest.raises(nx.NetworkXError, nx.tutte_graph,
                      create_using=nx.DiGraph)
        MG = nx.tutte_graph(create_using=nx.MultiGraph)
        assert sorted(MG.edges()) == sorted(G.edges())

max_stars_repo_name: jmmcd/networkx

max_issues_repo_name: jmmcd/networkx

max_forks_repo_name: jmmcd/networkx

reason: import networkx,from networkx


text:
from bot_code.conversions.input.simple_input_formatter import SimpleInputFormatter
from bot_code.models.base_model import BaseAgentModel
from keras.models import Model
from keras.layers import Input, Dense, Dropout
from keras import backend as K
from keras.callbacks import TensorBoard
# from keras.utils import plot_model
import numpy as np

class BaseKerasModel(BaseAgentModel):

    shared_hidden_layers = 0
    split_hidden_layers = 0
    model_activation = None
    kernel_regularizer = None
    loss_weights = None
    loss = None
    tensorboard = None
    names = []

    def __init__(self, session,
                 num_actions,
                 input_formatter_info=[0, 0],
                 player_index=-1,
                 action_handler=None,
                 is_training=False,
                 optimizer=None,
                 summary_writer=None,
                 summary_every=100,
                 config_file=None
                 ):
        K.set_session(session)
        super().__init__(session, num_actions,
                         input_formatter_info=input_formatter_info,
                         player_index=player_index,
                         action_handler=action_handler,
                         is_training=is_training,
                         optimizer=optimizer,
                         summary_writer=summary_writer,
                         summary_every=summary_every,
                         config_file=config_file)

    def printParameters(self):
        super().printParameters()

    def _create_variables(self):
        pass

    def add_input_formatter(self, team, index):
        self.input_formatter = SimpleInputFormatter(team, index)

    def sample_action(self, input_state):
        relative_positions = input_state[:, 13:16] - input_state[:, 0:3]
        rotations = input_state[:, 3:6]
        unrotated_positions = self.unrotate_positions(relative_positions, rotations)

        input_state = np.column_stack((input_state, unrotated_positions))
        outputs = self.model.predict(input_state)
        outputs = np.array(outputs).flatten().tolist()
        return outputs

    def unrotate_positions(self, relative_positions, rotations):
        new_positions = relative_positions

        # YAW
        yaws = rotations[:, 1]
        yaws = -yaws / 32768. * np.pi

        new_positions[:, 0], new_positions[:, 1] = new_positions[:, 0] * np.cos(yaws) - new_positions[:, 1] * np.sin(yaws), new_positions[:, 0] * np.sin(yaws) + new_positions[:, 1] * np.cos(yaws)

        # PITCH

        pitchs = rotations[:, 0]
        pitchs = pitchs / 32768. * np.pi

        new_positions[:, 2], new_positions[:, 0] = new_positions[:, 2] * np.cos(pitchs) - new_positions[:, 0] * np.sin(pitchs), new_positions[:, 2] * np.sin(pitchs) + new_positions[:, 0] * np.cos(pitchs)

        # ROLL

        rolls = rotations[:, 2]
        rolls = rolls / 32768. * np.pi

        new_positions[:, 1], new_positions[:, 2] = new_positions[:, 1] * np.cos(rolls) - new_positions[:, 2] * np.sin(rolls), new_positions[:, 1] * np.sin(rolls) + new_positions[:, 2] * np.cos(rolls)

        return new_positions

    def create_copy_training_model(self, model_input=None, taken_actions=None):
        loss_weights = {}
        for i, control in enumerate(self.action_handler.control_names):
            is_classification = self.action_handler.is_classification(i)
            loss_weights['o_%s' %
                         control] = 0.01 if is_classification else 0.1

        loss_weights['o_steer'] *= 20
        loss_weights['o_boost'] *= 10
        loss_weights['o_throttle'] *= 20
        loss_weights['o_jump'] *= 20
        self.loss_weights = loss_weights
        # loss_weights['o_pitch'] *= 3
        # loss_weights['o_pitch'] *= 0.001
        # loss_weights['o_yaw'] *= 0.001
        # loss_weights['o_roll'] *= 0.001

    def get_input(self, model_input=None):
        if model_input is None:
            return Input(shape=(self.state_dim + 3,))
        else:
            return Input(shape=(self.state_dim + 3,), tensor=model_input)

    def _create_model(self, model_input):
        """Generates the Keras model"""

        x = model_input
        for hidden_layer_i in range(1, self.shared_hidden_layers + 1):
            x = Dense(self.network_size, activation=self.model_activation, kernel_regularizer=self.kernel_regularizer, name='hidden_layer_%s' %
                      hidden_layer_i)(x)
            x = Dropout(0.4)(x)

        shared_output = x
        outputs = []

        extra_hidden_layer_nodes = self.network_size / self.action_handler.get_number_actions()
        loss = {}
        action_sizes = self.action_handler.get_action_sizes()
        for i, control in enumerate(self.action_handler.action_list_names):
            output_size = action_sizes[i]
            x = shared_output
            for hidden_layer_i in range(1, self.split_hidden_layers + 1):
                x = Dense(extra_hidden_layer_nodes, activation=self.model_activation, kernel_regularizer=self.kernel_regularizer,
                          name='hidden_layer_%s_%s' % (control, hidden_layer_i))(x)
                x = Dropout(0.4)(x)

            if self.action_handler.is_classification(i):
                activation = 'sigmoid'
                loss_name = 'categorical_crossentropy'
            else:
                activation = 'tanh'
                loss_name = 'mean_absolute_error'
            _output = Dense(output_size, activation=activation,
                            name='o_%s' % control)(x)
            if self.action_handler.is_classification(i):
                _output = K.argmax(_output, axis=1)
            outputs.append(_output)
            loss['o_%s' % control] = loss_name

        self.loss = loss

        self.model = Model(inputs=model_input, outputs=outputs)

        return None

    def initialize_model(self):
        self.model.compile(optimizer='adam', loss=self.loss, loss_weights=self.loss_weights)
        super().initialize_model()
        self.tensorboard.set_model(self.model)

    def _initialize_variables(self):
        super()._initialize_variables()

    def run_train_step(self, should_calculate_summaries, feed_dict=None, epoch=-1):
        model_input = None
        model_label = None
        if self.train_iteration is not -1:
            self.train_iteration = epoch
        if feed_dict is not None:
            model_input = feed_dict[self.get_input_placeholder()]
            model_label = feed_dict[self.get_labels_placeholder()]
        logs = self.model.train_on_batch(model_input, model_label)
        if should_calculate_summaries and self.tensorboard is not None:
            self.tensorboard.on_epoch_end(self.train_iteration, logs)
        self.train_iteration += 1

    def create_batched_inputs(self, inputs):
        return inputs

    def add_summary_writer(self, even_name, is_replay=False):
        log_dir = self.get_event_path(even_name)
        self.tensorboard = TensorBoard(
            write_graph=False, write_images=False, log_dir=log_dir, histogram_freq=10)

    def load_config_file(self):
        super().load_config_file()
        try:
            self.model_file = self.config_file.get('model_directory', self.model_file)
        except Exception as e:
            print('model directory is not in config', e)

    def add_saver(self, name, variable_list):
        super().add_saver(name, variable_list)

    def create_savers(self):
        self.add_saver(self.QUICK_SAVE_KEY, True)
        self.add_saver('NotQuickSave', False)

    def _save_model(self, session, saver, file_path, global_step):
        if saver:
            file_name = file_path + str(global_step)
        else:
            file_name = file_path
        self.model.save_weights(file_name)
        self.model.save(file_name + '.h5')

    def _load_model(self, session, saver, path):
        self.model.load_weights(path, by_name=True)

    def create_model_hash(self):
        return super().create_model_hash()

    def get_model_name(self):
        return 'keras'

    def get_input_placeholder(self):
        return 'Input'

    def get_labels_placeholder(self):
        return 'Output'

max_stars_repo_name: lokiwizz/Saltie

max_issues_repo_name: lokiwizz/Saltie

max_forks_repo_name: lokiwizz/Saltie


text:
from __future__ import absolute_import
from __future__ import print_function
import matplotlib.pyplot as plt
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd import grad
from autograd.core import getval
from autograd.scipy.special import logsumexp
from scipy.spatial.distance import pdist, squareform

from targets import *

import time

def KSD(z, Sqx,flag_U = False):

    # compute the rbf kernel
    K, dimZ = z.shape
    sq_dist = pdist(z)
    pdist_square = squareform(sq_dist)**2

    h_square = 1.0

    Kxy = np.exp(- pdist_square / h_square / 2.0)

    # now compute KSD
    Sqxdy = np.dot(getval(Sqx), z.T) - np.tile(np.sum(getval(Sqx) * z, 1, keepdims=True), (1, K))
    Sqxdy = -Sqxdy / h_square

    dxSqy = Sqxdy.T
    dxdy = -pdist_square / (h_square ** 2) + dimZ / h_square

    # M is a (K, K) tensor
    M = (np.dot(getval(Sqx), getval(Sqx).T) + Sqxdy + dxSqy + dxdy) * Kxy

    # U-statistic
    if flag_U:
        M2 = M - np.diag(np.diag(M))
        return np.sum(M2) / (K * (K - 1))
    # V-statistic
    else:
        return np.sum(M) / (K * K )

def init_random_params(L):
    eps = 0.01 + rs.rand(L,2) * 0.015
    log_eps = np.log(eps)
    log_v_r = np.zeros([ L, 2 ])
    mu0 = np.zeros((1,2))
    log_sigma0 = np.zeros((1,2))
    log_inflation = 0 * np.ones((1,2))
    return np.concatenate((log_eps, log_v_r, mu0, log_sigma0, log_inflation), 0)

def leapfrog(z, r, eps, log_v_r, dlogP):
    for i in range(5):
        r_half = r - eps / 2.0 * -getval(dlogP(z)) # stops the gradient computation
        z = z + eps * r_half / np.exp(log_v_r)
        r = r_half - eps / 2.0 * -getval(dlogP(z)) # stops the gradient computation
    return z, r

def generate_samples_HMC(params, n = 100):
    log_eps = params[ 0 : L, : ]
    log_v_r = params[ L : (2 * L), : ]

    mu0 = getval(params[-3,:])
    mu0 = np.ones((n,1)) * mu0
    log_sigma0 = getval(params[-2,:])
    sigma0 = np.exp(log_sigma0)

    log_inflation = getval(params[-1,:][0])
    inflation = np.exp(log_inflation)

    z = rs.randn(n, params.shape[ 1 ]) * (np.ones((n,1)) * (sigma0 * inflation)) + mu0

    for j in range(L):
        r = rs.randn(n, params.shape[ 1 ]) * np.exp(0.5 * log_v_r[ j, : ])
        z_new, r_new = leapfrog(z, r, np.exp(log_eps[ j, : ]), log_v_r[ j, : ], dlogP)
        p_acceptance = np.minimum(1, np.exp(logP(z_new) - logP(z) -0.5 * np.sum(r_new**2 /  np.exp(log_v_r[ j, : ]), 1) + \
            0.5 * np.sum(r**2 /  np.exp(log_v_r[ j, : ]), 1)))
        accepted = rs.rand(n) < p_acceptance
        accepted = np.transpose(np.tile(accepted, (params.shape[ 1 ], 1)))
        z = z_new * accepted + (1 - accepted) * z

    return z

def evaluate_objective(params):
    N = 100
    samples_HMC = generate_samples_HMC(params, N)

    sigma0 = np.exp(params[-2,:])
    var0 = sigma0**2
    mu0 = params[-3,:]

    epsilon0 = rs.randn(N,params.shape[1])
    samples0 = np.ones((N,1)) * mu0 + epsilon0* (np.ones((N,1)) * sigma0)

    elbo0 = np.mean(logP(samples0)) + np.log(2 * np.pi) + 1 + params[-2,0] + params[-2,1]
    return -np.mean(logP(samples_HMC)) - elbo0

def adam(evaluate_objective, params):
    print("    Step       |     objective      ")
    def print_perf(epoch, params):
        objective = evaluate_objective(params)
        print("{0:15}|{1:15}".format(epoch, -objective))
    m1 = 0
    m2 = 0
    beta1 = 0.9
    beta2 = 0.999
    epsilon = 1e-8
    alpha = 0.05
    t = 0
    grad_objective = grad(evaluate_objective)
    epochs = 200

    #start = time.time()
    for epoch in range(epochs):
        #if epoch + 1 == 100:
        #    end = time.time()
        #    print("time: {}".format(end-start))
        t += 1
        print_perf(epoch, params)
        grad_params= grad_objective(params)
        m1 = beta1 * m1 + (1 - beta1) * grad_params
        m2 = beta2 * m2 + (1 - beta2) * grad_params**2
        m1_hat = m1 / (1 - beta1**t)
        m2_hat = m2 / (1 - beta2**t)

        params = params - alpha * m1_hat / (np.sqrt(m2_hat) + epsilon)   #alpha is step size of adam

    return params

if __name__ == "__main__":
    rs = npr.RandomState(0)
    L = 30
    logP = logP_gauss     # can specify other targets included in targets.py
    dlogP = dlogP_gauss

    params = init_random_params(L)
    params = adam(evaluate_objective, params)
    exp_params = np.exp(params)
    exp_params[-3,:] = np.log(exp_params[-3,:])
    exp_params[-1,1] = None
    print("step_sizes, mu, sigma and inflation: {}".format(exp_params))

    z = generate_samples_HMC(params, 100000)

    print("-Expexted Log Target Estimate: {}".format(-np.mean(logP(z))))
    print("KSD: {}".format(KSD(z[:10000,:], dlogP(z[:10000,:]),flag_U = False)))

    z1=z[:,0]
    z2=z[:,1]
    plt.hist2d(z1, z2, bins=(300, 300))
    #plt.xlim(-4,4)
    #plt.ylim(-4,4)
    plt.show()

reason: from scipy


text:
import numpy as np

class GAF:
    def __init__(self, series, extremes=[None, None]):
        # MARK: - Scaling
        # convert list to ndarray
        series = np.array(series).copy()
        assert (len(series.shape) == 1)
        self.length = series.shape[0]
        # compute min and max of series
        extremes[0] = series.min() if extremes[0] is None else min(series.min(), extremes[0])
        extremes[1] = series.max() if extremes[1] is None else max(series.max(), extremes[1])
        self.extremes = extremes
        # scale series between -1 and 1
        series *= 2.0
        series -= sum(self.extremes)
        series /= self.extremes[1] - self.extremes[0]
        series[np.isnan(series)] = 0.0
        # correct for floating point errors
        self.series = np.clip(series, -1.0, 1.0)

        # MARK: - Polar Encoding
        phi = np.arccos(self.series)
        x = np.meshgrid(phi, phi)
        self.encoded = np.cos(x[0] + x[1])

max_stars_repo_name: haydenshively/Tezos-Prediction

max_issues_repo_name: haydenshively/Tezos-Prediction

max_forks_repo_name: haydenshively/Tezos-Prediction


text:
""" Optimize the initial cage for a new source shape """
from __future__ import print_function
from pprint import pprint
import traceback
import sys
import datetime
import shutil
import torch
import os
import numpy as np
import pymesh
from pytorch_points.misc import logger
from pytorch_points.network.operations import faiss_knn
from pytorch_points.network.geo_operations import mean_value_coordinates_3D, edge_vertex_indices
from pytorch_points.utils.pc_utils import load, save_ply, save_ply_with_face, center_bounding_box
from pytorch_points.utils.geometry_utils import get_edge_points
from pytorch_points.utils.pytorch_utils import weights_init, check_values, save_network, load_network, \
    clamp_gradient_norm, tolerating_collate, clamp_gradient, fix_network_parameters
from pytorch_points.network.model_loss import MeshLaplacianLoss
import network2 as networks
from common import loadInitCage, build_dataset, deform_with_MVC, read_trimesh
from losses import MVCRegularizer
from option import DeformationOptions
from matplotlib.colors import Normalize
from matplotlib import cm
import openmesh as om
import pandas as pd

class MyOptions(DeformationOptions):
    def initialize(self, parser):
        parser.add_argument(
            "--model", type=str, default="/home/mnt/points/data/MPI-FAUST/training/registrations/tr_reg_010.ply")
        parser.add_argument("--use_cage", type=str,
                            help="path to optimized cage")
        parser.add_argument("--opt_lap", action="store_true",
                            help="optimize deformed shape using laplacian")
        return super().initialize(parser)

    def parse(self):
        super().parse()
        assert(self.opt.source_model is not None), "source model is required for optimize_cage"
        if not isinstance(self.opt.source_model, str):
            self.opt.source_model = self.opt.source_model[0]
        return self.opt

def visualize_correspondence(opt, source_shape, source_face, target_shape, target_face, corres_1, corres_2):
    """
    source_shape (1,N,3)
    source_face (1,F,3)
    target_shape (1,N2,3)
    target_face (1,F2,3)
    corres_face_1 (P)
    corres_face_2 (P)
    """
    # save these points with color codes
    P = corres_2.shape[0]
    assert(corres_1.shape[0] == corres_2.shape[0])
    corres_1 = corres_1.cpu().numpy().reshape(-1)
    corres_2 = corres_2.cpu().numpy().reshape(-1)
    normalize = Normalize(vmin=0, vmax=corres_1.shape[0])
    cmap = cm.get_cmap("jet")
    colors_picked = cmap(normalize(np.arange(P, dtype=np.float32)))[:, :3]
    colors_source = np.ones((source_face.shape[1], 3), dtype=np.float32)
    colors_source[corres_1, :] = colors_picked
    save_ply_with_face(source_shape[0].cpu().detach().numpy(), source_face[0].cpu().detach().numpy(),
                       os.path.join(opt.log_dir, opt.subdir, "source_corr.ply"), colors_source)
    colors_target = np.ones((target_face.shape[1], 3), dtype=np.float32)
    colors_target[corres_2, :] = colors_picked
    save_ply_with_face(target_shape[0].cpu().detach().numpy(), target_face[0].cpu().detach().numpy(),
                       os.path.join(opt.log_dir, opt.subdir, "target_corr.ply"), colors_target)

def optimize(opt):
    """
    weights are the same with the original source mesh
    target=net(old_source)
    """
    # load new target
    if opt.is_poly:
        target_mesh = om.read_polymesh(opt.model)
    else:
        target_mesh = om.read_trimesh(opt.model)
    target_shape_arr = target_mesh.points()
    target_shape = target_shape_arr.copy()
    target_shape = torch.from_numpy(
        target_shape[:, :3].astype(np.float32)).cuda()
    target_shape.unsqueeze_(0)

    target_faces_arr = target_mesh.face_vertex_indices()
    target_faces = target_faces_arr.copy()
    target_faces = torch.from_numpy(
        target_faces[:, :3].astype(np.int64)).cuda()
    target_faces.unsqueeze_(0)

    states = torch.load(opt.ckpt)
    if "states" in states:
        states = states["states"]
    cage_v = states["template_vertices"].transpose(1, 2).cuda()
    cage_f = states["template_faces"].cuda()
    shape_v = states["source_vertices"].transpose(1, 2).cuda()
    shape_f = states["source_faces"].cuda()

    if os.path.isfile(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")) and os.path.isfile(opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")):
        new_label_path = opt.model.replace(os.path.splitext(opt.model)[1], ".picked")
        orig_label_path = opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")
        logger.info("Loading picked labels {} and {}".format(orig_label_path, new_label_path))
        new_label = pd.read_csv(new_label_path, delimiter=" ",skiprows=1, header=None)
        orig_label = pd.read_csv(orig_label_path, delimiter=" ",skiprows=1, header=None)
        orig_label_name = orig_label.iloc[:,5]
        new_label_name = new_label.iloc[:,5].tolist()
        new_to_orig_idx = []
        for i, name in enumerate(new_label_name):
            matched_idx = orig_label_name[orig_label_name==name].index
            if matched_idx.size == 1:
                new_to_orig_idx.append((i, matched_idx[0]))
        new_to_orig_idx = np.array(new_to_orig_idx)
        if new_label.shape[1] == 10:
            new_vidx = new_label.iloc[:,9].to_numpy()[new_to_orig_idx[:,0]]
            target_points = target_shape[:, new_vidx, :]
        else:
            new_label_points = torch.from_numpy(new_label.iloc[:,6:9].to_numpy().astype(np.float32))
            target_points = new_label_points.unsqueeze(0).cuda()
            target_points, new_vidx, _ = faiss_knn(1, target_points, target_shape, NCHW=False)
            target_points = target_points.squeeze(2) # B,N,3
            new_label[9] = new_vidx.squeeze(0).squeeze(-1).cpu().numpy()
            new_label.to_csv(new_label_path, sep=" ", header=[str(new_label.shape[0])]+[""]*(new_label.shape[1]-1), index=False)
            target_points = target_points[:, new_to_orig_idx[:,0], :]

        target_points = target_points.cuda()
        source_shape, _ = read_trimesh(opt.source_model)
        source_shape = torch.from_numpy(source_shape[None, :,:3]).float()
        if orig_label.shape[1] == 10:
            orig_vidx = orig_label.iloc[:,9].to_numpy()[new_to_orig_idx[:,1]]
            source_points = source_shape[:, orig_vidx, :]
        else:
            orig_label_points = torch.from_numpy(orig_label.iloc[:,6:9].to_numpy().astype(np.float32))
            source_points = orig_label_points.unsqueeze(0)
            # find the closest point on the original meshes
            source_points, new_vidx, _ = faiss_knn(1, source_points, source_shape, NCHW=False)
            source_points = source_points.squeeze(2) # B,N,3
            orig_label[9] = new_vidx.squeeze(0).squeeze(-1).cpu().numpy()
            orig_label.to_csv(orig_label_path, sep=" ", header=[str(orig_label.shape[0])]+[""]*(orig_label.shape[1]-1), index=False)
            source_points = source_points[:,new_to_orig_idx[:,1],:]

        _, source_center, _ = center_bounding_box(source_shape[0])
        source_points -= source_center
        source_points = source_points.cuda()
        # # shift target so that the belly match
        # try:
        #     orig_bellyUp_idx = orig_label_name[orig_label_name=="bellUp"].index[0]
        #     orig_bellyUp = orig_label_points[orig_bellyUp_idx, :]
        #     new_bellyUp_idx = [i for i, i2 in new_to_orig_idx if i2==orig_bellyUp_idx][0]
        #     new_bellyUp = new_label_points[new_bellyUp_idx,:]
        #     target_points += (orig_bellyUp - new_bellyUp)
        # except Exception as e:
        #     logger.warn("Couldn\'t match belly to belly")
        #     traceback.print_exc(file=sys.stdout)

        # source_points[0] = center_bounding_box(source_points[0])[0]
    elif not os.path.isfile(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")) and \
            os.path.isfile(opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")):
        logger.info("Could not find {}. Assuming SMPL model".format(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")))
        source_shape, source_faces = read_trimesh(opt.source_model)
        assert(source_faces.shape[0] == target_faces.shape[1]), \
            "opt.model must be a SMPL model with {} faces and {} vertices. Otherwise a correspondence file {} must be present.".format(
                source_faces.shape[0], source_shape.shape[0], opt.model.replace(os.path.splitext(opt.model)[1], ".picked"))
        # align faces not vertices
        orig_label_path = opt.source_model.replace(os.path.splitext(opt.source_model)[1], ".picked")
        logger.info("Loading picked labels {}".format(orig_label_path))
        orig_label = pd.read_csv(orig_label_path, delimiter=" ",skiprows=1, header=None)
        source_shape = torch.from_numpy(source_shape[None, :, :3]).cuda().float()
        source_faces = torch.from_numpy(source_faces[None, :, :3]).cuda().long()
        idx = torch.from_numpy(orig_label.iloc[:,1].to_numpy()).long()
        source_points = torch.gather(source_shape.unsqueeze(1).expand(-1, idx.numel(), -1, -1), 2, source_faces[:, idx, :, None].expand(-1, -1, -1, 3))
        source_points = source_points.mean(dim=-2)
        target_points = torch.gather(target_shape.unsqueeze(1).expand(-1, idx.numel(), -1, -1), 2, target_faces[:, idx, :, None].expand(-1, -1, -1, 3))
        target_points = target_points.mean(dim=-2)

        _, source_center, _ = center_bounding_box(source_shape[0])
        source_points -= source_center
    elif not os.path.isfile(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")):
        logger.info("Could not find {}. Assuming SMPL model".format(opt.model.replace(os.path.splitext(opt.model)[1], ".picked")))
        source_shape, source_faces = read_trimesh(opt.source_model)
        assert(source_faces.shape[0] == target_faces.shape[1]), \
            "opt.model must be a SMPL model with {} faces and {} vertices. Otherwise a correspondence file {} must be present.".format(
                source_faces.shape[0], source_shape.shape[0], opt.model.replace(os.path.splitext(opt.model)[1], ".picked"))
        source_shape, source_faces = read_trimesh(opt.source_model)

        _, source_center, _ = center_bounding_box(source_shape[0])
        source_points -= source_center

        source_shape = torch.from_numpy(source_shape[None, :, :3]).cuda().float()
        source_faces = torch.from_numpy(source_faces[None, :, :3]).cuda().long()
        # select a subset of faces, otherwise optimization is too slow
        idx = torch.from_numpy(np.random.permutation(2048)).cuda().long()
        source_points = torch.gather(source_shape.unsqueeze(1).expand(-1, source_faces.shape[1], -1, -1), 2, source_faces[:, idx,:, None].expand(-1, -1, -1, 3))
        source_points = source_points.mean(dim=-2)
        target_points = torch.gather(target_shape.unsqueeze(1).expand(-1, source_faces.shape[1], -1, -1), 2, target_faces[:,idx,: None].expand(-1, -1, -1, 3))
        target_points = target_points.mean(dim=-2)

        target_points = target_points[:, idx]
        source_points = source_points[:, idx]

    target_shape[0], target_center, target_scale = center_bounding_box(target_shape[0])
    _, _, source_scale = center_bounding_box(shape_v[0])
    # scale according y axis (body height)
    target_scale_factor = (source_scale/target_scale)[0,1]
    target_shape *= target_scale_factor
    target_points -= target_center
    target_points = (target_points*target_scale_factor).detach()
    # make sure test use the normalized
    target_shape_arr[:] = target_shape[0].cpu().numpy()
    om.write_mesh(os.path.join(opt.log_dir, opt.subdir, os.path.splitext(
        os.path.basename(opt.model))[0]+"_normalized.obj"), target_mesh)
    opt.model = os.path.join(opt.log_dir, opt.subdir, os.path.splitext(
        os.path.basename(opt.model))[0]+"_normalized.obj")
    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-initial.obj"),
                         shape_v[0].cpu().numpy(), shape_f[0].cpu().numpy())
    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "cage-initial.obj"),
                         cage_v[0].cpu().numpy(), cage_f[0].cpu().numpy())
    save_ply(target_points[0].cpu().numpy(), os.path.join(
        opt.log_dir, opt.subdir, "target_points.ply"))
    save_ply(source_points[0].cpu().numpy(), os.path.join(
        opt.log_dir, opt.subdir, "source_points.ply"))
    logger.info("Optimizing for {} corresponding vertices".format(
        target_points.shape[1]))

    cage_init = cage_v.clone().detach()
    lap_loss = MeshLaplacianLoss(torch.nn.MSELoss(reduction="none"), use_cot=True,
                                 use_norm=True, consistent_topology=True, precompute_L=True)
    mvc_reg_loss = MVCRegularizer(threshold=50, beta=1.0, alpha=0.0)
    cage_v.requires_grad_(True)
    optimizer = torch.optim.Adam([cage_v], lr=opt.lr, betas=(0.5, 0.9))
    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, int(opt.nepochs*0.4), gamma=0.5, last_epoch=-1)

    if opt.dim == 3:
        weights_ref = mean_value_coordinates_3D(
            source_points, cage_init, cage_f, verbose=False)
    else:
        raise NotImplementedError

    for t in range(opt.nepochs):
        optimizer.zero_grad()
        weights = mean_value_coordinates_3D(
            target_points, cage_v, cage_f, verbose=False)
        loss_mvc = torch.mean((weights-weights_ref)**2)
        # reg = torch.sum((cage_init-cage_v)**2, dim=-1)*1e-4
        reg = torch.tensor(0.0).cuda()
        if opt.clap_weight > 0:
            reg = lap_loss(cage_init, cage_v, face=cage_f)*opt.clap_weight
            reg = reg.mean()
        if opt.mvc_weight > 0:
            reg += mvc_reg_loss(weights)*opt.mvc_weight

        loss = loss_mvc + reg
        if (t+1) % 50 == 0:
            print("t {}/{} mvc_loss: {} reg: {}".format(t, opt.nepochs, loss_mvc.item(), reg.item()))

        if loss_mvc.item() < 5e-6:
            break
        loss.backward()
        optimizer.step()
        scheduler.step()

    return cage_v, cage_f

def test_one(opt, cage_shape, new_source, new_source_face, new_target, new_target_face):
    states = torch.load(opt.ckpt)
    if "states" in states:
        states = states["states"]

    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-initial.ply"),
                         states["source_vertices"][0].transpose(
                             0, 1).detach().cpu(),
                         states["source_faces"][0].detach().cpu())

    # states["template_vertices"] = cage_shape.transpose(1, 2)
    # states["source_vertices"] = new_source.transpose(1, 2)
    # states["source_faces"] = new_source_face

    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-Sa.ply"),
                         new_source[0].detach().cpu(), new_source_face[0].detach().cpu())
    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-Sb.ply"),
                         new_target[0].detach().cpu(), new_target_face[0].detach().cpu())

    net = networks.FixedSourceDeformer(opt, 3, opt.num_point, bottleneck_size=512,
                                       template_vertices=cage_shape.transpose(1, 2), template_faces=states["template_faces"].cuda(),
                                       source_vertices=new_source.transpose(1, 2), source_faces=new_source_face).cuda()

    net.eval()
    load_network(net, states)

    outputs = net(new_target.transpose(1, 2).contiguous())
    deformed = outputs["deformed"]

    pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-Sab.ply"),
                         deformed[0].detach().cpu(), new_target_face[0].detach().cpu())

def test_all(opt, new_cage_shape):
    opt.phase = "test"
    opt.target_model = None
    print(opt.model)

    if opt.is_poly:
        source_mesh = om.read_polymesh(opt.model)
    else:
        source_mesh = om.read_trimesh(opt.model)

    dataset = build_dataset(opt)
    dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, drop_last=False,
                                             collate_fn=tolerating_collate,
                                             num_workers=0, worker_init_fn=lambda id: np.random.seed(np.random.get_state()[1][0] + id))

    states = torch.load(opt.ckpt)
    if "states" in states:
        states = states["states"]
    # states["template_vertices"] = new_cage_shape.transpose(1, 2)
    # states["source_vertices"] = new_source.transpose(1,2)
    # states["source_faces"] = new_source_face
    # new_source_face = states["source_faces"]

    om.write_mesh(os.path.join(opt.log_dir, opt.subdir,
                               "template-Sa.ply"), source_mesh)

    net = networks.FixedSourceDeformer(opt, 3, opt.num_point, bottleneck_size=opt.bottleneck_size,
                                       template_vertices=states["template_vertices"], template_faces=states["template_faces"].cuda(),
                                       source_vertices=states["source_vertices"], source_faces=states["source_faces"]).cuda()
    print(net)
    load_network(net, states)

    source_points = torch.from_numpy(
        source_mesh.points().copy()).float().cuda().unsqueeze(0)
    with torch.no_grad():
        # source_face = net.source_faces.detach()
        for i, data in enumerate(dataloader):
            data = dataset.uncollate(data)

            target_shape, target_filename = data["target_shape"], data["target_file"]
            logger.info("", data["target_file"][0])

            sample_idx = None
            if "sample_idx" in data:
                sample_idx = data["sample_idx"]

            outputs = net(target_shape.transpose(1, 2), cage_only=True)
            if opt.d_residual:
                cage_offset = outputs["new_cage"]-outputs["cage"]
                outputs["cage"] = new_cage_shape
                outputs["new_cage"] = new_cage_shape+cage_offset

            deformed = deform_with_MVC(outputs["cage"], outputs["new_cage"], outputs["cage_face"].expand(
                outputs["cage"].shape[0], -1, -1), source_points)

            for b in range(deformed.shape[0]):
                t_filename = os.path.splitext(target_filename[b])[0]
                source_mesh_arr = source_mesh.points()
                source_mesh_arr[:] = deformed[0].cpu().detach().numpy()
                om.write_mesh(os.path.join(
                    opt.log_dir, opt.subdir, "template-{}-Sab.obj".format(t_filename)), source_mesh)
                pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "template-{}-Sb.ply".format(t_filename)),
                                     data["target_mesh"][b].detach().cpu(), data["target_face"][b].detach().cpu())

                pymesh.save_mesh_raw(
                    os.path.join(opt.log_dir, opt.subdir, "template-{}-cage1.ply".format(t_filename)),
                    outputs["cage"][b].detach().cpu(), outputs["cage_face"][b].detach().cpu(),
                                   )
                pymesh.save_mesh_raw(
                    os.path.join(opt.log_dir, opt.subdir, "template-{}-cage2.ply".format(t_filename)),
                    outputs["new_cage"][b].detach().cpu(), outputs["cage_face"][b].detach().cpu(),
                                   )
            if i % 20 == 0:
                logger.success("[{}/{}] Done".format(i, len(dataloader)))

    dataset.render_result(os.path.join(opt.log_dir, opt.subdir))

if __name__ == "__main__":
    parser = MyOptions()
    opt = parser.parse()

    opt.log_dir = os.path.dirname(opt.ckpt)

    os.makedirs(os.path.join(opt.log_dir, opt.subdir), exist_ok=True)
    if opt.use_cage is None:
        # optimize initial cage for the new target
        cage_v, cage_f = optimize(opt)
        pymesh.save_mesh_raw(os.path.join(opt.log_dir, opt.subdir, "optimized_template_cage.ply"),
                             cage_v[0].detach().cpu(), cage_f[0].detach().cpu())
    else:
        cage_v, cage_f = read_trimesh(opt.use_cage)
        cage_v = torch.from_numpy(cage_v[:, :3].astype(np.float32)).cuda()
        cage_f = torch.from_numpy(cage_f[:, :3].astype(np.int64)).cuda()
        cage_v.unsqueeze_(0)
        cage_f.unsqueeze_(0)

    # # test using the new source and initial cage
    # target_shape_pose, target_face_pose, _ = read_trimesh("/home/mnt/points/data/MPI-FAUST/training/registrations/tr_reg_002.ply")
    # target_shape_pose = torch.from_numpy(target_shape_pose[:,:3].astype(np.float32)).cuda()
    # target_face_pose = torch.from_numpy(target_face_pose[:,:3].astype(np.int64)).cuda()
    # target_shape_pose, _, _ = center_bounding_box(target_shape_pose)
    # target_shape_pose.unsqueeze_(0)
    # target_face_pose.unsqueeze_(0)
    # test_one(opt, cage_v, target_shape, target_face, target_shape_pose, target_face_pose)
    test_all(opt, cage_v)


text:
# Authors: Lukas Gemein <l.gemein@gmail.com>
#
# License: BSD-3

import os

import pytest
import numpy as np
import pandas as pd

from braindecode.datasets.moabb import MOABBDataset
from braindecode.datautil.windowers import create_windows_from_events
from braindecode.datautil.serialization import (
    save_concat_dataset, load_concat_dataset)

@pytest.fixture(scope="module")
def setup_concat_raw_dataset():
    return MOABBDataset(dataset_name="BNCI2014001", subject_ids=[1])

@pytest.fixture(scope="module")
def setup_concat_windows_dataset(setup_concat_raw_dataset):
    moabb_dataset = setup_concat_raw_dataset
    return create_windows_from_events(
        concat_ds=moabb_dataset,
        trial_start_offset_samples=0,
        trial_stop_offset_samples=0)

def test_save_concat_raw_dataset(setup_concat_raw_dataset, tmpdir):
    concat_raw_dataset = setup_concat_raw_dataset
    n_raw_datasets = len(concat_raw_dataset.datasets)
    save_concat_dataset(path=tmpdir, concat_dataset=concat_raw_dataset, overwrite=False)
    assert os.path.exists(tmpdir.join(f"description.json"))
    for raw_i in range(n_raw_datasets):
        assert os.path.exists(tmpdir.join(f"{raw_i}-raw.fif"))
    assert not os.path.exists(tmpdir.join(f"{n_raw_datasets}-raw.fif"))

def test_save_concat_windows_dataset(setup_concat_windows_dataset, tmpdir):
    concat_windows_dataset = setup_concat_windows_dataset
    n_windows_datasets = len(concat_windows_dataset.datasets)
    save_concat_dataset(path=tmpdir, concat_dataset=concat_windows_dataset, overwrite=False)
    assert os.path.exists(tmpdir.join(f"description.json"))
    for windows_i in range(n_windows_datasets):
        assert os.path.exists(tmpdir.join(f"{windows_i}-epo.fif"))
    assert not os.path.exists(tmpdir.join(f"{n_windows_datasets}-epo.fif"))

def test_load_concat_raw_dataset(setup_concat_raw_dataset, tmpdir):
    concat_raw_dataset = setup_concat_raw_dataset
    n_raw_datasets = len(concat_raw_dataset.datasets)
    save_concat_dataset(path=tmpdir, concat_dataset=concat_raw_dataset,
                        overwrite=False)
    loaded_concat_raw_dataset = load_concat_dataset(
        path=tmpdir, preload=False)
    assert len(concat_raw_dataset) == len(loaded_concat_raw_dataset)
    assert (len(concat_raw_dataset.datasets) ==
            len(loaded_concat_raw_dataset.datasets))
    assert (len(concat_raw_dataset.description) ==
            len(loaded_concat_raw_dataset.description))
    for raw_i in range(n_raw_datasets):
        actual_x, actual_y = concat_raw_dataset[raw_i]
        x, y = loaded_concat_raw_dataset[raw_i]
        np.testing.assert_allclose(x, actual_x, rtol=1e-4, atol=1e-5)
    pd.testing.assert_frame_equal(
        concat_raw_dataset.description, loaded_concat_raw_dataset.description)

def test_load_concat_windows_dataset(setup_concat_windows_dataset, tmpdir):
    concat_windows_dataset = setup_concat_windows_dataset
    n_windows_datasets = len(concat_windows_dataset.datasets)
    save_concat_dataset(path=tmpdir, concat_dataset=concat_windows_dataset,
                        overwrite=False)
    loaded_concat_windows_dataset = load_concat_dataset(
        path=tmpdir, preload=False)
    assert len(concat_windows_dataset) == len(loaded_concat_windows_dataset)
    assert (len(concat_windows_dataset.datasets) ==
            len(loaded_concat_windows_dataset.datasets))
    assert (len(concat_windows_dataset.description) ==
            len(loaded_concat_windows_dataset.description))
    for windows_i in range(n_windows_datasets):
        actual_x, actual_y, actual_crop_inds = concat_windows_dataset[windows_i]
        x, y, crop_inds = loaded_concat_windows_dataset[windows_i]
        np.testing.assert_allclose(x, actual_x, rtol=1e-4, atol=1e-5)
        np.testing.assert_allclose(y, actual_y, rtol=1e-4, atol=1e-5)
        np.testing.assert_array_equal(crop_inds, actual_crop_inds)
    pd.testing.assert_frame_equal(concat_windows_dataset.description,
                                  loaded_concat_windows_dataset.description)

max_stars_repo_name: ErikBjare/braindecode

max_issues_repo_name: ErikBjare/braindecode

max_forks_repo_name: ErikBjare/braindecode


text:
from model_selection import *
from net import Network
from utility import read_cup, save_blind
import numpy as np

""" Performs single computation for CUP dataset """
if __name__ == '__main__':

    # read cup {development set - internal test set}
    dev_set_x, dev_set_labels, int_ts_x, int_ts_labels, _ = read_cup(int_ts=True)
    MODE = 'prediction'
    # MODEL PARAMETERS
    units_per_layer = [20, 20, 2]
    act_functions = ['relu', 'relu', 'identity']

    # model parameters
    mod_par_cup = {
        'input_dim': 10,
        'units_per_layer': units_per_layer,
        'act_functions': act_functions,
        'weights_init': 'glorot'
    }

    # TRAINING PARAMETERS
    lr = 0.001
    lr_decay = None # or 'linear_decay'
    limit_step = None
    momentum = 0.6
    lambda_ = 0
    reg_type = 'ridge_regression'
    batch_size = 145

    # training parameters dict
    params_cup = {'lr': lr, 'lr_decay': lr_decay, 'limit_step': limit_step, 'momentum': momentum, 'nesterov': True, 'epochs': 350, 'batch_size': batch_size,
                    'error_func': 'squared_error', 'metr': 'euclidian_error', 'lambda_': lambda_}

    # MODEL SELECTION
    if MODE == 'validation':
        print("----- MODEL SELECTION -----")
        model_cup = Network(**mod_par_cup)
        # model selection cup
        # with plot=True it will plot a graph for each fold
        kfold_CV(net=model_cup, dataset='cup', **params_cup, k_folds=5, verbose=True, plot=True,
                disable_tqdms=(False, False))

    # MODEL ASSESSMENT ON INTERNAL TEST SET
    elif MODE == 'int_ts_assessment':
        print("----- MODEL ASSESSMENT ON INTERNAL TEST SET -----")
        # Average prediction results
        avg_tr_error, avg_tr_acc, avg_ts_error, avg_ts_acc = [], [], [], []
        # test prediction - 10 trials
        for trials in range(10):
            model_cup = Network(**mod_par_cup)
            model_cup.compile(**params_cup)
            tr_error_values, tr_acc_values, ts_error_values, ts_acc_values = model_cup.fit(
                tr_x=dev_set_x,
                tr_y=dev_set_labels,
                val_x=int_ts_x,
                val_y=int_ts_labels,
                disable_tqdm=False,
                epochs=350,
                batch_size= batch_size
            )
            # with path=None plot_curves will plot a graph for each trial. If we want only save images pass path != None to plot_curves
            path = None # path = '../images/int_ts_assessment/model_assessment_{}'.format(trials)
            plot_curves(tr_error_values, ts_error_values, tr_acc_values, ts_acc_values, ylim2 = (0., 20.), path=path)
            avg_tr_error.append(tr_error_values[-1])
            avg_tr_acc.append(tr_acc_values[-1])
            avg_ts_error.append(ts_error_values[-1])
            avg_ts_acc.append(ts_acc_values[-1])

        # display average loss/accuracy training - test
        print('Average predictions')
        print(f"Train Loss: {np.mean(avg_tr_error)} - Test Loss: {np.mean(avg_ts_error)}\n"
            f"Train Acc: {np.mean(avg_tr_acc)} - Test Acc: {np.mean(avg_ts_acc)}") # keep this for our Table 3 (dev set MEE and internal test set MEE)

    # PREDICTION ON BLIND TEST SET
    else:
        print("----- PREDICTION ON BLIND TEST SET -----")
        tr_data, tr_targets, cup_ts_data = read_cup()
        model_cup = Network(**mod_par_cup)
        model_cup.compile(**params_cup)
        tr_error_values, tr_acc_values, ts_error_values, ts_acc_values = model_cup.fit(
            tr_x=tr_data,
            tr_y=tr_targets,
            disable_tqdm=False,
            epochs=350,
            batch_size= batch_size
        )
        save_blind(model_cup, cup_ts_data)

max_stars_repo_name: dilettagoglia/impl-NN-from-scratch

max_issues_repo_name: dilettagoglia/impl-NN-from-scratch

max_forks_repo_name: dilettagoglia/impl-NN-from-scratch


text:
import numpy as np

class ColorofPoint:

    def __ColorofPointCorrespondence__(self, img, p):

        ColorofMatch = []

        for i in range(len(p)):
            x_point = p[i, 0]
            y_point = p[i, 1]
            try:
                color = img[x_point, y_point]
            except:
                color = (0,0,0)
            ColorofMatch.append(color)
        return np.array(ColorofMatch)


text:
# coding: utf-8
import numpy as np
import re
import copy
import sys
import networkx as nx
#import matplotlib.pyplot as plt
#import operator
#from collections import defaultdict
from collections import Counter
from collections import deque
import time

CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'

def delete_last_lines(n=1):
    for _ in range(n):
        print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
#        sys.stdout.write(CURSOR_UP_ONE)
#        sys.stdout.write(ERASE_LINE)

def print_field(xyids, DBG=True):
    coords = xyids.keys()
    if(DBG): print(xyids)
    x_min = min(coords, key = lambda t: t[0])[0]-1
    x_max = max(coords, key = lambda t: t[0])[0]+1
    y_min = min(coords, key = lambda t: t[1])[1]-1
    y_max = max(coords, key = lambda t: t[1])[1]+1

    if(DBG): print(x_min,x_max,y_min,y_max)

    for yy in range(y_min,y_max+1):
        ss = ""
        for xx in range(x_min,x_max+1):
            if (xx,yy) in xyids:
                ss += str(xyids[(xx,yy)])
            else:
                ss += " "
        print(ss)

    #delete_last_lines(y_max-y_min)

def print_tracks_and_vehicles(xyids, vehicles,vehicles_id_to_v_and_count, DBG=True):
    coords = xyids.keys()
    if(DBG): print(xyids)
    x_min = min(coords, key = lambda t: t[0])[0]-1
    x_max = max(coords, key = lambda t: t[0])[0]+1
    y_min = min(coords, key = lambda t: t[1])[1]-1
    y_max = max(coords, key = lambda t: t[1])[1]+1

    if(DBG): print(x_min,x_max,y_min,y_max)

    for yy in range(y_min,y_max+1):
        ss = ""
        for xx in range(x_min,x_max+1):
            if (xx,yy) in xyids:
                if (xx,yy) in vehicles:
                    v = vehicles_id_to_v_and_count[vehicles[(xx,yy)]][0]
                    ss += str(v)
                else:
                    ss += str(xyids[(xx,yy)])
            else:
                ss += " "
        print(ss)

    #delete_last_lines(y_max-y_min)

def create_world(ccc, DBG=True):
    field = {}
    vehicles = {}
    vehicles_id_to_v_and_count = {}
    x=-1
    y=-1
    v_id=0
    for line in ccc:
        y+=1
        x=-1
        for c in line:
            x+=1
            if c==' ' or c=='#':
                continue
            elif c=='<' or c=='>':
                field[(x,y)]='-'
                vehicles[(x,y)]=v_id
                vehicles_id_to_v_and_count[v_id] = (c,0)
                v_id = v_id+1
            elif c=='^' or c=='v':
                field[(x,y)]='|'
                vehicles[(x,y)]=v_id
                vehicles_id_to_v_and_count[v_id] = (c,0)
                v_id = v_id+1
            else:
                field[(x,y)]=c

    if DBG:print(field)
    if DBG:print_tracks_and_vehicles(field,vehicles,vehicles_id_to_v_and_count)

    return (field,vehicles,vehicles_id_to_v_and_count)

def move_vehicle(x,y,v,count,tracks, DBG=True):
    if v=='^':
        y = y-1
        if tracks[(x,y)]=='/':
            v='>'
        elif tracks[(x,y)]=='\\':
            v='<'
        elif tracks[(x,y)]=='+':
            if (count==0): #left
                v='<'
            elif (count==1): #straight
                pass
            elif (count==2): #right
                v='>'
            count = (count + 1) % 3
    elif v=='v':
        y = y+1
        if tracks[(x,y)]=='/':
            v='<'
        elif tracks[(x,y)]=='\\':
            v='>'
        elif tracks[(x,y)]=='+':
            if (count==0): #left
                v='>'
            elif (count==1): #straight
                pass
            elif (count==2): #right
                v='<'
            count = (count + 1) % 3
    elif v=='>':
        x = x+1
        if tracks[(x,y)]=='/':
            v='^'
        elif tracks[(x,y)]=='\\':
            v='v'
        elif tracks[(x,y)]=='+':
            if (count==0): #left
                v='^'
            elif (count==1): #straight
                pass
            elif (count==2): #right
                v='v'
            count = (count + 1) % 3
    elif v=='<':
        x = x-1
        if tracks[(x,y)]=='/':
            v='v'
        elif tracks[(x,y)]=='\\':
            v='^'
        elif tracks[(x,y)]=='+':
            if (count==0): #left
                v='v'
            elif (count==1): #straight
                pass
            elif (count==2): #right
                v='^'
            count = (count + 1) % 3
    return (x,y,v,count)

def function(ii, DBG = True):

    # parse tracks and vehicles from input
    (tracks, vehicles, vehicles_id_to_v_and_count) = create_world(ii, DBG)

    coords = tracks.keys()
    x_min = min(coords, key = lambda t: t[0])[0]
    x_max = max(coords, key = lambda t: t[0])[0]
    y_min = min(coords, key = lambda t: t[1])[1]
    y_max = max(coords, key = lambda t: t[1])[1]

    tick = 0
    collision = False
    # tick
    # move along x then y
    # if vehicle there, move it
    # check for collision

    while (not collision):
        #aa=input()
        tick = tick+1
        new_vehicles = {}
        for y in range(y_min,y_max+1):
            for x in range(x_min,x_max+1):
                if (x,y) in vehicles:
                    v_id = vehicles[(x,y)]
                    v = vehicles_id_to_v_and_count[v_id][0]
                    count = vehicles_id_to_v_and_count[v_id][1]
                    (new_x,new_y,new_v,new_count) = move_vehicle(x,y,v,count,tracks,DBG)
                    if (new_x,new_y) in new_vehicles:
                        collision = True
                        new_vehicles[(new_x,new_y)] = v_id
                        vehicles_id_to_v_and_count[v_id] = ('X',-1)
                        if DBG:print_tracks_and_vehicles(tracks,new_vehicles,vehicles_id_to_v_and_count)
                        return (new_x,new_y,tick)
                    else:
                        new_vehicles[(new_x,new_y)] = v_id
                        vehicles_id_to_v_and_count[v_id] = (new_v,new_count)
        vehicles = new_vehicles
        if DBG:print(tick)
        if DBG:print_tracks_and_vehicles(tracks,vehicles,vehicles_id_to_v_and_count)
        if(tick%100) == 0:
                print(tick)
                #print_tracks_and_vehicles(tracks,new_vehicles,vehicles_id_to_v_and_count,False)
        #if(tick==14):break

    return (-1,-1,-1)

def test(cc=None, expected=None, DBG = False):
    start_millis = int(round(time.time() * 1000))
    result = function(cc,DBG)
    stop_millis = int(round(time.time() * 1000))
    result = str(result)
    expected = str(expected)
    flag = (result == expected)
    if(expected=="None"):
        print("*** "+str(cc) + " *** -> Result = "+str(result))
    else:
        print("*** "+str(cc) + " *** -> Result = "+str(result), " -> success = "+ str(flag) + " -> expected " + expected)
    print((stop_millis-start_millis),"ms",int((stop_millis-start_millis)/1000),"s",int((stop_millis-start_millis)/1000/60),"min")
    return flag

#t1=r"""/->-\
#|   |  /----\
#| /-+--+-\  |
#| | |  | v  |
#\-+-/  \-+--/
#  \------/   """
t1=r"""/-<-\
|   |  /----\
| /-+--+-\  |
| | |  | |  |
\-+-/  \-+--/
  \------/   """
tt1 = t1.splitlines()
#test(tt1,(7,3,14),True)
#sys.exit()

INPUT_FILE="input-d13.txt"
f = open(INPUT_FILE, "r")
contents = f.read()
puzzle_input = contents.splitlines()
f.close()

ret = function(puzzle_input, False)
print(ret)

# (124, 90, 422)

max_stars_repo_name: jbudynek/advent-of-code

max_issues_repo_name: jbudynek/advent-of-code

max_forks_repo_name: jbudynek/advent-of-code