Python Forum
read a parameter after updating it in another class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
read a parameter after updating it in another class
#1
Hello, I am using the managedwindow to live plot IV from a keithley2420 using the pymeasure module. It works but for some reason i cannot read a parameter defined in the first class that is updated in the queue function. here i define a parameter mode that takes the nature of the measurement 2 or 4 wires. when i queue experiments i can change that parameter in the GUI and record a new set of data. i can check in the keithley that the 4w mode is on and in the data file i do see the right mode parameter. i am trying to get that parameter as a string for my filename so i typed in str(self.mode), but the mode is stuck to the default value defined in the parameter, it is not updated after typing in the new value in the GUI whereas the right data appears in the file?. I did inherit the second class from the first. i use fake data to test the code below.
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

import sys
import tempfile
from tempfile import NamedTemporaryFile
import random
import datetime
from datetime import datetime as dt, timedelta
import time
from time import sleep
import pandas as pd
from pymeasure.log import console_log
from pymeasure.display.Qt import QtGui
from pymeasure.display.windows import ManagedWindow
from pymeasure.experiment import Procedure, Results
from pymeasure.experiment import IntegerParameter, FloatParameter, Parameter

class RandomProcedure(Procedure):
    iterations = IntegerParameter('Loop Iterations', default=10)
    delay = FloatParameter('Delay Time', units='s', default=0.2)
    seed = Parameter('Random Seed', default='20')
    mode = IntegerParameter('2 or 4 probes measurement', default=2)

    DATA_COLUMNS = ['Mode', 'Iteration', 'Timecode', 'Elapsed', 'Random Number']

    def startup(self):
        log.info("Setting the time of the random number generator")
        random.seed(self.seed)

    def execute(self):
        log.info("Starting the loop of %d iterations" % self.iterations)
        start = datetime.datetime.now()
        for i in range(self.iterations):
            timecode = dt.now()
            elapsed = (datetime.datetime.now() - start).total_seconds()
            data = {
                'Mode': self.mode,
                'Iteration': i,
                'Timecode': timecode,
                'Elapsed': elapsed,
                'Random Number': random.randint(1, 100)
            }
            self.emit('results', data)
            log.debug("Emitting results: %s" % data)
            sleep(self.delay)
            if self.should_stop():
                log.warning("Caught the stop flag in the procedure")
                break

class MainWindow(ManagedWindow, RandomProcedure):
    def __init__(self):
        super(MainWindow, self).__init__(
            procedure_class=RandomProcedure,
            inputs=['iterations', 'delay', 'seed', 'mode'],
            displays=['iterations', 'delay', 'seed', 'mode'],
            x_axis='Iteration',
            y_axis='Random Number',
            sequencer=True,  # Added line
            sequencer_inputs=['iterations', 'delay', 'seed', 'mode'],  # Added line
            # sequence_file="gui_sequencer_example_sequence.txt",  # Added line, optional
        )
        self.setWindowTitle('GUI Example')
        self.count = 0

    def queue(self, *, procedure=None):
        self.count = self.count + 1
        filename = 'D:\\test\\' + str(dt.now().strftime("%m%d%Y"))+'_' + 'mode_' + str(self.mode) + '_' + str(self.count) + '.csv'
        log.info("Constructing the Results with a data file: %s" % filename)
        if procedure is None:
            procedure = self.make_procedure()
        results = Results(procedure, filename)
        experiment = self.new_experiment(results)
        self.manager.queue(experiment)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
Reply
#2
I don't see a line starting with self.mode = .... How do you expect self.mode to change?
Reply
#3
(Jul-22-2020, 12:30 PM)Gribouillis Wrote: I don't see a line starting with self.mode = .... How do you expect self.mode to change?

Thanks. I did add it in the data dictionary as 'Mode': self.mode this works i do get the right value first 2 and then 4 after updating the mode to 4 in the GUI. i try to get that data in the queue function so that i can call it in my filename and have the filename updated according to the mode of measurement. alternatively i also tried to add self.mode = mode but then i get NameError: name 'mode' is not defined. if the other way around mode = self.mode i don't get any error and the data file are correct but the filename is not update i.e in that function i get the default value of the parameter.
Reply
#4
I am trying to call a variable mode (can take either 2 or 4 ) declared in RandomProcedure class. I want to use it in the MainWindow class so that when I change the mode parameter in the GUI, I can save the mode into my file name. I called the first class into the second but if i put self.mode as a filename paramter it remains stuck to 2 even if I type in 4 in the GUI. here I use fake data to test. i can see the mode updated in the .csv datafile generated. now i want to get the self.mode that is updated in the execute() function (you can see in the print output when run the code below that the value changes). although i return it in the execute() i cannot pass it out to the Mainwindow class to use it as a filename paramter, i still get error.

import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

import sys
import tempfile
from tempfile import NamedTemporaryFile
import random
import datetime
from datetime import datetime as dt, timedelta
import time
from time import sleep
import pandas as pd
from pymeasure.log import console_log
from pymeasure.display.Qt import QtGui
from pymeasure.display.windows import ManagedWindow
from pymeasure.experiment import Procedure, Results
from pymeasure.experiment import IntegerParameter, FloatParameter, Parameter
from copy import deepcopy

class RandomProcedure(Procedure):

    iterations = IntegerParameter('Loop Iterations', default=10)
    delay = FloatParameter('Delay Time', units='s', default=0.2)
    seed = Parameter('Random Seed', default='20')
    mode = IntegerParameter('Measurement mode : 2 or 4 probes', default=2)

    DATA_COLUMNS = ['Mode', 'Iteration', 'Timecode', 'Elapsed', 'Random Number']

    def startup(self):
        log.info("Setting the time of the random number generator")
        random.seed(self.seed)

    def execute(self):
        log.info("Starting the loop of %d iterations" % self.iterations)
        start = datetime.datetime.now()
        for i in range(self.iterations):
            timecode = dt.now()
            elapsed = (datetime.datetime.now() - start).total_seconds()
            data = {
                'Mode': self.mode,
                'Iteration': i,
                'Timecode': timecode,
                'Elapsed': elapsed,
                'Random Number': random.randint(1, 100)
            }
            self.emit('results', data,)
            log.debug("Emitting results: %s" % data)
            sleep(self.delay)
            if self.should_stop():
                log.warning("Caught the stop flag in the procedure")
                break
        print(self.mode)
        val = self.mode
        # print(val)
        return val

class MainWindow(ManagedWindow, RandomProcedure):

    def __init__(self):
        self.val = self.mode
        super(MainWindow, self).__init__(
            procedure_class=RandomProcedure,
            inputs=['iterations', 'delay', 'seed', 'mode'],
            displays=['iterations', 'delay', 'seed', 'mode'],
            x_axis='Iteration',
            y_axis='Random Number',
            sequencer=True,  # Added line
            sequencer_inputs=['iterations', 'delay', 'seed', 'mode'],  # Added line
            # sequence_file="gui_sequencer_example_sequence.txt",  # Added line, optional
        )
        self.setWindowTitle('GUI Example')
        self.count = 0

    def queue(self, *, procedure=None):
        self.count = self.count + 1
        val = RandomProcedure.execute(self) # i call execute() to get the update value of the mode
        filename = 'D:\\test\\' + str(dt.now().strftime("%m%d%Y")) + '_' + 'mode_' + str(val) + '_' + str(self.count) + '.csv'
        log.info("Constructing the Results with a data file: %s" % filename)
        if procedure is None:
            procedure = self.make_procedure()
        results = Results(procedure, filename)
        experiment = self.new_experiment(results)
        self.manager.queue(experiment)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read module/class from list of strings? popular_dog 1 421 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 10,639 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  How to read file inside class Mekala 11 12,248 May-02-2020, 11:36 AM
Last Post: snippsat
  Assigning data read from CSV to class faruk61 2 2,075 Apr-15-2020, 05:52 PM
Last Post: buran
  The derivate class dosn't behave like the base when i pass parameter to them drudox 4 3,125 Aug-05-2018, 06:42 PM
Last Post: drudox
  Global accessing of parameter to class Mahamutha 3 3,477 Aug-23-2017, 07:04 PM
Last Post: nilamo
  Running Class methods in a loop and updating variables. ujjwalrathod007 3 6,264 Oct-05-2016, 07:11 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020