from artiq.experiment import *
from time import sleep, time
import numpy as np
from scipy.stats import poisson

from artiq.experiment import *


class Histograms(EnvExperiment):
    """Histograms demo"""
    def build(self):
        
        self.setattr_argument("nbins", NumberValue(100, ndecimals=0, step=10))
        self.setattr_argument("npoints", NumberValue(20, ndecimals=0, step=5))
        self.setattr_argument("histo_delay", NumberValue(0.6, ndecimals=2, step=0.01))
        self.setattr_device("ccb")

    def run(self):

        # Custom histogram plot creator (needs a reasonable --update-delay)
        self.ccb.issue("create_applet", "ticks_histogram",
                        "${artiq_applet}plot_hist "
                        f"histo --x hd_bins --title {tit} "
                        f"--update-delay {self.histo_delay}",
                        group="ExampleHistogram")

        bin_boundaries = np.linspace(-10, 30, self.nbins + 1)

        self.set_dataset("hd_bins", bin_boundaries,
                         broadcast=True, archive=False)

        self.set_dataset("histo", np.empty(self.nbins), broadcast=True, archive=False)

        """
        xs = np.empty(self.npoints)
        xs.fill(np.nan)
        self.set_dataset("hd_xs", xs,
                         broadcast=True, archive=False)

        self.set_dataset("hd_counts", np.empty((self.npoints, self.nbins)), 
                         broadcast=True, archive=False)
        """

        for i in range(self.npoints):
            tit = "hola"
            t1 = time()
            histogram, _ = np.histogram(np.random.normal(i, size=1000),
                                        bin_boundaries)
            
            for j in range(self.nbins):
                self.mutate_dataset("histo", j, histogram[j])

            #self.mutate_dataset("hd_counts", i, histogram)
            #self.mutate_dataset("hd_xs", i, i % 8)
            t2 = time()
            print(t2-t1)
            sleep(0.5)


sleep(0.3)
