Пример #1
0
    def knn_validate(data, kernel, metric, k_neighbors, show_plot):
        plot = Plot()
        matrix_full = [[0, 0], [0, 0]]
        y_predict_arr = []
        for i in range(len(data)):
            data.updateTrainTest(i)
            trainDots, trainClass = data.getDotsByMode('train', False)
            testDots, testClass = data.getDotsByMode('test', False)

            knn = KNN(kernel=kernel, metric=metric, neighbors=k_neighbors)
            knn.fit(trainDots, trainClass)
            y_predict, distance = knn.predict(testDots)
            y_predict_arr.append(y_predict[0])

            if show_plot:
                tDots = np.array(trainDots)
                tCls = np.array(trainClass)
                plot.knn(tDots[tCls == 1.0], tDots[tCls == -1.0], distance, testDots[0], y_predict[0])

            matrix = get_metrics(y_predict, testClass)
            matrix_full[0][0] += matrix[0][0]
            matrix_full[0][1] += matrix[0][1]
            matrix_full[1][0] += matrix[1][0]
            matrix_full[1][1] += matrix[1][1]

        return y_predict_arr, get_f_measure(matrix_full), matrix_full
Пример #2
0
def fillTab(frameNumber, tabName, labelNumber, portNumber):
    global Graph1, Graph2

    tkToggleScreenButton = tk.Button(
        frameNumber,
        text='Toggle Screen',
        command=lambda: toggleScreen(tabName, portNumber))
    tkToggleScreenButton.grid(column=0, row=1, sticky='W')

    tkToggleModeButton = tk.Button(
        frameNumber,
        text='Toggle mode',
        command=lambda: toggleMode(tabName, labelNumber))
    tkToggleModeButton.grid(column=0, row=2, sticky='W')

    tkGetDataButton = tk.Button(frameNumber, text='Get data', command=getData)
    tkGetDataButton.grid(column=0, row=1, sticky='E')

    temperatureLabel = tk.Label(frameNumber, text='Temperature: ')
    temperatureLabel.grid(column=0, row=5, sticky='W')

    brightnessLabel = tk.Label(frameNumber, text='Brightness: ')
    brightnessLabel.grid(column=1, row=5, sticky='W')

    Graph1 = Plot(frameNumber, 0, 6)
    Graph2 = Plot(frameNumber, 1, 6)

    labelNumber = tk.Label(frameNumber,
                           text='Mode: %s' % (deviceInfo[tabName]['mode']))
    labelNumber.grid(column=0, row=3, sticky='W')

    return Graph1, Graph2
Пример #3
0
    def svm_validate(data, kernel, svm_C, show_plot):
        plot = Plot()
        matrix_full = [[0, 0], [0, 0]]
        y_predict_arr = []

        for i in range(len(data)):
            data.updateTrainTest(i)
            trainDots, trainClass = data.getDotsByMode('train', True)
            testDots, testClass = data.getDotsByMode('test', True)

            clf = SVM(kernel=kernel, C=svm_C)
            clf.fit(trainDots, trainClass)
            y_predict = clf.predict(testDots)
            y_predict_arr.append(y_predict[0])

            if show_plot:
                plot.smv(trainDots[trainClass == 1], trainDots[trainClass == -1], clf, testDots[0], y_predict[0])

            matrix = get_metrics(y_predict, testClass)
            matrix_full[0][0] += matrix[0][0]
            matrix_full[0][1] += matrix[0][1]
            matrix_full[1][0] += matrix[1][0]
            matrix_full[1][1] += matrix[1][1]

        return y_predict_arr, get_f_measure(matrix_full), matrix_full
Пример #4
0
    def plot_summary(self):
        
        # Generate summary plot from chosen lattice and Hamiltonian
        
        K = -(4 * np.pi) / (3 * np.sqrt(3))

        if self.Haldane.value() != 0 or self.AntiHaldane.value() != 0:
            Lat = lattice('Sheet', 'Haldane') # Get correct lattice
        else:

            Lat = lattice('Sheet', 'Monolayer')


        if self.AntiHaldane.value() != 0:
            H = Hamiltonian(Lat, self.Hoppingt2.value(), 0, 0, self.AntiHaldane.value())
            H.add_antiHaldane() # If selected, add complex hopping
        else:
            H = Hamiltonian(Lat, self.Hoppingt2.value(), 0, 0, self.Haldane.value()) # If selected, add complex hopping
        if self.Magneticfield2.value() != 0: # Add magnetic field
            H.add_magnetic_field(self.Magneticfield2.value(), 'Perpendicular')
        if self.OnsiteV2.value() != 0: # Add sublattice imbalance
            H.add_lattice_imbalance(self.OnsiteV2.value())
        
        # Generate summary plot
        P = Plot(H)
        P.summary(self.Nk.value(), K, 0, self.xIndex.value(), self.yIndex.value(), self.dxIndex.value(),
                  self.dyIndex.value())
        plt.show()
Пример #5
0
def main(args):

    # Get current observer location and antenna pointing direction
    if args.use_config:
        config = read_config()
        lat, lon = config['latitude'], config['longitude']
        alt, az = config['altitude'], config['azimuth']
        if "none" in (lat, lon, alt, az):
            print('Please check your config file or use command line arguments.')
            quit()
    else:
        lat, lon = args.latitude, args.longitude
        alt, az = args.altitude, args.azimuth
    

    # Get current equatorial and galactic coordinates of antenna RA and Declination
    Coordinates_class = Coordinates(lat = lat, lon = lon, alt = alt, az = az)
    ra, dec = Coordinates_class.equatorial()
    gal_lat, gal_lon = Coordinates_class.galactic()

    # Receives and writes data
    Receiver_class = Receiver(frequency = args.frequency, sample_rate = args.sample_rate, ppm = args.ppm, resolution = args.resolution, num_FFT = args.num_FFT)
    freqs, data, SNR = Receiver_class.receive()

    # Plots data
    print('Plotting data...')
    name = f'ra={ra},dec={dec},SNR={SNR}'
    Plot_class = Plot()
    Plot_class.plot(freqs = freqs, data = data, name = name)
Пример #6
0
def main():
    x_data = np.linspace(-1000, 1000, 200)
    root = tkinter.Tk()
    plot = Plot(-500, 500, -500, 500, "g", root)
    plot.plot_data(x_data)

    root.mainloop()
Пример #7
0
def compareUpload(request):
    """
    Upload function of Compare mode
    """
    context_dict = {}
    if request.method == "POST":
        try:
            filename = request.FILES['file'].name
            axis = request.POST.get("axis")
            values = request.POST.get("values")

            # Upload the second file
            filename_second = request.FILES['files'].name
            axis_second = request.POST.get("axiss")
            values_second = request.POST.get("valuess")
            info = Plotinfo(filename, axis, values)
            info_second = Plotinfo(filename_second, axis_second, values_second)
            context_dict['show'] = 'yes'
            nu = float(values)
            nu_second = float(values_second)
            result = Plot(filename, axis, nu, figsize=(4.5, 3.8))
            result_second = Plot(filename_second, axis_second, nu_second, figsize=(4.5, 3.8))
            context_dict['info'] = info
            context_dict['info_second'] = info_second
            context_dict['graph1'] = result
            context_dict['graph2'] = result_second
            context_dict['vis_success'] = 'True'
            return render(request, 'compareMode.html', context=context_dict)

        except:
            context_dict['vis_success'] = 'False'
            context_dict['errorinfo'] = "You selected the wrong file or entered the wrong axis or missing an input"
            return render(request, 'compareMode.html', context=context_dict)
Пример #8
0
    def findChiParams(self):
        dataFileName = 'testData.txt'
        function = Function()
        chiLinear = ChiSquare(function.evalLinear, dataFileName)
        optimiser = Optimise()

        #m = params[0]
        #c = params[1]
        paramsGuess = [0., 1.]
        paramsAccuracy = [0.000000001, 0.000000001]
        paramsJump = [1., 1.]
        #evals minimum m and c for our ChiSquare
        params = optimiser.min(chiLinear.evalChiSquare, paramsGuess,
                               paramsJump, paramsAccuracy, [])

        minM = params[0]
        minC = params[1]
        minChi = chiLinear.evalChiSquare(params)

        #finding err of values in params by finding where the chiSquare
        #increases by 1 either side of the minimum
        mRootParamGuess = [minM + 1., minC]
        cRootParamGuess = [minM, minC + 1.]
        rootParamsJump = [0.0001, 0.001]
        rootParamsAccuracy = [0.000001, 0.000001]
        mErrPos = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, mRootParamGuess,
                rootParamsJump, rootParamsAccuracy, [1])[0] - minM)
        cErrPos = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, cRootParamGuess,
                rootParamsJump, rootParamsAccuracy, [0])[1] - minC)
        mErrNeg = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, [minM - mErrPos, minC],
                rootParamsJump, rootParamsAccuracy, [1])[0] - minM)
        cErrNeg = abs(
            optimiser.equalTo(
                (minChi + 1), chiLinear.evalChiSquare, [minM, minC - cErrPos],
                rootParamsJump, rootParamsAccuracy, [0])[1] - minC)

        mErrMean = (mErrPos + mErrNeg) / 2.
        cErrMean = (cErrPos + cErrNeg) / 2.

        print("")
        print("[m,c]:\t" + str(np.around(np.array(params), 6)) + "\n")
        print("mErr:\t+" + str(np.round(mErrPos, 6)) + "\t-" +
              str(np.round(mErrNeg, 6)))
        print("mean:\t" + str(np.round(mErrMean, 6)) + "\n")
        print("cErr:\t+" + str(np.round(cErrPos, 6)) + "\t-" +
              str(np.round(cErrNeg, 6)))
        print("Mean:\t" + str(np.round(cErrMean, 6)))
        print("")

        #self.plotChiAroundMin(chiLinear.evalChiSquare, params, [mErrPos, cErrPos], [mErrNeg, cErrNeg])
        plotter = Plot()
        plotter.plotChiAroundMin(chiLinear.evalChiSquare, params,
                                 [mErrPos, cErrPos], [mErrNeg, cErrNeg])
    def __init__(self,x,y,basic_path,nameFileEnd, startfillnumber, endfillnumber):
        Plot.__init__(self,x,y)

        loader=LoadDataFromFiles(basic_path, nameFileEnd, startfillnumber, endfillnumber)
        loader.load(basic_path+"Fillnumbers.txt","Condition")
        dataObject=loader.getData()

        self.datax=eval("dataObject.get"+x+"()")
        self.datay=eval("dataObject.get"+y+"()")
Пример #10
0
 def autoscale(self):
     """Autoscale now the Heroku App.
     
     This method gonna check the response time through Pingdom API, and adapt the number of dynos according to it.
     If the measured response time is below the response time low score defined in the HAConf object, the Heroku app will be scaled up.
     If the measured response time is over the response time high score defined in the HAConf object, the Heroku app will be scaled down.
     
     If the measured response time is between the response time low score and the response time high score :
     - If the tendency of the response times is strongly rising:  the Heroku app will be scaled up
     - If the tendency of the response times is strongly down:  the Heroku app will be scaled down
     """
     self._log("----> Start autoscale...")
     end = datetime.utcnow()
     end_time = int(time.mktime(end.timetuple()))
     begin = end - timedelta(minutes = self._conf.getPingdomCheckPeriod())
     begin_time =  int(time.mktime(begin.timetuple()))
     self._log("Pingdom period to request: Begin: {0}, End: {1}".format(begin.isoformat(), end.isoformat()))
     checks = self._pd_wrapper.getChecks(self._conf.getPingdomCheckId(), begin_time, end_time)
     
     rep_time_avg = getResponseTimeAvg(checks)
     self._log("Avg resp time: {0}".format(rep_time_avg))
     
     t = datetime.now()
     
     reg_coef = computeLinearRegressionModel(checks)
     self._log("Linear regression: y' = a * x + b with a = {0}, b = {1}".format(reg_coef[0], reg_coef[1]))
     
     if(rep_time_avg < self._conf.getResponseTimeLow()):
         if(reg_coef[0] < 0):
             self._removeDyno()
             settlement = "Revove dyno"
         else:
             self._log("===> Do nothing...")
             settlement = "Do nothing"
     elif(rep_time_avg >= self._conf.getResponseTimeLow() and 
          rep_time_avg < self._conf.getResponseTimeHigh()):
         
         if(reg_coef[0] > self._conf.getResponseTimeTrendHigh()):
             self._addDyno()
             settlement = "Add dyno"
         elif(reg_coef[0] < self._conf.getResponseTimeTrendLow()):
             self._removeDyno()
             settlement = "Revove dyno"
         else:
             self._log("===> Do nothing...")
             settlement = "Do nothing"
     else:
         if(reg_coef[0] > 0):
             self._addDyno()
             settlement = "Add dyno"
         else:
             self._log("===> Do nothing...")
             settlement = "Do nothing"
     
     if(self._conf.isPlotting()):
         Plot.plot(checks, rep_time_avg, reg_coef, self._conf.getResponseTimeLow(), self._conf.getResponseTimeHigh(), settlement, self._conf.getGraphsFolder() + '/' + t.strftime("%d-%m-%Y_%H-%M-%S") + "_out.pdf", "pdf")
Пример #11
0
    def setup(self):
        self.memory_map = self.mission.get_memory_map()

        if self.settings.get("plot"):
            # Setup memory map plot
            from Plot import Plot
            self.plot = Plot(self.environment, self.memory_map)

        if self.rf_sensor is not None:
            self.rf_sensor.activate()
Пример #12
0
def main(args):

    config = read_config()

    # Get y-axis limits from config
    low_y, high_y = config['low_y'], config['high_y']

    # Get current observer location and antenna pointing direction
    if args.use_config:
        lat, lon = config['latitude'], config['longitude']
        alt, az = config['altitude'], config['azimuth']
        if "none" in (lat, lon, alt, az):
            print('Please check your config file or use command line arguments.')
            quit()
    else:
        lat, lon = args.latitude, args.longitude
        alt, az = args.altitude, args.azimuth

    # Checks if 360 is divisable with the degree interval and calculates number of collections
    num_data = 360/args.interval if args.interval != 0 else 0
    second_interval = 24*60**2/num_data if num_data > 0 else None

    if float(num_data).is_integer():
        for i in range(int(num_data)+1):

            current_time = datetime.utcnow()
            if num_data != 0:
                end_time = current_time + timedelta(seconds = second_interval)

            # Get current equatorial and galactic coordinates of antenna RA and Declination
            Coordinates_class = Coordinates(lat = lat, lon = lon, alt = alt, az = az)
            ra, dec = Coordinates_class.equatorial()
            gal_lat, gal_lon = Coordinates_class.galactic()
            galactic_velocity = Coordinates_class.galactic_velocity(gal_lat, gal_lon)

            # Receives and writes data
            Receiver_class = Receiver(sample_rate = args.sample_rate, ppm = args.ppm, resolution = args.resolution, num_FFT = args.num_FFT, num_med = args.num_med)
            freqs, data = Receiver_class.receive()

            # Plots data
            print('Plotting data...')
            Plot_class = Plot(freqs = freqs, data = data, galactic_velocity = galactic_velocity)
            Plot_class.plot(ra = ra, dec = dec, low_y = low_y, high_y = high_y)
            
            if num_data != 0:
                time_remaining = end_time - datetime.utcnow()
                print(f'Waiting for next data collection in {time_remaining.total_seconds()} seconds')
                time.sleep(time_remaining.total_seconds())
                clear_console()

    else:
        print('360 must be divisable with the degree interval, eg. 360%\interval=0')
        quit()
Пример #13
0
def createPredictionPlot():

    if (request.method == 'POST'):
        data = request.get_json()
        predictDate = data['predictDate']
        payment = data['payment']

    plotCreator = Plot()

    graphJSON = plotCreator.createPredictionPlot(predictDate, payment)

    print(request.url)  #localhost:5000/electric/pattern
    return graphJSON
class MainManager(Aidlab.Aidlab):
    def __init__(self):
        super().__init__()
        self.plot = Plot()

    def did_connect(self, aidlab):
        print("Connected to: ", aidlab.address)

    def did_disconnect(self, aidlab):
        print("Disconnected from: ", aidlab.address)

    def did_receive_ecg(self, aidlab, timestamp, values):
        self.plot.add(values[0])
Пример #15
0
def createSchLinePlot():

    print('schLinePlot')
    if (request.method == 'POST'):
        data = request.get_json()
        predictDate = data['predictDate']

    plotCreator = Plot()

    graphJSON = plotCreator.createSchLinePlot(predictDate)

    print(request.url)  #localhost:5000/electric/pattern
    return graphJSON
Пример #16
0
    def upper_edge(self):
        
        # Calculate bandstructure and highlight edge states

        Lat = lattice('Ribbon', self.SelectEdge.currentText()+' '+self.SelectStack.currentText(), self.NUnit.value()) # Create lattice

        H = Hamiltonian(Lat, self.Hoppingt.value(), self.Hoppingtprime.value())# Create Hamiltonian
        if self.Magneticfield.value() != 0:# Add magnetic field
            H.add_magnetic_field(self.Magneticfield.value(), self.SelectBBil.currentText())
        if self.OnsiteV.value() != 0:# Add lattice imbalance
            H.add_lattice_imbalance(self.OnsiteV.value())
        P = Plot(H)
        P.upper_edge()
Пример #17
0
    def calc_bands(self):
        
        # Calculate bandstructure of finite system

        Lat = lattice('Ribbon', self.SelectEdge.currentText()+' '+self.SelectStack.currentText(), self.NUnit.value()) # Create lattice

        H = Hamiltonian(Lat, self.Hoppingt.value(), self.Hoppingtprime.value())# Create Hamiltonian
        if self.Magneticfield.value() != 0:# Add magnetic field
            H.add_magnetic_field(self.Magneticfield.value(), self.SelectBBil.currentText())
        if self.OnsiteV.value() != 0:# Add lattice imbalance
            H.add_lattice_imbalance(self.OnsiteV.value())
        P = Plot(H)
        P.show_rib()
Пример #18
0
def createLinePlot():

    if (request.method == 'POST'):
        data = request.get_json()
        startDate = data['startDate']
        endDate = data['endDate']
        period = int(data['period'])

    plotCreator = Plot()

    graphJSON = plotCreator.createLinePlot(startDate, endDate, 'abc', period)

    print(request.url)  #localhost:5000/electric/pattern
    return graphJSON
Пример #19
0
def train():
    """
    Trains the model using the agent and the game
    """
    # For Plots
    plot = Plot()
    plotScores = list()
    plotMeanScores = list()
    totalScore = 0
    meanScore = 0

    highestScore = 0
    agent = Agent()
    game = SnakeGame(ai=True)

    while True:
        # Get old/current state
        stateOld = agent.getState(game)

        # Get move based on current state
        finalAction = agent.getAction(stateOld)

        # Perform the move and get next state
        reward, done, score = game.playStep(finalAction)
        stateNew = agent.getState(game)

        # Train short memory
        agent.trainShortMemory(stateOld, finalAction, reward, stateNew, done)

        # Remember (to store in the memory)
        agent.remember(stateOld, finalAction, reward, stateNew, done)

        if done:
            # Train long memory
            game.reset()
            agent.games += 1
            agent.trainLongMemory()

            if score > highestScore:
                highestScore = score
                agent.model.save()

            print('Game', agent.games, 'Score', score, 'High Score:', highestScore)

            plotScores.append(score)
            totalScore += score
            meanScore = totalScore / agent.games
            plotMeanScores.append(meanScore)
            plot.plot(plotScores, plotMeanScores)
Пример #20
0
    def plot_summary(self):
        
        # Generate summary plot from chosen lattice and Hamiltonian
        
        K = -(4 * np.pi) / (3 * np.sqrt(3))

        Lat = lattice('Sheet', self.SelectStack.currentText()) # Create lattice

        H = Hamiltonian(Lat, self.Hoppingt2.value(), self.Hoppingtprime2.value()) # Create Hamiltonian
        if self.Magneticfield2.value() != 0: # Add magnetic field
            H.add_magnetic_field(self.Magneticfield2.value(), self.SelectBBil.currentText(), self.BAngle.value())

        if self.OnsiteV_2.value() != 0: # Add layer polarization
            H.add_sublattice_imbalance(self.OnsiteV_2.value())
        P = Plot(H)
        P.summary(self.Nk.value(), K, 0, self.xIndex.value(), self.yIndex.value(), self.dxIndex.value(), self.dyIndex.value())
Пример #21
0
 def putOutput(self, ticker, metrics, yahooVector, merged):
   print '\n---------- '+ticker+' THE RESULTS ----------'
   print 'Sharpe ratio\t\t ==> ' + str(round(metrics[0], 2))
   print 'Company Sharpe ratio\t ==> ' + str(round(metrics[8], 2))
   print 'Number of trades\t ==> ' + str(metrics[1][0])
   print 'Total days\t\t ==> ' + str(len(metrics[6]))
   print 'Percentage in\t\t ==> ' + str(round(metrics[1][1]*100, 2)) + '%'
   print 'Wins, losses\t\t ==> ' + str(metrics[2])
   print 'Average win, loss\t ==> ' + str(metrics[3])
   print 'Expectancy\t\t ==> ' + str(round(metrics[4], 4))
   print '---------------------------------------\n'
   
   print 'Plotting results..'
   we = Plot()
   # We want to plot equity, stock performance, and sentiment.
   we.plotThis(ticker, merged, metrics[6], metrics[7])
Пример #22
0
 def generate_2D_plots(self, data_dictionary):
     '''callback function... data_dictionary is a dictionary of
     data_set dictionaries. The data_set keys are x_dataFrame,
     y_dataFrame, x_series, y_series, x_axis, y_axis, title, style...'''
     for key in data_dictionary:
         idx = self.parent.project.get_next_figure_index()
         self.parent.project.add_figure(Plot(idx, data_dictionary[key]))
def update_plots():
    import wx
    while len(plots) < len(plot_data): plots.append(Plot())
    for plot,data in zip(plots,plot_data):
        try:
            if plot.data != data: plot.data = data; plot.update()
        except wx.PyDeadObjectError: pass
Пример #24
0
 def parseXml(node):
     block = Block()
     block.canBuild = ast.literal_eval(node.getAttribute("canBuild"))
     block.blockType = int(node.getAttribute("type"))
     for child in node.childNodes:
         block.addPlot(Plot.parseXml(child))
     return block
Пример #25
0
def bargraph_text(request):
    variableList = ["", "mdn", "pon", "spi", "spei", "pdsi", "pzi", "scpdsi"]
    if 'run_avg' in request.GET:
        run_avg = request.GET['run_avg']
        if not run_avg:
            runAvg = 0
        else:
            runAvg = int(run_avg)

    lat = float(request.GET['lat'])
    lon = float(request.GET['lon'])
    endYear = int(request.GET['end_year'])
    startYear = int(request.GET['start_year'])

    variable = int(request.GET['variable'])
    variable = variableList[variable]
    month = int(request.GET['month'])
    span = int(request.GET['span'])
    text = Plot(lat=lat,
                lon=lon,
                startYear=startYear,
                endYear=endYear,
                variable=variable,
                month=month,
                span=span,
                runavg=runAvg,
                data=None).getText()
    data = []
    for value in text:
        data.append(value)
    return render_to_response(
        'print.html', {'data': data})  #, {'year': data}, {'mean': data})
Пример #26
0
def accurateUpload(request):
    """
    Upload function of Accurate mode
    """
    context_dict = {}
    if request.method == "POST":
        try:
            filename = request.FILES['file'].name
            axis = request.POST.get("axis")
            values = request.POST.get("values")
            info = Plotinfo(filename, axis, axis_value=values)

            # Check value range
            if info["fixedmin"] <= float(values) <= info["fixedmax"]:
                context_dict['show'] = 'yes'
                nu = float(values)
                result = Plot(filename, axis, nu)
                context_dict['info'] = info
                context_dict['graph1'] = result
                context_dict['vis_success'] = 'True'
                return render(request, 'accurateMode.html', context=context_dict)
            else:
                context_dict['vis_success'] = 'Out'
                context_dict['errorinfo'] = "The Value is out of range. The value range of the axis you choose is " + \
                                            str(info["fixedmin"]) + " to " + str(info["fixedmax"]) + \
                                            " (" + info["fixedaxis"] + ")" + '.'

                return render(request, 'accurateMode.html', context=context_dict)
        except:
            context_dict['vis_success'] = 'False'
            context_dict['errorinfo'] = "You selected the wrong file or entered the wrong axis or missed an input"
            return render(request, 'accurateMode.html', context=context_dict)
Пример #27
0
def easyUpload(request):
    """
    Upload function of Easy mode
    """
    context_dict = {}
    if request.method == "POST":
        try:
            filename = request.FILES['file'].name
            axis = request.POST.get("axis")
            info = Plotinfo(filename, axis)
            zmin = info['zmin']
            zmax = info['zmax']
            context_dict['info'] = info
            context_dict['filename'] = str(request.POST)
            y = numpy.linspace(zmin, zmax, 10, endpoint=True).tolist()
            jslist = []
            context_dict['show'] = 'yes'

            # Create 10 Range
            for index in range(0, 10):
                context_dict['graph' + str(index)] = Plot(filename, axis, round(y[index], 2))
                jslist.append(round(y[index], 2))
            context_dict['jsl'] = jslist
            context_dict['vis_success'] = 'True'
            return render(request, 'easyMode.html', context=context_dict)
        except:
            context_dict['vis_success'] = 'False'
            context_dict['errorinfo'] = "Please upload the correct file and choose a valid axis"
            return render(request, 'easyMode.html', context=context_dict)
Пример #28
0
 def generate_maze(self, x, y):
     self.clear_widgets()
     self.number_of_cols = x
     self.number_of_rows = y
     for x in range(self.number_of_cols):
         for y in range(self.number_of_rows):
             print(f"{x}/{self.number_of_cols}, {y}/{self.number_of_rows}")
             self.add_widget(Plot())
Пример #29
0
    def calc_edge(self):

        # Calculate bandstructure from chosen lattice and Hamiltonian with colormap highlighting edge states

        Lat = lattice(
            'Ribbon',
            self.SelectEdge.currentText() + ' ' +
            self.SelectStack.currentText(), self.NUnit.value())

        H = Hamiltonian(Lat, self.Hoppingt.value(), self.Hoppingtprime.value())
        if self.Magneticfield.value() != 0:
            H.add_magnetic_field(self.Magneticfield.value(),
                                 self.SelectBBil.currentText())
        if self.OnsiteV.value() != 0:
            H.add_lattice_imbalance(self.OnsiteV.value())
        P = Plot(H)
        P.calc_edge()
Пример #30
0
def createBarLinePlot():

    if (request.method == 'POST'):
        data = request.get_json()
        startDate = data['startDate']
        endDate = data['endDate']
        payment = int(data['payment'])
        period = int(data['period'])
        contractElec = float(data['contractElec'])

    plotCreator = Plot()
    graphJSON = plotCreator.createBarLinePlot(startDate, endDate, contractElec,
                                              payment, 'abc', period)

    print(request.url)  #localhost:5000/electric/pattern
    print(a)
    return graphJSON
    def calc_edge(self):

        # Calculate bandstructure from chosen lattice and Hamiltonian and highlight edge states

        Lat = lattice('Ribbon', 'Twisted Bilayer', self.NUnit.value(),
                      self.TwistAngle.value())

        H = Hamiltonian(Lat, self.Hoppingt.value())
        if self.Magneticfield.value() != 0:
            H.add_magnetic_field(self.Magneticfield.value(),
                                 self.SelectBBil.currentText())
        if self.OnsiteV.value() != 0:
            H.add_lattice_imbalance(self.OnsiteV.value())
        if self.OnsiteV_2.value() != 0:
            H.add_sublattice_imbalance(self.OnsiteV_2.value())
        P = Plot(H)
        P.calc_edge()
Пример #32
0
    def Print(self, path, **kwargs):
        r"""Print the histogram to a file.

        Creates a PDF/PNG/... file with the absolute path defined by **path**. If a file
        with the same name already exists it will be overwritten (can be changed  with
        the **overwrite** keyword argument). If **mkdir** is set to ``True`` (default:
        ``False``) directories in **path** with do not yet exist will be created
        automatically. The styling of the histogram, pad and canvas can be configured
        via their respective properties passed as keyword arguments.

        :param path: path of the output file (must end with '.pdf', '.png', ...)
        :type path: ``str``

        :param \**kwargs: :class:`.Histo2D`, :class:`.Plot`, :class:`.Canvas` and
            :class:`.Pad` properties + additional properties (see below)

        Keyword Arguments:

            * **inject** (``list``, ``tuple``, ``ROOT.TObject``) -- inject a (list of)
              *drawable* :class:`ROOT` object(s) to the main pad, object properties can
              be specified by passing instead a ``tuple`` of the format
              :code:`(obj, props)` where :code:`props` is a ``dict`` holding the object
              properties (default: \[\])

            * **overwrite** (``bool``) -- overwrite an existing file located at **path**
              (default: ``True``)

            * **mkdir** (``bool``) -- create non-existing directories in **path**
              (default: ``False``)
        """
        injections = {"inject0": kwargs.pop("inject", [])}
        kwargs.setdefault("logy", False)  # overwriting Pad template's default value!
        properties = DissectProperties(kwargs, [Histo2D, Plot, Canvas, Pad])
        if any(
            map(
                lambda s: "Z" in s.upper(),
                [self.GetDrawOption(), properties["Pad"].get("drawoption", "")],
            )
        ):
            properties["Pad"].setdefault("rightmargin", 0.18)
        plot = Plot(npads=1)
        plot.Register(self, **MergeDicts(properties["Histo2D"], properties["Pad"]))
        plot.Print(
            path, **MergeDicts(properties["Plot"], properties["Canvas"], injections)
        )
Пример #33
0
    def plot_summary(self):

        # Generate summary plot of chosen lattice and Hamiltonian

        K = -(4 * np.pi) / (3 * np.sqrt(3))

        Lat = lattice('Sheet', 'Twisted Bilayer', 1, self.TwistAngle.value())

        H = Hamiltonian(Lat, self.Hoppingt2.value())
        if self.Magneticfield2.value() != 0:
            H.add_magnetic_field(self.Magneticfield2.value(),
                                 self.SelectBBil.currentText(),
                                 self.BAngle.value())
        if self.OnsiteV.value() != 0:
            H.add_lattice_imbalance(self.OnsiteV.value())
        if self.OnsiteV_2.value() != 0:
            H.add_sublattice_imbalance(self.OnsiteV_2.value())
        P = Plot(H)
        P.summary(self.Nk.value(), K, 0, 17, 75, 75, 75)
Пример #34
0
 def main(self):
     while(True):
         print("1-run,2-validate")
         choice=input()
         if choice=="1":
             self.run()
         elif choice=="2":
             Plot()
         else:
             return
    def start(cls):
        InOut.console_func_begin("Process")

        prePro = PreProcess()
        #prePro.start()
        #return

        pl = Plot()
        pl.start()
        return


        city = City()
        #city.start()

        resource = Resource()
        #resource.start()


        if(Config.flag_exp_generate_exp_data):
            getExpData = GetExpData()
            getExpData.start()

        if(Config.flag_exp_generate_ratio_data):
            getExpRatioData = GetExpRatioData()
            getExpRatioData.start()

        #return


        analyse = Analyse()
        #analyse.start()
        #return


        #Test.test()
        #return

        hli = HomeLocIdentify()
        hli.start()

        InOut.console_func_end("Process")
    def setup(self):
        self.memory_map = self.mission.get_memory_map()

        if self.settings.get("plot"):
            # Setup memory map plot
            from Plot import Plot

            self.plot = Plot(self.environment, self.memory_map)

        if self.rf_sensor is not None:
            self.rf_sensor.activate()
class Monitor(object):
    """
    Mission monitor class.

    Tracks sensors and mission actions in a stepwise fashion.
    """

    def __init__(self, mission, environment):
        self.mission = mission

        self.environment = environment
        arguments = self.environment.get_arguments()
        self.settings = arguments.get_settings("mission_monitor")

        # Seconds to wait before monitoring again
        self.step_delay = self.settings.get("step_delay")

        self.sensors = self.environment.get_distance_sensors()
        self.rf_sensor = self.environment.get_rf_sensor()

        self.colors = self.settings.get("plot_sensor_colors")

        self.memory_map = None
        self.plot = None
        self._paused = False

    def get_delay(self):
        return self.step_delay

    def use_viewer(self):
        return self.settings.get("viewer")

    def setup(self):
        self.memory_map = self.mission.get_memory_map()

        if self.settings.get("plot"):
            # Setup memory map plot
            from Plot import Plot

            self.plot = Plot(self.environment, self.memory_map)

        if self.rf_sensor is not None:
            self.rf_sensor.activate()

    def step(self, add_point=None):
        """
        Perform one step of a monitoring loop.

        `add_point` can be a callback function that accepts a Location object
        for a detected point from the distance sensors.

        Returns `False` if the loop should be halted.
        """

        if self._paused:
            return True

        # Put our current location on the map for visualization. Of course,
        # this location is also "safe" since we are flying there.
        vehicle_idx = self.memory_map.get_index(self.environment.get_location())
        try:
            self.memory_map.set(vehicle_idx, -1)
        except KeyError:
            print("Warning: Outside of memory map")

        self.mission.step()

        i = 0
        for sensor in self.sensors:
            yaw = sensor.get_angle()
            pitch = sensor.get_pitch()
            sensor_distance = sensor.get_distance()

            if self.mission.check_sensor_distance(sensor_distance, yaw, pitch):
                location = self.memory_map.handle_sensor(sensor_distance, yaw)
                if add_point is not None:
                    add_point(location)
                if self.plot:
                    # Display the edge of the simulated object that is
                    # responsible for the measured distance, and consequently
                    # the point itself. This should be the closest "wall" in
                    # the angle's direction. This is again a "cheat" for
                    # checking if walls get visualized correctly.
                    sensor.draw_current_edge(self.plot.get_plot(), self.memory_map, self.colors[i % len(self.colors)])

                print("=== [!] Distance to object: {} m (yaw {}, pitch {}) ===".format(sensor_distance, yaw, pitch))

            i = i + 1

        # Display the current memory map interactively.
        if self.plot:
            self.plot.plot_lines(self.mission.get_waypoints())
            self.plot.display()

        if not self.mission.check_waypoint():
            return False

        # Remove the vehicle from the current location. We set it to "safe"
        # since there is no object here.
        try:
            self.memory_map.set(vehicle_idx, 0)
        except KeyError:
            pass

        return True

    def sleep(self):
        time.sleep(self.step_delay)

    def start(self):
        self.mission.start()

        if self.rf_sensor is not None:
            self.rf_sensor.start()

    def pause(self):
        """
        Pause or unpause the mission.

        If the mission is currently paused, then this restarts the mission in
        the correct mode. Otherwise, the vehicle is paused and the RF sensor is
        put in its passive mode.
        """

        if self._paused:
            self.start()

            self._paused = False
        else:
            self.environment.get_vehicle().pause()
            if self.rf_sensor is not None:
                self.rf_sensor.stop()

            self._paused = True

    def stop(self):
        self.mission.stop()

        if self.rf_sensor is not None:
            self.rf_sensor.stop()

        if self.plot:
            self.plot.close()
Пример #38
0
        t_W = -R_WC.dot(t_C)

        T_CW = np.zeros((4, 4))
        T_CW[:3, :3] = R_CW
        T_CW[:3, 3:4] = t_C
        T_CW[3, 3] = 1.

        T_WC = np.zeros((4, 4))
        T_WC[:3, :3] = R_WC
        T_WC[:3, 3:4] = t_W
        T_WC[3, 3] = 1.
        return T_WC, T_CW


if __name__ == "__main__":
    p = Plot()
    geo = Geometry()
    d = 10
    pt0 = np.array([[0], [0], [0]])
    p.plotPoint(pt0)
    for i in range(10):
        angle = np.deg2rad(10 * i)
        pt = np.array([[d * np.cos(angle)],
                       [-d * np.sin(angle)],
                       [i]])
        if i == 0:
            p.plotPoint(pt, 'g.')
        else:
            p.plotPoint(pt)

        r = Ray(pt0, pt)
Пример #39
0
def bargraph_panel(request):
    try:
        data = [1,2,3,4,5]
        variableList = ["", "mdn","pon","spi","pdsi","pzi", "scpdsi"]
        if 'run_avg' in request.GET:
            run_avg = request.GET['run_avg']
            if not run_avg:
                runAvg = 0
            else:
                runAvg = int(run_avg)

        if 'lat' in request.GET:
            lat = request.GET['lat']
            if not lat:
                lat = 40
            else:
                lat = float(lat)

        if 'lon' in request.GET:
            lon = request.GET['lon']
            if not lon:
                lon = -100
            else:
                lon = float(lon)

        if 'start_year' in request.GET:
            startYear = request.GET['start_year']
            if startYear < 1895:
                startYear = 1895
            else:
                startYear = int(startYear)

        if 'end_year' in request.GET:
            endYear = request.GET['end_year']
            endYear = int(endYear)
            #if endYear > datetime.datetime.now().year:
            #    endYear = (datetime.datetime.now().year -1)
            #else:
            #    endYear = int(endYear)

        #if 'variable' in request.GET:
        #    variable = int(request.GET['variable'])
        #    variable = variableList[variable]

      
        variable = int(request.GET['variable'])
        variable = variableList[variable]
        month = int(request.GET['month'])
        span = int(request.GET['span'])
   
        # Print PNG to page
        try:
            canvas = Plot(lat=lat, lon=lon, startYear=startYear, endYear=endYear, variable=variable, month=month, span=span, runavg=runAvg, data=None).getData()
            response=HttpResponse(content_type='image/png')
            canvas.print_png(response)
            plt.close()
            return response
        except:
            return HttpResponse("Invalid plot")
    except:
        return HttpResponse("Invalid parameters")
Пример #40
0
#!/usr/bin/env python
import cv2
import numpy as np

from Plot import Plot
from Geometry import Geometry

PI = np.pi

if __name__ == "__main__":
    p = Plot()
    geo = Geometry()

    R = 18.1
    T = 42.8

    PO = np.zeros((3, 1))

    # Define test points
    PC = np.array([[0], [0], [R]])
    h, w = 3, 15
    Ppx = np.zeros((h, w, 3))
    Ppx[:, :, 0] = np.arange(-(h / 2), (h / 2) + 1).reshape((h, 1))
    Ppx[:, :, 1] = -np.arange(-(w / 2), (w / 2) + 1).reshape((1, w))
    Ppx[:, :, 2] = 1.2 * R

    # Define rotation angles
    Ppx_theta = np.pi / 2
    Ppx_phi = 3 * np.pi / 16

    # Rotate points
Пример #41
0
    def run_sim(self):
        """
        Sets up and runs the simulation
        """
        num_neurons = 1471  # total neurons in network
        num_inputs = 14     # number of neurons considered inputs
        num_runs = 1        # number of times to loop the learning
        num_samples = 1     # number of samples to learn`
        sim_time = 1000.0    # time to run sim for`
        inhibitory_split = 0.2
        connection_probability_factor = 0.02
        plot_spikes = True
        save_figures = True
        show_figures = True
        sim_start_time = strftime("%Y-%m-%d_%H:%M")

        cell_params_lif = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 10.0, 'tau_refrac': 2.0, 'tau_syn_E': 3.0,
                           'tau_syn_I': 3.0, 'v_reset': -65.0, 'v_rest': -65.0, 'v_thresh': -50.0}

        # Create the 3d structure of the NeuCube based on the user's given structure file
        network_structure = NetworkStructure()
        network_structure.load_structure_file()
        network_structure.load_input_location_file()
        # Calculate the inter-neuron distance to be used in the small world connections
        network_structure.calculate_distances()
        # Generate two connection matrices for excitatory and inhibitory neurons based on your defined split
        network_structure.calculate_connection_matrix(inhibitory_split, connection_probability_factor)
        # Get these lists to be used when connecting the neurons later
        excitatory_connection_list = network_structure.get_excitatory_connection_list()
        inhibitory_connection_list = network_structure.get_inhibitory_connection_list()
        # Choose the correct neurons to connect them to, based on your a-priori knowledge of the data source -- eg, EEG
        # to 10-20 locations, fMRI to voxel locations, etc.
        input_neuron_indexes = network_structure.find_input_neurons()
        # Make the input connections based on this new list
        input_weight = 4.0
        input_connection_list = []
        for index, input_neuron_index in enumerate(input_neuron_indexes):
            input_connection_list.append((index, input_neuron_index, input_weight, 0))

        for run_number in xrange(num_runs):
            excitatory_weights = []
            inhibitory_weights = []
            for sample_number in xrange(num_samples):
                # At the moment with the limitations of the SpiNNaker hardware we have to reinstantiate EVERYTHING
                # each run. In future there will be some form of repetition added, where the structure stays in memory
                # on the SpiNNaker and only the input spikes need to be updated.

                data_prefix = sim_start_time + "_r" + str(run_number + 1) + "-s" + str(sample_number + 1)

                # Set up the hardware - min_delay should never be less than the timestep.
                # Timestep should = 1.0 (ms) for normal realtime applications
                p.setup(timestep=1.0, min_delay=1.0)
                p.set_number_of_neurons_per_core("IF_curr_exp", 100)

                # Create a population of neurons for the reservoir
                neurons = p.Population(num_neurons, p.IF_curr_exp, cell_params_lif, label="Reservoir")

                # Setup excitatory STDP
                timing_rule_ex = p.SpikePairRule(tau_plus=20.0, tau_minus=20.0)
                weight_rule_ex = p.AdditiveWeightDependence(w_min=0.1, w_max=1.0, A_plus=0.02, A_minus=0.02)
                stdp_model_ex  = p.STDPMechanism(timing_dependence=timing_rule_ex, weight_dependence=weight_rule_ex)
                # Setup inhibitory STDP
                timing_rule_inh = p.SpikePairRule(tau_plus=20.0, tau_minus=20.0)
                weight_rule_inh = p.AdditiveWeightDependence(w_min=0.0, w_max=0.6, A_plus=0.02, A_minus=0.02)
                stdp_model_inh  = p.STDPMechanism(timing_dependence=timing_rule_inh, weight_dependence=weight_rule_inh)

                # record the spikes from that population
                neurons.record('spikes')

                # Generate a population of SpikeSourceArrays containing the encoded input spike data
                # eg. spike_sources = p.Population(14, p.SpikeSourceArray, {'spike_times': [[]]})
                # for the moment I'm going to cheat and just use poisson trains as I don't have data with me
                spike_sources = p.Population(num_inputs, p.SpikeSourcePoisson, {'rate': rand.randint(20, 80)},
                                             label="Poisson_pop_E")

                # Connect the input spike sources with the "input" neurons
                connected_inputs = p.Projection(spike_sources, neurons, p.FromListConnector(input_connection_list))

                # If we have weights saved/recorded from a previous run of this network, load them into the structure
                # population.set(weights=weights_list) and population.setWeights(weight_list) are not supported in
                # SpiNNaker at the moment so we have to do this manually.
                if excitatory_weights and inhibitory_weights:
                    for index, ex_connection in enumerate(excitatory_connection_list):
                        ex_connection[2] = excitatory_weights[index]
                    for index, in_connection in enumerate(inhibitory_connection_list):
                        in_connection[2] = inhibitory_weights[index]

                # Setup the connectors
                excitatory_connector = p.FromListConnector(excitatory_connection_list)
                inhibitory_connector = p.FromListConnector(inhibitory_connection_list)

                # Connect the excitatory and inhibitory neuron populations
                connected_excitatory_neurons = p.Projection(neurons, neurons, excitatory_connector,
                                                            synapse_dynamics=p.SynapseDynamics(slow=stdp_model_ex),
                                                            target="excitatory")
                connected_inhibitory_neurons = p.Projection(neurons, neurons, inhibitory_connector,
                                                            synapse_dynamics=p.SynapseDynamics(slow=stdp_model_inh),
                                                            target="inhibitory")

                # Set up recording the spike trains of all the neurons
                neurons.record()
                spike_sources.record()

                # Run the actual simulation
                p.run(sim_time)

                # Save the output spikes
                spikes_out = neurons.getSpikes(compatible_output=True)
                input_spikes_out = spike_sources.getSpikes(compatible_output=True)
                # Get the synaptic weights of all the neurons
                excitatory_weights = connected_excitatory_neurons.getWeights()
                inhibitory_weights = connected_inhibitory_neurons.getWeights()

                # when we're all done, clean up
                p.end()

                # Make some plots, save them if required. Check if you need to either save or show them, because if not,
                # there's no point wasting time plotting things nobody will ever see.
                if plot_spikes and (save_figures or show_figures):
                    plot = Plot(save_figures, data_prefix)
                    # Plot the 3D structure of the network
                    plot.plot_structure(network_structure.get_positions(), figure_number=0)
                    # Plot the spikes
                    plot.plot_spike_raster(spikes_out, sim_time, num_neurons, figure_number=1)
                    # Plot the weights
                    plot.plot_both_weights(excitatory_weights, inhibitory_weights, figure_number=2)
                    # If we want to show the figures, show them now, otherwise ignore and move on
                    if show_figures:
                        # Show them all at once
                        plot.show_plots()
                    plot.clear_figures()
                    plot = None
Пример #42
0
def bargraph_panel(request):
    try:
        data = [1,2,3,4,5]
        variableList = ["", "mdn","pon","spi","spei","pdsi","pzi", "scpdsi"]
        if 'run_avg' in request.GET:
            run_avg = request.GET['run_avg']
            if not run_avg:
                runAvg = 0
            else:
                runAvg = int(run_avg)

        if 'lat' in request.GET:
            lat = request.GET['lat']
            if not lat:
                lat = 40
            else:
                lat = float(lat)

        if 'lon' in request.GET:
            lon = request.GET['lon']
            if not lon:
                lon = -100
            else:
                lon = float(lon)

        if 'start_year' in request.GET:
            startYear = request.GET['start_year']
            if startYear < 1895:
                startYear = 1895
            else:
                startYear = int(startYear)

        if 'end_year' in request.GET:
            endYear = request.GET['end_year']
            endYear = int(endYear)
            #if endYear > datetime.datetime.now().year:
            #    endYear = (datetime.datetime.now().year -1)
            #else:
            #    endYear = int(endYear)

        #if 'variable' in request.GET:
        #    variable = int(request.GET['variable'])
        #    variable = variableList[variable]

      
        variable = int(request.GET['variable'])
        variable = variableList[variable]
        month = int(request.GET['month'])
        span = int(request.GET['span'])
   
        # Print PNG to page
        try:
            newPlot = Plot(lat=lat, lon=lon, startYear=startYear, endYear=endYear, variable=variable, month=month, span=span, runavg=runAvg, data=None)
            fig = newPlot.getData()            

            canvas=FigureCanvas(fig)
            response=django.http.HttpResponse(content_type='image/png')
            canvas.print_png(response)

            return response
        except:
            return HttpResponse("Plot feature under development for this location.")
    except:
        return HttpResponse("No data.")