text:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dpp

from dpp.utils import DotDict
from dpp.nn import BaseModule
import matplotlib.pyplot as plt

class Model(BaseModule):
    """Base model class.

    Attributes:
        rnn: RNN for encoding the event history.
        embedding: Retrieve static embedding for each sequence.
        decoder: Compute log-likelihood of the inter-event times given hist and emb.

    Args:
        config: General model configuration (see dpp.model.ModelConfig).
        decoder: Model for computing log probability of t given history and embeddings.
            (see dpp.decoders for a list of possible choices)
    """
    def __init__(self, config, decoder):
        super().__init__()
        self.use_history(config.use_history)
        self.use_embedding(config.use_embedding)
        self.use_marks(config.use_marks)

        self.rnn = dpp.nn.RNNLayer(config)
        if self.using_embedding:
            self.embedding = nn.Embedding(config.num_embeddings, config.embedding_size)
            self.embedding.weight.data.fill_(0.0)

        if self.using_marks:
            self.num_classes = config.num_classes
            self.mark_layer = nn.Sequential(
                nn.Linear(config.history_size, config.history_size),
                nn.ReLU(),
                nn.Linear(config.history_size, self.num_classes)
            )

        self.decoder = decoder

    def mark_nll(self, h, y):
        """Compute log likelihood and accuracy of predicted marks

        Args:
            h: History vector
            y: Out marks, true label

        Returns:
            loss: Negative log-likelihood for marks, shape (batch_size, seq_len)
            accuracy: Percentage of correctly classified marks
        """
        x = self.mark_layer(h)
        x = F.log_softmax(x, dim=-1)
        loss = F.nll_loss(x.view(-1, self.num_classes), y.view(-1), reduction='none').view_as(y)
        accuracy = (y == x.argmax(-1)).float()
        return loss, accuracy

    def expectation(self, input):
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        # Get sequence embedding
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        return self.decoder.expectation(h, emb)

    def pi(self, input, N = None):
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        if self.using_embedding:
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        t = input.out_time  # has shape (batch_size, seq_len)

        probs = torch.Tensor([0.05, 0.95])

        if N is not None:
            samples = self.decoder.sample(n_samples = N, h=h, emb=emb).detach()
            qf = torch.quantile(samples, probs, dim = 2).permute([1, 2, 0])
        else:
            params = self.decoder.get_params(h, emb)
            qf_1 = self.decoder.forward(torch.full(t.shape, probs[0]), params)
            qf_2 = self.decoder.forward(torch.full(t.shape, probs[1]), params)

    def score(self, input, scoring_rule = None, tau = None, return_details = True, N = None):
        """Compute log likelihood of the inter-event timesi in the batch.

        Args:
            input: Batch of data to score. See dpp.data.Input.

        Returns:
            time_log_prob: Log likelihood of each data point, shape (batch_size, seq_len)
            mark_nll: Negative log likelihood of marks, if using_marks is True
            accuracy: Accuracy of marks, if using_marks is True
        """
        # Encode the history with an RNN
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        # Get sequence embedding
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        t = input.out_time  # has shape (batch_size, seq_len)

        if scoring_rule == "crps" or scoring_rule is None:
            results = self.decoder.crps(t, h, emb)

        elif scoring_rule == "crps_qapprox":
            results = self.decoder.crps_qapprox(t, h, emb, N = N) # 100 1000

        elif scoring_rule == "crps_qapprox_reg":
            results = self.decoder.crps_qapprox_reg(t, h, emb, training_mode = self.training, lengths = input.length, N = N) # 100 vs 1000

        elif scoring_rule == "crps_iapprox":
            results = self.decoder.crps_iapprox(t, h, emb, N = N)

        elif scoring_rule == "crps_sapprox":
            results =self.decoder.crps_sapprox(t, h, emb, N = N, return_details = return_details)

        elif scoring_rule == "logs":
            results = -self.decoder.log_prob(t, h, emb) # DO NOT FORGET THE MINUS HERE.

        elif scoring_rule == "quantile_score":
            results = self.decoder.quantile_score(tau, t, h, emb, params=None)

        elif scoring_rule == "calibration_error":
            results = self.decoder.calibration_error(t, h, emb, params=None, N =N)

        else:
            raise Exception("The scoring rule is not implemented.")

        return results

    def aggregate(self, values, lengths):
        """Calculate masked average of values.

        Sequences may have different lengths, so it's necessary to exclude
        the masked values in the padded sequence when computing the average.

        Arguments:
            values (list[tensor]): List of batches where each batch contains
                padded values, shape (batch size, sequence length)
            lengths (list[tensor]): List of batches where each batch contains
                lengths of sequences in a batch, shape (batch size)

        Returns:
            mean (float): Average value in values taking padding into account
        """

        if not isinstance(values, list):
            values = [values]
        if not isinstance(lengths, list):
            lengths = [lengths]

        total = 0.0
        for batch, length in zip(values, lengths):
            length = length.long()
            mask = torch.arange(batch.shape[1])[None, :] < length[:, None]
            mask = mask.float()

            if (torch.isnan(batch)).any():
                breakpoint()

            assert((~torch.isnan(batch)).all())
            # batch[torch.isnan(batch)] = 0 # set NaNs to 0 (from ifl-tpp)

            if len(batch.shape) == 2:
                batch *= mask
                total += batch.sum()
            else:
                batch *= mask.unsqueeze(-1)
                total += torch.sum(batch, dim = [0, 1])

        total_length = sum([x.sum() for x in lengths])

        return total / total_length

    def get_total_calibration_loss(self, loader, N = None):
        loader_calib_error_mean = []
        loader_calib_error_max = []

        for input in loader:
            res_calib = self.score(input, "calibration_error", N = N)
            loader_calib_error_mean.append(res_calib[0])
            loader_calib_error_max.append(res_calib[1])

        return np.mean(loader_calib_error_mean), np.mean(loader_calib_error_max)

    def get_total_loss(self, loader, scoring_rule = None, tau = None, N = None):
        loader_score, loader_lengths = [], []
        for input in loader:
            loader_score.append(self.score(input, scoring_rule, tau, N = N).detach())
            loader_lengths.append(input.length.detach())
        return self.aggregate(loader_score, loader_lengths)

    def plot_functions(self, loader):
        input = next(iter(loader))
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        # sol = (cumwidths, widths, cumheights, heights, derivatives), normalized_params_tail, top
        params = self.decoder.get_params(h, emb)
        cumwidths = params[0][0][0, -1].detach()
        cumheights = params[0][2][0, -1].detach()
        derivatives = params[0][4][0, -1].detach()
        normalized_params_tail = params[1][0][0, -1].detach()
        top = params[2][0][-1, 0].detach()

        N = 1000 # 1000
        a = h.shape[0]
        b = h.shape[1]
        qtile = torch.empty(a, b, N)
        density = torch.empty(a, b, N)
        tau_all = torch.tensor(np.linspace(0, 1, N))
        for i in range(N):
            qtile[:, :, i] = self.decoder.forward(torch.full( (a, b), tau_all[i]), h = h, embed = emb)
            _, density[:, :, i] = self.decoder.inverse(qtile[:, :, i], h = h, embed = emb, compute_deriv = True)

        return tau_all, qtile, density, cumwidths, cumheights, normalized_params_tail, top, derivatives

    def get_total_loss_sampling(self, loader, return_details = True):
        loader_crps, loader_qs, loader_pits, loader_lengths, loader_means, loader_stds, loader_squared_errors, loader_abs_errors = [], [], [], [], [], [], [], []
        loader_target_interval_coverage, loader_abs_calibration_error, loader_mean_abs_calibration_error, loader_pi_coverage_prob =[], [], [], []
        for input in loader:
            results = self.score(input, "crps_sapprox", return_details = return_details)
            if return_details:
                crps_sampling, q_scores, pits, means, stds, squared_errors, abs_errors, target_interval_coverage, abs_calibration_error, mean_abs_calibration_error, pi_coverage_prob = results
            else:
                crps_sampling = results

            loader_crps.append(crps_sampling.detach())
            loader_lengths.append(input.length.detach())

            if return_details:
                loader_qs.append(q_scores.detach())
                # reduce size if N > 100
                loader_pits.append(pits.detach())

                loader_means.append(means.detach())
                loader_stds.append(stds.detach())

                loader_squared_errors.append(squared_errors.detach())
                loader_abs_errors.append(abs_errors.detach())

                # new
                loader_target_interval_coverage.append(target_interval_coverage.detach())
                loader_abs_calibration_error.append(abs_calibration_error.detach())
                loader_mean_abs_calibration_error.append(mean_abs_calibration_error)
                loader_pi_coverage_prob.append(pi_coverage_prob)

        crps = self.aggregate(loader_crps, loader_lengths)
        if return_details:
            quantile_scores = self.aggregate(loader_qs, loader_lengths)

            res_tuple = crps, quantile_scores, loader_pits, loader_means, loader_stds, loader_squared_errors, loader_abs_errors
            res_tuple = res_tuple + (loader_target_interval_coverage, loader_abs_calibration_error, loader_mean_abs_calibration_error, loader_pi_coverage_prob)
            return res_tuple

        else:
            return crps

    def get_predictions_and_true_obs(self, loader, N = 500, taus = None):
        loader_results = []
        for input in loader:
            loader_results.append(self.get_all_quantities(input, N, taus))
        return loader_results

    def get_all_quantities(self, input, N, taus):
        ############
         # Encode the history with an RNN
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        # Get sequence embedding
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None
        ############

        t = input.out_time  # has shape (batch_size, seq_len)

        samples = self.decoder.sample(N, h, emb).detach()

        quantiles = None
        q_densities = None
        params = None
        if taus is not None:
            params = self.decoder.get_params(h = h, embed = emb)
            ###
            all_q, all_d = [], []
            for tau in taus:
                q = self.decoder.forward(torch.full(t.shape, tau), params = params)
                _, d = self.decoder.inverse(q, params = params, compute_deriv = True)

                all_q.append(q)
                all_d.append(d)

            quantiles = torch.stack(all_q, dim = 2)
            q_densities = torch.stack(all_d, dim = 2)

        return (t, samples, quantiles, q_densities, params)

    def get_samples(self, input, N):
        # Encode the history with an RNN
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        # Get sequence embedding
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        #t = input.out_time  # has shape (batch_size, seq_len)
        samples = self.decoder.sample(N, h, emb).detach()
        #return (t, samples)
        return samples

    def get_quantiles(self, input, taus):
        # Encode the history with an RNN
        if self.using_history:
            h = self.rnn(input) # has shape (batch_size, seq_len, rnn_hidden_size)
        else:
            h = None
        # Get sequence embedding
        if self.using_embedding:
            # has shape (batch_size, seq_len, embedding_size)
            emb = self.embedding(input.index).unsqueeze(1).repeat(1, input.out_time.shape[1], 1)
        else:
            emb = None

        t = input.out_time  # has shape (batch_size, seq_len)

        params = self.decoder.get_params(h = h, embed = emb)
        all_q = []
        for tau in taus:
            all_q.append(self.decoder.forward(torch.full(t.shape, tau), params = params).detach())

        #return (t, torch.stack(all_q, dim = 2))
        return torch.stack(all_q, dim = 2)

class ModelConfig(DotDict):
    """Configuration of the model.

    This config only contains parameters that need to be know by all the
    submodules. Submodule-specific parameters are passed to the respective
    constructors.

    Args:
        use_history: Should the model use the history embedding?
        history_size: Dimension of the history embedding.
        rnn_type: {'RNN', 'LSTM', 'GRU'}: RNN architecture to use.
        use_embedding: Should the model use the sequence embedding?
        embedding_size: Dimension of the sequence embedding.
        num_embeddings: Number of unique sequences in the dataset.
        use_marks: Should the model use the marks?
        mark_embedding_size: Dimension of the mark embedding.
        num_classes: Number of unique mark types, used as dimension of output
    """
    def __init__(self,
                 use_history=True,
                 history_size=32,
                 rnn_type='RNN',
                 use_embedding=False,
                 embedding_size=32,
                 num_embeddings=None,
                 use_marks=False,
                 mark_embedding_size=64,
                 num_classes=None):
        super().__init__()
        # RNN parameters
        self.use_history = use_history
        self.history_size = history_size
        self.rnn_type = rnn_type

        # Sequence embedding parameters
        self.use_embedding = use_embedding
        self.embedding_size = embedding_size
        if use_embedding and num_embeddings is None:
            raise ValueError("Number of embeddings has to be specified")
        self.num_embeddings = num_embeddings

        self.use_marks = use_marks
        self.mark_embedding_size = mark_embedding_size
        self.num_classes = num_classes

max_stars_repo_name: bsouhaib/qf-tpp

max_issues_repo_name: bsouhaib/qf-tpp

max_forks_repo_name: bsouhaib/qf-tpp


text:
#!/usr/bin/env python
"""
    Module for basic plotting inside the TableCanvas. Uses matplotlib.
    Created August 2008
    Copyright (C) Damien Farrell

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

from __future__ import absolute_import, print_function
import sys, os
import copy
try:
    from tkinter import *
    from tkinter.ttk import *
except:
    from Tkinter import *
    from ttk import *
if (sys.version_info > (3, 0)):
    from tkinter import filedialog, messagebox, simpledialog
else:
    import tkFileDialog as filedialog
    import tkSimpleDialog as simpledialog
    import tkMessageBox as messagebox

from math import *
try:
    import numpy
except:
    pass

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.font_manager import FontProperties
import pylab

class pylabPlotter(object):
    """An interface to matplotlib for general plotting and stats, using tk backend"""

    colors = ['#0049B4','#C90B11','#437C17','#AFC7C7','#E9AB17','#7F525D','#F6358A',
              '#52D017','#FFFC17','#F76541','#F62217' ]
    linestyles = ['-','--']
    shapes = ['o','-','--',':','.' ,'p','^','<','s','+','x','D','1','4','h']
    legend_positions = ['best', 'upper left','upper center','upper right',
                         'center left','center','center right'
                         'lower left','lower center','lower right']

    graphtypes = ['XY', 'hist', 'bar', 'pie']
    fonts = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']

    def __init__(self):
        #Setup variables
        self.shape = 'o'
        self.grid = 0
        self.xscale = 0
        self.yscale = 0
        self.showlegend = 0
        self.legendloc = 'best'
        self.legendlines = []
        self.legendnames = []
        self.graphtype = 'XY'
        self.datacolors = self.colors
        self.dpi = 300
        self.linewidth = 1.5
        self.font = 'sans-serif'
        self.fontsize = 12
        try:
            self.setupPlotVars()
        except:
            print ('no tk running')
        self.currdata = None
        #self.format = None  #data format
        self.plottitle = ''
        self.plotxlabel = ''
        self.plotylabel = ''
        return

    def plotXY(self, x, y, title='', xlabel=None, ylabel=None, shape=None,
                            clr=None, lw=1):
        """Do x-y plot of 2 lists"""
        if shape == None:
            shape = self.shape
        if clr == None:
            clr = 'b'
        if self.xscale == 1:
            if self.yscale == 1:
                line, = pylab.loglog(x, y, shape, color=clr, linewidth=lw)
            else:
                line, = pylab.semilogx(x, y, shape, color=clr, linewidth=lw)
        elif self.yscale == 1:
            line, = pylab.semilogy(x, y, shape, color=clr, linewidth=lw)
        else:
            line, = pylab.plot(x, y, shape, color=clr, linewidth=lw)
        return line

    def doHistogram(self, data, bins=10):
        """Do a pylab histogram of 1 or more lists"""
        if len(data) == 1:
            ydim=1
        else:
            ydim=2
        dim=int(ceil(len(data)/2.0))
        i=1
        #fig = pylab.figure()
        for r in data:
            if len(r)==0:
                continue
            ax = pylab.subplot(ydim,dim,i)
            print (r)
            for j in range(len(r)):
                r[j] = float(r[j])
            pylab.hist(r,bins=bins)
            i=i+1
        return ax

    def doBarChart(self, x, y, clr):
        """Do a pylab bar chart"""
        #xloc = range(len(x))
        for i in range(len(x)):
            x[i] = float(x[i]);y[i] = float(y[i])
        plotfig = pylab.bar(x, y, color=clr, alpha=0.6)

        return plotfig

    def doPieChart(self, data):
        """Do a pylab bar chart"""
        if len(data) == 1:
            ydim=1
        else:
            ydim=2
        dim=int(ceil(len(data)/2.0))
        i=1
        for r in data:
            if len(r)==0:
                continue
            fig = pylab.subplot(ydim,dim,i)

            for j in range(len(r)):
                r[j] = float(r[j])
            pylab.pie(r)
            i=i+1

        return

    def setData(self, data):
        """Set the current plot data, useful for re-plotting without re-calling
           explicit functions from the parent"""

        self.currdata = data
        return

    def hasData(self):
        """Is there some plot data?"""
        if self.currdata != None and len(self.currdata) > 0:
            return True
        else:
            return False

    def setDataSeries(self, names=None, start=1):
        """Set the series names, for use in legend"""
        self.dataseriesvars=[]
        for i in range(start,len(names)):
           s=StringVar()
           s.set(names[i])
           self.dataseriesvars.append(s)
        #print self.dataseriesvars
        return

    def setFormat(self, format):
        """Set current data format of currdata"""
        self.format = format
        return

    def plotCurrent(self, data=None, graphtype='bar', show=True, guiopts=False,title=None):
        """Re-do the plot with the current options and data"""
        if guiopts == True:
            self.applyOptions()
        if title != None:
            self.settitle(title)
        self.clear()
        currfig = pylab.figure(1)

        if data == None:
            try:
                data = self.currdata
            except:
                print ('no data to plot')
                return
        else:
            self.setData(data)

        seriesnames = []
        legendlines = []
        for d in self.dataseriesvars:
            seriesnames.append(d.get())

        self.graphtype = graphtype
        #do an X-Y plot, with the first list as X xals
        if self.graphtype == 'bar' or len(data) == 1:
            i=0
            pdata = copy.deepcopy(data)
            if len(pdata)>1:
                x = pdata[0]
                pdata.remove(x)
                for y in pdata:
                    if i >= len(self.colors):
                        i = 0
                    c = self.colors[i]
                    self.doBarChart(x, y, clr=c)
                    i+=1
            else:
                y = pdata[0]
                x = range(len(y))
                self.doBarChart(x, y, clr='b')

        elif self.graphtype == 'XY':
            pdata = copy.deepcopy(data)
            x = pdata[0]
            pdata.remove(x)
            i=0
            for y in pdata:
                if i >= len(self.colors):
                    i = 0
                c = self.colors[i]
                line = self.plotXY(x, y, clr=c, lw=self.linewidth)
                legendlines.append(line)
                i+=1

        elif self.graphtype == 'hist':
            self.doHistogram(data)
        elif self.graphtype == 'pie':
            self.doPieChart(data)

        pylab.title(self.plottitle)
        pylab.xlabel(self.plotxlabel)
        pylab.ylabel(self.plotylabel)
        #create legend data
        if self.showlegend == 1:
            pylab.legend(legendlines,seriesnames,
                         loc=self.legendloc)
        if self.grid == 1:
            pylab.grid(True)

        if show == True:
            self.show()
        return currfig

    def clear(self):
        """clear plot"""
        pylab.clf()
        self.legendlines = []
        self.legendnames = []
        return

    def show(self):
        pylab.show()
        return

    def saveCurrent(self, filename=None):
        import tkFileDialog, os
        filename=tkFileDialog.asksaveasfilename(parent=self.plotprefswin,
                                                defaultextension='.png',
                                                filetypes=[("Png file","*.png"),
                                                           ("All files","*.*")])
        if not filename:
            return
        fig = self.plotCurrent(show=False)
        fig.savefig(filename, dpi=self.dpi)
        return

    def setTitle(self, title=None):
        self.plottitle = title

    def setxlabel(self, label=None):
        self.plotxlabel = label

    def setylabel(self, label=None):
        self.plotylabel = label

    def setOptions(self, shape=None, grid=None, xscale=None, yscale=None,
                    showlegend=None, legendloc=None, linewidth=None,
                    graphtype=None, font=None, fontsize=None):
        """Set the options before plotting"""
        if shape != None:
            self.shape = shape
        if grid != None:
            self.grid = grid
        if xscale != None:
            self.xscale = xscale
        if yscale != None:
            self.yscale = yscale
        if showlegend != None:
            self.showlegend = showlegend
        if legendloc != None:
            self.legendloc = legendloc
        if linewidth != None:
            self.linewidth = linewidth
        if graphtype !=None:
            self.graphtype = graphtype
        if font != None:
            self.font = font
        if fontsize != None:
            self.fontsize = fontsize
        pylab.rc("font", family=self.font, size=self.fontsize)
        return

    def setupPlotVars(self):
        """Plot Vars """
        self.pltgrid = IntVar()
        self.pltlegend = IntVar()
        self.pltsymbol = StringVar()
        self.pltsymbol.set(self.shape)
        self.legendlocvar = StringVar()
        self.legendlocvar.set(self.legendloc)
        self.xscalevar = IntVar()
        self.yscalevar = IntVar()
        self.xscalevar.set(0)
        self.yscalevar.set(0)
        self.graphtypevar = StringVar()
        self.graphtypevar.set(self.graphtype)
        self.linewidthvar = DoubleVar()
        self.linewidthvar.set(self.linewidth)
        self.fontvar = StringVar()
        self.fontvar.set(self.font)
        self.fontsizevar = DoubleVar()
        self.fontsizevar.set(self.fontsize)
        #plot specific
        self.plottitlevar = StringVar()
        self.plottitlevar.set('')
        self.plotxlabelvar = StringVar()
        self.plotxlabelvar.set('')
        self.plotylabelvar = StringVar()
        self.plotylabelvar.set('')
        self.dataseriesvars=[]
        return

    def applyOptions(self):
        """Apply the gui option vars to the plotter options"""
        self.setOptions(shape=self.pltsymbol.get(), grid=self.pltgrid.get(),
               xscale=self.xscalevar.get(), yscale=self.yscalevar.get(),
               showlegend = self.pltlegend.get(),
               legendloc = self.legendlocvar.get(),
               linewidth = self.linewidthvar.get(),
               graphtype = self.graphtypevar.get(),
               font = self.fontvar.get(),
               fontsize = self.fontsizevar.get())
        self.setTitle(self.plottitlevar.get())
        self.setxlabel(self.plotxlabelvar.get())
        self.setylabel(self.plotylabelvar.get())
        return

    def plotSetup(self, data=None):
        """Plot options dialog"""

        if data != None:
            self.setData(data)
        self.plotprefswin=Toplevel()
        self.plotprefswin.geometry('+300+450')
        self.plotprefswin.title('Plot Preferences')
        row=0
        frame1=LabelFrame(self.plotprefswin, text='General')
        frame1.grid(row=row,column=0,sticky='news',padx=2,pady=2)
        def close_prefsdialog():
            self.plotprefswin.destroy()

        def choosecolor(x):
            """Choose color for data series"""
            d=x[0]
            c=x[1]
            #print 'passed', 'd',d, 'c',c
            import tkColorChooser
            colour,colour_string = tkColorChooser.askcolor(c,parent=self.plotprefswin)
            if colour != None:
                self.datacolors[d] = str(colour_string)
                cbuttons[d].configure(bg=colour_string)

            return

        Checkbutton(frame1, text="Grid lines", variable=self.pltgrid,
                    onvalue=1, offvalue=0).grid(row=0,column=0, columnspan=2, sticky='news')
        Checkbutton(frame1, text="Legend", variable=self.pltlegend,
                    onvalue=1, offvalue=0).grid(row=1,column=0, columnspan=2, sticky='news')

        Label(frame1,text='Symbol:').grid(row=2,column=0,padx=2,pady=2)
        symbolbutton = Menubutton(frame1,textvariable=self.pltsymbol,
					                relief=GROOVE, width=16, bg='lightblue')
        symbol_menu = Menu(symbolbutton, tearoff=0)
        symbolbutton['menu'] = symbol_menu
        for text in self.shapes:
            symbol_menu.add_radiobutton(label=text,
                                            variable=self.pltsymbol,
                                            value=text,
                                            indicatoron=1)
        symbolbutton.grid(row=2,column=1, sticky='news',padx=2,pady=2)
        row=row+1

        Label(frame1,text='Legend pos:').grid(row=3,column=0,padx=2,pady=2)
        legendposbutton = Menubutton(frame1,textvariable=self.legendlocvar,
					                relief=GROOVE, width=16, bg='lightblue')
        legendpos_menu = Menu(legendposbutton, tearoff=0)
        legendposbutton['menu'] = legendpos_menu
        i=0
        for p in self.legend_positions:
            legendpos_menu.add_radiobutton(label=p,
                                        variable=self.legendlocvar,
                                        value=p,
                                        indicatoron=1)
            i+=1
        legendposbutton.grid(row=3,column=1, sticky='news',padx=2,pady=2)

        Label(frame1,text='Font:').grid(row=4,column=0,padx=2,pady=2)
        fontbutton = Menubutton(frame1,textvariable=self.fontvar,
					                relief=GROOVE, width=16, bg='lightblue')
        font_menu = Menu(fontbutton, tearoff=0)
        fontbutton['menu'] = font_menu
        for f in self.fonts:
            font_menu.add_radiobutton(label=f,
                                            variable=self.fontvar,
                                            value=f,
                                            indicatoron=1)
        fontbutton.grid(row=4,column=1, sticky='news',padx=2,pady=2)
        row=row+1
        Label(frame1,text='Font size:').grid(row=5,column=0,padx=2,pady=2)
        Scale(frame1,from_=8,to=26,resolution=0.5,orient='horizontal',
                            relief=GROOVE,variable=self.fontsizevar).grid(row=5,column=1,padx=2,pady=2)

        Label(frame1,text='linewidth:').grid(row=6,column=0,padx=2,pady=2)
        Scale(frame1,from_=1,to=10,resolution=0.5,orient='horizontal',
                            relief=GROOVE,variable=self.linewidthvar).grid(row=6,column=1,padx=2,pady=2)
        row=0
        scalesframe = LabelFrame(self.plotprefswin, text="Axes Scales")
        scales={0:'norm',1:'log'}
        for i in range(0,2):
            Radiobutton(scalesframe,text='x-'+scales[i],variable=self.xscalevar,
                            value=i).grid(row=0,column=i,pady=2)
            Radiobutton(scalesframe,text='y-'+scales[i],variable=self.yscalevar,
                            value=i).grid(row=1,column=i,pady=2)
        scalesframe.grid(row=row,column=1,sticky='news',padx=2,pady=2)

        row=row+1
        frame=LabelFrame(self.plotprefswin, text='Graph type')
        frame.grid(row=row,column=0,columnspan=2,sticky='news',padx=2,pady=2)
        for i in range(len(self.graphtypes)):
            Radiobutton(frame,text=self.graphtypes[i],variable=self.graphtypevar,
                            value=self.graphtypes[i]).grid(row=0,column=i,pady=2)

        row=row+1
        labelsframe = LabelFrame(self.plotprefswin,text='Labels')
        labelsframe.grid(row=row,column=0,columnspan=2,sticky='news',padx=2,pady=2)
        Label(labelsframe,text='Title:').grid(row=0,column=0,padx=2,pady=2)
        Entry(labelsframe,textvariable=self.plottitlevar,bg='white',relief=GROOVE).grid(row=0,column=1,padx=2,pady=2)
        Label(labelsframe,text='X-axis label:').grid(row=1,column=0,padx=2,pady=2)
        Entry(labelsframe,textvariable=self.plotxlabelvar,bg='white',relief=GROOVE).grid(row=1,column=1,padx=2,pady=2)
        Label(labelsframe,text='Y-axis label:').grid(row=2,column=0,padx=2,pady=2)
        Entry(labelsframe,textvariable=self.plotylabelvar,bg='white',relief=GROOVE).grid(row=2,column=1,padx=2,pady=2)

        if self.currdata != None:
            #print self.dataseriesvars
            row=row+1
            seriesframe = LabelFrame(self.plotprefswin, text="Data Series Labels")
            seriesframe.grid(row=row,column=0,columnspan=2,sticky='news',padx=2,pady=2)
            #self.dataseriesvars=[]
            if len(self.dataseriesvars) == 0:
                self.setDataSeries(range(len(self.currdata)))
            r=1
            sr=1
            cl=0
            for s in self.dataseriesvars:
                Label(seriesframe,text='Series '+str(r)).grid(row=r,column=cl,padx=2,pady=2)
                Entry(seriesframe,textvariable=s,bg='white',
                                          relief=GROOVE).grid(row=r,column=cl+1,padx=2,pady=2)
                r+=1
                if r > 8:
                    r=1
                    cl+=2
            row=row+1
            cbuttons = {}
            frame = LabelFrame(self.plotprefswin, text="Dataset Colors")
            r=1
            cl=0
            sr=1
            ci=0
            for d in range(len(self.dataseriesvars)):
                if d >= len(self.datacolors):
                    self.datacolors.append(self.colors[ci])
                    ci+=1
                c = self.datacolors[d]
                action = lambda x =(d,c): choosecolor(x)
                cbuttons[d]=Button(frame,text='Series '+str(sr),bg=c,command=action)
                cbuttons[d].grid(row=r,column=cl,sticky='news',padx=2,pady=2)
                r+=1
                sr+=1
                if r > 8:
                    r=1
                    cl+=1
            frame.grid(row=row,column=0,columnspan=2,sticky='news',padx=2,pady=2)

        row=row+1
        frame=Frame(self.plotprefswin)
        frame.grid(row=row,column=0,columnspan=2,sticky='news',padx=2,pady=2)
        replotb = Button(frame, text="Replot",
                command=lambda:self.plotCurrent(graphtype=self.graphtype,guiopts=True),
                relief=GROOVE, bg='#99ccff')
        replotb.pack(side=LEFT,fill=X,padx=2,pady=2)
        b = Button(frame, text="Apply", command=self.applyOptions, relief=GROOVE, bg='#99ccff')
        b.pack(side=LEFT,fill=X,padx=2,pady=2)
        b = Button(frame, text="Save", command=self.saveCurrent, relief=GROOVE, bg='#99ccff')
        b.pack(side=LEFT,fill=X,padx=2,pady=2)
        c=Button(frame,text='Close', command=close_prefsdialog, relief=GROOVE, bg='#99ccff')
        c.pack(side=LEFT,fill=X,padx=2,pady=2)
        if self.currdata == None:
            replotb.configure(state=DISABLED)

        self.plotprefswin.focus_set()
        self.plotprefswin.grab_set()

        return

ext: py

reason: import numpy


text:
import cv2
import numpy as np
from scipy import ndimage
import tensorflow as tf

def get_light_map_single(img):
    gray = img
    gray = gray[None]
    gray = gray.transpose((1, 2, 0))
    blur = cv2.GaussianBlur(gray, (0, 0), 3)
    gray = gray.reshape((gray.shape[0], gray.shape[1]))
    highPass = gray.astype(int) - blur.astype(int)
    highPass = highPass.astype(np.float)
    highPass = highPass / 128.0
    return highPass

def normalize_pic(img):
    img = img / np.max(img)
    return img

def resize_img_512_3d(img):
    zeros = np.zeros((1, 3, 512, 512), dtype=np.float)
    zeros[0, 0: img.shape[0], 0: img.shape[1], 0: img.shape[2]] = img
    return zeros.transpose((1, 2, 3, 0))

def active_img_denoise(img):
    mat = img.astype(np.float)
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat = mat.astype(np.uint8)
    mat = ndimage.median_filter(mat, 1)
    return mat

def active_img(img):
    mat = img.astype(np.float)
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat = mat.astype(np.uint8)
    return mat

class SketchKeras():
    __CKPT = "./GUI/src/saved_model/Liner"
    __MODEL_PATH = "./GUI/src/saved_model/Liner/Liner.meta"

    def __init__(self, sess):

        if sess is None:
            config = tf.ConfigProto()
            config.gpu_options.per_process_gpu_memory_fraction = 0.2
            self.sess = tf.Session(config=config)
        else:
            self.sess = sess

        self.__build_model()
        self.__zero_init()

    def __build_model(self):
        saver = tf.train.import_meta_graph(self.__MODEL_PATH, clear_devices=True)
        saver.restore(sess=self.sess, save_path=tf.train.latest_checkpoint(self.__CKPT))

        graph = tf.get_default_graph()
        self.ph_input = graph.get_tensor_by_name("input_1:0")
        self.model = graph.get_tensor_by_name("conv2d_18/BiasAdd:0")

    def __zero_init(self):
        feed = np.zeros(shape=(1, 512, 512, 1))
        self.sess.run(self.model, feed_dict={self.ph_input: feed})

    def get_line(self, image):
        width = float(image.shape[1])
        height = float(image.shape[0])

        from_mat = cv2.resize(image, (512, 512), interpolation=cv2.INTER_AREA)
        from_mat = from_mat.transpose((2, 0, 1))
        light_map = np.zeros(from_mat.shape, dtype=np.float)

        for channel in range(3):
            light_map[channel] = get_light_map_single(from_mat[channel])

        light_map = normalize_pic(light_map)
        light_map = resize_img_512_3d(light_map)
        outputs = list()
        # batch size 1
        for index in range(3):
            feed = np.expand_dims(light_map[index], 0)
            out = self.sess.run(self.model, feed_dict={self.ph_input: feed})
            outputs.append(out[0])

        line_mat = np.array(outputs)
        line_mat = line_mat.transpose((3, 1, 2, 0))[0]
        line_mat = np.amax(line_mat, 2)
        img = active_img_denoise(line_mat)

        if (width > height):
            rate = width / height
            new_height = 512
            new_width = int(512 * rate)

        else:
            rate = height / width
            new_width = 512
            new_height = int(rate * 512)

        img = cv2.resize(img, (new_width, new_height), cv2.INTER_LINEAR_EXACT)
        img = np.expand_dims(img, 3)
        line = np.concatenate([img, img, img], axis=2)
        return line

    def get_line_from_file(self, path):
        from_mat = cv2.imread(path)
        line = self.get_line(from_mat)
        return line

reason: import numpy,from scipy


text:
import os
from typing import List, Tuple

import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots

COLORS = ['#f4792e', '#24324f', '#ffd769', '#c7303b', '#457abf', '#298964']

def graph_2d_markers(x: np.ndarray, y: np.ndarray,
    xaxis_title: str, yaxis_title: str, title: str,
    dirname: str, filename: str) -> None:
    """Creates a simple 2D plot using markers.
    """
    path = os.path.join(dirname, filename)

    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=x,
            y=y,
            mode='markers',
            marker_color=COLORS[0],
            marker_size=10,
        )
    )
    fig.update_layout(
        title_text=title,
        xaxis_title_text=xaxis_title,
        yaxis_title_text=yaxis_title,
        yaxis_scaleanchor = 'x',
        yaxis_scaleratio = 1,
    )
    pio.write_html(fig, path)

max_stars_repo_name: bstollnitz/grad-school-portfolio

max_issues_repo_name: bstollnitz/portfolio

max_forks_repo_name: bstollnitz/portfolio


text:
import logging

import numpy as np
from tqdm import tqdm

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

class EmbeddingManager():
    """
    An EmbeddingManager takes a DataIndexer fit on a train dataset,
    and produces an embedding matrix with pretrained embedding files.
    """
    def __init__(self, data_indexer):
        if not data_indexer.is_fit:
            raise ValueError("Input DataIndexer to EmbeddingManager "
                             "must first be fit on input data.")
        self.data_indexer = data_indexer

    @staticmethod
    def initialize_random_matrix(shape, scale=0.05, seed=0):
        if len(shape) != 2:
            raise ValueError("Shape of embedding matrix must be 2D, "
                             "got shape {}".format(shape))
        numpy_rng = np.random.RandomState(seed)
        return numpy_rng.uniform(low=-scale, high=scale, size=shape)

    def get_embedding_matrix(self, embedding_dim,
                             pretrained_embeddings_file_path=None,
                             pretrained_embeddings_dict=None,
                             namespace="words"):
        """
        Given an int embedding_dim, initialize an embedding matrix for each
        index in the data_indexer. If a pretrained embeddings file is
        provided, words in the data_indexer are assigned the vectors in the
        file. If a pretrained embeddings dictionary (of word to vector) is
        provided, words in the data_indexer are assigned to the vectors in
        this dictionary. Else, the vectors are randomly initialized.

        If pretrained_embeddings_file_path is provided, all rows must have
        the same number of dimensions. If pretrained_embeddings_dict is
        provided, all vectors must have the same number of dimensions.

        If both pretrained_embeddings_file_path and
        pretrained_embeddings_dict are provided, we will first check for
        words in the pretrained_embeddings_dict, then in the
        pretrained_embeddings_file, then randomly initialize if it is not
        found in either.

        Parameters
        ----------
        embedding_dim: int
            The length of each word embedding (row in the matrix).

        pretrained_embeddings_file_path: str, default=None
            Path to text file, with tokens and their vectors.
            The file should be formatted as [word] [dim 1] [dim 2] ...,
            i.e. the word and each dimension should be separated by
            a space.

        pretrained_embeddings_dict: dictionary of str:ndarray, default=None
            A dictionary of words and their vectors. Each word key should
            be a string, and each vector value should be a NumPy array.

        namespace: str, optional (default="words")
            A string indicating the DataIndexer namespace to get the maximum
            vocab size from.

        Returns
        -------
        embedding_matrix: NumPy array
            A NumPy array embedding_matrix of shape
            (num_indices, embedding_dim) where embedding_matrix[i]
            indicates the word vector for index i in the input DataIndexer.
        """
        if not isinstance(embedding_dim, int):
            raise ValueError("Expected input embedding_dim to be of "
                             "type int, found {} of type {} "
                             "instead.".format(embedding_dim,
                                               type(embedding_dim)))
        if (pretrained_embeddings_file_path and
                not isinstance(pretrained_embeddings_file_path, str)):
            raise ValueError("Expected input "
                             "pretrained_embeddings_file_path "
                             "to be of type str, found {} of type "
                             "{}".format(
                                 pretrained_embeddings_file_path,
                                 type(pretrained_embeddings_file_path)))
        if (pretrained_embeddings_dict and
                not isinstance(pretrained_embeddings_dict, dict)):
            raise ValueError("Expected input pretrained_embeddings_dict "
                             "to be of type dict, found {} of type "
                             "{}".format(
                                 pretrained_embeddings_dict,
                                 type(pretrained_embeddings_dict)))

        embeddings_from_file = {}
        if pretrained_embeddings_file_path:
            logger.info("Reading pretrained "
                        "embeddings from {}".format(
                            pretrained_embeddings_file_path))
            with open(pretrained_embeddings_file_path) as embedding_file:
                for line in tqdm(embedding_file):
                    fields = line.strip().split(" ")
                    if len(fields) - 1 <= 1:
                        raise ValueError("Found embedding size of 1; "
                                         "do you have a header?")
                    if embedding_dim != len(fields) - 1:
                        raise ValueError("Provided embedding_dim of {}, but "
                                         "file at pretrained_embeddings_"
                                         "file_path has embeddings of "
                                         "size {}".format(embedding_dim,
                                                          len(fields) - 1))
                    word = fields[0]
                    vector = np.array(fields[1:], dtype='float32')
                    embeddings_from_file[word] = vector

        if pretrained_embeddings_dict:
            # Check the all the values in the dictionary have the same
            # length, and check that that length is the same as
            # embedding_dim
            embeddings_dict_dim = 0
            for word, vector in pretrained_embeddings_dict.items():
                if not embeddings_dict_dim:
                    embeddings_dict_dim = len(vector)
                if embeddings_dict_dim != len(vector):
                    raise ValueError("Found vectors of different lengths in "
                                     "the pretrained_embeddings_dict.")
            if embeddings_dict_dim != embedding_dim:
                raise ValueError("Provided embedding_dim of {}, but "
                                 "pretrained_embeddings_dict has embeddings "
                                 "of size {}".format(embedding_dim,
                                                     embeddings_dict_dim))

        vocab_size = self.data_indexer.get_vocab_size(namespace=namespace)
        # Build the embedding matrix
        embedding_matrix = self.initialize_random_matrix((vocab_size,
                                                          embedding_dim))
        # The 2 here because there is no point in setting vectors
        # for 0 (padding token) and 1 (OOV token)
        for i in range(2, vocab_size):
            # Get the word corresponding to the index
            word = self.data_indexer.get_word_from_index(i)
            # If we don't have a pre-trained vector for this word, just
            # leave this row alone so the word has a random initialization.
            if (pretrained_embeddings_dict and
                    word in pretrained_embeddings_dict):
                embedding_matrix[i] = pretrained_embeddings_dict[word]
            else:
                if embeddings_from_file and word in embeddings_from_file:
                    embedding_matrix[i] = embeddings_from_file[word]
        return embedding_matrix

max_stars_repo_name: y-fujiwr/paraphrase-id-tensorflow

max_issues_repo_name: y-fujiwr/paraphrase-id-tensorflow

max_forks_repo_name: y-fujiwr/paraphrase-id-tensorflow


text:
from kaplot import *
from numpy import *
import numpy
# i index of room
# j index of 'other room'

class Section(object):
	def __init__(self, heat_capacity, T0, measured=None):
		self.heat_capacity = heat_capacity
		self.T0 = T0
		self.number = None # this will be provided by the 'System'

	def heating(self, t):
		return 0.

class Outside(Section):
	def __init__(self, T0, measured=None):
		Section.__init__(self, 1e100, T0, measured=measured)

Room = Section

class Wall(object):
	def __init__(self, room1, room2, alpha):
		self.room1 = room1
		self.room2 = room2
		self.alpha = alpha

class System(object):
	def __init__(self, rooms, connections):
		self.connections = connections
		self.room_count = len(rooms)
		self.rooms = rooms
		self.alpha = zeros((self.room_count, self.room_count))
		for i, room in enumerate(rooms):
			room.number = i

		for wall in self.connections:
			assert wall.room1.number != None
			assert wall.room2.number != None
			self.alpha[wall.room1.number, wall.room2.number] += wall.alpha
			self.alpha[wall.room2.number, wall.room1.number] += wall.alpha
		self.alpha = numpy.matrix(self.alpha).T
		#3	dsa
	def dTdt(self, T, t):
		"""
		dT_i/dt = \alpha_{i,j} * (T_j - T_i) + \sum_k \gamma_{i,k} P_{i, k}
		"""
		deltaT = zeros((self.room_count, self.room_count))
		for i in range(self.room_count):
			for j in range(self.room_count):
				deltaT[i,j] = -(T[i] - T[j])
		deltaT = numpy.matrix(deltaT)
		if 1:
			print "T=", T
			print "deltaT=", deltaT
			print "alpha=", self.alpha
			print deltaT*self.alpha
			print "..."

		dTdt = zeros((self.room_count))
		for i in range(self.room_count):
			for j in range(self.room_count):
				dTdt[i] += self.alpha[i,j] * deltaT[i,j]
		#dTdt = sum(deltaT*self.alpha, axis=1) # + array([room.heating(tindex) for room in self.rooms])
		#dTdt = array(dTdt.reshape(-1))[0]
		#print "    ", dTdt
		return array([dTdt[k]/self.rooms[k].heat_capacity for k in range(len(dTdt))])

	def run(self, args, opts, scope):
		T0 = array([room.T0 for room in self.rooms])
		t0 = 0.
		dt = 0.02/5
		N = 100
		temperatures = zeros((self.room_count, N+1))
		temperatures[:,0] = T0
		Ti = T0
		for i in range(N):
			t = t0 + i * dt
			#print "T", Ti
			Ti = Ti + self.dTdt(Ti, t) * dt
			print Ti
			temperatures[:,i+1] = Ti * 1

		for i, color in zip(range(self.room_count), nicecolors):
			graph(temperatures[i], color=color)

		draw()

max_stars_repo_name: maartenbreddels/mab

max_issues_repo_name: maartenbreddels/mab

max_forks_repo_name: maartenbreddels/mab

reason: import numpy,from numpy


text:
# -*- coding: utf-8 -*-
import unittest
import numpy as np

from models import BlackScholesModel
from options import EuropeanCallOption
from pricers import bs_option_price

class TestBlackScholes(unittest.TestCase):
    def test_itm(self):
        model = BlackScholesModel(300 * np.exp(0.03 * 1), 0.15, 0.03)
        option = EuropeanCallOption(1, 250)

        result = bs_option_price(model, option)
        expected = 58.82

        self.assertAlmostEqual(result, expected, 2)

if __name__ == '__main__':
    unittest.main()

max_stars_repo_name: HrPedersen/anderson-lake-python

max_issues_repo_name: danniecuiuc/anderson-lake-python

max_forks_repo_name: danniecuiuc/anderson-lake-python


text:
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np

#General
def quiver(X,Y,U,V,title,units):
    Q = plt.figure()
    plt.title(title,size=30)
    ax1 = plt.quiver(X,Y,U,V,np.sqrt(U**2+V**2),angles='xy',cmap='coolwarm',scale=1e2,width=0.0009,headwidth=6,headlength=7)
    qk = plt.quiverkey(ax1, 0.9, 0.9, 1, r'1 '+units, labelpos='E',coordinates='figure')
    plt.colorbar()
    plt.xlabel('meter',size=20)
    plt.ylabel('meter',size=20)
    plt.show()
    return Q

def quiver_profile(grid_points,vel,title,units):
    plt.figure()
    plt.title(title,size=20)
    second_axis = np.zeros(grid_points.shape)
    Q = plt.quiver(second_axis,grid_points,vel,vel,width=0.0023,headwidth=3,headlength=5,angles='xy')
    qk = plt.quiverkey(Q, 0.9, 0.9, 1, r'1 '+units, labelpos='E',coordinates='figure')
    plt.show()

def contour(X,Y,Values,title):
    plt.figure()
    plt.title(title,size=20)
    cont = plt.contourf(X,Y,Values)
    plt.colorbar()
    plt.xlabel('')
    plt.ylabel('')
    plt.show()
    return cont

def plot(Data,grid,title,labels):
    #plt.figure()
    plt.title(title,size=20)
    plt.plot(Data , grid, 'o-' )
    plt.xlabel(labels[0],size=15)
    plt.ylabel(labels[1],size=15)
    plt.show()

#Frame
def frame_quiver(frame):
    X,Y = frame.return_grid()
    U,V = frame.return_all_velocities()
    title = 'Quiver of frame: '+ frame.properties.frame
    units = frame.properties.velocity_units
    quiver(X,Y,U,V,title,units)

#Run
def run_quiver_animation(run):
    fig, ax = plt.subplots(figsize=(21, 18))
    if run.check_same_grid_run():
        X,Y = run.run_grid()
        frames = run.frames()
        units = run.fields[frames[0]].properties.velocity_units
        shape = (X.shape[0],X.shape[1],len(frames))
        U = np.zeros(shape)
        V = np.zeros(shape)
        for ind in range(len(frames)):
            x,y,u,v = run.fields[frames[ind]].create_mesh_grid()
            U[:,:,ind] = u[::-1]
            V[:,:,ind] = v[::-1]

    else:
        print('Not all run in same grid')
        return

    Q = ax.quiver(X,Y,U[...,0],V[...,0],np.sqrt(U[...,0]**2+V[...,0]**2),angles='xy',cmap='coolwarm')
    qk = plt.quiverkey(Q, 0.9, 0.9, 1, r'1 '+units, labelpos='E',coordinates='figure')

    def update_quiver(i,Q,U,V):
        Q.set_UVC(U[...,i],V[...,i],np.sqrt(U[...,i]**2+V[...,i]**2))
        ax.set_title('Velocity field frame number: %d' % i )
        return Q,

    anim = animation.FuncAnimation(fig, update_quiver,frames=shape[2],interval=300,fargs=(Q,U,V), blit=False,repeat=True)
    fig.tight_layout()
    plt.show()
    return anim

def mean_run_profile(run,axis='y'):
    U_mean_profile,U_number_of_vectors,V_mean_profile,V_number_of_vectors,grid_points_agp = run.mean_profile(axis)
    v_units = run.fields[run.frames()[0]].properties.velocity_units
    l_units = run.fields[run.frames()[0]].properties.length_unit
    plot(U_mean_profile , grid_points_agp,'Mean run plot in the '+axis+' direction',[r'$\bar{u}$ '+v_units,l_units])

def run_vorticity_animation(run):
    fig, ax = plt.subplots(figsize=(21, 18))
    if run.check_same_grid_run():
        X,Y = run.run_grid()
        X=X[2:-2,2:-2]
        Y=Y[2:-2,2:-2]
        frames = run.frames()
        shape = (X.shape[0],X.shape[1],len(frames))
        W = np.zeros(shape)
        for ind in range(len(frames)):
            w_c = run.fields[frames[ind]].vorticity_field()
            W[:,:,ind] = w_c[:,:]

    else:
        print('Not all run in same grid')
        return

    def update_cont(i):
        ax.clear()
        ax.contourf(X,Y,W[:,:,i])
        ax.set_title('Vorticity field frame number: %d' % i )

    anim = animation.FuncAnimation(fig, update_cont,interval=400, blit=False,repeat=True)
    fig.tight_layout()
    plt.show()
    return anim,W

def mean_run_vorticity(run,square=1):
    X,Y,W = run.run_vorticity_field()
    contour(X,Y,W**square,'Mean run vorticity field')

def mean_reynolds_stress(run,direction='xy'):
    X,Y = run.run_grid()
    r_stress = run.run_reynolds_stress()
    contour(X,Y,r_stress,'Mean run reynolds stress in the '+direction+' direction')

def mean_run_quiver(run):
    X,Y = run.run_grid()
    U,V = run.run_mean_velocities()
    U[U>2.5]=np.nan

    title = 'Mean velocity (U_wind = 2.5 m/s)'
    units = run.fields[run.frames()[0]].properties.velocity_units
    quiver(X,Y,U,V,title,units)

def mean_run_quiver_profile(run,loc_per,axis='y'):
    X,Y = run.run_grid()
    U,V = run.run_mean_velocities()
    if axis=='x':
        border = int(X.shape[0]*(loc_per/100))
        grid_points= X[border,:]
        V_prof = np.nanmean(V[border-1:border+2,:],axis=0)
        title = 'Mean velocity porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        units = run.fields[run.frames()[0]].properties.velocity_units
        quiver_profile(grid_points,V_prof,title,units)
    else:
        border = int(Y.shape[1]*(loc_per/100))
        grid_points= Y[:,border]
        U_prof = np.nanmean(U[:,border-1:border+2],axis=1)
        title = 'Mean velocity porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        units = run.fields[run.frames()[0]].properties.velocity_units
        quiver_profile(grid_points,U_prof,title,units)

def mean_vorticity_profile(run,loc_per,axis='y'):
    X,Y,W = run.run_vorticity_field()
    if axis=='x':
        border = int(X.shape[0]*(loc_per/100))
        grid_points= X[border,:]
        W_prof = np.nanmean(W[border-1:border+2,:],axis=0)
        title = 'Mean vorticity porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        l_units = run.fields[run.frames()[0]].properties.length_unit
        plot(grid_points,W_prof,title,(l_units,'vorticity'))
    else:
        border = int(Y.shape[1]*(loc_per/100))
        grid_points= Y[:,border]
        W_prof = np.nanmean(W[:,border-1:border+2],axis=1)
        title = 'Mean vorticity porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        l_units = run.fields[run.frames()[0]].properties.length_unit
        plot(W_prof,grid_points,title,('vorticity',l_units))

def mean_reynolds_stress_profile(run,loc_per,axis='y'):
    X,Y = run.run_grid()
    r_stress = run.run_reynolds_stress()
    if axis=='x':
        border = int(X.shape[0]*(loc_per/100))
        grid_points= X[border,:]
        r_stress_prof = np.nanmean(r_stress[border-1:border+2,:],axis=0)
        title = 'Mean Reynolds stress porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        l_units = run.fields[run.frames()[0]].properties.length_unit
        plot(grid_points,r_stress_prof,title,(l_units,'Reynold Stress'))
    else:
        border = int(Y.shape[1]*(loc_per/100))
        grid_points= Y[:,border]
        r_stress_prof = np.nanmean(r_stress[:,border-1:border+2],axis=1)
        title = 'Mean Reynolds stress porfile in the '+axis+' direction over all frames at '+str(loc_per)+'% of area'
        l_units = run.fields[run.frames()[0]].properties.length_unit
        plot(r_stress_prof,grid_points,title,('Reynold Stress',l_units))

max_stars_repo_name: tomerast/Vecpy

max_issues_repo_name: tomerast/Vecpy

max_forks_repo_name: tomerast/Vecpy


text:
import PyBulletEnv
import Obj
from numpy import random

if __name__ == "__main__":
    env = PyBulletEnv.PyBulletEnv()
    env.setup()
    tree = Obj.Obj("data/tree/Tree.obj")

    forest = []
    for _ in range(2):
        x = random.uniform(0, 20)
        y = random.uniform(0, 20)
        forest.append(tree.createObjectObj([x, y , 3.7], 1.0))

    env.analyze(tree, forest)

    env.run()

reason: from numpy


text:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -*- mode: Python -*-

'''
maxwell interactive

Quoi pour debut fin ?

LICENCE : CC
Sam Neurohack

 LINK

  - bpm

  - beatnumber -> Event

 MIDI

 - cc : channel = layer / ccnumber = steps / ccvalue = stepmax -> /maxwell/cc channel ccnumber ccvalue

 - notes

 if midi.sync :

 - midix.bpm

 - start -> /maxwell/start

 - stop  -> /maxwell/stop

 - clock -> /maxwell/clock

 OSC

 - /maxwell/rawcc layer encoder value (to change given encoder parameter ie 0 = steps)

 - /maxwell/cc layer steps stepmax

 - /maxwell/fx/layernumber fxname ('ScanH', 'ScanV', 'Circle', 'Wave')

 - /maxwell/x/layernumber coord (0-1)
 - /maxwell/xcoord layernumber coord

 - /maxwell/y/layernumber coord (0-1)
 - /maxwell/ycoord layernumber coord

                        Scale 98
 - /maxwell/scale layer value

 - /maxwell/linesize layer value

 - /maxwell/color/layername colorname

                         X 100 Y 104 Z 108
 - /maxwell/rotspeed layernumber axe speed

                        X 114 Y 118 Z 122
 - /maxwell/transamt layernumber axe maxposition

                        X 102 Y 106 Z 110
 - /maxwell/rotdirec layernumber axe rotdirec

 - /maxwell/bpm

 - /maxwell/clock

 - /maxwell/start

 - /maxwell/stop

 - /maxwell/noteon layer note velocity

 - /maxwell/noteoff layer note

 - /maxwell/part partname

 - /maxwell/intensity layernumber intensity

 - /maxwell/radius    layernumber value

 - /maxwell/type  layer side axe value
 - /maxwell/freq  layer side axe freq
 - /maxwell/amp  layer side axe amp
 - /maxwell/inv  layer side axe inv

 to code

 /maxwell/scandots       layernumber value
 /maxwell/cu/freq        layernumber axe frequency
 /maxwell/cu/phaseoffset layernumber axe phaseoffset
 curvetype

mode ALIGN

mode LIVE

mode SONG

 trigger / layer / size / speed
 trigger / layer / stepmax / steps

 Layer : Xsteps, Ysteps, Sizesteps, rotXsteps,...

'''

import math

import numpy as np
import pdb
from datetime import datetime
from random import randrange
import redis
import sys
import ast
import os
import time,traceback
import midix, anim

ljpath = r'%s' % os.getcwd().replace('\\','/')

# import from shell
sys.path.append(ljpath +'/../../libs/')
sys.path.append(ljpath +'/../libs/')

#import from LJ
sys.path.append(ljpath +'/libs/')

sys.path.append('../libs')
sys.path.append(ljpath +'/../../libs')

import gstt

is_py2 = sys.version[0] == '2'
if is_py2:
    from OSC import OSCServer, OSCClient, OSCMessage
else:
    from OSC3 import OSCServer, OSCClient, OSCMessage

import lj23layers as lj
import argparse

print ("")
print ("maxwell v0.1b")

OSCinPort = 8090

ljscene = 0

# Useful variables init.
white = lj.rgb2int(255,255,255)
red = lj.rgb2int(255,0,0)
blue = lj.rgb2int(0,0,255)
green = lj.rgb2int(0,255,0)
cyan = lj.rgb2int(255,0,255)
yellow = lj.rgb2int(255,255,0)

screen_size = [700,700]
xy_center = [screen_size[0]/2,screen_size[1]/2]

width = 800
height = 600
centerX = width / 2
centerY = height / 2

# 3D to 2D projection parameters
fov = 256
viewer_distance = 2.2

inv = math.pi/2

print ("")
print ("Arguments parsing if needed...")
argsparser = argparse.ArgumentParser(description="maxwell for LJ")
argsparser.add_argument("-r","--redisIP",help="IP of the Redis server used by LJ (127.0.0.1 by default) ",type=str)
argsparser.add_argument("-m","--myIP",help="Local IP (127.0.0.1 by default) ",type=str)
argsparser.add_argument("-s","--scene",help="LJ scene number (0 by default)",type=int)
argsparser.add_argument("-v","--verbose",help="Verbosity level (0 by default)",type=int)
argsparser.add_argument("-L","--Lasers",help="Number of lasers connected (1 by default).",type=int)
argsparser.add_argument('-song',help="Run according to external (LIVE is default)", dest='song', action='store_true')
argsparser.set_defaults(song=False)
argsparser.add_argument('-nolink',help="Disable Ableton Link (enabled by default)", dest='link', action='store_false')
argsparser.set_defaults(link=True)
args = argsparser.parse_args()

if args.verbose:
    debug = args.verbose
else:
    debug = 0

if args.scene:
    ljscene = args.scene
else:
    ljscene = 0

# Redis Computer IP
if args.redisIP  != None:
    redisIP  = args.redisIP
else:
    redisIP = '127.0.0.1'

# myIP
if args.myIP  != None:
    gstt.myIP  = args.myIP
else:
    gstt.myIP = '127.0.0.1'

# Lasers = number of laser connected
if args.Lasers  != None:
    gstt.lasernumber = args.Lasers
else:
    gstt.lasernumber = 1

# with Ableton Link
if args.link  == True:
    import alink

    alink.Start()
    linked = True
else:
    print("Link DISABLED")
    linked = False

# Mode song
if args.song  == True:
    print("Mode SONG")
    mode = "song"
else:
    print("Mode LIVE")
    mode = "live"

lj.Config(redisIP, ljscene, "maxwell")

ccs =[[0] * 140] *4

# Animation parameters for each layer
Layer = [{'scandots': 10, 'mixer': 0, 'color': red, 'scale': 1,'intensity': 255}] * 3

LayerX = [{'coord': 250, 'rotspeed': 0, 'transpeed': 0, 'transamt': 250, "rotdirec": 0}] *3
LayerY = [{'coord': 250, 'rotspeed': 0, 'transpeed': 0, 'transamt': 250, "rotdirec": 0}] *3
LayerZ = [{'coord': 0,   'rotspeed': 0, 'transpeed': 0, 'transamt': 0,   "rotdirec": 0}] *3

# Maxwell Style
# sin:0/saw:33/squ:95/lin:127
CurveLX= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': 0}] * 3
CurveLY= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': np.pi/2}] * 3
CurveLZ= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': 0}] * 3

CurveRX= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': 0}] * 3
CurveRY= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': 0}] * 3
CurveRZ= [{'type': 0, 'freq': 1, 'amp': 150, 'phasemod': 0, 'phaseoffset': 0, 'inv': 0}] * 3

# Destination :           name, number, active, layer , scene, laser)
Dest000 = lj.DestObject('FX0', 0, True, 0 , 0, 0)
#Dest101 = lj.DestObject('FX1', 1, True, 1 , 0, 1)
#Dest202 = lj.DestObject('FX2', 2, True, 2 , 0, 2)

# RelativeObject              name, active, intensity, xy, color, red, green, blue, layer , closed, xpos , ypos , scale , rotx , roty , rotz
FX0Form = lj.RelativeObject('FX0', True, 255, [], Layer[0]['color'], 255, 0, 0, 0 , False, 250 , 250, 1 , 0 , 0 , 0)
FX1Form = lj.RelativeObject('FX1', True, 255, [], Layer[1]['color'], 255, 0, 0, 1 , False, 250 , 250, 1 , 0 , 0 , 0)
FX2Form = lj.RelativeObject('FX2', True, 255, [], Layer[2]['color'], 255, 0, 0, 2 , False, 250 , 250, 1 , 0 , 0 , 0)

#
# OSC
#

oscserver = OSCServer( (gstt.myIP, OSCinPort) )
oscserver.timeout = 0
#oscrun = True

# this method of reporting timeouts only works by convention
# that before calling handle_request() field .timed_out is
# set to False
def handle_timeout(self):
    self.timed_out = True

# funny python's way to add a method to an instance of a class
import types
oscserver.handle_timeout = types.MethodType(handle_timeout, oscserver)

# /maxwell/ljscene
def OSCljscene(path, tags, args, source):

    print("maxwell OSC : got /maxwell/ljscene with value", args[0])
    lj.WebStatus("maxwell to virtual "+ str(args[0]))
    ljscene = args[0]
    lj.ljscene(ljscene)

# default handler
def OSChandler(path, tags, args, source):

    oscaddress = ''.join(path.split("/"))
    print("maxwell default OSC Handler from Client :" + str(source[0]),)
    print("OSC address", path)
    print('Incoming OSC with path', path[8:])
    if len(args) > 0:
        print("with args", args)

    # /maxwell/fx/layer FXname
    if path.find('/maxwell/fx') == 0:
        layer = int(path[11:12])
        fx = args[0]
        FXs[layer] = "anim."+fx
        print("maxwell OSC Got new OSC FX generator for layer", layer,":", FXs[layer])

    # /maxwell/color/layer colorname
    if path.find('/maxwell/color') == 0:

        if args[1] =='1':
            layer = int(path[14:15])
            color = args[0]
            print("color was",Layer[layer]["color"] )
            Layer[layer]["color"] = eval(color)
            print("maxwell OSC :", color ,"for layer", layer)

    # /maxwell/x/layer coord
    if path.find('/maxwell/x') == 0:
        layer = int(path[10:11])
        value = float(args[0])
        print("xdefault layer", layer, "value", value)
        LayerX[layer]['coord'] = value * LayerX[layer]['transamt']
        print("maxwell default OSC Got new X coord for layer", layer,":", LayerX[layer]['coord'])

    # /maxwell/y/layer coord
    if path.find('/maxwell/y') == 0:
        layer = int(path[10:11])
        value = float(args[0])
        print("ydefault layer", layer, "value", value)
        LayerY[layer]['coord'] = value * LayerY[layer]['transamt']
        print("maxwell default OSC Got new Y coord for layer", layer,":", LayerY[layer]['coord'])

# /maxwell/color/layernumber color
def OSCcolor(path, tags, args, source):

    print("maxwell OSC : color got", path, args)

    if args[1] == '1':
        layer = int(path[14:15])
        color = args[0]

        Layer[layer]["color"] = eval(color)
        print("maxwell OSC :", color ,"for layer", layer)

# /maxwell/intensity layernumber intensity
def OSCintensity(path, tags, args, source):

    print("maxwell OSC : intensity got",path, args)
    layer = int(args[0])
    i = int(args[1])

    intensity[layer] = i

# /maxwell/rotspeed layernumber axe speed
def OSCrotspeed(path, tags, args, source):

    print("maxwell OSC : rotspeed got", path, args)
    layer = int(args[0])
    axe = args[1]
    speed = int(args[2])

    if axe =="X":
        LayerX[layer]['rotspeed'] =  ccs[layer][100] = speed
    if axe =="Y":
        LayerY[layer]['rotspeed'] =  ccs[layer][104] = speed
    if axe =="Z":
        LayerZ[layer]['rotspeed'] =  ccs[layer][108] = speed

# /maxwell/transamt layernumber axe maxposition
def OSCtransamt(path, tags, args, source):

    print("maxwell OSC : transamt got", path, args)
    layer = int(args[0])
    axe = args[1]
    maxpos = int(args[2])

    if axe =="X":
        LayerX[layer]['transamt'] = ccs[layer][114] = maxpos
    if axe =="Y":
        LayerY[layer]['transamt'] = ccs[layer][118] = maxpos
    if axe =="Z":
        LayerZ[layer]['transamt'] = ccs[layer][122] = maxpos

# /maxwell/transpeed layernumber axe transpeed
def OSCtranspeed(path, tags, args, source):

    print("maxwell OSC : transspeed got", path, args)
    layer = int(args[0])
    axe = args[1]
    speed = int(args[2])

    if axe =="X":
        LayerX[layer]['transpeed'] = ccs[layer][112] = speed
    if axe =="Y":
        LayerY[layer]['transpeed'] = ccs[layer][116] =  speed
    if axe =="Z":
        LayerZ[layer]['transpeed'] = ccs[layer][120] =  speed

# /maxwell/part partname
def OSCpart(path, tags, args, source):

    print("maxwell part got", path, args)
    gstt.maxwellpart = args[0]

# /maxwell/bpm set current bpm
def OSCbpm(path, tags, args, source):

    pass
    #gstt.currentbpm = int(args[0])
    #print("maxwell OSC New BPM :", int(args[0]))

#/maxwell/clock
def OSClock(path, tags, args, source):

    pass
    #print("maxwell OSC Got MIDI clock")

#/maxwell/mixer/value layernumber value
def OSCmixervalue(path, tags, args, source):

    print("maxwell OSC : got Mixer Value", path, args)
    layer = int(args[0])
    value = int(args[1])
    Layer[layer]['mixer'] = value
    ccs[layer][90] = value

# /maxwell/start
def OSCstart(path, tags, args, source):

    print("maxwell OSC Got MIDI start")
    for l in range(3):
        Layer[l]['run'] = True

# /maxwell/stop layer
def OSCstop(path, tags, args, source):

    print("maxwell OSC Got MIDI stop for layer", int(args[0]))
    Layer[int(args[0])]['run'] = False
    #for l in range(3):
    #    Layer[l]['run'] = not Layer[l]['run']

# 33 (B0) ScanH / 35 (B0) ScanV / 24 (C0) Wave / 26 (D0) Circle
#fxs = ["anim.ScanH", "anim.ScanV", "anim.Wave", "anim.Circle"]
# /maxwell/noteon note velocity
def OSCnoteon(path, tags, args, source):

    #print("maxwell OSC Got MIDI noteon")
    l = int(args[0])
    note = int(args[1])
    velocity = int(args[2])

    # A0
    if note == 33:
        FXs[l] = beatstepfxs[0]
     # B0
    if note == 35:
        FXs[l] = beatstepfxs[1]
    # C0
    if note == 24:
        FXs[l] = beatstepfxs[2]
    # D0
    if note == 26:
        FXs[l] = beatstepfxs[3]

    print ("maxwell OSC Got new MIDI FX generator for layer", l, ":", FXs[l])

# /maxwell/noteoff layer notenumber
def OSCnoteoff(path, tags, args, source):

    print("maxwell OSC Got MIDI noteoff")
    l = int(args[0])
    note = int(args[1])

# /maxwell/cc channel CC value
# /maxwell/cc layer steps stepmax
def OSCcc(path, tags, args, source):
    #global step, steps, stepmax, stepvals

    print("maxwell OSC Got CC")
    channel = int(args[0])
    ccnumber = int(args[1])
    ccvalue = int(args[2])

    Layer[channel]['step']    = 0
    Layer[channel]['steps']   = ccnumber * 5
    Layer[channel]['stepmax'] = ccvalue  * 5
    Layer[channel]['stepvals'] = anim.sbilinear(Layer[channel]['steps'], 0, Layer[channel]['stepmax'])

'''
0 type  LX
1 freq  LX
3 amp   LX
11 inv  LX

12 type LY
13 freq LY
15 amp  LY
23 inv  LY

24 type LZ
25 freq LZ
27 amp  LZ
35 inv  LZ

36 type RX
37 freq RX
39 amp  RX
47 inv  RX

48 type RY
49 freq RY
51 amp  RY
59 inv  RY

60 type RZ
61 freq RZ
63 amp  RZ
71 inv  RZ

100 rotspeedX[
104 rotspeedY
108 rotspeedZ

114 transamtX
118 transamtY
122 transamtZ

112 transpeedX
116 transpeedY
120 transpeedZ

Encoders :
LX freq amp phasemod transamt   RX freq amp phasemod rotdire
LY freq amp phasemod transamt   RL freq amp phasemod rotdire

'''

# /maxwell/rawcc layer encoder value Maxwell maxwell style
encoders = ['steps', 'stepmax','lineSize','radius']
def OSCrawcc(path, tags, args, source):
    #global step, steps, stepmax, stepvals

    layer = int(args[0])
    number = int(args[1])
    value = int(args[2])

    midix.SendUI('/beatstep/'+ "m" +str(layer)+ str(number+1) + '/value', [format(value, "03d")])
    ccs[layer][number] = value

    print(encoders[number],": value", value, "steps", Layer[layer]['steps'],"stepmax", Layer[layer]['stepmax'], "lineSize", Layer[layer]['lineSize'])
    #print("maxwell OSC Got rawCC for layer", layer, "encoder", encoders[number], "value", value)
    #print(value, Layer[layer]['stepmax'])
    if value * 2 < Layer[layer]['stepmax']:

        Layer[layer][encoders[number]] = value * 5
        Layer[layer]['stepvals'] = anim.sbilinear(Layer[layer]['steps'], 0, Layer[layer]['stepmax'])

'''
# /maxwell/rawcc layer encoder value maxwell style
encoders = ['steps', 'stepmax','lineSize','radius']
def OSCrawcc(path, tags, args, source):
    #global step, steps, stepmax, stepvals

    layer = int(args[0])
    number = int(args[1])
    value = int(args[2])

    midix.SendUI('/beatstep/'+ "m" +str(layer)+ str(number+1) + '/value', [format(value, "03d")])
    ccs[layer][number] = value

    print(encoders[number],": value", value, "steps", Layer[layer]['steps'],"stepmax", Layer[layer]['stepmax'], "lineSize", Layer[layer]['lineSize'])
    #print("maxwell OSC Got rawCC for layer", layer, "encoder", encoders[number], "value", value)
    #print(value, Layer[layer]['stepmax'])
    if value * 2 < Layer[layer]['stepmax']:

        Layer[layer][encoders[number]] = value * 5
        Layer[layer]['stepvals'] = anim.sbilinear(Layer[layer]['steps'], 0, Layer[layer]['stepmax'])
'''

# /maxwell/rotdirec layer axe direc
def OSCrotdirec(path, tags, args, source):

    layer = int(args[0])
    axe = args[1]
    direc = int(args[2])

    if axe =="X":
        LayerX[layer]['rotdirec'] = ccs[layer][102] = direc
    if axe =="Y":
        LayerY[layer]['rotdirec'] = ccs[layer][106] = direc
    if axe =="Z":
        LayerZ[layer]['rotdirec'] = ccs[layer][110] = direc

#
# /maxwell/xcoord layer value
def OSCXcoord(path, tags, args, source):

    Layer[layer]['run'] = False
    LayerX[int(args[0])]['coord'] = int(args[1])

    #layer = int(path[10:11])
    #value = float(args[0])
    #LayerX[layer]['coord'] = value * LayerX[layer]['lineSize']

    print("maxwell OSC Got new Xcoord for layer", layer,":", LayerX[layer]['coord'])

# /maxwell/ycoord layer value
def OSCYcoord(path, tags, args, source):

    Layer[layer]['run'] = False
    LayerX[int(args[0])]['coord'] = int(args[1])

    print("maxwell OSC Got new Ycoord for layer", layer,":", LayerY[layer]['coord'])

# [0-1] ?
# /maxwell/scale layer value
def OSCcale(path, tags, args, source):

    layer = int(args[0])
    value = int(args[1])

    Layer[int(args[0])]['scale'] = float(args[1])*200
    ccs[layer][98] = value * 200

# /maxwell/scandots       layernumber value
def OSCandots(path, tags, args, source):

    Layer[int(args[0])]['scandots'] = int(args[1])

    # ccs[layer][98] = value       2/11

# /maxwell/radius       layernumber radius
def OSCradius(path, tags, args, source):

    Layer[int(args[0])]['radius'] = int(args[1])

#                         L/R  X/Y/Z  sin:0/saw:33/squ:95/lin:127
# /maxwell/curvetype layer side axe type
def OSCurvetype(path, tags, args, source):

    layer = int(args[0])
    side = args[1]
    axe = args[2]
    value = args[3]

    if side == 'L':
        if axe =="X":
            CurveLX[layer]['type'] = ccs[layer][0] = value
        if axe =="Y":
            CurveLY[layer]['type'] = ccs[layer][12] = value
        if axe =="Z":
            CurveLZ[layer]['type'] = ccs[layer][24] = value

    else:
        if axe =="X":
            CurveRX[layer]['type'] = ccs[layer][36] = value
        if axe =="Y":
            CurveRY[layer]['type'] = ccs[layer][48] = value
        if axe =="Z":
            CurveRZ[layer]['type'] = ccs[layer][60] = value

# /maxwell/freq  layer side axe type
def OSCfreq(path, tags, args, source):

    layer = int(args[0])
    side = args[1]
    axe = args[2]
    value = args[3]

    if side == 'L':
        if axe =="X":
            CurveLX[layer]['freq'] = ccs[layer][1] = value
        if axe =="Y":
            CurveLY[layer]['freq'] = ccs[layer][13] = value
        if axe =="Z":
            CurveLZ[layer]['freq'] = ccs[layer][25] = value

    else:
        if axe =="X":
            CurveRX[layer]['freq'] = ccs[layer][37] = value
        if axe =="Y":
            CurveRY[layer]['freq'] = ccs[layer][49] = value
        if axe =="Z":
            CurveRZ[layer]['freq'] = ccs[layer][61] = value

# /maxwell/amp  layer side axe type
def OSCamp(path, tags, args, source):

    layer = int(args[0])
    side = args[1]
    axe = args[2]
    amp = args[3]

    if side == 'L':
        if axe =="X":
            CurveLX[layer]['amp'] = ccs[layer][3] = amp
        if axe =="Y":
            CurveLY[layer]['amp'] = ccs[layer][15] = amp
        if axe =="Z":
            CurveLZ[layer]['amp'] = ccs[layer][27] = amp

    else:
        if axe =="X":
            CurveRX[layer]['amp'] = ccs[layer][39] = amp
        if axe =="Y":
            CurveRY[layer]['amp'] = ccs[layer][51] = amp
        if axe =="Z":
            CurveRZ[layer]['amp'] = ccs[layer][63] = amp

#                         L/R  X/Y/Z  0/1
# /maxwell/inv layer side axe
def OSCurveinv(path, tags, args, source):

    layer = int(args[0])
    side = args[1]
    axe = args[2]
    value = args[3]

    if side == 'L':
        if axe =="X":
            CurveLX[layer]['inv'] = ccs[layer][11] = value * inv
        if axe =="Y":
            CurveLY[layer]['inv'] = ccs[layer][23] = value * inv
        if axe =="Z":
            CurveLZ[layer]['inv'] = ccs[layer][35] = value * inv

    else:
        if axe =="X":
            CurveRX[layer]['inv'] = ccs[layer][47] = value * inv
        if axe =="Y":
            CurveRY[layer]['inv'] = ccs[layer][59] = value * inv
        if axe =="Z":
            CurveRZ[layer]['inv'] = ccs[layer][71] = value * inv

'''

To code : what curve ?

#                                  CC : X 7 Y 21 Z 11
# /maxwell/cu/phaseoffset layernumber axe phaseoffset
def OSCphaseoffset((path, tags, args, source):

    layer = int(args[0])
    value = int(args[1])

    if axe =="X":
        LayerX[layer]['phaseoffset'] = ccs[layer][102] = direc

    if axe =="Y":
        Y[layer]['phaseoffset'] = ccs[layer][106] = direc

    if axe =="Z":
        LayerZ[layer]['phaseoffset'] = ccs[layer][110] = direc

Layer = [{'scandots': 100, 'radius': 150, 'color': red,
CurveL= [{'type': 64, 'freq': 1, 'phaseoffset': 0}] * 3
CurveR= [{'type': 64, 'freq': 1, 'phaseoffset': 0}] * 3

'''

# /maxwell/linesize layer value
def OSClinesize(path, tags, args, source):

    #Layer[layer]['run'] = False
    Layer[int(args[0])]['lineSize'] = float(args[1])*200
    #Layer[int(args[0])]['lineSize'] = float(args[1])

'''
/osc/left/X/curvetype is Artnet 0  MIDI Channel 1 CC 0
/osc/left/Y/curvetype is Artnet 12  MIDI Channel 1 CC 12
/osc/left/Z/curvetype is Artnet 24  MIDI Channel 1 CC 24

/osc/right/X/curvetype is Artnet 36  MIDI Channel 1 CC 36
/osc/right/Y/curvetype is Artnet 48  MIDI Channel 1 CC 48
/osc/right/Z/curvetype is Artnet 60  MIDI Channel 1 CC 60
"sin": 0, "saw": 33, "squ": 95, "lin": 127
'''

#
# OSC Audio
#

# /maxwell/audioR value
def OSCaudioR(path, tags, args, source):
    global audioR

    audioR = abs(float(args[0])* audiosize)
    #print("maxwell OSC Got audioR value", audioR )

# /maxwell/audioL value
def OSCaudioL(path, tags, args, source):
    global audioL

    audioL = abs(float(args[0]) * audiosize)
    #print("maxwell OSC Got audioR value", audioL )

# OSC FX selection

# /maxwell/fx/layer FXname
def OSCfx(path, tags, args, source):

    layer = int(path[11:12])
    fx = args[0]
    FXs[layer] = "anim."+fx
    print("maxwell OSC Got new WS FX generator for layer", layer,":", FXs[layer])

    '''
    layer = int(args[0])
    fx = args[1]
    FXs[layer] = "anim."+fx
    print("maxwell OSC Got new WS FX generator for layer", layer,":", FXs[layer])
    '''

#
# OSC Beatstep
#

beatstepfxs = ["anim.ScanH", "anim.ScanV", "anim.Wave", "anim.Circle"]
def beatstepUI():

    midix.SendUI('/beatstep', [1])
    midix.SendUI('/beatstep/on', [1])
    midix.SendUI('/status', ["maxwell"])
    if linked:
        midix.SendUI('/bpm', alink.bpm)

    for l in range(4):

        # First encoder line
        midix.SendUI('/beatstep/'+ "m1" + str(l+1) + '/line1', '')
        midix.SendUI('/beatstep/'+ "m1" + str(l+1) + '/line2', encoders[l])
        midix.SendUI('/beatstep/'+ "m1" + str(l+1) + '/value', [format(0, "03d")])
        midix.SendUI('/beatstep/'+ "m1" + str(4+l+1) + '/line1', '')
        midix.SendUI('/beatstep/'+ "m1" + str(4+l+1) + '/line2', encoders[l])
        midix.SendUI('/beatstep/'+ "m1" + str(4+l+1) + '/value', [format(0, "03d")])

        # First pad line
        fxname = beatstepfxs[l].split('.')
        print(fxname)
        midix.SendUI('/beatstep/'+ "m3" + str(l+1) + '/line1', fxname[0])
        midix.SendUI('/beatstep/'+ "m3" + str(l+1) + '/line2', fxname[1])
        midix.SendUI('/beatstep/'+ "m3" + str(4+l+1) + '/line1', fxname[0])
        midix.SendUI('/beatstep/'+ "m3" + str(4+l+1) + '/line2', fxname[1])

#
# Color functions
#

def hex2rgb(hexcode):
    return tuple(map(ord,hexcode[1:].decode('hex')))

def rgb2hex(rgb):
    return int('0x%02x%02x%02x' % tuple(rgb),0)

#
# Compute animations speed
#

def animSpeeds():

    print("Compute animations speed...")

    for l in range(3):
        Layer[l]['stepvals'] = anim.sbilinear(Layer[l]['steps'], 0, Layer[l]['stepmax'])
        #print(Layer[l]['stepvals'])

#
# ALl FXs points generation
#

def AllFX():
    global step, shapestep

    for l in range(3):

        if AllFXDisplay[l]: #and 0 <= x0 < screen_size[0] - 2 and 0 <= y0 < screen_size[1] - 2:

            LAY = Layer[l]
            #print(LAY)

            dots = []
            dotsL = anim.Maxwell(LAY, CurveLX[l], CurveLY[l], CurveLZ[l], LayerX[l], LayerY[l], LayerZ[l])
            dotsR = anim.Maxwell(LAY, CurveRX[l], CurveRY[l], CurveRZ[l], LayerX[l], LayerY[l], LayerZ[l])

            for dot in range(LAY['scandots']):
                dotX = (dotsL[dot][0]*(100-LAY['mixer'])/100) + (dotsR[dot][0]*LAY['mixer']/100)                #+ transX.values[point]
                dotY = (dotsL[dot][1]*(100-LAY['mixer'])/100) + (dotsR[dot][1]*LAY['mixer']/100)   #+ transY.values[point]
                dotZ = (dotsL[dot][2]*(100-LAY['mixer'])/100) + (dotsR[dot][2]*LAY['mixer']/100)   #+ transZ.values[point]
                dots.append((dotX, dotY, dotZ))

            lj.rPolyLineOneColor(dots, c = LAY['color'], layer = l, closed = FX0Form.closed, xpos = LayerX[l]['transamt'] + LAY['stepvals'][LAY['step']] - (LAY['lineSize']/2), ypos = LayerY[l]['transamt'], resize = LAY['scale'] * audioR, rotx = LayerX[l]['rotdirec'], roty = LayerY[l]['rotdirec'], rotz = LayerZ[l]['rotdirec'])

            #lj.rPolyLineOneColor(dots, c = LAY['color'], layer = l, closed = FX0Form.closed, xpos = FX0Form.xpos + LAY['stepvals'][LAY['step']] - (LAY['lineSize']/2), ypos = FX0Form.ypos, resize = LAY['scale'] * audioR, rotx = X[l]['rotdirec'], roty = Y[l]['rotdirec'], rotz = Z[l]['rotdirec'])
            # OSC cc Audio reactive audioR -> size

            if LAY['run']:
                if LAY['step'] < LAY['steps']-1:
                    LAY['step'] +=1
                else:
                    LAY['step'] = 0
                # print("stepmax", LAY['stepmax'], 'step', LAY['step'])

            if shapestep < shapesteps-1:
                shapestep +=1
            else:
                shapestep =0

        '''
        # morphing
            gstt.patchnumber[layer] = number
            for ccnumber in range(len(maxwell['ccs'])):

                gstt.morphCCinc[ccnumber] = (getPatchValue(gstt.patchnumber[layer], ccnumber) - gstt.ccs[layer][ccnumber]) / gstt.morphsteps
                gstt.morphCC[ccnumber] = gstt.ccs[layer][ccnumber]
                print("CC", ccnumber, "was", gstt.ccs[layer][ccnumber],"will be", getPatchValue(gstt.patchnumber[layer], ccnumber), "so inced is", gstt.morphCCinc[ccnumber])

            gstt.morphing = 0
        '''

#X0 = anim.COORDobject("X0",0, 0, 0, 0)
#L0 = LAYERobject("0", "saw", 100, 150, red, True, 0, 500, 200, [], 300, 255)

# Update Pose webUI
def UpdatemaxwellUI():

    lj.WebStatus("Maxwell say sthng")

print('Loading Maxwell...')
lj.WebStatus("Loading Maxwell...")

print("Starting OSC server at", gstt.myIP, "port", OSCinPort, "...")
oscserver.addMsgHandler("/maxwell/ljscene", OSCljscene)

oscserver.addMsgHandler("/maxwell/noteon", OSCnoteon)
#oscserver.addMsgHandler("/maxwell/fx", OSCfx)

oscserver.addMsgHandler("/maxwell/noteoff", OSCnoteoff)
#oscserver.addMsgHandler("/maxwell/color", OSCcolor)

oscserver.addMsgHandler("/maxwell/bpm",  OSCbpm)
oscserver.addMsgHandler("/maxwell/clock", OSClock)
oscserver.addMsgHandler("/maxwell/start", OSCstart)
oscserver.addMsgHandler("/maxwell/stop", OSCstop)
oscserver.addMsgHandler("/maxwell/part", OSCpart)

oscserver.addMsgHandler("/maxwell/rawcc", OSCrawcc)
oscserver.addMsgHandler("/maxwell/cc", OSCcc)

oscserver.addMsgHandler("/maxwell/audioR", OSCaudioR)
oscserver.addMsgHandler("/maxwell/autioL", OSCaudioL)

oscserver.addMsgHandler("/maxwell/xcoord", OSCXcoord)
oscserver.addMsgHandler("/maxwell/ycoord", OSCYcoord)
oscserver.addMsgHandler("/maxwell/linesize", OSClinesize)
oscserver.addMsgHandler("/maxwell/scale", OSCcale)
oscserver.addMsgHandler("/maxwell/scandots", OSCandots)

oscserver.addMsgHandler("/maxwell/intensity", OSCintensity)
oscserver.addMsgHandler("/maxwell/rotspeed", OSCrotspeed)
oscserver.addMsgHandler("/maxwell/transamt", OSCtransamt)
oscserver.addMsgHandler("/maxwell/rotdirec", OSCrotdirec)

# Add OSC generic layerugins commands : 'default", /ping, /quit, /pluginame/obj, /pluginame/var, /pluginame/adddest, /pluginame/deldest
lj.addOSCdefaults(oscserver)
oscserver.addMsgHandler( "default", OSChandler )
#anim.prepareSTARFIELD()

beatstepUI()

#beatstep.UpdatePatch(beatstep.patchnumber)

print("Updating maxwell UI...")
UpdatemaxwellUI()

midix.check()

animSpeeds()

audioR = 1
audioL = 1
audiosize = 1.1

'''
steps = 500
step = 0
stepmax = 200
stepvals = anim.sbilinear(steps, 0, stepmax)
'''

shapesteps = 50
shapestep = 0
shapemax = 2
shapevals = anim.ssquare(shapesteps, 1, 0, shapemax)

def Run():

    try:
        while lj.oscrun:

            # If you want an idea
            # t0 = time.time()
            lj.OSCframe()
            if linked:
                alink.BeatEvent()

            AllFX()

            time.sleep(0.002)

            #t1 = time.time()
            # looptime = t1 - t0
            # 25 frames/sec -> 1 frame is 0.04 sec long
            # if looptime is 0.01 sec
            # 0.04/0.01 = 4 loops with the same anim
            # so speedanim is 1 / 4 = 0.25
            # speedanim = 1 / (0.04 / looptime)

            lj.DrawDests()
            #print("Took %f" % (t1 - t0, ))

    #except KeyboardInterrupt:
    #    pass

    except Exception:
        traceback.print_exc()

    # Gently stop on CTRL C

    finally:

        lj.WebStatus("maxwell Exit")
        print("Stopping OSC...")
        lj.OSCstop()

    print ("maxwell Stopped.")

Run()

max_stars_repo_name: tmpbci/LJ

max_issues_repo_name: tmpbci/LJ

max_forks_repo_name: tmpbci/LJ


text:
from collections import namedtuple
from itertools import product

import numpy as np
import pandas as pd
import sklearn.model_selection as sklearn
import torch

class Utils:
    @staticmethod
    def convert_df_to_np_arr(data):
        return data.to_numpy()

    @staticmethod
    def convert_to_col_vector(np_arr):
        return np_arr.reshape(np_arr.shape[0], 1)

    @staticmethod
    def test_train_split(np_train_X, np_train_T, np_train_yf, np_train_ycf,
                         np_mu0, np_mu1, split_size=0.8):
        return sklearn.train_test_split(np_train_X, np_train_T, np_train_yf, np_train_ycf,
                                        np_mu0, np_mu1,
                                        train_size=split_size)

    @staticmethod
    def test_train_split_custom(np_train_X, np_train_T, np_train_yf, np_train_ycf, iter_id,
                                split_size=0.8):
        return sklearn.train_test_split(np_train_X, np_train_T, np_train_yf, np_train_ycf,
                                        train_size=split_size)

    @staticmethod
    def convert_to_tensor_DR_net(X, T, Y_f, Y_cf, pi, mu):
        tensor_x = torch.stack([torch.Tensor(i) for i in X])
        tensor_T = torch.from_numpy(T)
        tensor_y_f = torch.from_numpy(Y_f)
        tensor_y_cf = torch.from_numpy(Y_cf)
        tensor_pi = torch.from_numpy(pi)
        tensor_mu = torch.from_numpy(mu)

        processed_dataset = torch.utils.data.TensorDataset(tensor_x,
                                                           tensor_T,
                                                           tensor_y_f,
                                                           tensor_y_cf,
                                                           tensor_pi,
                                                           tensor_mu)
        return processed_dataset

    @staticmethod
    def convert_to_tensor(X, T, Y_f, Y_cf, np_train_mu0, np_train_mu1):
        tensor_x = torch.stack([torch.Tensor(i) for i in X])
        tensor_T = torch.from_numpy(T)
        tensor_y_f = torch.from_numpy(Y_f)
        tensor_y_cf = torch.from_numpy(Y_cf)
        tensor_mu0 = torch.from_numpy(np_train_mu0)
        tensor_mu1 = torch.from_numpy(np_train_mu1)

        processed_dataset = torch.utils.data.TensorDataset(tensor_x,
                                                           tensor_T,
                                                           tensor_y_f,
                                                           tensor_y_cf,
                                                           tensor_mu0,
                                                           tensor_mu1)
        return processed_dataset

    @staticmethod
    def convert_to_tensor_pi_net(X, T):
        tensor_x = torch.stack([torch.Tensor(i) for i in X])
        tensor_T = torch.from_numpy(T)

        processed_dataset = torch.utils.data.TensorDataset(tensor_x,
                                                           tensor_T)
        return processed_dataset

    @staticmethod
    def convert_to_tensor_mu_net(X, T, yf):
        tensor_x = torch.stack([torch.Tensor(i) for i in X])
        tensor_T = torch.from_numpy(T)
        tensor_y_f = torch.from_numpy(yf)

        processed_dataset = torch.utils.data.TensorDataset(tensor_x,
                                                           tensor_T,
                                                           tensor_y_f)
        return processed_dataset

    @staticmethod
    def concat_np_arr(X, Y, axis=1):
        return np.concatenate((X, Y), axis)

    @staticmethod
    def get_device():
        return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    @staticmethod
    def get_num_correct(preds, labels):
        return preds.argmax(dim=1).eq(labels).sum().item()

    @staticmethod
    def get_runs(params):
        """
        Gets the run parameters using cartesian products of the different parameters.
        :param params: different parameters like batch size, learning rates
        :return: iterable run set
        """
        Run = namedtuple("Run", params.keys())

        runs = []
        for v in product(*params.values()):
            runs.append(Run(*v))

        return runs

    @staticmethod
    def write_to_csv(file_name, list_to_write):
        pd.DataFrame.from_dict(
            list_to_write,
            orient='columns'
        ).to_csv(file_name)

    @staticmethod
    def vae_loss(mu, log_var):
        return -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())

    @staticmethod
    def kl_divergence(mu1, mu2, sigma_1, sigma_2):
        sigma_diag_1 = np.eye(sigma_1.shape[0]) * sigma_1
        sigma_diag_2 = np.eye(sigma_2.shape[0]) * sigma_2

        sigma_diag_2_inv = np.linalg.inv(sigma_diag_2)

        kl = 0.5 * (np.log(np.linalg.det(sigma_diag_2) / np.linalg.det(sigma_diag_2))
                    - mu1.shape[0] + np.trace(np.matmul(sigma_diag_2_inv, sigma_diag_1))
                    + np.matmul(np.matmul(np.transpose(mu2 - mu1), sigma_diag_2_inv), (mu2 - mu1))
                    )

        return kl

class NormalNLLLoss:
    """
    Calculate the negative log likelihood
    of normal distribution.
    This needs to be minimised.
    Treating Q(cj | x) as a factored Gaussian.
    """

    def __call__(self, noise_z, mu, var):
        logli = -0.5 * (var.mul(2 * np.pi) + 1e-6).log() - (noise_z - mu).pow(2).div(var.mul(2.0) + 1e-6)
        nll = -(logli.sum(1).mean())

        return nll

class EarlyStopping_DCN:
    """Early stops the training if validation loss doesn't improve after a given patience."""

    def __init__(self, patience=7, verbose=False, delta=0,
                 dr_net_shared_path="DR_WO_Info_CFR/IHDP/Models/dr_net_phi.pth",
                 dr_net_y1_path="DR_WO_Info_CFR/Models/IHDP/Models/dr_net_y1.pth",
                 dr_net_y0_path="DR_WO_Info_CFR/Models/IHDP/Models/dr_net_y0.pth",
                 pi_net_path="DR_WO_Info_CFR/Models/IHDP/Models/pi_net.pth",
                 mu_net_path="DR_WO_Info_CFR/Models/IHDP/Models/mu_net.pth",
                 trace_func=print):
        """
        Args:
            patience (int): How long to wait after last time validation loss improved.
                            Default: 7
            verbose (bool): If True, prints a message for each validation loss improvement.
                            Default: False
            delta (float): Minimum change in the monitored quantity to qualify as an improvement.
                            Default: 0
            path (str): Path for the checkpoint to be saved to.
                            Default: 'checkpoint.pt'
            trace_func (function): trace print function.
                            Default: print
        """
        self.patience = patience
        self.verbose = verbose
        self.counter = 0
        self.best_score = None
        self.early_stop = False
        self.val_loss_min = np.Inf
        self.delta = delta
        self.dr_net_shared_path = dr_net_shared_path
        self.dr_net_y1_path = dr_net_y1_path
        self.dr_net_y0_path = dr_net_y0_path
        self.pi_net_path = pi_net_path
        self.mu_net_path = mu_net_path
        self.trace_func = trace_func

    def __call__(self, val_loss, dr_net_shared, dr_net_y1_model, dr_net_y0_model,
                 pi_net_model, mu_net_model):

        score = -val_loss

        if self.best_score is None:
            self.best_score = score
            self.save_checkpoint(val_loss, dr_net_shared, dr_net_y1_model, dr_net_y0_model,
                                 pi_net_model, mu_net_model)
        elif score < self.best_score + self.delta:
            self.counter += 1
            self.trace_func(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            if self.counter >= self.patience:
                self.early_stop = True
        else:
            self.best_score = score
            self.save_checkpoint(val_loss, dr_net_shared, dr_net_y1_model, dr_net_y0_model,
                                 pi_net_model, mu_net_model)
            self.counter = 0

    def save_checkpoint(self, val_loss, dr_net_shared, dr_net_y1_model, dr_net_y0_model,
                        pi_net_model, mu_net_model):
        if self.verbose:
            self.trace_func(
                f'Validation loss decreased ({self.val_loss_min} --> {val_loss}).  Saving model ...')
        torch.save(dr_net_shared.state_dict(), self.dr_net_shared_path)
        torch.save(dr_net_y1_model.state_dict(), self.dr_net_y1_path)
        torch.save(dr_net_y0_model.state_dict(), self.dr_net_y0_path)
        torch.save(pi_net_model.state_dict(), self.pi_net_path)
        torch.save(mu_net_model.state_dict(), self.mu_net_path)
        self.val_loss_min = val_loss